UNPKG

@wayrisignals/kicad-webview

Version:

Interactive KiCad schematic, PCB and 3D viewer for the web, with Gerber, Excellon, linked views and offline HTML exports

5,028 lines • 1.87 MB
/*! KiCad WebView 1.2.1 | Copyright (c) 2026 wayri | SPDX-License-Identifier: MPL-2.0 | Source: https://github.com/wayri/kicad-webview/tree/v1.2.1 | Keep LICENSE and THIRD-PARTY-NOTICES.md; bundled dependencies retain their licenses. */
var vD=Object.create;var Q0=Object.defineProperty;var xD=Object.getOwnPropertyDescriptor;var bD=Object.getOwnPropertyNames;var wD=Object.getPrototypeOf,_D=Object.prototype.hasOwnProperty;var $c=(m=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(m,{get:(h,p)=>(typeof require<"u"?require:h)[p]}):m)(function(m){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+m+'" is not supported')});var Ui=(m,h)=>()=>(m&&(h=m(m=0)),h);var $n=(m,h)=>()=>(h||m((h={exports:{}}).exports,h),h.exports),Ol=(m,h)=>{for(var p in h)Q0(m,p,{get:h[p],enumerable:!0})},ED=(m,h,p,w)=>{if(h&&typeof h=="object"||typeof h=="function")for(let S of bD(h))!_D.call(m,S)&&S!==p&&Q0(m,S,{get:()=>h[S],enumerable:!(w=xD(h,S))||w.enumerable});return m};var Vn=(m,h,p)=>(p=m!=null?vD(wD(m)):{},ED(h||!m||!m.__esModule?Q0(p,"default",{value:m,enumerable:!0}):p,m));function AE(m,h,p){if(!p)return null;let w=m.getParts(),S=h.getParts(),A=[p.ownerUuid,p.parent?.uuid,p.uuid,p.id].filter(ee=>typeof ee=="string"&&ee),T=w.filter(ee=>A.includes(ee.uuid));if(T.length!==1)return null;let H=T[0],Y;if(m.kind==="pcb"&&h.kind==="schematic"&&H.schematicUuid)Y=S.filter(ee=>ee.uuid===H.schematicUuid);else if(m.kind==="schematic"&&h.kind==="pcb"&&H.uuid)Y=S.filter(ee=>ee.schematicUuid===H.uuid);else if(ev(m,h)&&H.uuid)Y=S.filter(ee=>ee.uuid===H.uuid);else return null;return Y.length===1?Y[0]:null}function SD(m,h,p){if(!ev(m,h))return null;let w=p.netName||p.net,S=m.getNets(),A=h.getNets(),T=(p.kind==="net"||p.type==="net")&&typeof p.id=="string"&&p.id?S.filter(G=>G.id===p.id):[],H=typeof w=="string"?S.filter(G=>G.name===w):[],Y=T.length===1?T[0]:H.length===1?H[0]:null;if(!Y)return null;let ee=typeof Y.id=="string"&&Y.id?A.filter(G=>G.id===Y.id):[];if(ee.length===1)return ee[0];let X=A.filter(G=>G.name===Y.name);return X.length===1?X[0]:null}function Qc(m,h,p){if(m===h||!Jc(m)||!Jc(h))return null;if(p===null)return h.clearSelection(),"clear";if(!p||typeof p!="object")return null;let w=String(p.kind||p.type||"").toLowerCase();if(ev(m,h)&&typeof h.selectObject=="function"&&["pad","pin","segment","track","arc","via","zone"].includes(w)){let H=w==="pin"?p.pinNumber!==void 0?p.ownerUuid:void 0:p.uuid;if(typeof H=="string"&&H&&h.selectObject(H,{locate:h.view==="3d"&&["pad","pin"].includes(w),...p.pinNumber!==void 0?{pinNumber:p.pinNumber}:{}}))return"object"}let A=p.kind==="net"||p.type==="net"?null:AE(m,h,p);if(A)return h.selectPart(A.id,{locate:h.view==="3d"})?"part":null;let T=SD(m,h,p);return T&&h.selectNet(T.id||T.name,{locate:!1})?"net":null}function MD(m,{enabled:h=!0}={}){if(!Array.isArray(m)||m.length<2||m.length>8||new Set(m).size!==m.length)throw new TypeError("Link 2 to 8 distinct viewer instances.");let p=["addEventListener","removeEventListener","getParts","getNets","selectPart","selectNet","clearSelection"];if(m.some(G=>!G||G.disposed||p.some(ae=>typeof G[ae]!="function")))throw new TypeError("Choose active KiCadViewer instances.");let w=[...m],S=new EventTarget,A=!1,T=!1,H=!!h,Y=[],ee=(G,ae)=>S.dispatchEvent(new CustomEvent(G,{detail:ae})),X=(G,ae)=>{if(A||T||!H||!Jc(G))return;let _e=ae.detail;if(!_e||!Object.hasOwn(_e,"item")||_e.path!==void 0&&_e.path!==G.path||_e.view!==void 0&&_e.view!==G.view)return;let J=_e.item===null?null:G.getSelection?.()||_e.item;T=!0;try{for(let Q of w){if(A||!H)break;if(!(Q===G||!Jc(Q)))try{let te=Qc(G,Q,J);te&&!A&&H&&ee("link",{source:G,target:Q,kind:te})}catch(te){Q.disposed||ee("linkerror",{source:G,target:Q,error:te})}}}finally{T=!1}};for(let G of w){let ae=_e=>X(G,_e);G.addEventListener("select",ae),Y.push(()=>G.removeEventListener("select",ae))}return Object.defineProperty(S,"enabled",{get:()=>H&&!A}),S.setEnabled=G=>{if(A)throw new Error("Linked viewers have been disposed.");H=!!G},S.dispose=()=>{if(!A){A=!0,H=!1;for(let G of Y)G();Y.length=0,w.length=0}},S}var Jc,ev,Qu=Ui(()=>{Jc=m=>!m.disposed&&typeof m.source=="string"&&m.source.length>0,ev=(m,h)=>Jc(m)&&Jc(h)&&m.kind===h.kind&&m.path===h.path&&m.source===h.source});var tv=$n((oF,rm)=>{(m=>{"use strict";let S=J=>({quoted:String(J??"")}),A=J=>{let Q=Number(J);if(!Number.isFinite(Q)||Math.abs(Q)>1e8)throw Error("Invalid legacy schematic coordinate.");return Math.round(Q*.0254*1e8)/1e8},T=J=>[...J.matchAll(/"((?:\\.|[^"\\])*)"|([^\s]+)/g)].map(Q=>Q[1]!==void 0?Q[1].replace(/\\(["\\])/g,"$1"):Q[2]),H=(J,Q,te=0)=>["at",A(J),A(Q),te],Y=(J=50,Q=!1)=>["effects",["font",["size",A(J),A(J)]],...Q?["hide"]:[]];function ee(J){if(typeof J!="string"||new TextEncoder().encode(J).length>8388608)throw Error("Legacy schematic/library exceeds its size limit.");let Q=J.replace(/^\uFEFF/,"").split(/\r?\n/);if(Q.length>15e4)throw Error("Legacy schematic/library exceeds its line limit.");return Q}function X(J,Q,te){let he,be=1,De=!1,Ke=!1,qe=0,$e=[];for(let Xe=Q;Xe<te;Xe++){let ve=J[Xe].trim();if(!ve)continue;if(ve==="EndData"&&De&&!Ke){Ke=!0;continue}if(De&&!Ke){if(!/^[0-9a-f]{2}(?:\s+[0-9a-f]{2})*$/i.test(ve))throw Error("Invalid saved bitmap bytes.");let re=ve.match(/[0-9a-f]{2}/gi);if(qe+=re.length,qe>4*1024*1024)throw Error("Saved bitmap exceeds its 4 MiB limit.");for(let R=0;R<re.length;R+=8192)$e.push(String.fromCharCode(...re.slice(R,R+8192).map($=>parseInt($,16))));continue}let[Ee,me,N]=T(ve);Ee==="Pos"&&me!==void 0&&N!==void 0&&(he=H(me,N)),Ee==="Scale"&&me!==void 0&&(be=Number(me)),Ee==="Data"&&!De&&(De=!0)}if(!he||!$e.length||!Ke||!Number.isFinite(be)||be<=0)throw Error("Invalid saved bitmap placement or data.");return["image",he,["scale",be],["uuid",S("legacy-bitmap-"+Q)],["data",S(btoa($e.join("")))]]}function G(J,Q){let te=new Map,he=0;if(!Array.isArray(J))return te;if(J.length>16)throw Error("Too many legacy symbol libraries.");for(let be of J){let De=typeof be=="string"?be:be?.content;if(typeof De!="string")continue;if(he+=De.length,he>16*1024*1024)throw Error("Legacy symbol libraries exceed their combined limit.");let Ke=null,qe=[],$e=!1,Xe=new Map;for(let ve of ee(De)){let Ee=T(ve),me=Ee[0];if(!me||me[0]==="#")continue;if(me==="DEF"){Ke=Ee,qe=[],Xe=new Map;continue}if(!Ke)continue;if(me==="ALIAS"){qe.push(...Ee.slice(1));continue}if(me==="DRAW"){$e=!0;continue}if(me==="ENDDRAW"){$e=!1;continue}if(me==="ENDDEF"){let $=Ke[1],V=["symbol",S($),...Ke[9]==="P"?[["power"]]:[],...Ke[5]==="N"?[["pin_numbers","hide"]]:[],...Ke[6]==="N"?[["pin_names","hide"]]:[],...Xe.values()];for(let O of[$,...qe])te.has(O)||te.set(O,V);Ke=null;continue}if(!$e)continue;let N=($,V,O)=>{let C=$+"_"+V;Xe.has(C)||Xe.set(C,["symbol",S(Ke[1]+"_"+C)]),Xe.get(C).push(O)},re=$=>["stroke",["width",Math.max(A($||6),.01)]],R=$=>["fill",["type",$==="F"?"outline":$==="f"?"background":"none"]];if(me==="S")N(Ee[5],Ee[6],["rectangle",["start",A(Ee[1]),A(Ee[2])],["end",A(Ee[3]),A(Ee[4])],re(Ee[7]),R(Ee[8])]);else if(me==="C")N(Ee[4],Ee[5],["circle",["center",A(Ee[1]),A(Ee[2])],["radius",A(Ee[3])],re(Ee[6]),R(Ee[7])]);else if(me==="P"){let $=Number(Ee[1]);if(!Number.isInteger($)||$<2||$>1e4||Ee.length<5+2*$)throw Error("Invalid legacy library polyline.");N(Ee[2],Ee[3],["polyline",["pts",...Array.from({length:$},(V,O)=>["xy",A(Ee[5+O*2]),A(Ee[6+O*2])])],re(Ee[4]),R(Ee[5+$*2])])}else if(me==="A"){let $=A(Ee[1]),V=A(Ee[2]),O=A(Ee[3]),C=Number(Ee[4])*Math.PI/1800,B=Number(Ee[5])*Math.PI/1800-C;for(;B<0;)B+=Math.PI*2;let W=K=>[$+O*Math.cos(K),V+O*Math.sin(K)];N(Ee[6],Ee[7],["arc",["start",...W(C)],["mid",...W(C+B/2)],["end",...W(C+B)],re(Ee[8]),R(Ee[9])])}else if(me==="X"){let $={I:"input",O:"output",B:"bidirectional",T:"tri_state",P:"passive",U:"unspecified",W:"power_in",w:"power_out",C:"open_collector",E:"open_emitter",N:"no_connect"},V={R:0,U:90,L:180,D:270}[Ee[6]],O={"":"line",I:"inverted",C:"clock",CI:"inverted_clock",L:"input_low",CL:"clock_low",V:"output_low",F:"edge_clock_high",X:"non_logic"},C=Ee[12]||"",j=C.includes("N"),B=O[C.replace(/N/g,"")];if(V===void 0||!B){Q("Unsupported legacy pin orientation/style omitted: "+Ee[1]);continue}N(Ee[9],Ee[10],["pin",$[Ee[11]]||"unspecified",B,H(Ee[3],Ee[4],V),["length",A(Ee[5])],["name",S(Ee[1]),Y(Ee[8])],["number",S(Ee[2]),Y(Ee[7])],...j?["hide"]:[]])}else Q(me==="T"?"Legacy library text is omitted; convert a copy in KiCad for complete typography.":"Unsupported legacy library graphic "+me+" omitted.")}}return te}function ae(J,Q={}){let te=ee(J);if(!/^EESchema Schematic File Version [24]\b/.test(te[0]))throw Error("Only legacy Eeschema v2/v4 schematics are supported.");let he=new Set(["Restricted legacy schematic preview: only recognized saved records and supplied cache-library graphics are rendered. Convert a separate copy in KiCad for a complete modern preview."]),be=Ee=>{he.size<200&&he.add(Ee)},De=G(Q.libraries,be),Ke=["kicad_sch",["version",Number(te[0].match(/\d+$/)[0])],["legacy_source",S(te[0])]],qe=["lib_symbols"],$e=[],Xe=(Ee,me,N,re,R=50,$=!1,V=0)=>["property",S(Ee),S(me),H(N,re,V),Y(R,$)];function ve(Ee,me){let N=[],re=Ee;for(;re<te.length&&te[re]!==me;re++)N.push(T(te[re]));if(re===te.length)throw Error("Incomplete legacy schematic "+me+" block.");return{records:N,end:re}}for(let Ee=1;Ee<te.length;Ee++){let me=T(te[Ee]),N=me[0];if(!(!N||N[0]==="#")){if(N==="$Descr"){Ke.push(["paper",S(me[1])]);continue}if(/^Comment[1-9]$/.test(N)){let re=Ke.find(R=>Array.isArray(R)&&R[0]==="title_block");re||(re=["title_block"],Ke.push(re)),re.push(["comment",Number(N.slice(7)),S(me[1])]);continue}if(["Title","Date","Rev","Comp"].includes(N)){let re=Ke.find(R=>Array.isArray(R)&&R[0]==="title_block");re||(re=["title_block"],Ke.push(re)),re.push([{Title:"title",Date:"date",Rev:"rev",Comp:"company"}[N],S(me[1])]);continue}if(N==="Wire"||N==="Entry"){let re=T(te[++Ee]||"");if(re.length!==4)throw Error("Invalid legacy wire record.");if(N==="Entry"){be("Legacy bus-entry geometry omitted.");continue}Ke.push([me[1]==="Bus"?"bus":"wire",["pts",["xy",A(re[0]),A(re[1])],["xy",A(re[2]),A(re[3])]]]);continue}if(N==="Connection"||N==="NoConn"){Ke.push([N==="Connection"?"junction":"no_connect",H(me[2],me[3])]);continue}if(N==="Text"){let re=te[++Ee]??"",R={Label:"label",GLabel:"global_label",HLabel:"hierarchical_label",Notes:"text"}[me[1]];if(!R){be("Unsupported legacy text record "+me[1]+" omitted.");continue}let $=[0,90,180,270],V=$[Number(me[4])];if(V===void 0){be("Unsupported legacy text orientation omitted.");continue}let O={Input:"input",Output:"output",BiDi:"bidirectional",TriState:"tri_state",UnSpc:"passive"}[me[6]];!["text","label"].includes(R)&&!O&&be("Unknown legacy label shape "+me[6]+"; passive outline used."),Ke.push([R,S(re.replace(/\\n/g,`
`)),H(me[2],me[3],V),Y(me[5]),...R==="text"||R==="label"?[]:[["shape",O||"passive"]]]);continue}if(N==="$Sheet"){let re=ve(Ee+1,"$EndSheet");Ee=re.end;let R=re.records,$=R.find(C=>C[0]==="S"),V=R.find(C=>C[0]==="U");if(!$)throw Error("Legacy sheet has no bounds.");let O=["sheet",H($[1],$[2]),["size",A($[3]),A($[4])],["uuid",S(V?.[1]||"legacy-sheet-"+Ee)]];for(let C of R.filter(j=>/^F\d+$/.test(j[0])))if(C[0]==="F0"||C[0]==="F1")O.push(Xe(C[0]==="F0"?"Sheetname":"Sheetfile",C[1],$[1],$[2],C[2]));else{let j=C[3],B={L:180,R:0,U:90,D:270}[j];O.push(["pin",S(C[1]),{I:"input",O:"output",B:"bidirectional",T:"tri_state",U:"passive"}[C[2]]||"passive",H(C[4],C[5],B??0),Y(C[6])])}Ke.push(O);continue}if(N==="$Comp"){let re=ve(Ee+1,"$EndComp");Ee=re.end;let R=re.records,$=R.find(ge=>ge[0]==="L"),V=R.find(ge=>ge[0]==="U"),O=R.find(ge=>ge[0]==="P");if(!$||!O)throw Error("Incomplete legacy component.");let C=$[1],j=R.find(ge=>ge.length===4&&ge.every(Ne=>/^-?\d+$/.test(Ne)))?.map(Number)||[1,0,0,-1],B=null;for(let ge of[0,90,180,270])for(let Ne of["","x","y"]){let ne=ge*Math.PI/180,we=Math.round(Math.cos(ne)),xe=Math.round(Math.sin(ne)),ke=Ne==="y"?-1:1,Me=Ne==="x"?-1:1,Ce=[ke*we,-ke*xe,-Me*xe,-Me*we];j.every((tt,Ze)=>tt===Ce[Ze])&&(B={angle:ge,mirror:Ne})}if(!B){be("Legacy component "+C+" has an unsupported orientation and is omitted.");continue}let W=["symbol",["lib_id",S(C)],H(O[1],O[2],B.angle),["unit",Number(V?.[1]||1)],["convert",Number(V?.[2]||1)],["uuid",S(V?.[3]||"legacy-component-"+Ee)],...B.mirror?[["mirror",B.mirror]]:[]];for(let ge of R.filter(Ne=>Ne[0]==="F")){let Ne=["Reference","Value","Footprint","Datasheet"][Number(ge[1])]||ge[11]||"Field"+ge[1];W.push(Xe(Ne,ge[2],ge[4],ge[5],ge[6],ge[7]!=="0000",(((ge[3]==="V"?90:0)-B.angle)%180+180)%180))}let K=De.get(C)||De.get(C.split(":").pop());K?$e.includes(C)||(qe.push(["symbol",S(C),...K.slice(2)]),$e.push(C)):be("Missing saved legacy library definition for "+C+": symbol body and pins omitted; fields remain visible."),Ke.push(W);continue}if(N==="$Bitmap"){let re=te.indexOf("$EndBitmap",Ee+1);if(re<0){be("Legacy bitmap omitted: missing block terminator.");break}try{Ke.push(X(te,Ee+1,re))}catch(R){be("Legacy bitmap omitted: "+R.message)}Ee=re}}}if(!te.some(Ee=>Ee==="$EndSCHEMATC"))throw Error("Incomplete legacy schematic terminator.");return Ke.push(qe,...[...he].map(Ee=>["legacy_diagnostic",S(Ee)])),Ke}function _e(J){let Q=ee(J),te=[],he=!1;for(let be of Q)if(be==="$Sheet")he=!0;else if(be==="$EndSheet")he=!1;else if(he){let De=T(be);De[0]==="F1"&&te.push(De[1])}return te}m.KiCadLegacy={parse:ae,sheetFiles:_e},typeof rm=="object"&&rm.exports&&(rm.exports=m.KiCadLegacy)})(globalThis)});var im,TE=Ui(()=>{im=class{constructor({WeakRefClass:h=globalThis.WeakRef}={}){this.entries=[],this.current=new WeakMap,this.WeakRefClass=h}identity(h){let p=this.current.get(h);return(!p||p.source!==h.source)&&(p={source:h.source,key:{}},this.current.set(h,p)),p}remember(h){let p=h.view==="3d"?h.getCamera3D():h.getCamera();if(!p||!h.source)return;let w=this.identity(h),S=h.textInstancePath??null;this.entries=this.entries.filter(A=>A.path!==h.path||A.view!==h.view||A.instancePath!==S),this.entries.push({key:w.key,sourceRef:typeof this.WeakRefClass=="function"?new this.WeakRefClass(w):null,path:h.path,view:h.view,instancePath:S,camera:structuredClone(p),explode:h.view==="3d"&&h.renderer?.getExplode?.()||0}),this.entries.length>4&&this.entries.shift()}restore(h){let p=this.identity(h),w=this.entries.find(S=>S.path===h.path&&S.view===h.view&&S.instancePath===(h.textInstancePath??null)&&(S.key===p.key||S.sourceRef?.deref()?.source===h.source));return w?(w.view==="3d"?((h.renderer.restoreExpand||h.renderer.setExplode)?.call(h.renderer,w.explode),h.setCamera3D(structuredClone(w.camera))):h.setCamera(structuredClone(w.camera)),!0):!1}clear(){this.entries=[],this.current=new WeakMap}}});function CE(m){let h=m.host.ownerDocument,p=h.createElement("div");p.className="viewer-loading",p.hidden=!0,p.setAttribute("role","status"),p.setAttribute("aria-live","polite");let w=h.createElement("strong"),S=h.createElement("span"),A=h.createElement("progress"),T=h.createElement("button");w.textContent="Opening design",A.setAttribute("aria-label","Loading design"),T.type="button",T.textContent="Stop",T.setAttribute("aria-label","Stop loading"),p.append(w,S,A,T),m.surface.append(p);let H=h.createElement("style");H.textContent=".viewer-loading[hidden]{display:none}.viewer-loading{position:absolute;inset:0;z-index:20;display:flex;align-items:center;justify-content:center;flex-direction:column;gap:12px;padding:16px;box-sizing:border-box;background:var(--viewer-bg,#151a21);color:var(--viewer-ink,#e1eaf3);font:13px system-ui;text-align:center}.viewer-loading span{overflow-wrap:anywhere;max-width:100%}.viewer-loading progress{width:min(240px,85%);accent-color:#59c9d2}.viewer-loading button{font:inherit;min-height:44px;padding:8px 20px;background:transparent;color:inherit;border:1px solid currentColor;border-radius:6px}.viewer-loading button:focus-visible{outline:2px solid #59c9d2;outline-offset:3px}@media(prefers-reduced-motion:reduce){.viewer-loading progress{animation:none}}",m.surface.append(H);let Y=null;return{show(ee,X){Y=ee,S.textContent="Preparing drawing\u2026",T.disabled=!1,T.onclick=()=>{Y!==ee||T.disabled||(T.disabled=!0,S.textContent="Stopping\u2026",X())},p.hidden=!1,m.root.setAttribute("aria-busy","true")},stage(ee,X){Y===ee&&!T.disabled&&(S.textContent=X)},hide(ee){Y===ee&&(Y=null,p.hidden=!0,T.onclick=null,m.root.setAttribute("aria-busy","false"))},dispose(){Y=null,T.onclick=null,p.remove(),H.remove(),m.root.setAttribute("aria-busy","false")}}}function RE(m){return typeof requestAnimationFrame!="function"?Promise.resolve():new Promise((h,p)=>{let w,S,A=()=>{clearTimeout(S),w!==void 0&&cancelAnimationFrame(w),m.removeEventListener("abort",T),h()},T=()=>{clearTimeout(S),w!==void 0&&cancelAnimationFrame(w),m.removeEventListener("abort",T),p(new DOMException("The operation was aborted.","AbortError"))};if(m.aborted){T();return}m.addEventListener("abort",T,{once:!0}),S=setTimeout(A,32),w=requestAnimationFrame(A)})}var PE=Ui(()=>{});function Dl(m){let h=m.renderer;if(!h)return null;let p=h.design||m.design,w=m.path,S=m.view,A=IE.get(h);return(!A||A.design!==p||A.path!==w||A.view!==S)&&(A&&typeof h.layerPreset!="function"&&(h.layerPresetName=null,h.layerSnapshot=null),A={design:p,path:w,view:S,snapshot:null,preset:null},IE.set(h,A)),A}function ed(m="dim",h="accent"){if(!["dim","bright","isolate"].includes(m))throw new TypeError("Choose dim, bright or isolate highlight style.");if(!["accent","source"].includes(h))throw new TypeError("Choose accent or source highlight color.");return{mode:m,color:h}}function NE(m,h,{color:p=m.highlightColor}={}){m.assertActive();let w=ed(h,p);return m.highlightMode=w.mode,m.highlightColor=w.color,m.inspector?.refreshHighlight(),m.updateControls(),m.emit("highlightstylechange",{...w}),{...w}}function eh(m){m.assertActive();let h=m.renderer,w=["pcb","3d","manufacturing"].includes(m.view)&&!!h?m.view==="3d"?h.getCopperLayers?.()||[]:m.getLayers():[],S=Dl(m),A=m.view==="3d"?h?.getVisibleCopperLayers?.()||[]:[...h?.visibleLayers||[]];return{layers:[...w],preset:(typeof h?.layerPreset=="function"?h.layerPresetName:S?.preset)||null,visible:A.filter(T=>w.includes(T)),focused:m.view==="pcb"&&h?.focusedLayer||null,focusMode:h?.layerFocusMode||"dim",canFocus:m.view==="pcb"&&typeof h?.focusLayer=="function",canRestore:!!(h&&(h.layerSnapshot||S?.snapshot))}}function td(m){m.renderer?.draw?.(),m.updateControls();let h=eh(m);return m.emit("layerschange",h),h}function th(m){if(m.assertActive(),!["pcb","3d","manufacturing"].includes(m.view)||!m.renderer)throw new Error("Layer control requires a loaded PCB, 3D or manufacturing view.")}function LE(m){let h=Dl(m);h.snapshot||(h.snapshot=eh(m).visible)}function rv(m,h){th(m);let p=eh(m).layers;if(!Array.isArray(h)||h.some(w=>!p.includes(w)))throw new TypeError("Choose saved PCB layer names.");return Dl(m).preset=null,m.renderer.layerPresetName=null,m.view==="3d"?m.renderer.setVisibleCopperLayers([...new Set(h)]):(m.renderer.visibleLayers=new Set(h),m.renderer.focusedLayer&&!m.renderer.visibleLayers.has(m.renderer.focusedLayer)&&(m.renderer.focusedLayer=null)),td(m)}function kE(m,h){if(th(m),!["all","none","front","back","copper","overview","outline"].includes(h))throw new TypeError("Choose all, overview, outline, none, front, back or copper layers.");if(["overview","outline"].includes(h)&&m.view!=="pcb")throw new Error("This layer preset requires the 2D PCB view.");if(LE(m),m.view==="pcb"&&m.renderer.layerPreset)m.renderer.layerPreset(h);else{let p=eh(m).layers,w=p.filter(S=>h==="all"||h!=="none"&&(S==="Edge.Cuts"||h==="copper"&&/^(?:F|B|In\d+)\.Cu$/.test(S)||h==="front"&&S.startsWith("F.")||h==="back"&&S.startsWith("B.")||h==="overview"&&["F.Cu","B.Cu","F.SilkS","B.SilkS"].includes(S)));m.view==="3d"?m.renderer.setVisibleCopperLayers(w):(m.renderer.visibleLayers=new Set(w),m.renderer.focusedLayer=null),Dl(m).preset=h}return td(m)}function OE(m,h,{mode:p="dim",fit:w=!1}={}){if(th(m),m.view!=="pcb"||!m.renderer.focusLayer)throw new Error("Layer focus requires the 2D PCB view.");if(!m.getLayers().includes(h)||!["dim","isolate"].includes(p)||typeof w!="boolean")throw new TypeError("Choose a saved layer and dim or isolate focus mode.");return LE(m),Dl(m).preset=null,m.renderer.layerPresetName=null,m.renderer.focusLayer(h,p),w&&m.renderer.fitLayer?.(),td(m)}function DE(m){return th(m),m.renderer.focusedLayer=null,m.renderer.layerPresetName=null,Dl(m).preset=null,td(m)}function UE(m){th(m);let h=m.renderer,p=Dl(m),w=p.snapshot;if(p.snapshot=null,p.preset=null,h.layerPresetName=null,h.layerSnapshot)h.restoreLayers();else if(w)return rv(m,w);return td(m)}function FE(m){if(th(m),m.view!=="pcb"||!m.renderer.focusedLayer)return!1;let h=!!m.renderer.fitLayer?.();return m.renderer.draw?.(),m.reportCamera?.(),h}var IE,iv=Ui(()=>{IE=new WeakMap});function sv(m){if(typeof m!="string"||!/^#[0-9a-f]{6}$/i.test(m))throw new TypeError("Use a six-digit hex demo color.");return m.toLowerCase()}function $a(m,h){if(m!==void 0&&typeof m!="function")throw new TypeError(h+" must be a function.");return m}function RD(m){if(!m||typeof m!="object")throw new TypeError("Choose a source-bound anchor or a selected 3D face.");let h={...m};if(m.anchor){let p=m.anchor;if(typeof p!="object")throw new TypeError("Choose a saved component anchor.");let w={};for(let S of["uuid","reference","pinNumber"])if(p[S]!==void 0){if(typeof p[S]!="string"||!p[S]||p[S].length>500||/[\x00-\x1f\x7f]/.test(p[S]))throw new TypeError("Choose a bounded saved anchor identity.");w[S]=p[S]}if(p.face!==void 0){if(!["top","bottom","front","back","left","right"].includes(p.face))throw new TypeError("Choose a named component face.");w.face=p.face}if(!w.uuid&&!w.reference)throw new TypeError("An anchor needs a saved UUID or reference.");h.anchor=w}if(!h.anchor&&!h.face)throw new TypeError("Choose a source-bound anchor or a selected 3D face.");return h}function jE(m){return(m.composedPath?.()||[m.target]).some(h=>{let p=String(h?.tagName||"").toLowerCase(),w=h?.getAttribute?.("role");return["input","textarea","select","button","a"].includes(p)||h?.isContentEditable||h?.getAttribute?.("contenteditable")==="true"||["textbox","searchbox","combobox","button","link","slider","spinbutton"].includes(w)})}function PD(m,h){for(let p=m;p;p=p.parentNode||p.getRootNode?.().host)if(p===h)return!0;return!1}function VE(m,h){let p=rh.get(m),w=p?.active&&p.bindings.get(h.code);return!!(w&&!h.isComposing&&!jE(h)&&["ctrlKey","metaKey","altKey","shiftKey"].every(S=>!!h[S]==!!w[S]))}var rh,TD,CD,nv,zE,Za,BE,av,ov=Ui(()=>{rh=new WeakMap,TD=64,CD=4*1024*1024,nv=(m,h)=>Object.prototype.hasOwnProperty.call(m,h),zE=m=>{if(typeof m!="string"||!m||m.length>128||/[\x00-\x1f\x7f]/.test(m))throw new TypeError("Choose a demo control ID of 1 to 128 characters.");return m},Za=(m,h,p,w)=>{if(typeof m!="number"||!Number.isFinite(m)||m<h||m>p)throw new TypeError("Choose a finite "+w+" from "+h+" to "+p+".");return m};BE=m=>{let h=sv(m);return[parseInt(h.slice(1,3),16),parseInt(h.slice(3,5),16),parseInt(h.slice(5,7),16),255]},av=class extends EventTarget{constructor(h){if(super(),!h||typeof h.addEventListener!="function"||!h.root?.addEventListener)throw new TypeError("Choose an existing KiCadViewer.");h.assertActive?.();let p=rh.get(h);if(p&&(p._check(),rh.get(h)))throw new Error("This viewer already has an active demo controller.");if(h.disposed||h.view!=="3d"||typeof h.source!="string"||!h.source||typeof h.renderer?.createDemoSurface!="function"||typeof h.renderer?.setDemoInputHandler!="function")throw new Error("Load a supported 3D board before creating demo controls.");this.viewer=h,this.renderer=h.renderer,this.source=h.source,this.path=h.path,this.root=h.root,this.doc=h.host?.ownerDocument||h.root.ownerDocument,this.records=new Map,this.bindings=new Map,this.held=new Map,this.listeners=[],this.pixels=0,this.disposed=!1,this.suspended=!1,this.originalTabIndex=this.root.getAttribute?.("tabindex"),this.ownsTabIndex=this.originalTabIndex===null||this.originalTabIndex===void 0,this.ownsTabIndex&&this.root.setAttribute?.("tabindex","0");let w=(S,A,T,H)=>{S?.addEventListener?.(A,T,H),this.listeners.push(()=>S?.removeEventListener?.(A,T,H))};w(h,"ready",()=>this._check()),w(h,"viewchange",()=>this._check()),w(h,"dispose",()=>this.dispose()),w(this.root,"keydown",S=>this._keyDown(S)),w(this.root,"keyup",S=>this._keyUp(S)),w(this.root,"focusout",S=>{PD(S.relatedTarget,this.root)||this._cancelHeld("focus")}),w(this.root,"pointerdown",S=>{this.active&&String(S.composedPath?.()[0]?.tagName||S.target?.tagName||"").toLowerCase()==="canvas"&&this.root.focus?.({preventScroll:!0})},{capture:!0}),w(this.doc,"visibilitychange",()=>{this.doc.hidden&&this._cancelHeld("hidden")}),w(this.doc?.defaultView,"blur",()=>this._cancelHeld("window"));try{this.renderer.setDemoInputHandler(S=>this._input(S)),rh.set(h,this)}catch(S){throw this._teardown(),S}}get active(){return!this.disposed&&!this.suspended&&!this.viewer.disposed&&this.viewer.view==="3d"&&this.viewer.source===this.source&&this.viewer.path===this.path&&this.viewer.renderer===this.renderer}_check(){return!this.disposed&&!this.suspended&&!this.active&&this.suspend("The bound 3D scene changed. Recreate demo controls explicitly."),this.active}assertActive(){if(!this._check())throw new Error(this.disposed?"Demo controller has been disposed.":"Demo controller is suspended; recreate it for the current 3D scene.")}_emit(h,p){this.dispatchEvent(new CustomEvent(h,{detail:p}))}_error(h,p,w){this._emit("error",{id:h,phase:p,error:w})}_invoke(h,p){if(h)try{let w=h(p);w&&typeof w.then=="function"&&Promise.resolve(w).catch(S=>{this._check()&&this._error(p.id,"callback",S)})}catch(w){this._error(p.id,"callback",w)}}_record(h,p){this.assertActive();let w=this.records.get(zE(h));if(!w||p&&w.kind!==p)throw new Error("Choose an existing "+(p||"demo")+" control.");return w}_add(h,p,w,S){if(this.assertActive(),zE(h),this.records.has(h))throw new Error("Demo control IDs must be unique.");if(this.records.size>=TD)throw new RangeError("A demo supports at most 64 controls.");let A=RD(w),T=this.renderer.createDemoSurface(h,{...A,...S,kind:p});if(!T||typeof T.dispose!="function")throw new Error("The 3D renderer could not create this demo surface.");let H={id:h,kind:p,options:A,state:{...S},surface:T,pressed:!1,pressSources:new Set};if(!this.active)throw T.dispose(),new Error("The bound 3D scene changed while creating a control.");return this.records.set(h,H),H}addLED(h,p={}){let w={on:p.on??!1,brightness:p.brightness??1,color:sv(p.color??"#65ff84")};if(typeof w.on!="boolean")throw new TypeError("LED on must be boolean.");return Za(w.brightness,0,1,"LED brightness"),this._add(h,"led",p,w),h}setLED(h,p){let w=this._record(h,"led");if(typeof p=="boolean"&&(p={on:p}),!p||typeof p!="object"||Array.isArray(p)||Object.keys(p).some(A=>!["on","brightness","color"].includes(A)))throw new TypeError("Choose LED on, brightness and/or color.");let S={...w.state};if(nv(p,"on")){if(typeof p.on!="boolean")throw new TypeError("LED on must be boolean.");S.on=p.on}return nv(p,"brightness")&&(S.brightness=Za(p.brightness,0,1,"LED brightness")),nv(p,"color")&&(S.color=sv(p.color)),w.surface.setLED?.({...S}),w.state=S,this.getState(h)}addDisplay(h,p={}){let w=p.mode??"oled";if(!["matrix","oled","lcd","tft"].includes(w))throw new TypeError("Choose matrix, oled, lcd or tft display mode.");let S=w==="lcd"||w==="tft",A=p.width??(w==="matrix"?16:S?320:128),T=p.height??(w==="matrix"?8:S?240:64);if(!Number.isInteger(A)||!Number.isInteger(T)||A<1||T<1||A>1024||T>1024)throw new RangeError("Display dimensions must be integers from 1 to 1024.");if(this.pixels+A*T>CD)throw new RangeError("Demo display canvases are limited to four million pixels.");$a(p.onPress,"onPress"),$a(p.onRelease,"onRelease");let H=this._add(h,"display",p,{mode:w,width:A,height:T});try{let Y=H.surface.canvas;if(!Y||Y.width!==A||Y.height!==T||!Y.getContext?.("2d"))throw new Error("A display needs a matching 2D canvas surface.");this.pixels+=A*T}catch(Y){throw this.records.delete(h),H.surface.dispose(),Y}return h}drawDisplay(h,p){let w=this._record(h,"display");if(typeof p!="function")throw new TypeError("Provide a synchronous canvas drawing function.");let S=w.surface.canvas;try{let A=p(S.getContext("2d"),S);if(A&&typeof A.then=="function")throw Promise.resolve(A).catch(()=>{}),new TypeError("Display drawing callbacks must be synchronous.")}catch(A){return this._error(h,"draw",A),!1}if(!this.active||this.records.get(h)!==w)return!1;try{return w.surface.update?.(),!0}catch(A){return this._error(h,"upload",A),!1}}writeImage(h,p){return this.drawDisplay(h,(w,S)=>{w.clearRect(0,0,S.width,S.height),w.drawImage(p,0,0,S.width,S.height)})}setPixels(h,p,{format:w,foreground:S,background:A}={}){let T=this._record(h,"display"),{width:H,height:Y,mode:ee}=T.state;if(!(p instanceof Uint8Array)&&!(p instanceof Uint8ClampedArray))throw new TypeError("Display pixels must be Uint8Array or Uint8ClampedArray.");if(w??=p.length===H*Y*4?"rgba":"mono",!["rgba","mono","mono1"].includes(w))throw new TypeError("Choose rgba, mono or mono1 pixels.");let X=Math.ceil(H/8),G=w==="rgba"?H*Y*4:w==="mono1"?X*Y:H*Y;if(p.length!==G)throw new RangeError("Pixel byte length does not match this display and format.");let ae=T.surface.canvas.getContext("2d"),_e=ae.createImageData(H,Y);if(w==="rgba")_e.data.set(p);else{let J=BE(S??(ee==="matrix"?"#65ff84":"#e6ffff")),Q=BE(A??"#000000");for(let te=0;te<Y;te++)for(let he=0;he<H;he++){let be=w==="mono1"?p[te*X+(he>>3)]&128>>(he&7):p[te*H+he];_e.data.set(be?J:Q,(te*H+he)*4)}}if(ae.putImageData(_e,0,0),!this.active||this.records.get(h)!==T)return!1;try{return T.surface.update?.(),!0}catch(J){return this._error(h,"upload",J),!1}}addButton(h,p={}){return $a(p.onPress,"onPress"),$a(p.onRelease,"onRelease"),this._add(h,"button",p,{pressed:!1}),h}addKnob(h,p={}){let w=Za(p.min??0,-1e6,1e6,"knob minimum"),S=Za(p.max??100,-1e6,1e6,"knob maximum"),A=Za(p.step??1,1e-6,2e6,"knob step");if(S<=w||A>S-w)throw new RangeError("A knob needs maximum above minimum and a step within its range.");$a(p.onChange,"onChange");let T=this._knobValue({min:w,max:S,step:A},p.value??w);return this._add(h,"knob",p,{min:w,max:S,step:A,value:T}),h}_knobValue(h,p){Za(p,-1e9,1e9,"knob value");let w=Math.max(h.min,Math.min(h.max,p));return Math.max(h.min,Math.min(h.max,h.min+Math.round((w-h.min)/h.step)*h.step))}setKnob(h,p,{source:w="script"}={}){let S=this._record(h,"knob"),A=this._knobValue(S.state,p);if(A===S.state.value)return!1;S.surface.setValue?.(A),S.state.value=A;let T={id:h,type:"change",value:A,source:w};return this._invoke(S.options.onChange,T),this._emit("input",T),!0}change(h,p,{source:w="script"}={}){let S=this._record(h,"knob");return Za(p,-1e6,1e6,"knob delta"),this.setKnob(h,S.state.value+p*S.state.step,{source:w})}press(h,p={}){let w=this._record(h);if(!["button","display"].includes(w.kind))throw new Error("Press a button or display control.");let S=this._pressToken(p);if(w.pressSources.add(S),w.pressed)return!1;w.surface.setValue?.(1),w.pressed=!0,w.state.pressed=!0;let A={...p,id:h,type:"press",source:p.source||"script"};return this._invoke(w.options.onPress,A),this._emit("input",A),!0}_pressToken(h){return h.source==="keyboard"?"key:"+h.code:h.source==="pointer"?"pointer:"+(h.originalEvent?.pointerId??"primary"):"script"}_releaseRecord(h,p={},w=!1){if(w)h.pressSources.clear();else if(p.cancelled&&p.source==="pointer"&&p.originalEvent?.pointerId===void 0)for(let A of h.pressSources)A.startsWith("pointer:")&&h.pressSources.delete(A);else h.pressSources.delete(this._pressToken(p));if(h.pressSources.size||!h.pressed)return!1;h.pressed=!1,h.state.pressed=!1,this.active&&h.surface.setValue?.(0);let S={...p,id:h.id,type:"release",source:p.source||"script"};return this._invoke(h.options.onRelease,S),this._emit("input",S),!0}release(h,p={}){let w=this._record(h);return this._releaseRecord(w,p)}toggle(h,{source:p="script"}={}){let w=this._record(h);if(w.kind==="led"){let S=this.setLED(h,{on:!w.state.on});return this._emit("input",{id:h,type:"change",value:S.on,source:p}),S.on}if(w.kind==="button"||w.kind==="display")return w.pressed?this.release(h,{source:p}):this.press(h,{source:p});throw new Error("Toggle an LED or button control.")}_input(h){if(!this._check()||!h||typeof h.id!="string")return;let p=this.records.get(h.id);if(!p)return;let w={source:"pointer",...h.uv?{uv:{...h.uv}}:{},...h.originalEvent?{originalEvent:h.originalEvent}:{}};try{if(p.kind==="knob"&&["press","release"].includes(h.type)){this._emit("input",{...w,id:h.id,type:h.type,value:p.state.value,cancelled:!!h.cancelled});return}h.type==="press"?this.press(h.id,w):h.type==="release"?this.release(h.id,{...w,cancelled:!!h.cancelled}):h.type==="change"&&p.kind==="knob"&&(h.value!==void 0?this.setKnob(h.id,h.value,w):h.delta!==void 0&&this.change(h.id,h.delta,w))}catch(S){this._error(h.id,"input",S)}}focus(){return this.assertActive(),typeof this.root.focus!="function"?!1:(this.root.focus({preventScroll:!0}),!0)}getFace(h){let p=this._record(h),w=p.surface.getFace?.()||p.surface.face;if(!w)throw new Error("The demo surface does not expose its actual face frame.");let S=T=>{let H=Array.isArray(T)?[...T]:[T?.x,T?.y,T?.z];if(H.length!==3||!H.every(Y=>typeof Y=="number"&&Number.isFinite(Y)))throw new Error("Invalid demo surface face frame.");return H},A={center:S(w.center),normal:w.normal===null?null:S(w.normal),width:Za(w.width,Number.MIN_VALUE,1e7,"face width"),height:Za(w.height,Number.MIN_VALUE,1e7,"face height")};if(w.shape!==void 0){if(!["component","face"].includes(w.shape))throw new Error("Invalid demo surface shape.");A.shape=w.shape}for(let T of["up","right"])w[T]&&(A[T]=S(w[T]));return A}getState(h){let p=this._record(h);return{id:p.id,kind:p.kind,...p.state}}bindKey(h,p={}){if(this.assertActive(),typeof h!="string"||!/^[A-Za-z][A-Za-z0-9]{0,63}$/.test(h))throw new TypeError("Use a KeyboardEvent.code such as KeyL, Space or ArrowUp.");if(!p||typeof p!="object")throw new TypeError("Choose a key action or callbacks.");for(let w of["repeat","preventDefault","ctrlKey","metaKey","altKey","shiftKey"])if(p[w]!==void 0&&typeof p[w]!="boolean")throw new TypeError("Key flags must be boolean.");if(p.id!==void 0){let w=this._record(p.id);if(!["press","toggle","increment","decrement"].includes(p.action))throw new TypeError("Choose press, toggle, increment or decrement.");if(p.action==="press"&&!["button","display"].includes(w.kind)||["increment","decrement"].includes(p.action)&&w.kind!=="knob"||p.action==="toggle"&&!["led","button","display"].includes(w.kind))throw new TypeError("Key action does not match this demo control.")}else if(!$a(p.onDown,"onDown")&&!$a(p.onUp,"onUp"))throw new TypeError("Provide a control ID/action or onDown/onUp callbacks.");if($a(p.onDown,"onDown"),$a(p.onUp,"onUp"),!this.bindings.has(h)&&this.bindings.size>=128)throw new RangeError("A demo supports at most 128 key bindings.");return this.unbindKey(h),this.bindings.set(h,{...p}),()=>this.unbindKey(h)}unbindKey(h){return this.held.has(h)&&this._keyRelease(h,{cancelled:!0,source:"keyboard"}),this.bindings.delete(h)}_keyDown(h){if(h.defaultPrevented||!this._check()||h.isComposing||jE(h))return;let p=this.bindings.get(h.code);if(!p||["ctrlKey","metaKey","altKey","shiftKey"].some(A=>!!h[A]!=!!p[A])||this.held.has(h.code)&&!p.repeat||h.repeat&&!p.repeat)return;p.preventDefault!==!1&&h.preventDefault?.();let w=!this.held.has(h.code);this.held.set(h.code,p);let S={source:"keyboard",code:h.code,originalEvent:h};try{p.id!==void 0&&(p.action==="press"?this.press(p.id,S):p.action==="toggle"?w&&this.toggle(p.id,S):this.change(p.id,p.action==="increment"?1:-1,S)),this._invoke(p.onDown,{...S,id:p.id})}catch(A){this._error(p.id,"keyboard",A)}}_keyRelease(h,p){let w=this.held.get(h);if(!w)return!1;this.held.delete(h);try{if(w.id!==void 0&&w.action==="press"){let S=this.records.get(w.id);S&&this._releaseRecord(S,{...p,code:h})}this._invoke(w.onUp,{...p,id:w.id,code:h})}catch(S){this._error(w.id,"keyboard",S)}return!0}_keyUp(h){if(!this.held.has(h.code))return;this.held.get(h.code).preventDefault!==!1&&h.preventDefault?.(),this._keyRelease(h.code,{source:"keyboard",code:h.code,originalEvent:h})}_cancelHeld(h){for(let p of[...this.held.keys()])this._keyRelease(p,{source:"keyboard",cancelled:!0,reason:h});for(let p of this.records.values())if(p.pressed)try{this._releaseRecord(p,{source:"pointer",cancelled:!0,reason:h},!0)}catch(w){this._error(p.id,"release",w)}}remove(h){let p=this._record(h);for(let[w,S]of this.bindings)S.id===h&&this.unbindKey(w);return this._releaseRecord(p,{cancelled:!0,reason:"removed"},!0),this.records.get(h)!==p||(this.records.delete(h),p.kind==="display"&&(this.pixels-=p.state.width*p.state.height),p.surface.dispose()),!0}_teardown(){this._cancelHeld("scene");for(let p of this.listeners)p();this.listeners=[],this.bindings.clear(),this.held.clear();let h=this.renderer;this.renderer=null;try{h?.setDemoInputHandler?.(null)}catch(p){this._error(void 0,"dispose",p)}for(let p of this.records.values())try{p.surface.dispose()}catch(w){this._error(p.id,"dispose",w)}this.records.clear(),this.pixels=0,this.ownsTabIndex&&(this.root.getAttribute?.("tabindex")==="0"&&this.root.removeAttribute?.("tabindex"),this.ownsTabIndex=!1),rh.get(this.viewer)===this&&rh.delete(this.viewer)}suspend(h="The bound 3D scene changed."){this.disposed||this.suspended||(this.suspended=!0,this._teardown(),this._emit("suspend",{reason:h}))}dispose(){this.disposed||(this.disposed=!0,this._teardown())}}});function GE(m,h,p=15){if(!ID.includes(h)||typeof p!="number"||!Number.isFinite(p)||p<=0||p>90)throw new TypeError("Choose a rotation direction and angle from 0 to 90 degrees.");for(let X of["position","target","up"])if(!Array.isArray(m?.[X])||m[X].length!==3||!m[X].every(Number.isFinite))throw new TypeError("Choose a finite 3D camera.");let w=m.position.map((X,G)=>X-m.target[G]),S=nm(m.up),A=nm(w),T=S.reduce((X,G,ae)=>X+G*A[ae],0);S=nm(S.map((X,G)=>X-T*A[G]));let H=nm(HE(S,A)),Y,ee=p*Math.PI/180;return h==="left"||h==="right"?(Y=S,h==="right"&&(ee=-ee),w=sm(w,Y,ee)):h==="up"||h==="down"?(Y=H,h==="up"&&(ee=-ee),w=sm(w,Y,ee),S=sm(S,Y,ee)):(h==="counterclockwise"&&(ee=-ee),S=sm(S,A,ee)),{position:w.map((X,G)=>X+m.target[G]),target:[...m.target],up:S}}function LD(m){if(m.defaultPrevented||m.isComposing||m.ctrlKey||m.metaKey||m.altKey||ND(m))return null;let h={Digit0:"isometric",Numpad0:"isometric",Digit1:"top",Numpad1:"top",Digit2:"bottom",Numpad2:"bottom",Digit3:"front",Numpad3:"front",Digit4:"back",Numpad4:"back",Digit5:"left",Numpad5:"left",Digit6:"right",Numpad6:"right"};if(m.shiftKey){let p={ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up",ArrowDown:"down",KeyQ:"counterclockwise",KeyE:"clockwise"};return p[m.code]?{type:"rotate",value:p[m.code]}:m.code==="Equal"?{type:"zoom",value:1.2}:null}return h[m.code]?{type:"view",value:h[m.code]}:m.code==="KeyF"?{type:"fit"}:["Equal","NumpadAdd"].includes(m.code)?{type:"zoom",value:1.2}:["Minus","NumpadSubtract"].includes(m.code)?{type:"zoom",value:1/1.2}:null}function XE(m,h){let p=m.host.ownerDocument,w=p.createElement("div");w.className="viewer-navigation",w.hidden=!0,w.setAttribute("role","group"),w.setAttribute("aria-label","3D view and rotation");let S=[["Top","Top view (1)",{type:"view",value:"top"}],["Bottom","Bottom view (2)",{type:"view",value:"bottom"}],["Iso","Isometric view (0)",{type:"view",value:"isometric"}],["\u2190","Rotate view left (Shift + Left)",{type:"rotate",value:"left"}],["\u2191","Tilt view up (Shift + Up)",{type:"rotate",value:"up"}],["\u2193","Tilt view down (Shift + Down)",{type:"rotate",value:"down"}],["\u2192","Rotate view right (Shift + Right)",{type:"rotate",value:"right"}],["\u21B6","Roll counterclockwise (Shift + Q)",{type:"rotate",value:"counterclockwise"}],["\u21B7","Roll clockwise (Shift + E)",{type:"rotate",value:"clockwise"}],["\u2212","Zoom out (\u2212)",{type:"zoom",value:1/1.2}],["+","Zoom in (+)",{type:"zoom",value:1.2}]],A=Q=>{if(m.disposed||m.view!=="3d"||!m.renderer)return!1;if(Q.type==="view")return m.setCamera3D(Q.value);if(Q.type==="rotate")return m.rotate3D(Q.value);if(Q.type==="fit")return m.fit();if(Q.type==="zoom")return m.renderer.zoom?.(Q.value)},T=p.defaultView?.ResizeObserver||globalThis.ResizeObserver,H=null,Y=()=>{let Q=m.stage.getBoundingClientRect?.(),te=m.renderer?.host?.shadowRoot?.querySelector?.(".bar")?.getBoundingClientRect?.();Q&&te&&(w.style.maxHeight=Math.max(32,Q.height-Math.max(0,te.bottom-Q.top)-16)+"px")},ee=T?new T(Y):null,X=[],G;for(let[Q,[te,he,be]]of S.entries()){(Q===0||Q===3||Q===7)&&(G=p.createElement("div"),G.className="viewer-navigation-row",w.append(G));let De=p.createElement("button");De.type="button",De.textContent=te,De.title=he,De.setAttribute("aria-label",he),De.onclick=()=>{try{A(be)}catch(Ke){h(Ke)}},X.push(De),G.append(De)}let ae=Q=>{if(m.view!=="3d"||!m.renderer||VE(m,Q))return;let te=LD(Q);if(te)try{A(te),Q.preventDefault(),Q.stopPropagation()}catch(he){h(he)}},_e=Q=>{m.view==="3d"&&(Q.composedPath?.()||[]).some(te=>te?.tagName==="CANVAS")&&m.root.focus?.({preventScroll:!0})},J=m.root.getAttribute?.("tabindex")??null;return J===null&&m.root.setAttribute("tabindex","0"),m.root.addEventListener?.("keydown",ae),m.root.addEventListener?.("pointerdown",_e),{panel:w,update(){if(w.hidden=m.view!=="3d"||!m.renderer,w.parentNode!==m.stage&&m.stage.append(w),H!==m.renderer){ee?.disconnect(),H=m.renderer,ee?.observe(m.stage);let Q=m.renderer?.host?.shadowRoot?.querySelector?.(".bar");Q&&ee?.observe(Q)}Y()},dispose(){ee?.disconnect(),m.root.removeEventListener?.("keydown",ae),m.root.removeEventListener?.("pointerdown",_e);for(let Q of X)Q.onclick=null;J===null&&m.root.getAttribute?.("tabindex")==="0"&&m.root.removeAttribute?.("tabindex"),w.remove()}}}var ID,HE,nm,sm,ND,WE,lv=Ui(()=>{ov();ID=["left","right","up","down","clockwise","counterclockwise"],HE=(m,h)=>[m[1]*h[2]-m[2]*h[1],m[2]*h[0]-m[0]*h[2],m[0]*h[1]-m[1]*h[0]],nm=m=>{let h=Math.hypot(...m);if(h<1e-8)throw new TypeError("Choose a nondegenerate camera.");return m.map(p=>p/h)},sm=(m,h,p)=>{let w=Math.cos(p),S=Math.sin(p),A=m.reduce((H,Y,ee)=>H+Y*h[ee],0),T=HE(h,m);return m.map((H,Y)=>H*w+T[Y]*S+h[Y]*A*(1-w))};ND=m=>(m.composedPath?.()||[m.target]).some(h=>h?.isContentEditable||/^(INPUT|TEXTAREA|SELECT|BUTTON|A|SUMMARY)$/.test(h?.tagName||"")||["slider","combobox","textbox","spinbutton","button","menuitem"].includes(h?.getAttribute?.("role")));WE=`
.viewer-navigation{position:absolute;right:8px;bottom:8px;z-index:3;display:grid;gap:3px;width:156px;max-width:calc(100% - 16px);max-height:calc(100% - 64px);overflow:auto;overscroll-behavior:contain;padding:5px;border:1px solid var(--viewer-border);border-radius:9px;background:var(--viewer-bar);color:var(--viewer-ink);box-shadow:var(--viewer-shadow)}
.viewer-navigation-row{display:flex;gap:2px;min-width:0}.viewer-navigation button{display:inline-flex;align-items:center;justify-content:center;flex:1;min-width:0;min-height:29px;border:0;border-radius:5px;padding:4px 2px;background:transparent;color:var(--viewer-ink);font:600 11px/1.2 system-ui;cursor:pointer}.viewer-navigation button:hover{background:var(--viewer-hover);color:var(--viewer-accent)}.viewer-navigation button:focus-visible{outline:2px solid var(--viewer-accent);outline-offset:-2px}.viewer-navigation-row:not(:first-child) button{font-size:17px}.viewer-navigation[hidden]{display:none!important}@media(pointer:coarse){.viewer-navigation button{min-height:36px}}
@container (max-width:540px){.viewer-navigation{width:196px}.viewer-navigation button{min-height:40px;min-width:40px}}
@media(pointer:coarse){.viewer-navigation{width:208px}.viewer-navigation button{min-width:44px;min-height:44px}}
`});var To=$n((YE,ih)=>{(m=>{"use strict";let p=()=>268435456,Y=new Set(["symbol","sheet","wire","bus","bus_entry","label","global_label","hierarchical_label","junction","no_connect","text","text_box","polyline","rectangle","circle","arc","image","rule_area","netclass_flag","directive_label"]),ee=new Set(["footprint","segment","arc","via","zone","gr_line","gr_rect","gr_circle","gr_arc","gr_poly","gr_curve","gr_text","gr_text_box","gr_bitmap","dimension","target"]),X=new Set(["uuid","tstamp","filled_polygon","fill_segments"]),G=/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?$/;function ae(ne){if(typeof ne!="string")throw new TypeError("KiCad source must be a string.");if(!/[^\x00-\x7f]/.test(ne))return ne.length;let we=ne.length;for(let xe=0;xe<ne.length;xe++){let ke=ne.charCodeAt(xe);if(!(ke<128)){if(ke<2048){we++;continue}if(ke>=55296&&ke<=56319&&xe+1<ne.length){let Me=ne.charCodeAt(xe+1);if(Me>=56320&&Me<=57343){we+=2,xe++;continue}}we+=2}}return we}let _e=ne=>ne===32||ne>=9&&ne<=13||ne>127&&/\s/.test(String.fromCharCode(ne));function J(ne){if(!Array.isArray(ne)||ne.length!==4||ne.some(tt=>!tt||!Number.isFinite(tt.x)||!Number.isFinite(tt.y)))throw Error("Bezier requires four finite control points.");let we=[{...ne[0]}],xe=[ne],ke=.005**2,Me=(tt,Ze,Ye)=>{let vt=Ye.x-Ze.x,Rt=Ye.y-Ze.y,Je=vt*vt+Rt*Rt,_t=Je?Math.max(0,Math.min(1,((tt.x-Ze.x)*vt+(tt.y-Ze.y)*Rt)/Je)):0;return(tt.x-Ze.x-_t*vt)**2+(tt.y-Ze.y-_t*Rt)**2},Ce=(tt,Ze)=>({x:tt.x/2+Ze.x/2,y:tt.y/2+Ze.y/2});for(;xe.length;){let[tt,Ze,Ye,vt]=xe.pop();if(Math.max(Me(Ze,tt,vt),Me(Ye,tt,vt))<=ke){if(we.length>=2049)throw Error("Bezier exceeds the bounded tessellation budget.");we.push({...vt})}else{let Rt=Ce(tt,Ze),Je=Ce(Ze,Ye),_t=Ce(Ye,vt),Et=Ce(Rt,Je),gt=Ce(Je,_t),Ht=Ce(Et,gt);if(xe.length>32||[Rt,Je,_t,Et,gt,Ht].some(lt=>!Number.isFinite(lt.x)||!Number.isFinite(lt.y)))throw Error("Bezier exceeds the bounded tessellation budget.");xe.push([Ht,gt,_t,vt],[tt,Rt,Et,Ht])}}return we}let Q=new Set(["version","generator","generator_version","uuid","paper","title_block","property","sheet","symbol","footprint","module","sheet_instances","legacy_source","legacy_diagnostic"]),te=new Set([...Q,"embedded_files"]),he=new Set(["property","uuid","path","instances"]);function be(ne,we={}){if(typeof ne!="string")throw new TypeError("KiCad source must be a string.");if(/^\s*PCBNEW-BOARD/.test(ne))throw Error("Legacy .brd boards are detected but this drawing format is not yet rendered. Open and save a separate .kicad_pcb copy in KiCad.");if(/^\s*EESchema Schematic File Version [24]\b/.test(ne)){let Je=m.KiCadLegacy||(typeof ih=="object"&&ih.exports?tv():null);if(!Je)throw Error("Legacy schematic adapter is unavailable; reload the extension.");return Je.parse(ne,we)}if(ne.length>268435456||ne.length>268435456/3&&ae(ne)>268435456)throw new Error("KiCad file exceeds browser parser size limits.");let xe=[],ke=[],Me=/\(xy[ \t]+([-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?)[ \t]+([-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?)[ \t]*\)/y,Ce=0,tt=0,Ze=0,Ye=()=>xe.length===3&&xe[0][0]==="kicad_pcb"&&xe[1][0]==="zone"&&xe[2][0]==="filled_polygon";function vt(Je){let _t=Je+4,Et=0,gt=new Float64Array(128);for(;_t<ne.length;){for(;_e(ne.charCodeAt(_t));)_t++;if(ne.charCodeAt(_t)===41)return Et<6?null:(tt+=1+Et*2,Rt(["pts",Et===gt.length?gt:gt.slice(0,Et)]),_t+1);Me.lastIndex=_t;let Ht=Me.exec(ne);if(!Ht)return null;let lt=Number(Ht[1]),et=Number(Ht[2]);if(!Number.isFinite(lt)||!Number.isFinite(et))throw new Error("Invalid numeric KiCad value.");if(tt+6+Et*2>12e6)throw new Error("KiCad file has too many S-expression nodes.");if(Et===gt.length){let St=new Float64Array(gt.length*2);St.set(gt),gt=St}gt[Et++]=lt,gt[Et++]=et,_t=Me.lastIndex}return null}let Rt=Je=>{if(++tt>12e6)throw new Error("KiCad file has too many S-expression nodes.");Ze||(xe.at(-1)||ke).push(Je)};for(;Ce<ne.length;){let Je=ne[Ce];if(_e(ne.charCodeAt(Ce))){Ce++;continue}if((Je==="<"||Je===">")&&/^(?:<{7,}|>{7,})(?:\s|$)/.test(ne.slice(Ce,Ce+120)))throw new Error("Unresolved Git merge conflict at line "+ne.slice(0,Ce).split(`
`).length+". Resolve the conflict in a separate copy before viewing.");if(Je===";"){for(;Ce<ne.length&&ne[Ce]!==`
`;)Ce++;continue}if(Je==="("){if(xe.length>=96)throw new Error("KiCad S-expression is too deep.");if(we.compactCopper&&!we.metadataOnly&&ne.startsWith("(pts",Ce)&&_e(ne.charCodeAt(Ce+4))&&Ye()){let Ht=vt(Ce);if(Ht!==null){Ce=Ht;continue}}if(!we.metadataOnly&&xe.length&&ne.startsWith("(xy",Ce)){Me.lastIndex=Ce;let Ht=Me.exec(ne);if(Ht){let lt=Number(Ht[1]),et=Number(Ht[2]);if(!Number.isFinite(lt)||!Number.isFinite(et))throw new Error("Invalid numeric KiCad value.");tt+=3,Rt(["xy",lt,et]),Ce=Me.lastIndex;continue}}if(we.metadataOnly&&!Ze){let Ht=null;if(xe.length===1?Ht=we.includeEmbeddedFonts?te:Q:xe.length===2&&["symbol","footprint","module"].includes(xe.at(-1)?.[0])?Ht=he:xe.at(-1)?.[0]==="property"&&(Ht=new Set),Ht){let lt=Ce+1;for(;lt<ne.length&&_e(ne.charCodeAt(lt));)lt++;let et=lt;for(;et<ne.length&&!_e(ne.charCodeAt(et))&&!["(",")",";"].includes(ne[et]);)et++;Ht.has(ne.slice(lt,et))||(Ze=xe.length+1)}}let gt=[];Rt(gt),xe.push(gt),Ce++;continue}if(Je===")"){if(!xe.length)throw new Error("Unexpected closing parenthesis in KiCad file.");let gt=xe.pop();if(!Ze&&gt.length>0&&gt.length<=4){let Ht=gt.slice(),lt=xe.at(-1)||ke;lt[lt.length-1]=Ht}Ze&&xe.length<Ze&&(Ze=0),Ce++;continue}if(!xe.length)throw new Error("Expected a KiCad S-expression.");if(Je==='"'){let gt=null,Ht=++Ce,lt=!1,et="";for(;Ce<ne.length;){let St=ne[Ce++];if(St==='"'){if(lt=!0,!Ze){let At=ne.slice(Ht,Ce-1);gt?(gt.push(At),et=gt.join("")):et=At}break}if(St==="\\"){if(Ce>=ne.length)throw new Error("Unterminated KiCad escape sequence.");let At=ne[Ce++];if(!Ze){gt??=[],gt.push(ne.slice(Ht,Ce-2));let Wt={n:`
`,r:"\r",t:"	",'"':'"',"\\":"\\"}[At];gt.push(Wt===void 0?"\\"+At:Wt)}Ht=Ce}}if(!lt)throw new Error("Unterminated quoted KiCad string.");Rt(Ze?null:{quoted:et});continue}let _t=Ce;for(;Ce<ne.length;){let gt=ne.charCodeAt(Ce);if(gt===40||gt===41||gt===59||gt===34||_e(gt))break;Ce++}if(_t===Ce)throw new Error("Unexpected KiCad source character.");if(Ze){Rt(null);continue}let Et=ne.slice(_t,Ce);if(G.test(Et)){let gt=Number(Et);if(!Number.isFinite(gt))throw new Error("Invalid numeric KiCad value.");Rt(gt)}else Rt(Et==="xy"?"xy":Et)}if(xe.length||ke.length!==1||!Array.isArray(ke[0]))throw new Error("Incomplete KiCad S-expression.");return ke[0]}let De=ne=>ne&&typeof ne=="object"&&!Array.isArray(ne)?ne.quoted:ne,Ke=ne=>Array.isArray(ne)?String(De(ne[0])):"",qe=(ne,we)=>ne.filter(xe=>Array.isArray(xe)&&Ke(xe)===we),$e=(ne,we)=>ne.find(xe=>Array.isArray(xe)&&Ke(xe)===we),Xe=(ne,we)=>De($e(ne,we)?.[1]);function ve(ne){let we=$e(ne,"polyline"),xe=we&&$e(we,"pts");if(!xe||xe.length<4||xe.length>4097)return null;let ke=[];for(let tt of xe.slice(1)){let Ze=De(tt?.[1]),Ye=De(tt?.[2]);if(!Array.isArray(tt)||Ke(tt)!=="xy"||!Number.isFinite(Ze)||!Number.isFinite(Ye))return null;let vt=ke.at(-1);(vt?.x!==Ze||vt.y!==Ye)&&ke.push({x:Ze,y:Ye})}if(ke[0].x===ke.at(-1).x&&ke[0].y===ke.at(-1).y&&ke.pop(),ke.length<3)return null;let Me=ke[0],Ce=0;for(let tt=1;tt<ke.length-1;tt++){let Ze=ke[tt],Ye=ke[tt+1];Ce+=(Ze.x-Me.x)*(Ye.y-Me.y)-(Ze.y-Me.y)*(Ye.x-Me.x)}return Number.isFinite(Ce)&&Ce!==0?ke:null}function Ee(ne){for(let we of["at","start","center","end","xy"]){let xe=$e(ne,we);if(xe&&Number.isFinite(De(xe[1]))&&Number.isFinite(De(xe[2])))return{x:De(xe[1]),y:De(xe[2])}}for(let we of["pts","polygon"]){let xe=$e(ne,we),ke=xe&&$e(we==="polygon"&&$e(xe,"pts")||xe,"xy");if(ke&&Number.isFinite(De(ke[1]))&&Number.isFinite(De(ke[2])))return{x:De(ke[1]),y:De(ke[2])}}return null}function me(ne,we){let xe=[];for(let tt of qe(ne,"property"))tt.length>=3&&xe.push([String(De(tt[1])),String(De(tt[2]))]);if(we==="footprint")for(let[tt,Ze]of[["reference","Reference"],["value","Value"]]){let Ye=qe(ne,"fp_text").find(vt=>De(vt[1])===tt);Ye&&Ye.length>=3&&!xe.some(([vt])=>vt===Ze)&&xe.push([Ze,String(De(Ye[2]))])}for(let tt of["lib_id","layer","width","drill","size","unit"]){let Ze=$e(ne,tt);Ze&&xe.push([tt,Ze.slice(1).map(De).join(", ")])}let ke=$e(ne,"layers");ke&&xe.push(["Layers",ke.slice(1).map(De).join(", ")]);let Me=$e(ne,"net");Me&&xe.push(["Net",String(De(Me[2]??Me[1]))]);let Ce=$e(ne,"at");return Ce&&Number.isFinite(De(Ce[3]))&&xe.push(["Angle",String(De(Ce[3]))]),["label","global_label","hierarchical_label","text","gr_text","gr_text_box"].includes(we)&&xe.push(["Text",String(De(ne[1]??""))]),we==="pad"&&(xe.push(["Number",String(De(ne[1]??""))]),xe.push(["Type",String(De(ne[2]??""))]),xe.push(["Shape",String(De(ne[3]??""))])),Object.fromEntries(xe)}function N(ne){return Array.isArray(ne)?ne.filter(we=>!Array.isArray(we)||!X.has(Ke(we))).map(N):ne&&typeof ne=="object"?["quoted",ne.quoted]:ne}function re(ne){let we=2166136261;for(let xe=0;xe<ne.length;xe++)we=Math.imul(we^ne.charCodeAt(xe),16777619);return(we>>>0).toString(16).padStart(8,"0")}function R(ne,we,xe,ke){let Me=Xe(ne,"uuid")??Xe(ne,"tstamp")??(we==="rule_area"&&$e(ne,"polyline")?Xe($e(ne,"polyline"),"uuid"):void 0);if(Me!=null&&String(Me))return{key:`uuid:${Me}`,uuid:String(Me)};let Ce=we==="pad"?xe.Number:we==="sheet"?xe.Sheetfile:we==="symbol"||we==="footprint"?xe.Reference:void 0;return{key:Ce?`fallback:${String(Ce)}`:`fallback:${re(typeof ke=="function"?ke():ke)}`,uuid:null}}function $(ne,we,xe,ke){return we==="pad"?`${ke||"Footprint"} pad ${xe.Number||""}`.trim():xe.Reference||xe.Sheetname||xe["Sheet name"]||xe.Text||(we==="footprint"?String(De(ne[1]??"Footprint")):we==="symbol"?xe.lib_id||"symbol":we==="netclass_flag"||we==="directive_label"?"Directive label":we==="rule_area"?"Rule area":we.replace(/_/g," "))}function V(ne,we){if(!ne||!we?.position)return null;let xe=Number(De($e(we.form,"at")?.[3]??0)),ke=(Number.isFinite(xe)?xe:0)*Math.PI/180,Me=Math.cos(ke),Ce=Math.sin(ke),tt=we.position.x+ne.x*Me+ne.y*Ce,Ze=we.position.y-ne.x*Ce+ne.y*Me,Ye=vt=>Math.round(vt*1e6)/1e6;return{x:Ye(tt),y:Ye(Ze)}}function O(ne,we,xe=null,ke=null,Me=!1){let Ce=Ke(we),tt=me(we,Ce),Ze=Ee(Ce==="rule_area"&&$e(we,"polyline")||we),Ye=Ce==="pad"?V(Ze,xe):Ze,vt,Rt=()=>vt??=JSON.stringify([N(we),Ye,typeof ke=="function"?ke():ke]);Me||(tt["Source fingerprint"]=re(Rt()));let Je=R(we,Ce,tt,Rt),Et=`${xe?`${xe.scope}/`:`${ne}/`}${Ce}:${Je.key}`,gt=$(we,Ce,tt,xe?.label);return{key:Et,scope:Et,signature:Me?null:Rt(),metadata:{uuid:Je.uuid,position:Ye,properties:tt},path:ne,kind:Ce,label:gt,form:we}}function C(ne,we,xe=null,{forConnectivity:ke=!1,parseOnly:Me=!1,compactCopper:Ce=!1}={},tt){let Ze=tt||be(we,{compactCopper:Ce});xe?.(Ze);let Ye=Ke(Ze);if(Ye!=="kicad_sch"&&Ye!=="kicad_pcb")throw new Error("Expected a KiCad schematic or board.");if(Me)return[];let vt=Ye==="kicad_sch"?Y:ee,Rt=new Map;if(Ye==="kicad_sch"){let _t=$e(Ze,"lib_symbols");if(_t)for(let Et of qe(_t,"symbol")){let gt=De(Et[1]);typeof gt=="string"&&Rt.set(gt,ke?Et:JSON.stringify(N(Et)))}}let Je=[];for(let _t of Ze){if(!Array.isArray(_t)||!vt.has(Ke(_t)))continue;let Et=Ke(_t)==="symbol"?Rt.get(String(Xe(_t,"lib_name")??Xe(_t,"lib_id"))):null,gt=O(ne,_t,null,ke&&Et?()=>JSON.stringify(N(Et)):Et,ke);if(Je.push(gt),Ye==="kicad_pcb"&&gt.kind==="footprint")for(let Ht of qe(_t,"pad"))Je.push(O(ne,Ht,{form:_t,position:gt.metadata.position,scope:gt.scope,label:gt.label},null,ke))}return Je}function j(ne,we={}){return be(ne,{...we,metadataOnly:!0}).filter((ke,Me)=>Me===0||Array.isArray(ke)&&(we.includeEmbeddedFonts?te:Q).has(ke[0])).map(ke=>Array.isArray(ke)&&["symbol","footprint","module"].includes(ke[0])?ke.filter((Me,Ce)=>Ce===0||Array.isArray(Me)&&he.has(Me[0])):ke)}let B=new WeakMap;function W(ne,{forConnectivity:we=!1,compactCopper:xe=!1}={}){let ke=new Map,Me=ge(ne,(tt,Ze)=>ke.set(tt.path,Ze),null,{forConnectivity:we,parseOnly:we,compactCopper:we&&xe}),Ce=Object.freeze({});return B.set(Ce,{files:ne.map(tt=>({path:tt.path,content:tt.content})),parsed:ke,records:we?null:Me,forConnectivity:we}),Ce}function K(ne,we,xe){let ke=B.get(ne);if(!ke||!ke.parsed.has(we))throw new Error("Prepared KiCad file is unavailable.");if(xe!==void 0&&!ke.files.some(Me=>Me.path===we&&Me.content===xe))throw new Error("Prepared KiCad file differs from source.");return ke.parsed.get(we)}function ge(ne,we=null,xe=null,{forConnectivity:ke=!1,parseOnly:Me=!1,compactCopper:Ce=!1}={}){if(xe){let vt=B.get(xe);if(!vt||!Array.isArray(ne)||ne.length!==vt.files.length||ne.some((Rt,Je)=>Rt?.path!==vt.files[Je].path||Rt?.content!==vt.files[Je].content))throw new Error("Prepared KiCad project differs from source.");if(vt.forConnectivity!==ke||!vt.records){let Rt=[];for(let Je of ne)for(let _t of C(Je.path,Je.content,Et=>we?.(Je,Et),{forConnectivity:ke},vt.parsed.get(Je.path)))Rt.push(_t);return Rt}for(let Rt of ne)we?.(Rt,vt.parsed.get(Rt.path));return vt.records.map(Rt=>({...Rt}))}if(!Array.isArray(ne)||ne.length>128)throw new Error("Too many KiCad files to compare.");let tt=new Set,Ze=[],Ye=0;for(let vt of ne){if(!vt||typeof vt.path!="string"||typeof vt.content!="string"||!/\.kicad_(?:sch|pcb)$/i.test(vt.path)||tt.has(vt.path))throw new Error("Invalid or duplicate KiCad file entry.");tt.add(vt.path);let Rt=ae(vt.content);if(Ye+=Rt,Rt>268435456||Ye>536870912)throw new Error("KiCad project exceeds browser comparison size limits.");for(let Je of C(vt.path,vt.content,_t=>we?.(vt,_t),{forConnectivity:ke,parseOnly:Me,compactCopper:Ce}))Ze.push(Je)}return Ze}function Ne(ne,we){let xe=ge(ne),ke=ge(we),Me=new Map;for(let Ye of xe)Me.has(Ye.key)||Me.set(Ye.key,{before:[],after:[]}),Me.get(Ye.key).before.push(Ye);for(let Ye of ke)Me.has(Ye.key)||Me.set(Ye.key,{before:[],after:[]}),Me.get(Ye.key).after.push(Ye);let Ce=[],tt={added:0,removed:0,modified:0},Ze=(Ye,vt,Rt,Je,_t)=>{Ce.push({id:_t,path:Ye.path,kind:Ye.kind,label:Ye.label,status:vt,before:Rt?.metadata??null,after:Je?.metadata??null}),tt[vt]++};for(let[Ye,vt]of Me){let Rt=[...vt.before],Je=[...vt.after];for(let Et=Rt.length-1;Et>=0;Et--){let gt=Je.findIndex(Ht=>Ht.signature===Rt[Et].signature);gt>=0&&(Rt.splice(Et,1),Je.splice(gt,1))}Rt.sort((Et,gt)=>Et.signature.localeCompare(gt.signature)),Je.sort((Et,gt)=>Et.signature.localeCompare(gt.signature));let _t=Math.max(Rt.length,Je.length);for(let Et=0;Et<_t;Et++){let gt=Rt[Et]||null,Ht=Je[Et]||null;Ze(Ht||gt,gt&&Ht?"modified":gt?"removed":"added",gt,Ht,_t>1?`${Ye}#${Et+1}`:Ye)}}return Ce.sort((Ye,vt)=>Ye.path.localeCompare(vt.path)||Ye.id.localeCompare(vt.id)||Ye.status.localeCompare(vt.status)),{changes:Ce,counts:tt}}m.KiCadDesignDiff={compareProjects:Ne,projectObjects:ge,parse:be,parseMetadata:j,sourceByteLimit:p,sourceByteLength:ae,prepareProject:W,preparedFile:K,cubicBezierPoints:J,MAX_FILES:128,MAX_FILE_BYTES:268435456,MAX_PROJECT_BYTES:536870912,MAX_RENDER_PRIMITIVES:15e5,ruleAreaPoints:ve},typeof ih=="object"&&ih.exports&&(ih.exports=m.KiCadDesignDiff)})(typeof globalThis=="object"?globalThis:YE)});var KE=$n((qE,am)=>{(m=>{"use strict";let h=m.KiCadDesignDiff||(typeof $c=="function"?To():null),p=Number.isSafeInteger(h?.MAX_RENDER_PRIMITIVES)&&h.MAX_RENDER_PRIMITIVES>0?h.MAX_RENDER_PRIMITIVES:25e4,w=R=>R&&typeof R=="object"&&!Array.isArray(R)?R.quoted:R,S=R=>Array.isArray(R)?String(w(R[0])):"",A=(R,$)=>Array.isArray(R)?R.filter(V=>S(V)===$):[],T=(R,$)=>A(R,$)[0],H=(R,$)=>w(T(R,$)?.[1]),Y=(R,$)=>{let V=T(R,$);return V&&Number.isFinite(w(V[1]))&&Number.isFinite(w(V[2]))?{x:w(V[1]),y:w(V[2])}:null},ee=R=>R&&Number.isFinite(R.x)&&Number.isFinite(R.y),X=(R,$)=>Math.hypot($.x-R.x,$.y-R.y),G=1e-7,ae=new Set(["label","global_label","hierarchical_label"]),_e=new Set(["netclass_flag","directive_label"]),J=5e-6,Q=(R,$,V,O)=>({id:`${R}/net:${$}`,path:R,code:$,name:V,displayName:V,kind:O,objectIds:[],uuids:[],primitives:[],stats:{pads:0,tracks:0,vias:0,zones:0,lengthMm:0},members:[]});function te(R){return typeof R?.displayName=="string"&&R.displayName?R.displayName:R?.kind==="schematic"&&/^Unnamed network \(/.test(R.name||"")?"Unnamed network":typeof R?.name=="string"&&R.name?R.name:"Unnamed network"}function he(R){let $=Y(R,"start"),V=Y(R,"mid"),O=Y(R,"end");if(!$||!V||!O)return null;let C=V.x-$.x,j=V.y-$.y,B=O.x-$.x,W=O.y-$.y,K=2*(C*W-j*B);if(Math.abs(K)<=1e-12*Math.max(1,C*C+j*j,B*B+W*W))return null;let ge=C*C+j*j,Ne=B*B+W*W,ne=(W*ge-j*Ne)/K,we=(C*Ne-B*ge)/K,xe=(vt,Rt)=>Math.atan2(Rt-we,vt-ne),ke=2*Math.PI,Me=vt=>(vt%ke+ke)%ke,Ce=xe(0,0),tt=Me(xe(C,j)-Ce),Ze=Me(xe(B,W)-Ce),Ye=tt<=Ze+1e-12?Ze:ke-Ze;return Math.hypot(ne,we)*Ye}function be(R,$,V,O,C,j){let B=new Map,W=new Map,K=Number(H($,"version"))>=20260206,ge=Me=>{let Ce=w(Me?.[1]);return K&&typeof Ce=="string"&&Ce&&Me.length===2?`name:${Ce}`:typeof Ce=="number"&&Number.isSafeInteger(Ce)&&Ce>=0?String(Ce):null},Ne=Me=>{let Ce=ge(Me),tt=Ce?.startsWith("name:")?w(Me?.[1]):w(Me?.[2]);!Ce||Ce==="0"||typeof tt!="string"||!tt||(W.has(Ce)&&W.get(Ce)!==tt?C(`${R}: net code ${Ce} has conflicting saved names; using ${W.get(Ce)}.`):W.set(Ce,tt))};A($,"net").forEach(Ne);for(let Me of V)Ne(T(Me.form,"net"));let ne=Me=>(B.has(Me)||B.set(Me,Q(R,Me,W.get(Me)||`Net ${Me} (name unavailable)`,"pcb")),B.get(Me));W.forEach((Me,Ce)=>ne(Ce));let we=new Map,xe=new Map,ke=new Map(V.filter(Me=>Me.kind==="footprint").map(Me=>[Me.key,Me]));for(let Me of O)if(Me.uuid){let Ce=we.get(Me.uuid);if(Ce===void 0?we.set(Me.uuid,Me):Array.isArray(Ce)?Ce.push(Me):we.set(Me.uuid,[Ce,Me]),Me.kind==="pad"&&Me.ownerUuid&&Me.name!=null){let tt=JSON.stringify([Me.ownerUuid,String(Me.name)]);xe.has(tt)||xe.set(tt,[]),xe.get(tt).push(Me)}}for(let Me of V){if(!["pad","segment","arc","via","zone"].includes(Me.kind))continue;let Ce=T(Me.form,"net");if(!Ce)continue;let tt=ge(Ce);if(tt==="0")continue;if(tt===null){C(`${R}: ${Me.label} has an unsupported net code and was excluded.`);continue}W.has(tt)||C(`${R}: net code ${tt} has no saved name declaration.`);let Ze=ne(tt),Ye=Me.metadata.uuid;Ze.objectIds.push(Me.id||Me.key),Ye&&Ze.uuids.push(Ye);let vt=Me.kind==="pad"?ke.get(Me.key.slice(0,Me.key.lastIndexOf("/pad:"))):null,Rt=Ye?we.get(Ye):vt?xe.get(JSON.stringify([vt.metadata.uuid,String(w(Me.form[1]))])):void 0,Je=Et=>Me.kind==="pad"?Et.kind==="pad"||Et.kind==="drill":Me.kind==="zone"?Et.kind==="zone"||Et.kind==="zone-outline":Me.kind==="segment"?Et.kind==="track":Me.kind==="arc"?Et.kind==="arc"||Et.kind==="track":Et.kind==="via"||Et.kind==="drill";if(Array.isArray(Rt)){j(Rt.length);for(let Et of Rt)Je(Et)&&Ze.primitives.push(Et)}else Rt&&(j(1),Je(Rt)&&Ze.primitives.push(Rt));Ze.members.push({uuid:Ye,reference:vt?.metadata.properties.Reference||"",pad:Me.kind==="pad"?String(w(Me.form[1])):"",kind:Me.kind,position:Me.metadata.position});let _t={pad:"pads",segment:"tracks",arc:"tracks",via:"vias",zone:"zones"}[Me.kind];if(Ze.stats[_t]++,Me.kind==="segment"){let Et=Y(Me.form,"start"),gt=Y(Me.form,"end");Et&&gt?Ze.stats.lengthMm+=X(Et,gt):C(`${R}: track ${Ye||Me.label} has incomplete geometry; length omitted.`)}else if(Me.kind==="arc"){let Et=he(Me.form);Et!==null?Ze.stats.lengthMm+=Et:C(`${R}: arc ${Ye||Me.label} has unsupported or degenerate geometry; length omitted.`)}}return[...B.values()]}function De(R,$,V=G){let{a:O,b:C}=$,j=C.x-O.x,B=C.y-O.y,W=Math.hypot(j,B);return W?Math.abs((R.x-O.x)*B-(R.y-O.y)*j)<=V*W&&R.x>=Math.min(O.x,C.x)-V&&R.x<=Math.max(O.x,C.x)+V&&R.y>=Math.min(O.y,C.y)-V&&R.y<=Math.max(O.y,C.y)+V:X(O,R)<=V}function Ke(R,$=0){if(!R.length)return null;let V=Math.min(...R.map(K=>Math.min(K.a.x,K.b.x))),O=Math.max(...R.map(K=>Math.max(K.a.x,K.b.x))),C=Math.min(...R.map(K=>Math.min(K.a.y,K.b.y))),j=Math.max(...R.map(K=>Math.max(K.a.y,K.b.y)));if(R.length<=16)return{minX:V,maxX:O,minY:C,maxY:j,edges:R};let B=$%2?"y":"x";R.sort((K,ge)=>K.a[B]+K.b[B]-(ge.a[B]+ge.b[B]));let W=Math.floor(R.length/2);return{minX:V,maxX:O,minY:C,maxY:j,left:Ke(R.slice(0,W),$+1),right:Ke(R.slice(W),$+1)}}function qe(R,$){let V=!1;for(let O of $){let{a:C,b:j}=O;if(De(R,O))return!0;C.y>R.y!=j.y>R.y&&R.x<C.x+(j.x-C.x)*(R.y-C.y)/(j.y-C.y)&&(V=!V)}return V}let $e=(R,$,V)=>(V.x-$.x)*(R.y-$.y)-(V.y-$.y)*(R.x-$.x);function Xe(R,$){let V=(O,{a:C,b:j})=>{let B=$e(C,O.a,O.b),W=$e(j,O.a,O.b);return B<0&&W>0||B>0&&W<0};return V(R,$)&&V($,R)||De(R.a,$)||De(R.b,$)||De($.a,R)||De($.b,R)}function ve(R,$,V,O,C,j,B,W,K,ge,Ne){let ne=new Map,we=new Map;if(!V.length)return{netClasses:ne,objectClasses:we};if(V.length>1e4||$.length>1e4)return Ne(`${R}: schematic class assignments exceeded the rule area or directive limit and were omitted.`),{netClasses:ne,objectClasses:we};let xe=0,ke=0,Me=(Je=1)=>{if((xe+=Je)>2e6)throw new Error("Rule geometry limit")},Ce=(Je,_t,Et)=>{let gt=Je.get(_t);if(gt||Je.set(_t,gt=new Set),!gt.has(Et)){if(++ke>1e5)throw new Error("Class assignment link limit");gt.add(Et)}},tt=[],Ze=0;for(let Je of $){let _t=h.ruleAreaPoints(Je.form);if(!_t){Ne(`${R}: a schematic rule area has invalid or oversized geometry.`);continue}if((Ze+=_t.length)>5e4)return Ne(`${R}: schematic class assignments exceeded the rule area vertex limit and were omitted.`),{netClasses:ne,objectClasses:we};let Et=_t.map((lt,et)=>({a:lt,b:_t[(et+1)%_t.length]})),gt={x:Math.min(..._t.map(lt=>lt.x)),y:Math.min(..._t.map(lt=>lt.y))},Ht={x:Math.max(..._t.map(lt=>lt.x)),y:Math.max(..._t.map(lt=>lt.y))};tt.push({a:gt,b:Ht,border:Et,record:Je,net:[],component:[]})}let Ye=Ke(tt),vt=(Je,_t)=>{let Et=Math.min(Je.a.x,Je.b.x),gt=Math.max(Je.a.x,Je.b.x),Ht=Math.min(Je.a.y,Je.b.y),lt=Math.max(Je.a.y,Je.b.y);function et(St){if(!(!St||Et>St.maxX+J||gt<St.minX-J||Ht>St.maxY+J||lt<St.minY-J)){if(!St.edges){et(St.left),et(St.right);return}for(let At of St.edges)Me(),!(Et>At.b.x+J||gt<At.a.x-J||Ht>At.b.y+J||lt<At.a.y-J)&&_t(At)}}et(Ye)},Rt=Je=>{let _t=new Set,Et=[];for(let gt of A(Je.form,"property")){let Ht=w(gt[1]),lt=w(gt[2]),et=Ht==="Component Class"?"component":["Netclass","Net Class"].includes(Ht)?"net":null;if(!et||typeof lt!="string"||!lt||lt.length>4096)continue;if(lt.includes("${")){Ne(`${R}: schematic class fields with text variables require KiCad instance resolution.`);continue}let St=JSON.stringify([et,lt]);if(!_t.has(St)){if(Et.length>=512)throw new Error("Directive class field limit");_t.add(St),Et.push(Object.freeze({name:lt,type:et,directiveId:Je.id,directiveUuid:Je.metadata.uuid}))}}return Et};try{for(let Et of V){let gt=Y(Et.form,"at");if(!gt)continue;let Ht=Rt(Et);if(!Ht.length||(vt({a:gt,b:gt},St=>{if(Me(St.border.length),!!St.border.some(At=>De(gt,At,J)))for(let At of Ht){let Wt=Object.freeze({...At,ruleAreaId:St.record.id,ruleAreaUuid:St.record.metadata.uuid});Ce(we,St.record.id,Wt),St[At.type].push(Wt)}}),!Ht.some(St=>St.type==="net")))continue;let lt=new Set;ge(gt,lt),W.has(K(gt))&&lt.add(W.get(K(gt)));let et=new Set;for(let St of lt)et.add(B(St));if(et.size===1)for(let St of Ht)St.type==="net"&&Ce(ne,et.values().next().value,St);else et.size>1&&Ne(`${R}: a directive at an ambiguous electrical crossing has no direct net assignment.`)}let Je=(Et,gt,Ht)=>{Me(Ht.length);for(let lt of Ht)Ce(Et,gt,lt)},_t=(Et,gt)=>vt({a:Et,b:Et},Ht=>{!Ht.net.length&&!Ht.component.length||(Me(Ht.border.length),qe(Et,Ht.border)&&gt(Ht))});for(let Et of O)!ae.has(Et.kind)&&Et.kind!=="pin"||_t(Et.position,gt=>{Je(ne,B(Et.index),gt.net),Et.kind==="pin"&&Je(we,Et.record.id,gt.component)});for(let Et of C)vt(Et,gt=>{gt.net.length&&(Me(2*gt.border.length),(qe(Et.a,gt.border)||gt.border.some(Ht=>Xe(Et,Ht)))&&Je(ne,B(Et.index),gt.net))});for(let Et of j.values())ee(Et.metadata.position)&&_t(Et.metadata.position,gt=>Je(we,Et.id,gt.component))}catch{Ne(`${R}: schematic class assignments exceeded the geometry or assignment limit and were omitted.`),ne.clear(),we.clear()}return{netClasses:ne,objectClasses:we}}function Ee(R,$,V,O,C,j,B){C(`${R}: schematic nets show per-file source connectivity only; cross-sheet hierarchy, implicit hidden power pins and bus expansion are not resolved. This is not a KiCad netlist.`);let W=[],K=[],ge=[],Ne=[],ne=[],we=pt=>(pt.index=W.length,W.push(pt),pt);for(let pt of V)if(pt.kind==="rule_area")Ne.push(pt);else if(_e.has(pt.kind))ne.push(pt);else if(pt.kind==="wire"){let ft=A(T(pt.form,"pts"),"xy").map(Yt=>({x:w(Yt[1]),y:w(Yt[2])}));if(ft.length<2||!ft.every(ee)){C(`${R}: wire with invalid geometry was excluded.`);continue}let Bt=we({record:pt,kind:"wire",position:ft[0],length:0});for(let Yt=1;Yt<ft.length;Yt++)K.push({a:ft[Yt-1],b:ft[Yt],index:Bt.index}),Bt.length+=X(ft[Yt-1],ft[Yt]);for(let Yt of ft)ge.push({p:Yt,index:Bt.index,endpoint:!0})}else if(pt.kind==="sheet")for(let ft of A(pt.form,"pin")){let Bt=Y(ft,"at"),Yt=w(ft[1]);if(!Bt||typeof Yt!="string"||!Yt)continue;let kr=H(ft,"uuid"),Gr=pt.metadata.uuid||pt.id||pt.key,Qr={...pt,id:`${pt.id||pt.key}/pin:${kr||Yt}`,metadata:{...pt.metadata,uuid:kr}},Zr=we({record:Qr,kind:"sheet_pin",position:Bt,sheetPin:{sheetId:Gr,name:Yt}});ge.push({p:Bt,index:Zr.index})}else if(ae.has(pt.kind)||pt.kind==="junction"){let ft=Y(pt.form,"at");if(!ft)continue;let Bt=we({record:pt,kind:pt.kind,position:ft,name:ae.has(pt.kind)?String(w(pt.form[1])):null,namePriority:{global_label:0,label:2,hierarchical_label:3}[pt.kind]});ge.push({p:ft,index:Bt.index,junction:pt.kind==="junction"})}let xe=new Map(V.filter(pt=>pt.kind==="symbol"&&pt.metadata.uuid).map(pt=>[pt.metadata.uuid,pt])),ke=new Map(A(T($,"lib_symbols"),"symbol").map(pt=>[String(w(pt[1])),pt])),Me=new Map,Ce=new Set,tt=Number(H($,"version"));for(let[pt,ft]of xe){let Bt=ke.get(String(H(ft.form,"lib_name")??H(ft.form,"lib_id"))),Yt=T(Bt,"power");if(!Yt)continue;let kr=w(Yt[1]);if(kr!==void 0&&!["global","local"].includes(kr)){C(`${R}: unsupported explicit power-symbol scope ${kr}; naming omitted.`);continue}let Gr=A(Bt,"symbol").flatMap(ur=>A(ur,"pin"));if(Gr.length===1&&w(Gr[0][1])==="power_out"){Ce.add(pt);continue}if(Gr.length!==1||w(Gr[0][1])!=="power_in"){C(`${R}: explicit power symbol ${ft.label} is not a supported single power-input pin; naming omitted.`);continue}let Qr=Gr[0],Zr=String(H(Qr,"number")??""),ii;if(Number.isSafeInteger(tt)&&tt>=20231120)ii=ft.metadata.properties.Value;else if(Number.isSafeInteger(tt)&&tt>0&&tt<=20230121&&(T(Qr,"hide")||Qr.some(ur=>w(ur)==="hide")))ii=H(Qr,"name");else{C(`${R}: power symbol ${ft.label} has an unproven schematic version; naming omitted.`);continue}if(typeof ii!="string"||!ii||ii==="~"){C(`${R}: power symbol ${ft.label} has no usable saved net name; naming omitted.`);continue}Me.set(pt,{name:ii,pinNumber:Zr,global:kr!=="local"})}let Ze=new Map;for(let pt of O)if(pt.kind==="pin"&&ee(pt.connectPoint)&&pt.pinNumber!=null){let ft=pt.ownerUuid||pt.uuid,Bt=xe.get(ft);if(!Bt)continue;let Yt=JSON.stringify([ft,String(pt.pinNumber),pt.connectPoint.x,pt.connectPoint.y]);if(Ze.has(Yt)){Ze.get(Yt).primitives.push(pt);continue}let kr=Me.get(ft),Gr=kr&&kr.pinNumber===String(pt.pinNumber),Qr=we({record:Bt,kind:"pin",position:pt.connectPoint,pin:String(pt.pinNumber),primitives:[pt],name:Gr?kr.name:null,namePriority:Gr?1:void 0,power:!!Gr,flag:Ce.has(ft),global:!!(Gr&&kr.global)});Ze.set(Yt,Qr),ge.push({p:pt.connectPoint,index:Qr.index})}if(xe.size&&!Ze.size&&C(`${R}: no conductive pin metadata is available; symbol pin membership was omitted.`),W.length>3e4||K.length>3e4)return C(`${R}: schematic connectivity exceeds the 30000-object limit and was omitted.`),[];let Ye=W.map((pt,ft)=>ft),vt=W.map(()=>0),Rt=pt=>{let ft=pt;for(;Ye[ft]!==ft;)ft=Ye[ft];for(;Ye[pt]!==pt;){let Bt=Ye[pt];Ye[pt]=ft,pt=Bt}return ft},Je=(pt,ft)=>{pt=Rt(pt),ft=Rt(ft),pt!==ft&&(vt[pt]<vt[ft]&&([pt,ft]=[ft,pt]),Ye[ft]=pt,vt[pt]===vt[ft]&&vt[pt]++)},_t=Ke(K.slice()),Et=new Map,gt=pt=>JSON.stringify([pt.x,pt.y]);for(let pt of ge){let ft=gt(pt.p);Et.has(ft)?Je(pt.index,Et.get(ft)):Et.set(ft,pt.index)}let Ht=0,lt=(pt,ft,Bt)=>{if(!(!pt||ft.x<pt.minX-G||ft.x>pt.maxX+G||ft.y<pt.minY-G||ft.y>pt.maxY+G))if(pt.edges)for(let Yt of pt.edges){if(++Ht>2e6)throw new Error("attachment limit");De(ft,Yt)&&Bt.add(Yt.index)}else lt(pt.left,ft,Bt),lt(pt.right,ft,Bt)};try{for(let pt of ge.filter(ft=>ft.endpoint||ft.junction)){let ft=new Set;lt(_t,pt.p,ft);for(let Bt of ft)Je(pt.index,Bt)}for(let pt of ge.filter(ft=>!ft.endpoint&&!ft.junction)){let ft=new Set;if(lt(_t,pt.p,ft),new Set([...ft].map(Rt)).size>1){C(`${R}: ambiguous label/pin at a wire crossing without a junction was not attached.`);continue}for(let Bt of ft)Je(pt.index,Bt)}}catch{return C(`${R}: schematic connectivity exceeds the attachment-work limit and was omitted.`),[]}let et=new Map;for(let pt of W)pt.name&&(et.has(pt.name)?Je(pt.index,et.get(pt.name)):et.set(pt.name,pt.index));let St=ve(R,Ne,ne,W,K,xe,Rt,Et,gt,(pt,ft)=>lt(_t,pt,ft),C);for(let[pt,ft]of St.objectClasses)B.set(pt,Object.freeze([...ft]));let At=new Map;for(let pt of W){let ft=Rt(pt.index);At.has(ft)||At.set(ft,[]),At.get(ft).push(pt)}let Wt=new Map;for(let pt of O)for(let ft of new Set([pt.uuid,pt.pinUuid,pt.savedPinUuid].filter(Boolean)))Wt.has(ft)||Wt.set(ft,[]),Wt.get(ft).push(pt);let nr=[];for(let[pt,ft]of At){if(!ft.some(ur=>ur.kind==="wire"||ur.name||ur.sheetPin))continue;let Bt=[...new Set(ft.map(ur=>ur.name).filter(Boolean))].sort(),Yt=ft.filter(ur=>ur.name).sort((ur,Gi)=>(ur.namePriority??4)-(Gi.namePriority??4)||ur.name.localeCompare(Gi.name))[0]?.name,kr=ft.filter(ur=>ur.kind==="wire"||ur.sheetPin).map(ur=>ur.record.id||ur.record.key).sort()[0],Gr=Bt.length?`label:${Bt[0]}`:`source:${kr}`,Qr=Q(R,Gr,Yt||`Unnamed network (${ft.find(ur=>ur.kind==="wire")?.record.metadata.uuid||"wire"})`,"schematic");St.netClasses.has(pt)&&(Qr.classAssignments=Object.freeze([...St.netClasses.get(pt)]));let Zr=[...new Set(ft.map(ur=>ur.sheetPin?.name).filter(Boolean))].sort(),ii=[...new Set(ft.filter(ur=>ur.kind==="pin"&&ur.record.metadata.properties.Reference).map(ur=>`${ur.record.metadata.properties.Reference} pin ${ur.pin}`))].sort();Qr.displayName=Yt||(Zr.length?Zr.join(" / "):"Unnamed network"+(ii.length?" \xB7 "+ii.slice(0,2).join(", ")+(ii.length>2?" \u2026":""):"")),Qr.scope="file",Qr.names=Bt,Qr.globalNames=[...new Set(ft.filter(ur=>ur.kind==="global_label"||ur.global).map(ur=>ur.name).filter(Boolean))].sort(),Qr.hierarchicalNames=[...new Set(ft.filter(ur=>ur.kind==="hierarchical_label").map(ur=>ur.name))].sort(),Qr.sheetPins=ft.filter(ur=>ur.sheetPin).map(ur=>({...ur.sheetPin})),Bt.length>1&&C(`${R}: connected schematic source network has multiple labels: ${Bt.join(", ")}.`);for(let ur of ft){let Gi=ur.record,yt=Gi.metadata.uuid;Qr.objectIds.push(Gi.id||Gi.key),yt&&Qr.uuids.push(yt),j((ur.kind==="pin"&&!ur.power&&!ur.flag?ur.primitives:Wt.get(yt)||[]).length),Qr.primitives.push(...ur.power||ur.flag?(Wt.get(yt)||[]).filter(jt=>!jt.frame):ur.kind==="pin"?ur.primitives:(Wt.get(yt)||[]).filter(jt=>jt.kind===ur.kind||ur.kind==="sheet_pin"&&jt.kind==="sheet-pin"||jt.kind==="text-overbar"&&(jt.electricalKind===ur.kind||ur.kind==="sheet_pin"&&jt.electricalKind==="sheet-pin"))),Qr.members.push({uuid:yt,reference:ur.kind==="pin"&&Gi.metadata.properties.Reference||"",pad:"",pin:ur.pin||"",kind:ur.kind,position:ur.position}),Qr.stats.lengthMm+=ur.length||0}nr.push(Qr)}return nr}function me(R,$=new Map,V=null){if(!h?.projectObjects||!h?.parse)throw new Error("KiCadDesignDiff is required for net extraction.");let O=new Map,C=h.projectObjects(R,(ke,Me)=>O.set(ke.path,Me),V,{forConnectivity:!0}),j=new Map,B=new Map;for(let ke of C){B.has(ke.path)||B.set(ke.path,[]),B.get(ke.path).push(ke);let Me=(j.get(ke.key)||0)+1;j.set(ke.key,Me),ke.id=Me===1?ke.key:`${ke.key}#${Me}`}j.clear();let W=[],K=[],ge=new Set,Ne=new Map,ne=0,we=ke=>{if(ne+=ke,ne>4e5)throw new Error("Net geometry membership exceeds the 400,000-reference work limit.")},xe=ke=>{K.length<1e3&&!ge.has(ke)&&(ge.add(ke),K.push(ke))};for(let ke of R){let Me=O.get(ke.path),Ce=B.get(ke.path)||[],tt=$ instanceof Map?$.get(ke.path):$?.[ke.path],Ze=Array.isArray(tt?.primitives)?tt.primitives:[],Ye=new Map;for(let Je of Ce){let _t=Je.metadata.uuid;if(_t&&Ye.set(_t,(Ye.get(_t)||0)+1),["sheet","symbol"].includes(S(Je.form)))for(let Et of A(Je.form,"pin")){let gt=H(Et,"uuid");gt&&Ye.set(gt,(Ye.get(gt)||0)+1)}}let vt=new Set;for(let[Je,_t]of Ye)_t>1&&vt.add(Je);Ye.clear(),vt.size&&xe(ke.path+": "+vt.size+" duplicate saved UUIDs excluded from net geometry membership.");let Rt=vt.size?Ze.filter(Je=>![Je.uuid,Je.pinUuid,Je.savedPinUuid].some(_t=>_t&&vt.has(_t))):Ze;if(Rt.length>p)throw new Error("Too many render primitives for net selection.");W.push(...S(Me)==="kicad_pcb"?be(ke.path,Me,Ce,Rt,xe,we):Ee(ke.path,Me,Ce,Rt,xe,we,Ne))}for(let ke of W)ke.objectIds=[...new Set(ke.objectIds)],ke.uuids=[...new Set(ke.uuids)],ke.primitives=[...new Set(ke.primitives)];return W.sort((ke,Me)=>ke.path.localeCompare(Me.path)||ke.name.localeCompare(Me.name)||ke.code.localeCompare(Me.code)),{nets:W,warnings:K,...Ne.size?{objectClasses:Ne}:{}}}function N(R,$,V=[]){let O=["Only loaded schematic files are searched.","Only unambiguous resolved sheet links are searched; cyclic hierarchy, repeated sheet instances, implicit hidden power pins and buses are not resolved; this is not a KiCad netlist."],C=R.find(Je=>Je.id===$&&Je.kind==="schematic");if(!C)return{matches:[],paths:[],limits:O};if(!V.length&&!C.globalNames?.length)return{matches:[C],paths:[C.path],limits:O};let j=new Map,B=new Map,W=new Map,K=(Je,_t,Et)=>{Je.has(_t)||Je.set(_t,[]),Je.get(_t).push(Et)},ge=(...Je)=>JSON.stringify(Je);for(let Je of R)if(Je.kind==="schematic"){for(let _t of Je.globalNames||[])K(j,_t,Je);for(let _t of V.length?Je.sheetPins||[]:[])K(B,ge(Je.path,_t.sheetId),{net:Je,name:_t.name});for(let _t of V.length?Je.hierarchicalNames||[]:[])K(W,ge(Je.path,_t),Je)}let Ne=[...new Map(V.map(Je=>[ge(Je.path,Je.target,Je.sheetId),Je])).values()],ne=new Map,we=new Map;for(let Je of Ne)ne.set(Je.target,(ne.get(Je.target)||0)+1),K(we,Je.path,Je.target);let xe=new Map,ke=(Je,_t)=>{K(xe,Je.id,_t),K(xe,_t.id,Je)},Me=new Map,Ce=Je=>{if(Me.has(Je))return Me.get(Je);let _t=[Je],Et=new Set;for(let gt=0;gt<_t.length;gt++){let Ht=_t[gt];if(!Et.has(Ht)){Et.add(Ht);for(let lt of we.get(Ht)||[])_t.push(lt)}}return Me.set(Je,Et),Et},tt=new Set;for(let[Je,_t]of ne)if(_t>1)for(let Et of Ce(Je))tt.add(Et);for(let Je of Ne)if(ne.get(Je.target)===1&&!tt.has(Je.path)&&!Ce(Je.target).has(Je.path))for(let _t of B.get(ge(Je.path,Je.sheetId))||[])for(let Et of W.get(ge(Je.target,_t.name))||[])ke(_t.net,Et);let Ze=new Map([[C.id,C]]),Ye=[C],vt=new Set;for(let Je=0;Je<Ye.length;Je++){let _t=[...xe.get(Ye[Je].id)||[]];for(let Et of Ye[Je].globalNames||[])vt.has(Et)||(vt.add(Et),_t.push(...j.get(Et)||[]));for(let Et of _t)Ze.has(Et.id)||(Ze.set(Et.id,Et),Ye.push(Et))}let Rt=[...Ze.values()].sort((Je,_t)=>Je.path.localeCompare(_t.path)||Je.id.localeCompare(_t.id));return{matches:Rt,paths:[...new Set(Rt.map(Je=>Je.path))],limits:O}}function re(){let R=new Map,$=new TextEncoder,V=new WeakMap,O=0,C=96*1024*1024;function j(ge){if(ge.length>p)throw new Error("Too many render primitives for net selection.");let Ne=[],ne=0;for(let we of ge){let xe;!we||typeof we!="object"?xe=[typeof we,String(we)]:(V.has(we)||V.set(we,++O),xe=[V.get(we),we.kind,we.uuid,we.ownerUuid,we.pinUuid,we.savedPinUuid,we.name,we.pinNumber,we.connectPoint?.x,we.connectPoint?.y,!!we.frame]);let ke=JSON.stringify(xe);if(ne+=ke.length+1,ne>4*1024*1024)return null;Ne.push(ke)}return"["+Ne.join(",")+"]"}function B(ge){return{...ge,objectIds:[...ge.objectIds],uuids:[...ge.uuids],primitives:[...ge.primitives],stats:{...ge.stats},members:ge.members.map(Ne=>({...Ne,...Ne.position?{position:{...Ne.position}}:{}})),...ge.names?{names:[...ge.names]}:{},...ge.globalNames?{globalNames:[...ge.globalNames]}:{},...ge.hierarchicalNames?{hierarchicalNames:[...ge.hierarchicalNames]}:{},...ge.sheetPins?{sheetPins:ge.sheetPins.map(Ne=>({...Ne}))}:{}}}function W(ge,Ne=new Map){if(!Array.isArray(ge)||ge.length>(h.MAX_FILES||128))throw new Error("Too many KiCad files to compare.");let ne=new Set,we=[],xe=0;for(let Ye of ge){if(!Ye||typeof Ye.path!="string"||typeof Ye.content!="string"||!/\.kicad_(?:sch|pcb)$/i.test(Ye.path)||ne.has(Ye.path))throw new Error("Invalid or duplicate KiCad file entry.");ne.add(Ye.path);let vt=R.get(Ye.path),Rt=vt?.content===Ye.content?vt.sourceBytes:h.sourceByteLength?h.sourceByteLength(Ye.content):$.encode(Ye.content).length;if(xe+=Rt,Rt>h.MAX_FILE_BYTES||xe>h.MAX_PROJECT_BYTES)throw new Error("KiCad project exceeds browser comparison size limits.");let Je=Ne instanceof Map?Ne.get(Ye.path):Ne?.[Ye.path],_t=Array.isArray(Je?.primitives)?Je.primitives:[];if(_t.length>p)throw new Error("Too many render primitives for net selection.");we.push({file:Ye,sourceBytes:Rt,primitives:_t,design:Je})}for(let Ye of R.keys())ne.has(Ye)||R.delete(Ye);let ke=[],Me=[],Ce=new Set,tt=new Map,Ze=0;for(let Ye of we){let{file:vt,primitives:Rt,design:Je}=Ye,_t=j(Rt),Et=R.get(vt.path),gt;_t!==null&&Et?.content===vt.content&&Et.signature===_t?gt=Et.snapshot:gt=me([vt],new Map([[vt.path,Je]]));let Ht=Ye.sourceBytes+(_t===null?1/0:_t.length*2);Ze+Ht<=C?(R.set(vt.path,{content:vt.content,sourceBytes:Ye.sourceBytes,signature:_t,snapshot:gt}),Ze+=Ht):R.delete(vt.path),ke.push(...gt.nets.map(B));for(let[lt,et]of gt.objectClasses||[])tt.set(lt,et);for(let lt of gt.warnings)Me.length<1e3&&!Ce.has(lt)&&(Ce.add(lt),Me.push(lt))}return ke.sort((Ye,vt)=>Ye.path.localeCompare(vt.path)||Ye.name.localeCompare(vt.name)||Ye.code.localeCompare(vt.code)),{nets:ke,warnings:Me,...tt.size?{objectClasses:tt}:{}}}function K(){R.clear(),V=new WeakMap,O=0}return{build:W,clear:K}}m.KiCadNetModel={build:me,createBuilder:re,relatedSchematicNets:N,displayName:te},typeof am=="object"&&am.exports&&(am.exports=m.KiCadNetModel)})(typeof globalThis=="object"?globalThis:qE)});var lm=$n((ZE,om)=>{(m=>{"use strict";let h=J=>J&&typeof J=="object"&&!Array.isArray(J)?J.quoted:J;function p(J){let Q=J.find(De=>Array.isArray(De)&&De[0]==="embedded_files");if(!Q)return;let te=new Map,he=0;for(let De of Q){if(!Array.isArray(De)||De[0]!=="file")continue;let Ke=Ee=>De.find(me=>Array.isArray(me)&&me[0]===Ee),qe=h(Ke("name")?.[1]);if(h(Ke("type")?.[1])!=="font"||typeof qe!="string"||qe.length>255||!/[.](ttf|otf)$/i.test(qe))continue;if(te.has(qe)){te.set(qe,null);continue}let $e=Ke("data");if(!$e)continue;let Xe=0;for(let Ee=1;Ee<$e.length&&Xe<=3e6;Ee++)Xe+=String(h($e[Ee])).length;if(Xe>3e6||he+Xe>8e6||te.size>=16)continue;let ve=$e.slice(1).map(h).join("");!ve.startsWith("|")||!ve.endsWith("|")||(he+=Xe,te.set(qe,{name:qe,base64:ve.slice(1,-1),checksum:h(Ke("checksum")?.[1])}))}let be=[...te.values()].filter(Boolean);return be.length?be:void 0}let w="version generator generator_version uuid paper title_block embedded_fonts embedded_files".split(" "),S={kicad_pcb:new Set([...w,..."general layers setup net footprint segment arc via zone gr_line gr_arc gr_rect gr_circle gr_poly gr_text gr_curve gr_text_box gr_bitmap dimension target property group image".split(" ")]),kicad_sch:new Set([...w,..."lib_symbols symbol sheet wire bus bus_entry junction no_connect label global_label hierarchical_label netclass_flag directive_label text text_box table image rule_area polyline rectangle circle arc sheet_instances symbol_instances group".split(" ")])};function A(J){if(J.length>4096)throw Error("expression length limit");let Q=[],te=0;for(;te<J.length;){if(/\s/.test(J[te])){te++;continue}let Xe=/^(?:(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|[a-zA-Z_][a-zA-Z_0-9]*|[+*/%^(),-])/.exec(J.slice(te));if(!Xe)throw Error("unsupported expression syntax, unit or function");if(Q.push(Xe[0]),te+=Xe[0].length,Q.length>256)throw Error("expression token limit")}let he=0,be=Xe=>{if(!Number.isFinite(Xe))throw Error("non-finite expression result or invalid domain");return Xe},De=Xe=>Q[he]===Xe?(he++,!0):!1;function Ke(Xe){if(Xe>32)throw Error("expression nesting limit");if(De("(")){let N=qe(0,Xe+1);if(!De(")"))throw Error("missing closing parenthesis");return N}let ve=Q[he++];if(ve===void 0)throw Error("missing expression operand");if(/^(?:\d|\.)/.test(ve))return be(Number(ve));if(!/^[a-z]/.test(ve)||!De("("))throw Error("unsupported expression syntax, unit or function");let Ee=[];if(!De(")")){do Ee.push(qe(0,Xe+1));while(De(","));if(!De(")"))throw Error("missing closing parenthesis")}let me={abs:Math.abs,sqrt:Math.sqrt,floor:Math.floor,ceil:Math.ceil};if(Object.prototype.hasOwnProperty.call(me,ve)){if(Ee.length!==1)throw Error("invalid function argument count");return be(me[ve](Ee[0]))}if(ve==="pow"){if(Ee.length!==2)throw Error("invalid function argument count");return be(Math.pow(Ee[0],Ee[1]))}if(["min","max","sum","avg"].includes(ve)){if(!Ee.length)throw Error("invalid function argument count");return be(ve==="min"?Math.min(...Ee):ve==="max"?Math.max(...Ee):Ee.reduce((N,re)=>N+re,0)/(ve==="avg"?Ee.length:1))}throw Error("unsupported expression function "+ve)}function qe(Xe,ve){if(ve>32)throw Error("expression nesting limit");let Ee=De("+")?qe(3,ve+1):De("-")?-qe(3,ve+1):Ke(ve+1),me={"+":1,"-":1,"*":2,"/":2,"%":2,"^":3};for(;Object.prototype.hasOwnProperty.call(me,Q[he])&&me[Q[he]]>=Xe;){let N=Q[he++],re=qe(me[N]+(N==="^"?0:1),ve+1);if((N==="/"||N==="%")&&re===0)throw Error("division or modulo by zero");Ee=be(N==="+"?Ee+re:N==="-"?Ee-re:N==="*"?Ee*re:N==="/"?Ee/re:N==="%"?Ee%re:Math.pow(Ee,re))}return be(Ee)}let $e=qe(0,0);if(he!==Q.length)throw Error("unsupported expression syntax, unit or function");return String(Object.is($e,-0)?0:$e)}function T(J,Q=()=>{}){let te=String(J??""),he=[],be=0;if(!te.includes("@{"))return{value:te,expressions:he};if(te.length>65536){let qe="text expression input limit";return Q(qe+"; preserved literally."),{value:te,expressions:[{raw:te,value:te,status:"unresolved",reason:qe}]}}let De=(qe,$e)=>{let Xe=1,ve=null;for(let Ee=$e+2;Ee<qe.length;Ee++){let me=qe[Ee];if(ve){if(me==="\\"){Ee++;continue}me===ve&&(ve=null);continue}if(me==='"'||me==="'"){ve=me;continue}if(me==="{")Xe++;else if(me==="}"&&!--Xe)return Ee}return-1};function Ke(qe,$e,Xe){if($e>16)throw Error("nested text expression limit");let ve="",Ee=0,me;for(;(me=qe.indexOf("@{",Ee))>=0;){if(be>=128){let V="text expression count limit";if(!Xe)throw Error(V);let O=qe.slice(me);return he.push({raw:O,value:O,status:"unresolved",reason:V}),Q(V+"; remaining text preserved literally."),ve+qe.slice(Ee)}ve+=qe.slice(Ee,me);let N=De(qe,me),re=qe.slice(me,N<0?qe.length:N+1),R=re,$;try{if(++be>128)throw Error("text expression count limit");if(N<0)throw Error("unclosed text expression");if(re.length>4099)throw Error("expression length limit");R=A(Ke(re.slice(2,-1),$e+1,!1))}catch(V){if($=V.message,!Xe)throw V;Q("Unsupported or invalid text expression: "+$+"; preserved literally.")}Xe&&he.push({raw:re,value:R,status:$?"unresolved":"resolved",...$?{reason:$}:{}}),ve+=R,Ee=N<0?qe.length:N+1}return ve+qe.slice(Ee)}return{value:Ke(te,0,!0),expressions:he}}function H(J,Q){let te=be=>{if(typeof be!="string"||be.length>4096||/[\x00-\x20\x7f]/.test(be))return null;if(/^#[^#/?\\]{1,64}$/.test(be))return{kind:"sheet",page:be.slice(1),target:be};if(!/^https?:\/\//i.test(be))return null;try{let De=new URL(be);return De.username||De.password||!De.hostname?null:{kind:"web",target:De.href}}catch{return null}};if(Q!==void 0&&Q!=="")return[te(Q)].filter(Boolean);let he=new Map;for(let be of String(J??"").slice(0,65536).matchAll(/https?:\/\/[^\s<>"\u0000-\u001f]+/gi)){let De=te(be[0].replace(/[.,;!]+$/,""));if(De&&he.set(De.target,De),he.size>=32)break}return[...he.values()]}function Y(J,Q={},te=()=>{}){let he=C=>{let j=Object.fromEntries((C||[]).filter(B=>Array.isArray(B)&&h(B[0])==="property").map(B=>[String(h(B[1])),String(h(B[2])??"")]));for(let B of["Reference","Value","Footprint","Datasheet","Description"])Object.prototype.hasOwnProperty.call(j,B)&&(j[B.toUpperCase()]=j[B]);return j},be=(Q.sheetContexts||[]).map(C=>({...C,fields:Object.assign(Object.create(null),C.fields)})),De=new Set(Q.unavailableVariables||[]),Ke=Object.create(null),qe=Object.create(null),$e=(J||[]).find(C=>Array.isArray(C)&&h(C[0])==="title_block"),Xe=(C,j,B)=>{Ke[C]=j,qe[C]=B};for(let C of $e||[]){if(!Array.isArray(C))continue;let j=String(h(C[0]));["title","date","rev","company"].includes(j)&&Xe({title:"TITLE",date:"ISSUE_DATE",rev:"REVISION",company:"COMPANY"}[j],String(h(C[1])??""),"Title block"),j==="comment"&&Xe("COMMENT"+h(C[1]),String(h(C[2])??""),"Title block")}let ve=Q.textVariables||Q.project?.text_variables||Q.projectSettings?.text_variables||{},Ee=Object.create(null);for(let[C,j]of Object.entries(ve))typeof j=="string"&&C.length<=200&&j.length<=65536&&(Ee[C]=j,Object.prototype.hasOwnProperty.call(Ke,C)||Xe(C,j,"Project"));for(let[C,j]of Object.entries(he(J)))Xe(C,j,"Drawing field");typeof Q.path=="string"&&(Xe("FILENAME",Q.path.split("/").pop(),"Drawing context"),Xe("FILEPATH",Q.path,"Drawing context"));for(let[C,j]of[["#",Q.sheetNumber],["##",Q.sheetCount],["SHEETNAME",Q.sheetName],["PROJECTNAME",Q.projectName]])j!==void 0&&Xe(C,String(j),"Sheet context");let me=new Map;for(let C of J||[]){if(!Array.isArray(C)||!["symbol","footprint","module"].includes(h(C[0])))continue;let j=he(C),B=j.Reference;B&&me.set(B,me.has(B)?null:j)}let N=(C,j)=>{if(Object.prototype.hasOwnProperty.call(C||{},j))return j;let B=Object.keys(C||{}).filter(W=>W.toUpperCase()===j.toUpperCase());return B.length===1?B[0]:null},re=new Set;function R(C,j={},B=0,W=!1){let K=String(C??""),ge=new Map,Ne=new Set;if(!K.includes("${")&&!K.includes("@{"))return{raw:K,value:K,fromVariable:!1,variables:[],unresolved:[],status:"literal"};j=Object.assign(Object.create(null),j);for(let Me of["Reference","Value","Footprint","Datasheet","Description"])Object.prototype.hasOwnProperty.call(j,Me)&&(j[Me.toUpperCase()]=j[Me]);let ne=0,we=(Me,Ce=[],tt=j,Ze=0,Ye=!1)=>Me.replace(/\$\{([^{}]{1,200})\}/g,(vt,Rt)=>{let Je=Rt.lastIndexOf(":"),_t=Je>0?me.get(Rt.slice(0,Je)):null,Et=Je>0?Rt.slice(Je+1):Rt,gt,Ht=Rt,lt,et=tt,St=Ze,At=Ye;if(!Ye&&Je>0&&me.has(Rt.slice(0,Je)))gt=_t,Ht=N(_t,Et),lt="Reference "+Rt.slice(0,Je),et=_t||{};else if(!Ye&&N(tt,Rt)!==null)gt=tt,Ht=N(tt,Rt),lt=tt===j?"Selected object field":"Referenced object field";else if(!Ye&&De.has(Rt))lt="Ambiguous sheet instance";else{let nr=Ye?-1:be.findIndex((pt,ft)=>ft>=Ze&&Object.prototype.hasOwnProperty.call(pt.fields,Rt));nr>Ze&&Object.prototype.hasOwnProperty.call(Ke,Rt)&&qe[Rt]!=="Project"&&(nr=-1),nr>=0?(gt=be[nr].fields,lt=be[nr].source||"Sheet field",et={},St=nr):(gt=Ye?Ee:Ke,lt=Ye?"Project":qe[Rt],(lt==="Project"||lt==="Title block")&&(et={},At=!0))}if(!gt||!Object.prototype.hasOwnProperty.call(gt,Ht)||typeof gt[Ht]!="string")return Ne.add(Rt),ge.set(Rt,{name:Rt,source:lt==="Ambiguous sheet instance"?lt:Je>0&&me.has(Rt.slice(0,Je))?"Ambiguous or missing reference field":"Unavailable",raw:vt}),re.has(Rt)||(re.add(Rt),te("Unresolved saved text variable "+vt+"; preserved literally.")),vt;let Wt=lt+"\0"+Rt+"\0"+St;return++ne>256||Ce.length>=8||Ce.includes(Wt)?(Ne.add(Rt),re.has(Rt)||(re.add(Rt),te("Text variable "+vt+" is recursive or exceeds the substitution limit; preserved literally.")),vt):(ge.set(Rt,{name:Rt,source:lt||"Saved field",raw:gt[Ht]}),we(gt[Ht],Ce.concat(Wt),et,St,At))}),xe=we(K,[],j,B,W);xe.length>65536&&(te("Expanded text exceeds the saved-text limit; preserved literally."),xe=K,Ne.add("Expansion limit"));let ke=T(xe,te);xe=ke.value;for(let Me of ke.expressions)Me.status==="unresolved"&&Ne.add(Me.raw);return{raw:K,value:xe,fromVariable:K.includes("${"),fromExpression:ke.expressions.length>0,expressions:ke.expressions,variables:[...ge.values()],unresolved:[...Ne],status:Ne.size?"unresolved":"resolved"}}let $=(C,j={})=>R(C,j).value;function V(C={},{includeShadowed:j=!1}={}){let B=new Set([...Object.keys(Ke),...be.flatMap(K=>Object.keys(K.fields)),...De,...Object.keys(C)]);for(let K of[...Object.values(Ke),...be.flatMap(ge=>Object.values(ge.fields)),...Object.values(C)])if(typeof K=="string")for(let ge of K.matchAll(/\$\{([^{}]{1,200})\}/g))B.add(ge[1]);let W=[...B].sort().slice(0,512).map(K=>{let ge=R("${"+K+"}",C),Ne=ge.variables.find(ne=>ne.name===K);return{name:K,source:Ne?.source||"Unavailable",raw:Ne?.raw??"${"+K+"}",value:ge.value,status:ge.status,unresolved:ge.unresolved}});if(j){let K=(ge,Ne,ne,we,xe)=>{W.some(ke=>ke.name===ge&&ke.source===Ne)||W.push({name:ge,source:Ne,raw:ne,value:we.value,status:we.status,unresolved:we.unresolved,scope:xe,shadowed:!0})};for(let[ge,Ne]of Object.entries(Ee))K(ge,"Project",Ne,R("${"+ge+"}",{},0,!0),"project");for(let[ge,Ne]of be.entries())for(let[ne,we]of Object.entries(Ne.fields))K(ne,Ne.source||"Sheet field",we,R("${"+ne+"}",{},ge),"sheet")}return W.slice(0,1024)}function O(C){let j=Object.create(null),B=Object.create(null);for(let[W,K]of Object.entries(C||{})){let ge=R(K,C);j[W]=ge.value,(ge.fromVariable||ge.fromExpression)&&(B[W]=ge)}return{values:j,provenance:B}}return{resolve:$,fields:he,inspect:R,list:V,properties:O}}function ee(J,Q,{rootFile:te=Q,instancePath:he,parse:be}={}){let De=(Ne,ne)=>(Ne||[]).find(we=>Array.isArray(we)&&h(we[0])===ne),Ke=(Ne,ne)=>h(De(Ne,ne)?.[1]),qe=new Map((J||[]).map(Ne=>[Ne.path,Ne])),$e=new Map,Xe=[],ve=Ne=>{if($e.has(Ne))return $e.get(Ne);let ne=qe.get(Ne),we=ne?.ast;try{!we&&ne&&be&&(we=be(ne.content,ne))}catch{}return $e.set(Ne,we),we},Ee=Ne=>Object.fromEntries((Ne||[]).filter(ne=>Array.isArray(ne)&&h(ne[0])==="property").map(ne=>[String(h(ne[1])),String(h(ne[2])??"")])),me=(Ne,ne)=>{if(typeof ne!="string"||!ne||/^(?:[a-z]+:|[\\/])/i.test(ne)||ne.includes("${"))return null;let we=Ne.split("/").slice(0,-1);for(let xe of ne.replace(/\\/g,"/").split("/"))if(xe===".."){if(!we.length)return null;we.pop()}else xe&&xe!=="."&&we.push(xe);return we.join("/")},N=0,re=!1;function R(Ne,ne,we,xe,ke){if(++N>512||ke.length>=32||ke.includes(Ne)){re=!0;return}let Me=ve(Ne);if(!Me)return;let Ce=we.every(Boolean)?"/"+we.join("/"):null,tt=xe.every(Ze=>typeof Ze=="string")?xe.length?"/"+xe.join("/")+"/":"/":void 0;Ne===Q&&Xe.push({instancePath:Ce,parentPath:ke.at(-1)||null,parentInstancePath:we.length>1&&we.every(Boolean)?"/"+we.slice(0,-1).join("/"):null,sheetContexts:ne,sheetName:xe.length?xe.at(-1):"/",sheetPath:tt,...W.has(Ce)?{sheetNumber:W.get(Ce)}:{}});for(let Ze of(Me||[]).filter(Ye=>Array.isArray(Ye)&&h(Ye[0])==="sheet")){let Ye=Ee(Ze),vt=me(Ne,Ye.Sheetfile??Ye["Sheet file"]),Rt=Ke(Ze,"uuid");if(!vt||!qe.has(vt))continue;let Je=Ye.Sheetname??Ye["Sheet name"],_t=we.concat(Rt),Et=xe.concat(Je),gt=_t.every(Boolean)?"/"+_t.join("/"):null;for(let lt of(Ze||[]).filter(et=>Array.isArray(et)&&h(et[0])==="instances"))for(let et of lt.filter(St=>Array.isArray(St)&&h(St[0])==="project"))for(let St of et.filter(At=>Array.isArray(At)&&h(At[0])==="path"))if(String(h(St[1])).replace(/\/$/,"")===Ce){let At=Ke(St,"page");gt&&At!==void 0&&W.set(gt,String(At))}let Ht={...Ye,SHEETFILE:Ye.Sheetfile??Ye["Sheet file"]};Je!==void 0&&(Ht.SHEETNAME=Je),Et.every(lt=>typeof lt=="string")&&(Ht.SHEETPATH="/"+Et.join("/")+"/"),R(vt,[{fields:Ht,source:Ht.SHEETPATH?"Sheet "+Ht.SHEETPATH:"Sheet fields ("+vt+")",instancePath:_t.every(Boolean)?"/"+_t.join("/"):null},...ne],_t,Et,ke.concat(Ne))}}let $=new Map;for(let Ne of(J||[]).slice(0,512))for(let ne of(ve(Ne.path)||[]).filter(we=>Array.isArray(we)&&h(we[0])==="sheet")){let we=Ee(ne),xe=me(Ne.path,we.Sheetfile??we["Sheet file"]);xe&&qe.has(xe)&&($.has(xe)||$.set(xe,new Set),$.get(xe).add(Ne.path))}let V=new Set,O=new Set;function C(Ne){if(O.has(Ne))return;O.add(Ne);let ne=$.get(Ne);if(!ne?.size)V.add(Ne);else for(let we of ne)C(we)}C(te),V.size===1?te=[...V][0]:V.size!==1&&(re=!0);let j=ve(te),B=Ke(j,"uuid"),W=new Map;for(let Ne of(j||[]).filter(ne=>Array.isArray(ne)&&h(ne[0])==="sheet_instances"))for(let ne of Ne.filter(we=>Array.isArray(we)&&h(we[0])==="path")){let we=String(h(ne[1])).split("/").filter(Boolean);we[0]!==B&&we.unshift(B);let xe=Ke(ne,"page");we.every(Boolean)&&xe!==void 0&&W.set("/"+we.join("/"),String(xe))}R(te,[],[B],[],[]);let K=he?Xe.filter(Ne=>Ne.instancePath?.replace(/\/$/,"")===String(he).replace(/\/$/,"")):Xe;if(K.length===1&&!re)return{...K[0],contextStatus:"resolved",rootPath:te,instances:Xe};let ge=[...new Set([...Xe.flatMap(Ne=>Ne.sheetContexts.flatMap(ne=>Object.keys(ne.fields))),"SHEETNAME","SHEETPATH","#"])];return{sheetContexts:[],unavailableVariables:ge,contextStatus:K.length>1?"ambiguous":"unavailable",instances:Xe}}function X(J){let Q=String(h(J?.[0])),te=$e=>h(J.find(Xe=>Array.isArray(Xe)&&h(Xe[0])===$e)?.[1]);if(!Array.isArray(J)||!S[Q])throw Error("Unsupported KiCad drawing root.");let he=String(te("generator_version")??""),be=te("version")??null,De=/^(\d+)(?:\.|$)/.exec(he),Ke=[];De&&Number(De[1])>10&&Ke.push(`KiCad ${he} is a forward-compatibility preview: only recognized saved constructs are rendered; new version features are not verified.`);let qe=[...new Set(J.filter(Array.isArray).map($e=>String(h($e[0]))).filter($e=>!S[Q].has($e)))];return qe.length&&Ke.push("Unrecognized saved drawing constructs omitted: "+qe.slice(0,40).join(", ")+(qe.length>40?" \u2026":"")),{majorVersion:De?Number(De[1]):null,kind:Q,generatorVersion:he||null,formatVersion:be,forwardPreview:!!(De&&Number(De[1])>10),unknown:qe,warnings:Ke}}let G=Object.freeze([{id:"drawing",label:"Saved schematic / PCB geometry",since:8,implemented:!0},{id:"review",label:"Selection, properties, comments and comparison",since:8,implemented:!0},{id:"hierarchy",label:"Sheet navigation and cross-sheet highlighting",since:8,implemented:!0},{id:"copper",label:"Saved copper fills and zone outlines",since:8,implemented:!0},{id:"models",label:"Repository-linked 3D models",since:8,implemented:!0},{id:"embeddedAssets",label:"Embedded fonts and 3D assets",since:9,implemented:!0,limitation:"Uses saved TrueType or OpenType faces and supported embedded PCB models. Invalid or oversized assets are skipped."},{id:"componentClasses",label:"Component classes",since:9,implemented:!0,limitation:"Shows saved PCB and schematic classes and rule-area matches supported by drawing geometry. Dynamic PCB conditions and custom DRC expressions require native KiCad."},{id:"netclassRuleAreas",label:"Schematic net-class rule areas",since:9,implemented:!0,limitation:"Shows saved directives, rule areas and sheet-local net assignments. Bus expansion and cross-sheet rule resolution require native KiCad."},{id:"schematicTables",label:"Native schematic tables (horizontal)",since:9,implemented:!0,limitation:"Horizontal tables with saved cell geometry are rendered. Rotated tables are omitted with a drawing diagnostic; table-cell contextual variables are not implemented."}]);function ae(J,Q){let te=G.find(be=>be.id===Q);if(!te)return{available:!1,reason:"This feature is not recognized by the viewer.",upgrade:!1};let he=J?.majorVersion;return Number.isInteger(he)&&he<te.since?{available:!1,upgrade:!0,reason:`${te.label} requires KiCad ${te.since} or later. This drawing identifies itself as KiCad ${J.generatorVersion||he}. Upgrade to the latest stable KiCad and save a separate project copy. `+(te.implemented?"":"This viewer also needs support for this feature; upgrading the project alone will not enable it.")}:te.implemented?{available:!0,upgrade:!1,reason:te.limitation||"Available for recognized saved data; existing geometry and connectivity limits still apply."}:{available:!1,upgrade:!1,reason:`${te.label} is not implemented in this viewer. Upgrading KiCad alone will not enable it.`}}function _e(J,Q){let te=J.ownerDocument||m.document,he=te.createElement("button");he.type="button",he.className="compatibility-button",he.title="Saved-file compatibility and feature availability",J.append(he);let be=te.createElement("dialog");be.className="compatibility-dialog",be.setAttribute("aria-label","Saved-file compatibility"),te.body.append(be);let De=(Xe,ve)=>{let Ee=te.createElement(Xe);return Ee.textContent=ve,Ee};function Ke(Xe){let ve=ae(Q(),Xe.id);if(ve.available)return!0;if(be.replaceChildren(De("h2",Xe.label),De("p",ve.reason)),ve.upgrade){let me=De("a","Get the latest stable KiCad");me.href="https://www.kicad.org/download/",me.target="_blank",me.rel="noopener noreferrer",be.append(me)}let Ee=De("button","Close");return Ee.type="button",Ee.onclick=()=>be.close(),be.append(Ee),be.open||be.showModal(),!1}function qe(){let Xe=Q();be.replaceChildren(De("h2","Saved-file compatibility"),De("p",Xe?.generatorVersion?`KiCad ${Xe.generatorVersion} \xB7 saved format ${Xe.formatVersion??"unknown"}`:"Generator version unknown; no major version inferred from the format date."));for(let Ee of G){let me=ae(Xe,Ee.id),N=De("button",`${me.available?"Available":"Blocked"} \xB7 ${Ee.label}${me.available?"":" \xB7 Why?"}`);N.type="button",N.className="compatibility-feature",N.setAttribute("data-blocked",String(!me.available)),N.title=me.reason,N.onclick=()=>me.available?void 0:Ke(Ee),be.append(N)}Xe?.unknown?.length&&be.append(De("p","Omitted saved constructs: "+Xe.unknown.join(", ")+". These are renderer limitations; upgrading alone is not a remedy."));let ve=De("button","Close");ve.type="button",ve.onclick=()=>be.close(),be.append(ve),be.open||be.showModal()}be.addEventListener("click",Xe=>{if(Xe.target===be){let ve=be.getBoundingClientRect();(Xe.clientX<ve.left||Xe.clientX>ve.right||Xe.clientY<ve.top||Xe.clientY>ve.bottom)&&be.close()}}),he.onclick=qe;let $e=()=>{let Xe=Q();he.textContent=Xe?.majorVersion?`KiCad ${Xe.majorVersion} \xB7 Features`:"File features",be.open&&be.close()};return $e(),{refresh:$e,check(Xe){let ve=G.find(Ee=>Ee.id===Xe);return ve?Ke(ve):!1},dispose(){be.remove(),he.remove()}}}m.KiCadFileCompatibility={embeddedFonts:p,textResolver:Y,textContext:ee,textExpressions:T,textLinks:H,inspect:X,features:G,capability:ae,mountStatus:_e},typeof om=="object"&&om.exports&&(om.exports=m.KiCadFileCompatibility)})(typeof globalThis=="object"?globalThis:ZE)});var hm=$n(($E,cm)=>{(m=>{"use strict";function h(p,w="",S={}){let{width:A,height:T}=p||{};if(!Number.isFinite(A)||!Number.isFinite(T)||A<=20||T<=20)return[];let H=[],Y=p.titleBlock||{},ee=te=>H.push({color:"#a0a0a0",width:.1524,frame:!0,path:w,...te}),X=(te,he,be,De,Ke="title-block")=>ee({type:"line",points:[{x:te,y:he},{x:be,y:De}],kind:Ke}),G=(te,he,be,De,Ke)=>ee({type:"polygon",points:[{x:te,y:he},{x:be,y:he},{x:be,y:De},{x:te,y:De}],kind:Ke}),ae=(te,he,be,De=1.5,Ke={})=>{be==null||be===""||ee({type:"text",x:te,y:he,text:String(be),size:De,fontWidth:De,fontHeight:De,angle:0,align:"left",baseline:"middle",kind:"title-block",...Ke})};G(0,0,A,T,"page"),G(10,10,A-10,T-10,"page-frame"),G(12,12,A-12,T-12,"page-frame");for(let te=60;te<A-10;te+=50)X(te,10,te,12,"page-zone"),X(te,T-12,te,T-10,"page-zone");for(let te=35,he=1;te<A-10;te+=50,he++)ae(te,11,he,1.3,{kind:"page-zone"}),ae(te,T-11,he,1.3,{kind:"page-zone"});for(let te=60;te<T-10;te+=50)X(10,te,12,te,"page-zone"),X(A-12,te,A-10,te,"page-zone");for(let te=35,he=0;te<T-10;te+=50,he++)ae(11,te,String.fromCharCode(65+he),1.3,{kind:"page-zone",align:"center"}),ae(A-11,te,String.fromCharCode(65+he),1.3,{kind:"page-zone",align:"center"});let _e=A-10,J=T-10,Q=_e-110;G(Q,J-34,_e-2,J-2,"title-block");for(let te of[5.5,8.5,12.5,18.5])X(Q,J-te,_e-2,J-te);X(_e-90,J-8.5,_e-90,J-5.5),X(_e-26,J-8.5,_e-26,J-2),ae(_e-87,J-6.9,`Date: ${Y.date||""}`),ae(_e-109,J-4.1,S.kicadVersion?`KiCad E.D.A. ${S.kicadVersion}`:"KiCad E.D.A."),ae(_e-24,J-6.9,`Rev: ${Y.rev||""}`,1.5,{bold:!0}),ae(_e-109,J-6.9,`Size: ${p.format||"User"}`),ae(_e-24,J-4.1,`Id: ${S.sheetNumber||1}/${S.sheetCount||1}`),ae(_e-109,J-10.7,`Title: ${Y.title||""}`,2,{bold:!0,italic:!0}),ae(_e-109,J-14.3,`File: ${String(w).split(/[\\/]/).pop()||""}`),ae(_e-109,J-17,`Sheet: ${S.sheetName||"/"}`),ae(_e-109,J-20,Y.company,1.5,{bold:!0});for(let te=0;te<4;te++)ae(_e-109,J-23-te*3,Y.comments?.[te]);return H}m.KiCadWorksheet={build:h},typeof cm=="object"&&cm.exports&&(cm.exports=m.KiCadWorksheet)})(typeof globalThis=="object"?globalThis:$E)});var cv=$n((fF,um)=>{(m=>{"use strict";let h={"F.Cu":["#c83434",1],"B.Cu":["#4d7fc4",1],"In1.Cu":["#7fc87f",1],"In2.Cu":["#ce7d2c",1],"In3.Cu":["#4fcbcb",1],"In4.Cu":["#db628b",1],"In5.Cu":["#a7a5c6",1],"In6.Cu":["#28ccd9",1],"In7.Cu":["#e8b2a7",1],"In8.Cu":["#f2eda1",1],"In9.Cu":["#8dcb81",1],"In10.Cu":["#ed7c33",1],"In11.Cu":["#5bc3eb",1],"In12.Cu":["#f76f8e",1],"In13.Cu":["#a7a5c6",1],"In14.Cu":["#28ccd9",1],"In15.Cu":["#e8b2a7",1],"In16.Cu":["#f2eda1",1],"In17.Cu":["#ed7c33",1],"In18.Cu":["#5bc3eb",1],"In19.Cu":["#f76f8e",1],"In20.Cu":["#a7a5c6",1],"In21.Cu":["#28ccd9",1],"In22.Cu":["#e8b2a7",1],"In23.Cu":["#f2eda1",1],"In24.Cu":["#ed7c33",1],"In25.Cu":["#5bc3eb",1],"In26.Cu":["#f76f8e",1],"In27.Cu":["#a7a5c6",1],"In28.Cu":["#28ccd9",1],"In29.Cu":["#e8b2a7",1],"In30.Cu":["#f2eda1",1],"F.Adhes":["#840084",1],"B.Adhes":["#000084",1],"F.Paste":["#b4a09a",.9],"B.Paste":["#00c2c2",.9],"F.SilkS":["#f2eda1",1],"B.SilkS":["#e8b2a7",1],"F.Mask":["#d864ff",.4],"B.Mask":["#02ffee",.4],"F.Fab":["#afafaf",1],"B.Fab":["#585d84",1],"F.CrtYd":["#ff26e2",1],"B.CrtYd":["#26e9ff",1],"Edge.Cuts":["#d0d2cd",1],Margin:["#ff26e2",1],"Dwgs.User":["#c2c2c2",1],"Cmts.User":["#5994dc",1],"Eco1.User":["#b4dbd2",1],"Eco2.User":["#d8c852",1],"User.1":["#c2c2c2",1],"User.2":["#5994dc",1],"User.3":["#b4dbd2",1],"User.4":["#d8c852",1],"User.5":["#c2c2c2",1],"User.6":["#5994dc",1],"User.7":["#b4dbd2",1],"User.8":["#d8c852",1],"User.9":["#e8b2a7",1],"User.10":["#5994dc",1],"User.11":["#b4dbd2",1],"User.12":["#d8c852",1],"User.13":["#c2c2c2",1],"User.14":["#5994dc",1],"User.15":["#b4dbd2",1],"User.16":["#d8c852",1],"User.17":["#c2c2c2",1],"User.18":["#5994dc",1],"User.19":["#b4dbd2",1],"User.20":["#d8c852",1],"User.21":["#c2c2c2",1],"User.22":["#5994dc",1],"User.23":["#b4dbd2",1],"User.24":["#d8c852",1],"User.25":["#c2c2c2",1],"User.26":["#5994dc",1],"User.27":["#b4dbd2",1],"User.28":["#d8c852",1],"User.29":["#c2c2c2",1],"User.30":["#5994dc",1],"User.31":["#b4dbd2",1],"User.32":["#d8c852",1],"User.33":["#c2c2c2",1],"User.34":["#5994dc",1],"User.35":["#b4dbd2",1],"User.36":["#d8c852",1],"User.37":["#c2c2c2",1],"User.38":["#5994dc",1],"User.39":["#b4dbd2",1],"User.40":["#d8c852",1],"User.41":["#c2c2c2",1],"User.42":["#5994dc",1],"User.43":["#b4dbd2",1],"User.44":["#d8c852",1],"User.45":["#c2c2c2",1]};for(let X of Object.values(h))Object.freeze(X);Object.freeze(h);let p=X=>h[String(X)]?.[0]||"#c2c2c2",w=X=>h[String(X)]?.[1]??1,S=X=>{let G=p(X),ae=w(X);return ae===1?G:`rgba(${parseInt(G.slice(1,3),16)},${parseInt(G.slice(3,5),16)},${parseInt(G.slice(5,7),16)},${ae})`},A=Object.freeze({"F.Cu":"#fa6f68","B.Cu":"#63a5ff","F.SilkS":"#e8dcae","B.SilkS":"#b5c8df","F.Fab":"#b2bbc9","B.Fab":"#8d9ab0","F.CrtYd":"#c59be0","B.CrtYd":"#7bc6cf","Edge.Cuts":"#d6deea","F.Mask":"#b197d7","B.Mask":"#77bdb5","F.Paste":"#d2afa0","B.Paste":"#98c9ce"}),T=Object.freeze({"F.Cu":"#b9474c","B.Cu":"#3268ae","F.SilkS":"#766126","B.SilkS":"#596a87","F.Fab":"#647086","B.Fab":"#606c83","F.CrtYd":"#8c519e","B.CrtYd":"#257b85","Edge.Cuts":"#465368","F.Mask":"#9279b8","B.Mask":"#4d968a","F.Paste":"#9d796a","B.Paste":"#448b93"});function H(X,G=!0){let ae=(G?A:T)[String(X)]||p(X),_e=w(X);return _e===1?ae:`rgba(${parseInt(ae.slice(1,3),16)},${parseInt(ae.slice(3,5),16)},${parseInt(ae.slice(5,7),16)},${_e})`}function Y(X){let G=String(X||"").toLowerCase(),ae=/bottom|\bbot\b/.test(G),_e=ae?"B.":"F.";if(/drill|plated/.test(G))return null;if(/outline|profile/.test(G))return"Edge.Cuts";if(/copper/.test(G)){if(/inner|inr/.test(G)){let J=/copper,\s*l(\d+),\s*inr/.exec(G),Q=/inner copper\s*(\d+)/.exec(G),te=J?Number(J[1])-1:Q?Number(Q[1]):0;return te>=1&&te<=30?"In"+te+".Cu":null}return _e+"Cu"}return/mask/.test(G)?_e+"Mask":/silk|legend/.test(G)?_e+"SilkS":/paste/.test(G)?_e+"Paste":null}let ee=Object.freeze({entries:h,hexFor:p,opacityFor:w,colorFor:S,reviewColorFor:H,fabricationLayer:Y});m.KiCadLayerColors=ee,typeof um=="object"&&um.exports&&(um.exports=ee)})(globalThis)});var QE=$n((JE,zs)=>{(m=>{"use strict";let h=m.KiCadFileCompatibility||(typeof zs=="object"&&zs.exports?lm():null),p=m.KiCadWorksheet||(typeof zs=="object"&&zs.exports?hm():null),w=m.KiCadDesignDiff||(typeof zs=="object"&&zs.exports?To():null),S=Number.isSafeInteger(w?.MAX_RENDER_PRIMITIVES)&&w.MAX_RENDER_PRIMITIVES>0?w.MAX_RENDER_PRIMITIVES:25e4,A=C=>C&&typeof C=="object"&&!Array.isArray(C)?C.quoted:C,T=C=>Array.isArray(C)?String(A(C[0])):"",H=(C,j)=>Array.isArray(C)?C.filter(B=>Array.isArray(B)&&T(B)===j):[],Y=(C,j)=>Array.isArray(C)?C.find(B=>Array.isArray(B)&&T(B)===j):void 0,ee=(C,j)=>A(Y(C,j)?.[1]),X=(C,j=0)=>{let B=Number(A(C));return Number.isFinite(B)?B:j},G=(C,j)=>{let B=Y(C,j);return!B||!Number.isFinite(Number(A(B[1])))||!Number.isFinite(Number(A(B[2])))?null:{x:X(B[1]),y:X(B[2])}},ae=C=>{let j=C?.[1];if(!(j instanceof Float64Array))return H(C,"xy").map(W=>({x:X(W[1]),y:X(W[2])}));let B=new Array(j.length/2);for(let W=0;W<B.length;W++)B[W]={x:j[W*2],y:j[W*2+1]};return B},_e=C=>ae(Y(C,"pts"));function J(C){if(C?.[1]instanceof Float64Array)return C[1].length>=6;let j=0;for(let B of C||[])if(T(B)==="xy"&&++j===3)return!0;return!1}function Q(){let C=new WeakMap,j=0,B=0;return{get(W){let K=C.get(W);return K||(K=ae(W),C.set(W,K),j++,B+=K.length),K},release(){C=new WeakMap,j=B=0},stats(){return{contours:j,vertices:B}}}}let te=C=>String(ee(C,"uuid")||ee(C,"tstamp")||""),he=(C,j)=>Array.isArray(C)&&C.some(B=>!Array.isArray(B)&&A(B)===j),be=(C,j)=>Array.isArray(C)&&C.some(B=>{if(Array.isArray(B)&&T(B)===j){let W=A(B[1]);return W===void 0||W===!0||W==="yes"||W==="true"||W===1}return!Array.isArray(B)&&!(B&&typeof B=="object")&&B===j}),De=C=>be(C,"hide")||be(Y(C,"effects"),"hide")||be(Y(Y(C,"effects"),"font"),"hide"),Ke=C=>X(Y(C,"at")?.[3]),qe=Math.PI,$e=C=>C*qe/180,Xe=C=>Math.round(C*1e8)/1e8,ve=m.KiCadLayerColors||(typeof zs=="object"&&zs.exports?cv():null),Ee=C=>ve.colorFor(C),me={A0:[1189,841],A1:[841,594],A2:[594,420],A3:[420,297],A4:[297,210],A5:[210,148],A:[279.4,215.9],B:[431.8,279.4],C:[558.8,431.8],D:[863.6,558.8],E:[1117.6,863.6],USLetter:[279.4,215.9],USLegal:[355.6,215.9],USLedger:[431.8,279.4]};function N(C,j){let B=Y(C,"paper"),W=String(A(B?.[1])||"A4"),K=me[W];W==="User"&&(K=[X(B?.[2]),X(B?.[3])]),(!K||K.some(we=>we<=0))&&(j.push(`Unsupported PCB paper ${W}; using A4 page dimensions.`),K=me.A4);let ge=B?.some(we=>A(we)==="portrait"),Ne=Y(C,"title_block"),ne=Array(9).fill("");for(let we of H(Ne,"comment")){let xe=X(we[1]);xe>=1&&xe<=9&&(ne[xe-1]=String(A(we[2])||""))}return{width:ge?K[1]:K[0],height:ge?K[0]:K[1],name:W,title:String(ee(Ne,"title")||""),date:String(ee(Ne,"date")||""),revision:String(ee(Ne,"rev")||""),company:String(ee(Ne,"company")||""),comments:ne,format:W,titleBlock:{title:String(ee(Ne,"title")||""),date:String(ee(Ne,"date")||""),rev:String(ee(Ne,"rev")||""),company:String(ee(Ne,"company")||""),comments:ne}}}function re(C,j){let B=Math.cos($e(j)),W=Math.sin($e(j));return K=>({x:Xe(C.x+K.x*B+K.y*W),y:Xe(C.y-K.x*W+K.y*B)})}let R=C=>C;function $(C,j,B){let W=C/2,K=j/2,ge=Math.max(0,Math.min(B,W,K));if(ge<1e-6)return[{x:-W,y:-K},{x:W,y:-K},{x:W,y:K},{x:-W,y:K}];let Ne=[];for(let[ne,we,xe]of[[W-ge,-K+ge,-90],[W-ge,K-ge,0],[-W+ge,K-ge,90],[-W+ge,-K+ge,180]])for(let ke=0;ke<=6;ke++){let Me=$e(xe+ke*15);Ne.push({x:ne+ge*Math.cos(Me),y:we+ge*Math.sin(Me)})}return Ne}function V(C,j){let B=Math.min(C,j)/2;if(Math.abs(C-j)<1e-9)return null;if(C>j){let W=C/2-B,K=[];for(let ge=0;ge<=12;ge++){let Ne=$e(-90+ge*15);K.push({x:W+B*Math.cos(Ne),y:B*Math.sin(Ne)})}for(let ge=0;ge<=12;ge++){let Ne=$e(90+ge*15);K.push({x:-W+B*Math.cos(Ne),y:B*Math.sin(Ne)})}return K}return V(j,C).map(W=>({x:W.y,y:W.x}))}function O(C,j="",B={}){let W=[],K=[],ge=0;if(T(C)!=="kicad_pcb")throw new Error("Expected a KiCad PCB AST.");let Ne=B.deferZonePoints?Q():null,ne=h?.inspect(C);W.push(...ne?.warnings||[]);let we=h?.textResolver(C,{...B,path:j},lt=>{W.includes(lt)||W.push(lt)}),xe=new Map,ke=N(C,W),Me=(Y(C,"layers")||[]).slice(1).filter(Array.isArray).map(lt=>String(A(lt[1]))),Ce=lt=>{if(K.length>=S)throw new Error("PCB has too many render primitives.");K.push(lt)};function tt(lt,et,St){let At=Y(lt,"pts"),Wt=Ne?null:ae(At);if(Ne?!J(At):Wt.length<3)return;let nr=Ne&&At[1]instanceof Float64Array?At[1]:null,pt;if(nr){let ft=1/0,Bt=1/0,Yt=-1/0,kr=-1/0;for(let Gr=0;Gr<nr.length;Gr+=2)ft=Math.min(ft,nr[Gr]),Bt=Math.min(Bt,nr[Gr+1]),Yt=Math.max(Yt,nr[Gr]),kr=Math.max(kr,nr[Gr+1]);pt={x:ft,y:Bt,w:Yt-ft,h:kr-Bt}}for(let ft of et){let Bt={type:"polygon",points:Wt,layer:ft,color:Ee(ft),...St};nr&&Object.defineProperties(Bt,{zoneCoordinates:{value:nr},zoneBounds:{value:pt}}),Ne&&Object.defineProperty(Bt,"points",{get:()=>Ne.get(At),enumerable:!0,configurable:!0}),Ce(Bt)}}let Ze=new Set,Ye=(lt,et)=>{Ze.has(lt)||W.length>=1e3||(Ze.add(lt),W.push(`${lt}${te(et)?` (example ${te(et)})`:""} is not drawn exactly.`))};if(!B.silkscreenOnly)if(p)for(let lt of B.worksheet?B.worksheet(ke,j,B,et=>we?.resolve(et)??et,et=>{W.length<1e3&&!W.includes(et)&&W.push(et)}):p.build(ke,j))Ce({...lt,layer:"Worksheet"});else W.push("Default worksheet module is unavailable.");function vt(lt,et,St={}){let At=ee(Y(lt,"stroke"),"type");return{layer:et,color:Ee(et),...["dash","dot","dash_dot","dash_dot_dot"].includes(At)?{lineStyle:At}:{},uuid:te(lt)||St.uuid||void 0,ownerUuid:St.ownerUuid||St.uuid||void 0,reference:St.reference||void 0,kind:St.kind||T(lt),...St.kind==="pad"?{name:St.name,pinNumber:St.pinNumber,pinName:St.pinName,netName:St.netName,padCenter:St.padCenter,padWidth:St.padWidth,padHeight:St.padHeight,padAngle:St.padAngle}:{}}}function Rt(lt){let et=Y(lt,"fill");return["yes","solid"].includes(A(et?.[1]))||ee(et,"type")==="solid"}function Je(lt){let et=Y(lt,"stroke");return Math.max(.01,X(Y(et,"width")?.[1],X(ee(lt,"width"),.15)))}function _t(lt,et,St=R,At={}){let Wt=T(lt),nr=vt(lt,et,At),pt=Je(lt),ft=(Bt,Yt,kr=!1)=>{Yt.some(Gr=>!Gr)||Ce({type:Bt,points:Yt.map(St),width:pt,fill:kr,...nr})};if(["gr_line","fp_line"].includes(Wt))ft("line",[G(lt,"start"),G(lt,"end")]);else if(["gr_curve","fp_curve"].includes(Wt)){let Bt=H(Y(lt,"pts"),"xy").map(Yt=>({x:Number(A(Yt[1])),y:Number(A(Yt[2]))}));try{let Yt=w.cubicBezierPoints(Bt.map(St));if(ge+Yt.length>25e4)throw Error("Bezier point budget reached.");ge+=Yt.length,Ce({type:"polyline",points:Yt,width:pt,...nr})}catch{Ye("Invalid or over-budget "+Wt,lt)}}else if(["gr_arc","fp_arc","arc"].includes(Wt)){let Bt=G(lt,"start"),Yt=G(lt,"mid"),kr=G(lt,"end");Bt&&Yt&&kr?Ce({type:"arc",start:St(Bt),mid:St(Yt),end:St(kr),width:pt,...nr}):Ye(Wt,lt)}else if(["gr_rect","fp_rect"].includes(Wt)){let Bt=G(lt,"start"),Yt=G(lt,"end");Bt&&Yt&&ft("polygon",[{x:Bt.x,y:Bt.y},{x:Yt.x,y:Bt.y},{x:Yt.x,y:Yt.y},{x:Bt.x,y:Yt.y}],Rt(lt))}else if(["gr_circle","fp_circle"].includes(Wt)){let Bt=G(lt,"center"),Yt=G(lt,"end");if(Bt&&Yt){let kr=St(Bt),Gr=St(Yt);Ce({type:"circle",x:kr.x,y:kr.y,r:Math.hypot(Gr.x-kr.x,Gr.y-kr.y),width:pt,fill:Rt(lt),...nr})}}else if(["gr_poly","fp_poly"].includes(Wt)){let Bt=_e(lt);Bt.length>=3&&ft("polygon",Bt,Rt(lt))}else if(["gr_text","fp_text","property"].includes(Wt)){if(De(lt))return;let Bt=G(lt,"at"),Yt=A(Wt==="property"?lt[2]:lt[Wt==="fp_text"?2:1]),kr=Y(lt,"effects"),Gr=Y(kr,"font"),Qr=Y(Gr,"size"),ii=Y(kr,"justify")?.slice(1).map(ur=>String(A(ur)))||[];Bt&&Yt!=null&&Ce({type:"text",text:we?.resolve(Yt,xe.get(At.uuid)||{})??String(Yt),...St(Bt),size:X(Qr?.[2],1),angle:-Ke(lt),width:.15,property:Wt==="property"?String(A(lt[1])):Wt==="fp_text"&&A(lt[1])==="reference"?"Reference":Wt==="fp_text"&&A(lt[1])==="value"?"Value":void 0,...ii.includes("mirror")?{mirror:!0}:{},fontFace:ee(Gr,"face"),bold:he(Gr,"bold")||!!Y(Gr,"bold"),italic:he(Gr,"italic")||!!Y(Gr,"italic"),mirrored:ii.includes("mirror"),align:ii.includes("left")?"left":ii.includes("right")?"right":"center",baseline:ii.includes("top")?"top":ii.includes("bottom")?"bottom":"middle",...nr})}else Ye(Wt,lt)}function Et(lt,et,St){let At=G(lt,"at")||{x:0,y:0},Wt=St(At),nr=String(A(lt[3])||"rect"),pt=Y(lt,"size"),ft=X(pt?.[1]),Bt=X(pt?.[2]);if(ft<=0||Bt<=0){Ye("Pad with invalid size",lt);return}let Yt=(Y(lt,"layers")||[]).slice(1).map(Xt=>String(A(Xt))),kr=[...new Set(Yt.flatMap(Xt=>Xt.startsWith("*.")?Me.filter(qt=>qt.endsWith(Xt.slice(1))):Xt==="F&B.Cu"?["F.Cu","B.Cu"]:[Xt]))];if(!kr.length){Ye("Pad without renderable layers",lt);return}let Gr=Ke(lt),Qr=re(Wt,Gr),Zr=te(lt)||et.uuid,ii=Y(lt,"drill"),ur=A(ii?.[1])==="oval",Gi=X(ii?.[ur?2:1]),yt=ur?X(ii?.[3]):Gi,jt=Y(ii,"offset"),Jt=jt?{x:X(jt[1]),y:X(jt[2])}:{x:0,y:0},sr=Qr(Jt);for(let Xt of kr){let qt={layer:Xt,color:Ee(Xt),uuid:Zr,ownerUuid:et.uuid,reference:et.reference,kind:"pad",name:String(A(lt[1])||""),pinNumber:String(A(lt[1])||""),padCenter:{...Wt},padWidth:ft,padHeight:Bt,padAngle:-Gr,pinName:String(ee(lt,"pinfunction")||""),netName:String(A(Y(lt,"net")?.[2])||""),padType:String(A(lt[2])||""),fill:!0};if(nr==="circle")Ce({type:"pad",x:Wt.x,y:Wt.y,r:ft/2,...qt});else if(nr==="custom"){let gr=Y(lt,"options"),ar=String(ee(gr,"anchor")||"");if(ar==="rect")Ce({type:"pad",points:$(ft,Bt,0).map(Qr),...qt});else if(ar==="circle")Math.abs(ft-Bt)>1e-8&&Ye("Noncircular custom pad anchor",lt),Ce({type:"pad",x:Wt.x,y:Wt.y,r:Math.min(ft,Bt)/2,...qt});else{Ye(`Unsupported custom pad anchor ${ar||"(missing)"}`,lt);continue}let Ar=Y(lt,"primitives");if(Ar)for(let mr of Ar.slice(1)){if(!Array.isArray(mr))continue;let Br=T(mr);if(!["gr_poly","gr_line","gr_arc","gr_circle","gr_rect"].includes(Br)){Ye(`Unsupported custom pad primitive ${Br}`,lt);continue}let Dr=ee(mr,"width");if(["gr_line","gr_arc"].includes(Br)&&Dr!==void 0&&X(Dr)<=0){Ye(`Zero-width custom pad ${Br}`,lt);continue}_t(mr,Xt,Qr,qt)}}else{let gr;if(nr==="rect")gr=$(ft,Bt,0);else if(nr==="roundrect")gr=$(ft,Bt,Math.min(ft,Bt)*X(ee(lt,"roundrect_rratio"),.25));else if(nr==="oval")gr=V(ft,Bt)||$(ft,Bt,Math.min(ft,Bt)/2);else{Ye(`Unsupported ${nr} pad`,lt);continue}Ce({type:"pad",points:gr.map(Qr),...qt})}if(Gi>0&&yt>0){let gr={layer:Xt,color:"#111b25",fill:!0,hole:!0,uuid:Zr,ownerUuid:et.uuid,reference:et.reference,kind:"drill",objectCategory:"pads"};if(ur&&Math.abs(Gi-yt)>1e-9){let ar=re(sr,Gr);Ce({type:"polygon",points:V(Gi,yt).map(ar),...gr})}else Ce({type:"circle",x:sr.x,y:sr.y,r:Gi/2,...gr})}}}for(let lt of C.slice(1)){if(!Array.isArray(lt))continue;let et=T(lt),St=String(ee(lt,"layer")||"F.Cu");if(!(B.silkscreenOnly&&!["footprint","module"].includes(et)&&!["F.SilkS","B.SilkS"].includes(St)))if(et==="segment"){let At=G(lt,"start"),Wt=G(lt,"end");At&&Wt&&Ce({type:"line",points:[At,Wt],layer:St,color:Ee(St),width:X(ee(lt,"width"),.2),fill:!1,uuid:te(lt)||void 0,kind:"track"})}else if(et==="arc")_t(lt,St);else if(et==="via"){let At=G(lt,"at"),Wt=X(ee(lt,"size")),nr=X(ee(lt,"drill"));if(!At||Wt<=0){Ye("Via with invalid dimensions",lt);continue}let pt=(Y(lt,"layers")||[]).slice(1).map(Yt=>String(A(Yt))),ft=Me.filter(Yt=>Yt.endsWith(".Cu")),Bt=pt.filter(Yt=>Yt.endsWith(".Cu"));if(Bt.length>=2){let Yt=ft.indexOf(Bt[0]),kr=ft.indexOf(Bt.at(-1));Yt>=0&&kr>=0&&(Bt=ft.slice(Math.min(Yt,kr),Math.max(Yt,kr)+1))}for(let Yt of Bt.length?Bt:["F.Cu","B.Cu"])Ce({type:"circle",...At,r:Wt/2,layer:Yt,color:"#c5aa6c",fill:!0,uuid:te(lt)||void 0,kind:"via"}),nr>0&&Ce({type:"circle",...At,r:nr/2,layer:Yt,color:"#111b25",fill:!0,hole:!0,uuid:te(lt)||void 0,kind:"drill",objectCategory:"vias"})}else if(et==="footprint"){let At=G(lt,"at");if(!At){Ye("Footprint without placement",lt);continue}let Wt=Ke(lt),nr=re(At,Wt),pt=H(lt,"property"),ft=we?.fields(lt)||{};for(let Zr of H(lt,"fp_text")){let ii=String(A(Zr[1]));ii==="reference"&&(ft.Reference=String(A(Zr[2])??"")),ii==="value"&&(ft.Value=String(A(Zr[2])??""))}ft.Reference!==void 0&&(ft.REFERENCE=ft.Reference),ft.Value!==void 0&&(ft.VALUE=ft.Value),te(lt)&&xe.set(te(lt),ft);let Bt=ft.Reference||"",Yt={uuid:te(lt),reference:Bt},kr=K.length;for(let Zr of lt.slice(1)){if(!Array.isArray(Zr))continue;let ii=T(Zr),ur=String(ee(Zr,"layer")||St);B.silkscreenOnly&&!["F.SilkS","B.SilkS"].includes(ur)||(ii==="pad"?Et(Zr,Yt,nr):(["fp_line","fp_arc","fp_rect","fp_circle","fp_poly","fp_curve","fp_text"].includes(ii)||ii==="property")&&_t(Zr,ur,nr,Yt))}let Qr=K.slice(kr).filter(Zr=>Zr.type==="pad").flatMap(Zr=>Zr.points||(Zr.r?[{x:Zr.x-Zr.r,y:Zr.y-Zr.r},{x:Zr.x+Zr.r,y:Zr.y+Zr.r}]:[]));if(Qr.length&&Yt.uuid){let Zr=Qr.map(Jt=>Jt.x),ii=Qr.map(Jt=>Jt.y),ur=Math.min(...Zr)-.3,Gi=Math.max(...Zr)+.3,yt=Math.min(...ii)-.3,jt=Math.max(...ii)+.3;if(K.length>=S)throw new Error("PCB has too many render primitives.");K.splice(kr,0,{type:"polygon",points:[{x:ur,y:yt},{x:Gi,y:yt},{x:Gi,y:jt},{x:ur,y:jt}],layer:St,color:"#000000",fill:!1,stroke:!1,pick:!0,uuid:Yt.uuid,ownerUuid:Yt.uuid,reference:Bt,kind:"footprint-hit"})}}else if(et==="zone"){let At=H(lt,"filled_polygon");if(At.length)for(let nr of At){let pt=String(ee(nr,"layer")||St);tt(nr,[pt],{fill:!0,stroke:!1,opacity:.22,uuid:te(lt)||void 0,kind:"zone"})}else Ye("Unfilled zone",lt);let Wt=(Y(lt,"layers")||[]).slice(1).map(nr=>String(A(nr)));for(let nr of H(lt,"polygon"))tt(nr,Wt.length?Wt:[St],{fill:!1,width:.15,uuid:te(lt)||void 0,kind:"zone-outline"})}else["gr_line","gr_arc","gr_rect","gr_circle","gr_poly","gr_curve","gr_text"].includes(et)?_t(lt,St):["gr_text_box","gr_bitmap","dimension","target"].includes(et)&&Ye(et,lt)}let gt=lt=>lt.frame?-100:lt.kind==="footprint-hit"?-20:lt.kind==="zone"?-10:lt.kind==="zone-outline"?-9:lt.kind==="track"?0:lt.kind==="via"?1:lt.kind==="pad"?2:lt.kind==="drill"?3:0;K.sort((lt,et)=>gt(lt)-gt(et));let Ht={primitives:K,page:ke,warnings:W,compatibility:ne,embeddedFonts:h?.embeddedFonts?.(C),layers:Me.length?Me:[...new Set(K.map(lt=>lt.layer))],path:j};return Ne&&Object.defineProperties(Ht,{releaseZonePoints:{value:Ne.release},zonePointStats:{value:Ne.stats}}),Ht}m.KiCadPCBRenderer={build:O,colorFor:Ee},typeof zs=="object"&&zs.exports&&(zs.exports=m.KiCadPCBRenderer)})(typeof globalThis=="object"?globalThis:JE)});var tS=$n((eS,dm)=>{(m=>{"use strict";function p(X,{maxBytes:G=8388608,padded:ae=!1,host:_e=m}={}){if(!Number.isSafeInteger(G)||G<0||G>8388608||typeof X!="string"||X.length>112e5)throw Error("Invalid or oversized model base64.");let J=X.length,Q=X.endsWith("==")?2:X.endsWith("=")?1:0;if(J%4===1||(Q||ae)&&J%4!==0)throw Error("Invalid model base64 padding.");let te=J-Q;for(let qe=0;qe<te;qe++){let $e=X.charCodeAt(qe);if(!($e>=65&&$e<=90||$e>=97&&$e<=122||$e>=48&&$e<=57||$e===43||$e===47))throw Error("Invalid model base64.")}let he=Math.floor(J*3/4)-Q;if(he>G)throw Error("Model base64 exceeds its decoded byte limit.");let be=_e.Uint8Array?.fromBase64;if(typeof be=="function")return be.call(_e.Uint8Array,X);let De=_e.atob(X),Ke=new Uint8Array(he);for(let qe=0;qe<he;qe++)Ke[qe]=De.charCodeAt(qe);return Ke}function w(X,G=!1){let ae=(1n<<64n)-1n,_e=0x87c37b91114253d5n,J=0x4cf5ad432745937fn,Q=(ve,Ee)=>(ve<<Ee|ve>>64n-Ee)&ae,te=(ve,Ee)=>{let me=0n;for(let N=0;N<Ee;N++)me|=BigInt(X[ve+N]||0)<<BigInt(N*8);return me},he=ve=>(ve^=ve>>33n,ve=ve*0xff51afd7ed558ccdn&ae,ve^=ve>>33n,ve=ve*0xc4ceb9fe1a85ec53n&ae,ve^ve>>33n),be=0xabba2345n,De=be,Ke=new DataView(X.buffer,X.byteOffset,X.byteLength),qe=X.length-X.length%16;for(let ve=0;ve<qe;ve+=16){let Ee=Ke.getBigUint64(ve,!0),me=Ke.getBigUint64(ve+8,!0);Ee=Q(Ee*_e&ae,31n)*J&ae,be^=Ee,be=(Q(be,27n)+De)*5n+0x52dce729n&ae,me=Q(me*J&ae,33n)*_e&ae,De^=me,De=(Q(De,31n)+be)*5n+0x38495ab5n&ae}let $e=G?Math.ceil(X.length/4)*4:X.length,Xe=$e%16;return Xe>8&&(De^=Q(te(qe+8,Xe-8)*J&ae,33n)*_e&ae),Xe&&(be^=Q(te(qe,Math.min(8,Xe))*_e&ae,31n)*J&ae),be^=BigInt($e),De^=BigInt($e),be=be+De&ae,De=De+be&ae,be=he(be),De=he(De),be=be+De&ae,De=De+be&ae,be.toString(16).padStart(16,"0")+De.toString(16).padStart(16,"0")}function S(X){let G=new DataView(X.buffer,X.byteOffset,X.byteLength);if(X.length<6||G.getUint32(0,!0)!==4247762216)throw Error("Embedded model is not Zstandard.");let ae=X[4],_e=!!(ae&32),J=ae>>>6;if(ae&24)throw Error("Unsupported Zstandard frame flags.");let Q=5;if(!_e){let Ke=X[Q++];if(2**(10+(Ke>>>3))*(1+(Ke&7)/8)>8388608)throw Error("Embedded model window exceeds 8 MiB.")}if([0,1,2,4][ae&3])throw Error("Embedded model requires a Zstandard dictionary.");let he=J?[0,2,4,8][J]:_e?1:0;if(!he||Q+he>X.length)throw Error("Embedded model has no bounded content size.");let be=0;for(let Ke=0;Ke<he;Ke++)be+=X[Q++]*2**(8*Ke);if(J===1&&(be+=256),!Number.isSafeInteger(be)||be<=0||be>8388608)throw Error("Embedded model exceeds 8 MiB.");let De=!1;for(;!De;){if(Q+3>X.length)throw Error("Truncated embedded model block.");let Ke=X[Q]|X[Q+1]<<8|X[Q+2]<<16;Q+=3,De=!!(Ke&1);let qe=Ke>>>1&3,$e=Ke>>>3;if(qe===3||$e>131072)throw Error("Invalid embedded model block.");if(Q+=qe===1?1:$e,Q>X.length)throw Error("Truncated embedded model block.")}if(ae&4&&(Q+=4),Q!==X.length)throw Error("Embedded model has trailing or missing frame data.");return be}async function A(X,G=m.fzstd?.decompress,ae=8388608){let _e=X?.base64,J=p(_e,{padded:!0});if(J.length>8388608)throw Error("Compressed embedded model exceeds 8 MiB.");let Q=S(J);if(Q>ae)throw Error("Embedded asset exceeds its allocation budget.");if(typeof G!="function")throw Error("Embedded model decoder unavailable.");let te=G(J,new Uint8Array(Q));if(!(te instanceof Uint8Array)||te.length!==Q)throw Error("Embedded model size mismatch.");if(/^[a-f0-9]{64}$/i.test(X.checksum||"")){let he=new Uint8Array(await m.crypto.subtle.digest("SHA-256",te));if(Array.from(he,De=>De.toString(16).padStart(2,"0")).join("")!==X.checksum.toLowerCase())throw Error("Embedded model checksum mismatch.")}else if(/^[a-f0-9]{32}$/i.test(X.checksum||"")){let he=X.checksum.toLowerCase();if(w(te)!==he&&w(te,!0)!==he)throw Error("Embedded model checksum mismatch.")}else throw Error("Embedded model checksum is missing or unsupported.");return te}function T(X){let G=new DataView(X.buffer,X.byteOffset,X.byteLength),ae=new Set;if(G.byteLength<12||![65536,1330926671,1953658213].includes(G.getUint32(0)))return ae;let _e=G.getUint16(4);if(_e>256||12+_e*16>G.byteLength)return ae;for(let J=12;J<12+_e*16;J+=16){if(G.getUint32(J)!==1851878757)continue;let Q=G.getUint32(J+8),te=G.getUint32(J+12);if(te<6||Q+te>G.byteLength)break;let he=G.getUint16(Q+2),be=Q+G.getUint16(Q+4);if(he>2048||be<Q+6+he*12||be>Q+te)break;let De=new TextDecoder("utf-16be");for(let Ke=0;Ke<he;Ke++){let qe=Q+6+Ke*12,$e=G.getUint16(qe),Xe=G.getUint16(qe+6);if(![0,3].includes($e)||![1,4,6,16].includes(Xe))continue;let ve=G.getUint16(qe+8),Ee=be+G.getUint16(qe+10);if(!ve||ve>512||ve%2||Ee+ve>Q+te)continue;let me=De.decode(X.subarray(Ee,Ee+ve)).trim().toLowerCase();me&&!me.includes("\0")&&ae.add(me)}break}return ae}function H(X){let G=new DataView(X.buffer,X.byteOffset,X.byteLength),ae=G.getUint16(4);for(let _e=12;_e<12+ae*16;_e+=16){if(G.getUint32(_e)!==1751474532)continue;let J=G.getUint32(_e+8),Q=G.getUint32(_e+12);if(Q<46||J+Q>X.length)break;let te=G.getUint16(J+44);return{weight:te&1?"bold":"normal",style:te&2?"italic":"normal"}}return{weight:"normal",style:"normal"}}let Y=0;function ee(X,G,ae,_e,J=m,Q){if(!X?.length||!G.size||typeof J.FontFace!="function"||!J.document?.fonts)return null;let te=++Y,he=new Map,be=[],De=new Set,Ke=J.document.fonts,qe=!1,$e=8*1024*1024,Xe;async function ve(){for(let Ee of X){if(await new Promise(me=>setTimeout(me,0)),qe||$e<=0)return;try{if(Xe??=Q?await Q():J.fzstd?.decompress,qe)return;let me=await A(Ee,Xe,Math.min($e,2*1024*1024));if(qe)return;$e-=me.length;let N=[...T(me)].filter(R=>G.has(R));if(!N.length)continue;let re=H(me);for(let R of N){let $=JSON.stringify([R,re.weight,re.style]);if(De.has($))continue;let V=he.get(R)||"kivi-embedded-"+te+"-"+he.size,O=await new J.FontFace(V,me,re).load();if(qe)return;Ke.add(O),be.push(O),De.add($),he.set(R,V)}}catch(me){qe||_e?.(Ee.name,me.message)}}!qe&&be.length&&ae()}return ve(),{family(Ee){return typeof Ee=="string"?he.get(Ee.trim().toLowerCase()):void 0},dispose(){qe=!0;for(let Ee of be)Ke.delete(Ee);be.length=0,he.clear()}}}m.KiCadEmbeddedFonts={mount:ee,fontNames:T},m.KiCadEmbeddedModels={decode:A,decodeBase64:p,frameSize:S,murmur:w,MAX_BYTES:8388608,fontNames:T,mountFonts:ee},typeof dm=="object"&&dm.exports&&(dm.exports=m.KiCadEmbeddedModels)})(typeof globalThis=="object"?globalThis:eS)});var rS=$n((mF,pm)=>{(m=>{"use strict";let A=me=>Number.isFinite(me?.x)&&Number.isFinite(me?.y);function T(me,N,re=1){let R=Number.isFinite(me)&&me>0?me:1,$=Number.isFinite(N)&&N>0?N:1,V=Number.isFinite(re)&&re>0?re:1,O=Math.min(V,3,Math.sqrt(8e6/R/$),8192/R,8192/$);return{ratio:O,width:Math.max(1,Math.floor(R*O)),height:Math.max(1,Math.floor($*O))}}let H=Object.freeze({dark:Object.freeze({"#000000":"#e8edf5","#840000":"#f2bb74","#a90000":"#ff8587","#008400":"#59dba8","#008484":"#65c6ed","#000080":"#71aaff","#a0a0a0":"#718298","#725600":"#8bbcff"}),light:Object.freeze({"#000000":"#283447","#840000":"#8e4358","#a90000":"#9a4051","#008400":"#217864","#008484":"#2c6f89","#000080":"#3e64a3","#a0a0a0":"#a3adbb","#725600":"#48678f"})});function Y(me,N){return H[N?"dark":"light"][String(me).toLowerCase()]||me}function ee(me,N,re){if(![me,N,re].every(A))return null;let R=2*(me.x*(N.y-re.y)+N.x*(re.y-me.y)+re.x*(me.y-N.y));if(Math.abs(R)<1e-10)return null;let $=me.x*me.x+me.y*me.y,V=N.x*N.x+N.y*N.y,O=re.x*re.x+re.y*re.y,C=($*(N.y-re.y)+V*(re.y-me.y)+O*(me.y-N.y))/R,j=($*(re.x-N.x)+V*(me.x-re.x)+O*(N.x-me.x))/R,B=Math.atan2(me.y-j,me.x-C),W=Math.atan2(N.y-j,N.x-C),K=Math.atan2(re.y-j,re.x-C),ge=Ne=>(Ne+Math.PI*4)%(Math.PI*2);return{x:C,y:j,r:Math.hypot(me.x-C,me.y-j),start:B,end:K,ccw:ge(W-B)>ge(K-B)}}function X(me){if(me.type==="arc"){let N=ee(me.start,me.mid,me.end);if(N){let re=N.end-N.start;if(N.ccw)for(;re>0;)re-=Math.PI*2;else for(;re<0;)re+=Math.PI*2;return Array.from({length:33},(R,$)=>({x:N.x+Math.cos(N.start+re*$/32)*N.r,y:N.y+Math.sin(N.start+re*$/32)*N.r}))}return[me.start,me.end].filter(A)}if(me.points)return me.points.filter(A);if(me.type==="circle"||me.type==="pad"&&me.r)return[{x:me.x-me.r,y:me.y-me.r},{x:me.x+me.r,y:me.y+me.r}];if(me.type==="text"){let N=me.fontHeight||me.size||1.27,re=String(me.text||"").split(`
`),R=Math.max(...re.map(W=>Array.from(W).length))*(me.fontWidth||N)*.65,$=N*1.4,V=(re.length-1)*N*(me.lineSpacing||1.5)/2,O=(me.angle||0)*Math.PI/180,C=me.align==="left"?0:me.align==="right"?-R:-R/2,j=(me.baseline==="top"?0:me.baseline==="bottom"?-$:-$/2)-V,B=j+$+V*2;return[{x:C,y:j},{x:C+R,y:j},{x:C+R,y:B},{x:C,y:B}].map(W=>({x:me.x+W.x*Math.cos(O)-W.y*Math.sin(O),y:me.y+W.x*Math.sin(O)+W.y*Math.cos(O)}))}return A(me)?[me]:[]}function G(me,N=!1){let re=1/0,R=1/0,$=-1/0,V=-1/0;for(let O of me){if(O.hidden||O.frame&&!N)continue;let C=(O.width||0)/2;if(O.zoneBounds){let{x:j,y:B,w:W,h:K}=O.zoneBounds;re=Math.min(re,j-C),R=Math.min(R,B-C),$=Math.max($,j+W+C),V=Math.max(V,B+K+C)}else for(let j of X(O))re=Math.min(re,j.x-C),R=Math.min(R,j.y-C),$=Math.max($,j.x+C),V=Math.max(V,j.y+C)}return re===1/0?null:{x:re,y:R,w:Math.max(.01,$-re),h:Math.max(.01,V-R)}}function ae(me,N,re){let R=re.x-N.x,$=re.y-N.y,V=R*R+$*$,O=V?Math.max(0,Math.min(1,((me.x-N.x)*R+(me.y-N.y)*$)/V)):0;return Math.hypot(me.x-N.x-O*R,me.y-N.y-O*$)}function _e(me,N){let re=!1;for(let R=0,$=N.length-1;R<N.length;$=R++){let V=N[R],O=N[$];V.y>me.y!=O.y>me.y&&me.x<(O.x-V.x)*(me.y-V.y)/(O.y-V.y)+V.x&&(re=!re)}return re}function J(me,N){let re=me.zoneCoordinates,R={x:re[re.length-2],y:re[re.length-1]},$={x:0,y:0},V=!1,O=1/0;for(let C=0;C<re.length;C+=2)$.x=re[C],$.y=re[C+1],R.y>N.y!=$.y>N.y&&N.x<($.x-R.x)*(N.y-R.y)/($.y-R.y)+R.x&&(V=!V),O=Math.min(O,ae(N,R,$)),R.x=$.x,R.y=$.y;return me.fill&&V?0:Math.max(0,O-(me.width||.1)/2)}function Q(me,N,re){if(me.hole||me.frame)return!1;if(me.zoneCoordinates)return J(me,N)<=re;if(me.type==="circle"||me.type==="pad"&&me.r){let V=Math.hypot(N.x-me.x,N.y-me.y);return me.fill?V<=me.r+re:Math.abs(V-me.r)<=re+(me.width||.1)/2}let R=X(me);if((me.type==="pad"||me.type==="text"||me.type==="image"||me.type==="bezier"&&me.fill||me.type==="polygon"&&(me.fill||["symbol","footprint","footprint-hit","sheet","global_label","hierarchical_label","sheet-pin"].includes(me.kind)))&&_e(N,R))return!0;let $=re+(me.width||.1)/2;for(let V=1;V<R.length;V++)if(ae(N,R[V-1],R[V])<=$)return!0;return me.type==="polygon"&&R.length>2&&ae(N,R.at(-1),R[0])<=$}function te(me,N,re=.01){if(!me||me.frame||me.hole)return 1/0;if(me.zoneCoordinates)return J(me,N);if(me.type==="circle"||me.type==="pad"&&me.r){let V=Math.hypot(N.x-me.x,N.y-me.y);return Math.max(0,(me.fill?V-me.r:Math.abs(V-me.r))-(me.width||.1)/2)}let R=X(me),$=1/0;if((["pad","text","image"].includes(me.type)||me.type==="bezier"&&me.fill||me.type==="polygon"&&(me.fill||["symbol","footprint","footprint-hit","sheet","global_label","hierarchical_label","sheet-pin"].includes(me.kind)))&&_e(N,R))return 0;for(let V=1;V<R.length;V++)$=Math.min($,ae(N,R[V-1],R[V]));return["polygon","pad","image","text"].includes(me.type)&&R.length>2&&($=Math.min($,ae(N,R.at(-1),R[0]))),Math.max(0,$-(me.width||.1)/2)}function he(me){if(me.type==="text")return null;if(me.zoneBounds){let{x:re,y:R,w:$,h:V}=me.zoneBounds,O=(me.width||.15)/2;return{x:re-O,y:R-O,w:$+O*2,h:V+O*2}}if(me.type==="arc"){let re=ee(me.start,me.mid,me.end);if(re){let R=re.r+(me.width||.15)/2;return{x:re.x-R,y:re.y-R,w:2*R,h:2*R}}}let N=G([{...me,hidden:!1,width:me.width||.15}],!0);return N&&[N.x,N.y,N.w,N.h].every(Number.isFinite)?N:null}class be{constructor(N){this.primitives=N,this.length=N.length,this.cells=new Map,this.overflow=[];let re=N.map(he),R=1/0,$=1/0,V=-1/0,O=-1/0;for(let C of re)C&&(R=Math.min(R,C.x),$=Math.min($,C.y),V=Math.max(V,C.x+C.w),O=Math.max(O,C.y+C.h));this.box={x:R,y:$,w:Math.max(.01,V-R),h:Math.max(.01,O-$)},this.references=0;for(let C=0;C<re.length;C++){let j=re[C];if(!j){this.overflow.push(C);continue}let B=this.range(j),W=(B.x1-B.x0+1)*(B.y1-B.y0+1);if(W>64||this.references+W>1e6){this.overflow.push(C);continue}for(let K=B.y0;K<=B.y1;K++)for(let ge=B.x0;ge<=B.x1;ge++){let Ne=K*64+ge;this.cells.has(Ne)||this.cells.set(Ne,[]),this.cells.get(Ne).push(C)}this.references+=W}}range(N){let re=(R,$,V)=>Math.max(0,Math.min(63,Math.floor((R-$)/V*64)));return{x0:re(N.x,this.box.x,this.box.w),x1:re(N.x+N.w,this.box.x,this.box.w),y0:re(N.y,this.box.y,this.box.h),y1:re(N.y+N.h,this.box.y,this.box.h)}}query(N){let re=this.range(N);if(re.x0===0&&re.y0===0&&re.x1===63&&re.y1===63)return this.primitives;let R=this.queryMarks??=new Uint8Array(this.length),$=this.queryIndices??=new Uint32Array(this.length),V=0,O=B=>{R[B]||(R[B]=1,$[V++]=B)};for(let B of this.overflow)O(B);if(N.x+N.w>=this.box.x&&N.x<=this.box.x+this.box.w&&N.y+N.h>=this.box.y&&N.y<=this.box.y+this.box.h)for(let B=re.y0;B<=re.y1;B++)for(let W=re.x0;W<=re.x1;W++){let K=this.cells.get(B*64+W);if(K)for(let ge of K)O(ge)}let C=$.subarray(0,V).sort(),j=new Array(V);for(let B=0;B<V;B++){let W=C[B];R[W]=0,j[B]=this.primitives[W]}return j}}function De(me,N,re=300){let R=[],$=[],V=N.zoom,O=N.bbox;if(!(V>0)||!Number.isFinite(V))return R;let C=(B,W,K,ge,Ne,ne)=>{if(R.length>=re||!Number.isFinite(K+ge+Ne+ne))return;let we=N.world_to_screen({x:K,y:ge}),xe=Ne*Math.PI/180,ke=ne*(Math.max(...W.split(`
`).map(Ye=>Ye.length))*.65+1),Me=ne*1.4*W.split(`
`).length,Ce=Math.abs(Math.cos(xe))*ke+Math.abs(Math.sin(xe))*Me,tt=Math.abs(Math.sin(xe))*ke+Math.abs(Math.cos(xe))*Me,Ze={x:we.x-Ce/2-3,y:we.y-tt/2-3,w:Ce+6,h:tt+6};Ze.x<0||Ze.y<0||Ze.x+Ze.w>N.width||Ze.y+Ze.h>N.height||$.some(Ye=>Ze.x<Ye.x+Ye.w&&Ze.x+Ze.w>Ye.x&&Ze.y<Ye.y+Ye.h&&Ze.y+Ze.h>Ye.y)||($.push(Ze),R.push({text:W,x:we.x,y:we.y,angle:Ne,size:ne,primitive:B}))},j=new Set;for(let[B,W]of me){if(R.length>=re)break;let K=W;if(B.kind==="pad"&&!B.hole&&B.layer?.endsWith(".Cu")){if(B.padWidth&&B.padHeight&&Math.min(B.padWidth,B.padHeight)*V<13)continue;let ge=String(B.pinNumber??B.name??"");if(ge.length>160||String(B.pinName||"").length>160||/[\x00-\x1f\x7f]/.test(ge+String(B.pinName||"")))continue;let Ne=JSON.stringify([B.ownerUuid,B.uuid,ge,B.padCenter]);if(j.has(Ne))continue;let ne=B.padCenter&&B.padWidth&&B.padHeight?null:he(B),we=B.padCenter||(ne?{x:ne.x+ne.w/2,y:ne.y+ne.h/2}:null);if(!we)continue;let xe=(B.padWidth||ne?.w||0)*V,ke=(B.padHeight||ne?.h||0)*V;if(Math.min(xe,ke)<13)continue;let Me=Math.min(18,Math.max(9,Math.min(xe,ke)*.25)),Ce=typeof K=="string"&&K.length<=160?K:"",Ze=[[ge,B.pinName].filter(Boolean).join(" "),Ce].filter(Boolean);if(!Ze.length)continue;let Ye=Ze.join(`
`);if(Math.max(...Ze.map(Je=>Je.length))*Me*.65>Math.max(xe,ke)*1.7)continue;let Rt=R.length;C(B,Ye,we.x,we.y,0,Me),R.length>Rt&&j.add(Ne);continue}if(!(typeof K!="string"||!K.trim()||K.length>160||B.hole||!B.layer?.endsWith(".Cu"))){if(B.kind==="track"&&B.type==="line"&&B.points?.length===2){let[ge,Ne]=B.points,ne=Ne.x-ge.x,we=Ne.y-ge.y,xe=Math.min(11,B.width*V*.8);if(!(xe>=7))continue;let ke=0,Me=1;for(let[Ze,Ye]of[[-ne,ge.x-O.x],[ne,O.x+O.w-ge.x],[-we,ge.y-O.y],[we,O.y+O.h-ge.y]])Ze===0?Ye<0&&(Me=-1):Ze<0?ke=Math.max(ke,Ye/Ze):Me=Math.min(Me,Ye/Ze);if(Me<=ke||Math.hypot(ne,we)*(Me-ke)*V<xe*(K.length*.65+1))continue;let Ce=Math.atan2(we,ne*(N.flipped?-1:1))*180/Math.PI;Ce>90&&(Ce-=180),Ce<-90&&(Ce+=180);let tt=(ke+Me)/2;C(B,K,ge.x+ne*tt,ge.y+we*tt,Ce,xe)}else if(B.kind==="zone"&&B.fill&&B.points?.length>=3){let ge=B.points,Ne=11,ne=Ne*(K.length*.65+1)/V,we=1/0,xe=-1/0;for(let Ce of ge)we=Math.min(we,Ce.y),xe=Math.max(xe,Ce.y);we=Math.max(we,O.y),xe=Math.min(xe,O.y+O.h);let ke=Ce=>{let tt=[];for(let Ye=0,vt=ge.length-1;Ye<ge.length;vt=Ye++){let Rt=ge[vt],Je=ge[Ye];Rt.y>Ce!=Je.y>Ce&&tt.push(Rt.x+(Ce-Rt.y)*(Je.x-Rt.x)/(Je.y-Rt.y))}tt.sort((Ye,vt)=>Ye-vt);let Ze=[];for(let Ye=0;Ye+1<tt.length;Ye+=2)Ze.push([Math.max(tt[Ye],O.x),Math.min(tt[Ye+1],O.x+O.w)]);return Ze},Me=null;for(let Ce of[.5,.25,.75]){let tt=we+(xe-we)*Ce;for(let[Ze,Ye]of ke(tt)){let vt=(Ze+Ye)/2;Ye-Ze<ne||Me&&Ye-Ze<=Me.width||[-.8,0,.8].every(Rt=>ke(tt+Rt*Ne/V).some(([Je,_t])=>vt-ne/2>=Je&&vt+ne/2<=_t))&&(Me={x:vt,y:tt,width:Ye-Ze})}}Me&&C(B,K,Me.x,Me.y,0,Ne)}}}return R}class Ke{constructor(N=800,re=600){this.width=N,this.height=re,this.zoom=4,this.center={x:0,y:0,set(R,$){this.x=R,this.y=$}},this.flipped=!1,this.quarterTurns=0}get quarterTurns(){return this._quarterTurns}set quarterTurns(N){this._quarterTurns=Number.isFinite(N)?Math.round((N%4+4)%4*90*1e9)/1e9/90%4:0;let re=this._quarterTurns*Math.PI/2;this.rotationCos=Math.abs(Math.cos(re))<1e-12?0:Math.cos(re),this.rotationSin=Math.abs(Math.sin(re))<1e-12?0:Math.sin(re)}get bbox(){let N=Math.abs(this.rotationCos),re=Math.abs(this.rotationSin),R=(N*this.width+re*this.height)/this.zoom,$=(re*this.width+N*this.height)/this.zoom;return{x:this.center.x-R/2,y:this.center.y-$/2,w:R,h:$}}set bbox(N){if(!N||![N.x,N.y,N.w,N.h].every(Number.isFinite)||N.w<=0||N.h<=0)return;this.center.set(N.x+N.w/2,N.y+N.h/2);let re=Math.abs(this.rotationCos),R=Math.abs(this.rotationSin);this.zoom=Math.max(.001,Math.min(1e4,Math.min(this.width/(re*N.w+R*N.h),this.height/(R*N.w+re*N.h))))}worldDeltaToScreen(N){let re=N.x*this.zoom*(this.flipped?-1:1),R=N.y*this.zoom;return{x:re*this.rotationCos-R*this.rotationSin,y:re*this.rotationSin+R*this.rotationCos}}screenDeltaToWorld(N){let re=N.x/this.zoom,R=N.y/this.zoom;return{x:(re*this.rotationCos+R*this.rotationSin)*(this.flipped?-1:1),y:-re*this.rotationSin+R*this.rotationCos}}screen_to_world(N){let re=this.screenDeltaToWorld({x:N.x-this.width/2,y:N.y-this.height/2});return{x:this.center.x+re.x,y:this.center.y+re.y}}world_to_screen(N){let re=this.worldDeltaToScreen({x:N.x-this.center.x,y:N.y-this.center.y});return{x:this.width/2+re.x,y:this.height/2+re.y}}}let qe=Object.freeze([["arcs","Arcs"],["pads","Pads"],["vias","Vias"],["tracks","Tracks"],["texts","Texts"],["fills","Fills"],["polygons","Polygons"],["regions","Regions"],["graphics","Graphics"],["bodies","3D bodies"],["dimensions","Dimensions"],["rooms","Rooms"]].map(([me,N])=>Object.freeze({id:me,label:N})));function $e(me){return!me||me.frame||me.kind==="footprint-hit"?null:me.objectCategory?me.objectCategory:me.kind==="drill"?me.ownerUuid?"pads":"vias":me.kind==="pad"?"pads":me.kind==="via"?"vias":me.type==="text"?"texts":me.type==="arc"?"arcs":me.kind==="track"||me.kind==="segment"?"tracks":me.kind==="zone"?"fills":me.kind==="zone-outline"?"polygons":["gr_poly","fp_poly"].includes(me.kind)?me.fill?"regions":"polygons":me.fill?"fills":"graphics"}function Xe(me,N={}){if(!me||me.frame)return!0;let re=$e(me),R=N.hiddenTypes;if(re&&(R?.has?.(re)||Array.isArray(R)&&R.includes(re)))return!1;let $=me.layer||"";return!(N.side==="top"&&$.startsWith("B."))&&!(N.side==="bottom"&&$.startsWith("F."))}class ve extends EventTarget{constructor(N,re={}){if(super(),this.loadFontDecoder=re.loadFontDecoder,this.onFontWarning=re.onFontWarning,this.host=N,this.geometryBounds=new WeakMap,this.frameRequest=null,this.canvas=document.createElement("canvas"),this.canvas.className="owned-canvas",this.canvas.tabIndex=0,this.canvas.setAttribute("aria-label","Interactive KiCad drawing; click to select, right-drag to pan, wheel to zoom"),N.append(this.canvas),this.ctx=this.canvas.getContext("2d"),!this.ctx)throw new Error("Canvas2D rendering is unavailable.");this.viewport={camera:new Ke},this.primitives=[],this.visibleLayers=new Set,this.dark=!!re.dark,this.pcb=!!re.pcb,this.grid=!1,this.selected=null,this.drag=null,this.netHighlight=null,this.netPrimitives=new Set,this.isolateNet=!1,this.paperVisible=!this.pcb,this.activeLayer="F.Cu",this.focusedLayer=null,this.layerFocusMode="dim",this.layerSnapshot=null,this.layerPresetName=null,this.acceleration=re.acceleration==="off"?"off":"auto",this.motion=null,this.motionSnapshot=null,this.motionActive=!1,this.motionFailed=!1,this.motionTimer=null,this.wheelMotion=!1,this.touchMotion=!1,this.layers={query_point:V=>this.query(V).map(O=>({bbox:{context:{uuid:O.uuid,reference:O.reference,kind:O.kind,name:O.name,pinNumber:O.pinNumber,pinName:O.pinName,ownerUuid:O.ownerUuid,connectPoint:O.connectPoint,parent:O.ownerUuid?{uuid:O.ownerUuid}:null},primitive:O}}))},this.handlers=[];let R=(V,O,C)=>{this.canvas.addEventListener(V,O,C),this.handlers.push(()=>this.canvas.removeEventListener(V,O,C))};R("pointerdown",V=>{(V.button===1||V.button===2)&&(V.preventDefault(),this.drag={x:V.clientX,y:V.clientY,id:V.pointerId,moved:!1},this.canvas.setPointerCapture(V.pointerId))}),R("pointerleave",()=>this.reportPartHover(null)),R("pointermove",V=>{if(!this.partHoverEnabled||this.drag||this.wheelMotion||this.touchMotion||V.pointerType==="touch"||V.buttons)return;let O=this.canvas.getBoundingClientRect(),C=this.viewport.camera.screen_to_world({x:V.clientX-O.left,y:V.clientY-O.top}),j=this.query(C,5,B=>!!(B.ownerUuid||B.reference))[0];this.reportPartHover(j||null)}),R("pointermove",V=>{if(!this.drag||V.pointerId!==this.drag.id)return;let O=V.clientX-this.drag.x,C=V.clientY-this.drag.y;if(!O&&!C)return;this.drag.moved=!0;let j=this.viewport.camera;j.center.x-=O/j.zoom*(j.flipped?-1:1),j.center.y-=C/j.zoom,this.drag.x=V.clientX,this.drag.y=V.clientY,this.requestDraw()});let $=V=>{if(!this.drag||this.drag.id!==V.pointerId)return;let O=this.drag.moved;this.drag=null,O&&this.requestDraw()};R("pointerup",V=>{$(V),this.canvas.hasPointerCapture(V.pointerId)&&this.canvas.releasePointerCapture(V.pointerId)}),R("pointercancel",$),R("lostpointercapture",$),R("click",V=>{if(V.pointerType==="touch"&&this.touchNetPick?.(V))return;let O=this.canvas.getBoundingClientRect(),C=this.viewport.camera.screen_to_world({x:V.clientX-O.left,y:V.clientY-O.top}),j=this.query(C)[0];this.select(j?{primitive:j,context:{uuid:j.uuid,reference:j.reference,kind:j.kind,name:j.name,pinNumber:j.pinNumber,pinName:j.pinName,ownerUuid:j.ownerUuid,connectPoint:j.connectPoint,parent:j.ownerUuid?{uuid:j.ownerUuid}:null}}:null,{multi:!!(V.ctrlKey||V.metaKey||V.shiftKey)})}),R("wheel",V=>{V.preventDefault();let O=this.canvas.getBoundingClientRect(),C={x:V.clientX-O.left,y:V.clientY-O.top},j=this.viewport.camera,B=j.screen_to_world(C);j.zoom=Math.max(.001,Math.min(1e4,j.zoom*Math.exp(-Math.max(-100,Math.min(100,V.deltaY))*.004)));let W=j.screen_to_world(C);j.center.x+=B.x-W.x,j.center.y+=B.y-W.y,typeof setTimeout=="function"&&(this.wheelMotion=!0,this.motionTimer!==null&&clearTimeout(this.motionTimer),this.motionTimer=setTimeout(()=>{this.motionTimer=null,this.wheelMotion=!1,this.requestDraw()},this.primitives.length>=2e4?280:120)),this.requestDraw()},{passive:!1}),R("contextmenu",V=>V.preventDefault()),this.observer=new ResizeObserver(()=>{let V=this.viewport.camera.zoom;this.resize(),this.viewport.camera.zoom=V,this.draw()}),this.observer.observe(N),this.resize()}resize(){if(this.disposed)return;let N=this.host.getBoundingClientRect(),re=this.viewport.camera;if(this.hasSize=Number.isFinite(N.width)&&Number.isFinite(N.height)&&N.width>0&&N.height>0,!this.hasSize){this.hideMotion();return}re.width=N.width,re.height=N.height;let R=T(re.width,re.height,globalThis.devicePixelRatio);this.pixelRatio=R.ratio,this.canvas.width!==R.width&&(this.canvas.width=R.width),this.canvas.height!==R.height&&(this.canvas.height=R.height),this.canvas.style.width=re.width+"px",this.canvas.style.height=re.height+"px"}setDocument(N,re,R){this.resize(),this.design=N,this.document={filename:re},this.primitives=N.primitives,this.visibleLayers=new Set((N.layers||[]).filter(B=>!this.pcb||["F.Cu","B.Cu","F.SilkS","B.SilkS","Edge.Cuts"].includes(B))),this.selected=null,this.focusedLayer=null,this.layerSnapshot=null,this.layerPresetName=null,this.setNetHighlight(null);let $=N.embeddedFonts,V=$||R,O=new Set;if(V?.length&&m.KiCadEmbeddedFonts)for(let B of N.primitives)typeof B.fontFace=="string"&&O.add(B.fontFace.trim().toLowerCase());if(this.embeddedFontSet&&this.fontSource===V&&this.inheritedFonts===R&&O.size&&[...O].every(B=>this.fontFaces.has(B))){this.zoom_to_board(),this.draw();return}if(this.embeddedFontSet?.dispose(),this.embeddedFontSet=null,this.fontSource=V,this.inheritedFonts=R,this.fontFaces=O,this.zoom_to_board(),this.draw(),!O.size)return;let C=new Set($?.map(B=>B.name)),j=$&&R&&$!==R?[...$,...R.filter(B=>!C.has(B.name))]:V;this.embeddedFontSet=m.KiCadEmbeddedFonts.mount(j,O,()=>{this.geometryBounds=new WeakMap,this.textBoundsCache=new WeakMap,this.spatialIndex=null,this.releaseMotion(),this.draw()},(B,W)=>{let K="Embedded font "+B+": "+W;N.warnings&&!N.warnings.includes(K)&&(N.warnings.push(K),this.onFontWarning?.())},this.canvas.ownerDocument?.defaultView||m,this.loadFontDecoder)}get primitives(){return this._primitives}set primitives(N){this.hoverParts=null,this.hoverCanvas&&(this.hoverCanvas.hidden=!0),this.releaseImages(),this._primitives=N,this.spatialIndex=null,this.geometryBounds=new WeakMap,this.textBoundsCache=new WeakMap,this.ownedGeometry=new Map;for(let re of N||[])if(re.ownerUuid&&re.kind!=="footprint-hit"){let R=this.ownedGeometry.get(re.ownerUuid)||[];R.push(re),this.ownedGeometry.set(re.ownerUuid,R)}}releaseImages(){for(let N of this.images?.values()||[])N.image&&(N.image.onload=N.image.onerror=null,N.image.src="");this.images=new Map,this.imagePixels=0}imageResource(N){if(this.images.has(N))return this.images.get(N);let re={ready:!1};this.images.set(N,re);let R=N.pixelWidth,$=N.pixelHeight,V=R*$;if(typeof m.Image!="function"||typeof N.dataUrl!="string"||N.dataUrl.length>56e5||!/^data:image\/(?:png;base64,iVBORw0KGgo|bmp;base64,Qk[0123])[A-Za-z0-9+/]*={0,2}$/.test(N.dataUrl)||!Number.isSafeInteger(R)||!Number.isSafeInteger($)||R<1||$<1||V>16e6||this.imagePixels+V>16e6||this.images.size>16)return re;this.imagePixels+=V;let O=new m.Image,C={image:O,ready:!1};return this.images.set(N,C),O.decoding="async",O.onload=()=>{this.disposed||this.images.get(N)!==C||(C.ready=O.naturalWidth===R&&O.naturalHeight===$,C.ready&&this.requestDraw())},O.onerror=()=>{C.ready=!1},O.src=N.dataUrl,C}candidates(N){return this.primitives.length<512?this.primitives:((!this.spatialIndex||this.spatialIndex.length!==this.primitives.length)&&(this.spatialIndex=new be(this.primitives)),this.spatialIndex.query(N))}geometryVisible(N){if(N.hidden||!Xe(N,this.objectVisibility)||N.kind==="zone"&&this.showFilledCopper===!1||N.kind==="zone-outline"&&this.showZoneOutlines===!1)return!1;if(N.kind==="footprint-hit"){let re=this.ownedGeometry?.get(N.ownerUuid||N.uuid);if(re?.length)return re.some(R=>this.geometryVisible(R)&&(!R.layer||this.visibleLayers.has(R.layer)))}return!0}setObjectVisibility({hiddenTypes:N=[],side:re="all"}={}){this.objectVisibility={hiddenTypes:new Set(N.filter(R=>qe.some($=>$.id===R))),side:["all","top","bottom"].includes(re)?re:"all"},this.selected&&!this.geometryVisible(this.selected)&&(this.selected=null),this.finishMotion()}setZoneVisibility({filled:N=this.showFilledCopper!==!1,outlines:re=this.showZoneOutlines!==!1}={}){this.showFilledCopper=!!N,this.showZoneOutlines=!!re,this.finishMotion()}setNetNames(N){this.netNames=new Map;for(let re of N||[])for(let R of re.primitives||[])this.netNames.set(R,re.name)}drawNetNames(){if(!this.pcb||!this.showNetNames||!this.netNames||this.objectVisibility?.hiddenTypes.has("texts"))return;let N=this;function*re(){for(let V of N.candidates(N.viewport.camera.bbox))(N.netNames.has(V)||V.kind==="pad")&&N.geometryVisible(V)&&N.visibleLayers.has(V.layer)&&(!N.focusedLayer||V.layer===N.focusedLayer)&&(!(N.netHighlight&&N.highlightMode!=="bright")||N.netPrimitives.has(V))&&(yield[V,N.netNames.get(V)||V.netName||""])}let R=De(re(),this.viewport.camera),$=this.ctx;$.save(),$.font="11px monospace",$.textAlign="center",$.textBaseline="middle",$.lineJoin="round",$.lineWidth=3,$.fillStyle=this.dark?"#f3f8fa":"#17212b",$.strokeStyle=this.dark?"#101820":"#ffffff";for(let V of R){$.save(),$.translate(V.x,V.y),$.rotate(V.angle*Math.PI/180),$.font=V.size+"px monospace";let O=V.text.split(`
`);O.forEach((C,j)=>{let B=(j-(O.length-1)/2)*V.size*1.4;$.strokeText(C,0,B),$.fillText(C,0,B)}),$.restore()}$.restore()}setSelectionMode(N){this.selectionMode=["all","part","net","pin"].includes(N)?N:"all"}pickDistance(N,re){if(!N||N.frame||N.hole)return 1/0;let R=this.viewport.camera;if(N.type==="text"){this.textBounds(N);let $=this.textBoundsCache.get(N)?.rects;if($){let V=R.world_to_screen(N),O=R.world_to_screen(re),C=((N.angle||0)*(R.flipped?-1:1)+R.quarterTurns*90)*Math.PI/180,j=O.x-V.x,B=O.y-V.y,W=j*Math.cos(C)+B*Math.sin(C),K=-j*Math.sin(C)+B*Math.cos(C),ge=1/0;for(let Ne of $)ge=Math.min(ge,Math.hypot(Math.max(Ne.left-W,0,W-Ne.right),Math.max(Ne.top-K,0,K-Ne.bottom)));return ge}}return te(N,re,.25/R.zoom)*R.zoom}query(N,re=5,R){let $=this.viewport.camera,V=re/$.zoom,O=this.focusedLayer||($.flipped?"B.Cu":"F.Cu"),C=this.primitives.slice(0,0),j=(W,K)=>W.score-K.score,B=1/0;for(let W of this.candidates({x:N.x-V,y:N.y-V,w:2*V,h:2*V})){if(R&&!R(W)||W.pick===!1||W.hole||W.frame||!(W.uuid||W.reference)||!this.geometryVisible(W)||this.isolateNet&&this.netHighlight&&!this.netPrimitives.has(W)||!R&&this.selectionMode==="pin"&&!["pad","pin","pin-marker","pin-name","pin-number"].includes(W.kind)||W.layer&&!this.visibleLayers.has(W.layer)||this.focusedLayer&&this.layerFocusMode==="isolate"&&W.layer!==this.focusedLayer)continue;let K=W.type==="text"||W.zoneCoordinates;if(!K&&!Q(W,N,V))continue;let ge=this.pickDistance(W,N);if(K&&ge>re)continue;let Ne=W.electricalKind||W.kind,ne=["pad","pin","via"].includes(Ne)?0:["wire","track","arc","junction","label","global_label","hierarchical_label","sheet-pin","pin-number","pin-name"].includes(Ne)?1:["footprint","symbol","footprint-hit","sheet"].includes(Ne)?2:W.type==="image"?12:3,we=this.pcb&&W.layer&&W.layer!==O?.25:0,xe=W.kind==="zone"||W.kind==="zone-outline",ke=ge+ne*.35+we+(xe?re+1:0);ke>=B||(C.push({p:W,score:ke}),C.length===80&&(C.sort(j),C.length=40,B=C[39].score))}return C.sort(j).slice(0,40).map(W=>W.p)}reportPartHover(N){!this.partHoverEnabled||this.hoveredPrimitive===N||(this.hoveredPrimitive=N,this.dispatchEvent(new CustomEvent("kicad:parthover",{detail:N})))}setPartHover(N){this.hoverParts=N,this.paintPartHover()}paintPartHover(){if(!this.hoverParts?.length||!this.hasSize||this.canvas.hidden){this.hoverCanvas&&(this.hoverCanvas.hidden=!0);return}this.hoverCanvas||(this.hoverCanvas=this.canvas.ownerDocument.createElement("canvas"),this.hoverCanvas.setAttribute("aria-hidden","true"),this.hoverCanvas.style.cssText="position:absolute;inset:0;width:100%;height:100%;pointer-events:none",this.canvas.after(this.hoverCanvas));let N=this.hoverCanvas,re=N.getContext("2d");if(!re)return;(N.width!==this.canvas.width||N.height!==this.canvas.height)&&(N.width=this.canvas.width,N.height=this.canvas.height),N.hidden=!1,re.setTransform(1,0,0,1,0,0),re.clearRect(0,0,N.width,N.height);let R=this.pixelRatio||1;re.setTransform(R,0,0,R,0,0);let $=this.ctx,V=this.viewport.camera.bbox;this.ctx=re;try{let O=0;for(let C of this.hoverParts)if(!(C.kind==="footprint-hit"||C.hole||!this.geometryVisible(C)||C.layer&&!this.visibleLayers.has(C.layer)||!this.inView(C,V))&&(this.paint(C,{color:this.dark?"#ffbf52":"#a45600",opacity:C.fill?.65:1}),++O===1800))break}finally{this.ctx=$}}select(N,re={}){this.selected=N?.primitive||null,this.draw(),this.dispatchEvent(new CustomEvent("kicad:select",{detail:{item:N?.context||null,multi:!!re.multi}}))}setNetHighlight(N,re={}){this.setNetHighlights(N?[N]:[],re)}setNetHighlights(N,re={}){let R=Array.isArray(N)?N.slice(0,200):[];this.netHighlight=R.length?R[0]:null,this.highlightCount=R.length;let $=new Set;R.forEach(V=>{let O=V.primitives||[];Array.isArray(O)?O.forEach(C=>$.add(C)):$.add(O)}),this.netPrimitives=$,this.isolateNet=!!re.isolate,this.highlightMode=["bright","dim","isolate"].includes(re.mode)?re.mode:this.isolateNet?"isolate":"dim",this.isolateNet=this.highlightMode==="isolate",this.selectionColor=re.selectionColor==="source"?"source":"accent"}focusLayer(N,re="dim"){return!(this.design?.layers||[]).includes(N)||!["dim","isolate"].includes(re)?!1:(this.layerSnapshot||(this.layerSnapshot=new Set(this.visibleLayers)),this.focusedLayer=N,this.layerPresetName=null,this.layerFocusMode=re,this.activeLayer=N,this.visibleLayers.add(N),!0)}restoreLayers(){this.layerSnapshot&&(this.visibleLayers=new Set(this.layerSnapshot)),this.layerSnapshot=null,this.focusedLayer=null,this.layerPresetName=null}layerPreset(N){let re=this.design?.layers||[];return["all","none","front","back","copper","overview","outline"].includes(N)?(this.layerSnapshot||(this.layerSnapshot=new Set(this.visibleLayers)),this.focusedLayer=null,this.layerPresetName=N,this.visibleLayers=new Set(re.filter(R=>N==="all"||N!=="none"&&(R==="Edge.Cuts"||N==="copper"&&R.endsWith(".Cu")||N==="front"&&R.startsWith("F.")||N==="back"&&R.startsWith("B.")||N==="overview"&&["F.Cu","B.Cu","F.SilkS","B.SilkS"].includes(R)))),!0):!1}fitLayer(){let N=this.primitives.filter($=>this.geometryVisible($)&&!$.frame&&$.layer===this.focusedLayer),re=G(N);if(!re)return!1;let R=Math.max(1,Math.max(re.w,re.h)*.08);return this.viewport.camera.bbox={x:re.x-R,y:re.y-R,w:re.w+2*R,h:re.h+2*R},this.paperVisible=!1,!0}zoom_to_board(){this.paperVisible=!this.pcb;let N=this.pcb?this.primitives.filter(R=>R.layer==="Edge.Cuts"):[],re=G(N.length?N:this.primitives);if(re){let R=Math.max(3,Math.max(re.w,re.h)*.06);this.viewport.camera.bbox={x:re.x-R,y:re.y-R,w:re.w+2*R,h:re.h+2*R}}else this.zoom_to_page()}zoom_to_page(){this.paperVisible=!0;let N=this.design?.page||{width:297,height:210};this.viewport.camera.bbox={x:-5,y:-5,w:N.width+10,h:N.height+10}}background(){return this.dark?"#151820":"#e7ebf1"}paperColor(){return this.dark?"#1c2029":"#fdfdff"}cameraState(){let N=this.viewport.camera;return{x:N.center.x,y:N.center.y,zoom:N.zoom,width:N.width,height:N.height,flipped:N.flipped}}canUseMotionTexture(){return this.hasSize&&!this.disposed&&this.acceleration!=="off"&&!this.motionFailed&&this.primitives.length>=4096&&this.primitives.length<2e4&&!this.renderPrimitives&&!!m.KiCadMotionWebGL}prepareMotion(){if(!this.canUseMotionTexture())return!1;try{this.motion||(this.motion=new m.KiCadMotionWebGL.Motion(this.host),this.motion.onLost=()=>{this.motionFailed=!0,this.hideMotion(),this.releaseMotion(),this.requestDraw()});let N=this.viewport.camera,re=N.width,R=N.height,$=re*1.5,V=R*1.5,O=this.motion.gl.getParameter(this.motion.gl.MAX_TEXTURE_SIZE),C=Math.min(4e6,m.KiCadMotionWebGL.MAX_PIXELS),j=Math.min(this.pixelRatio||1,Math.sqrt(C/$/V),O/$,O/V),B=Math.max(1,Math.floor($*j)),W=Math.max(1,Math.floor(V*j)),K=this.motionSnapshot||=document.createElement("canvas");K.width>B&&(K.width=B),K.height!==W&&(K.height=W),K.width!==B&&(K.width=B);let ge=K.getContext("2d");if(!ge)throw Error("Canvas2D motion snapshot is unavailable.");let Ne=this.canvas,ne=this.ctx,we;try{this.canvas=K,this.ctx=ge,N.width=$,N.height=V,we=this.cameraState(),this.drawGeometry(!0,j)}finally{this.canvas=Ne,this.ctx=ne,N.width=re,N.height=R}return this.motion.upload(K,we),!0}catch{return this.motionFailed=!0,this.releaseMotion(),!1}}motionFrame(){if(!this.canUseMotionTexture())return!1;let N=this.cameraState(),re=this.pixelRatio||1;return this.motion?.saved&&!this.motion.show(N,re)&&(this.motion.saved=null),!this.motion?.saved&&(!this.prepareMotion()||!this.motion.show(N,re))?!1:(this.canvas.style.opacity="0",this.motionActive=!0,!0)}bitmapMotionFrame(){if(!this.hasSize||this.acceleration==="off"||this.renderPrimitives||this.primitives.length<500)return!1;let N=this.cameraState(),re=this.bitmapMotionState||this.paintedCamera;if(!re||re.width!==N.width||re.height!==N.height||re.flipped!==N.flipped)return!1;let R=C=>{let j=N.zoom/C.zoom;return{scale:j,x:(C.x-N.x)*N.zoom*(N.flipped?-1:1)+(1-j)*N.width/2,y:(C.y-N.y)*N.zoom+(1-j)*N.height/2}},$=R(re),V=$.scale<.76||$.scale>1.55||Math.abs($.x-(1-$.scale)*N.width/2)>N.width*.24||Math.abs($.y-(1-$.scale)*N.height/2)>N.height*.24;V&&(this.drawGeometry(!0),re=N,$=R(re)),this.bitmapMotion||(this.bitmapMotion=document.createElement("canvas"),this.bitmapMotion.setAttribute("aria-hidden","true"),this.bitmapMotion.style.cssText="position:absolute;inset:0;width:100%;height:100%;pointer-events:none;transform-origin:0 0",this.bitmapMotion.hidden=!0,this.host.append(this.bitmapMotion));let O=this.bitmapMotion;if(V||!this.bitmapMotionState){let C=Math.min(this.pixelRatio||1,Math.sqrt(16e5/N.width/N.height));O.width=Math.max(1,Math.floor(N.width*C)),O.height=Math.max(1,Math.floor(N.height*C));let j=O.getContext("2d");if(!j)return!1;j.drawImage(this.canvas,0,0,O.width,O.height),this.bitmapMotionState=re}return O.style.transform=`translate3d(${$.x}px,${$.y}px,0) scale(${$.scale})`,O.hidden=!1,this.canvas.style.opacity="0",this.motionActive=!0,!0}hideMotion(){this.motion?.hide(),this.bitmapMotion&&!this.bitmapMotion.hidden&&(this.bitmapMotion.hidden=!0,this.bitmapMotion.width=this.bitmapMotion.height=1),this.bitmapMotionState=null,this.canvas.style.opacity="",this.motionActive=!1}releaseMotion(){this.motion?.dispose(),this.motion=null,this.motionSnapshot&&(this.motionSnapshot.width=this.motionSnapshot.height=1,this.motionSnapshot=null)}finishMotion(){this.motionTimer!==null&&(clearTimeout(this.motionTimer),this.motionTimer=null),this.frameRequest!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(this.frameRequest),this.frameRequest=null,this.wheelMotion=!1,this.disposed||this.draw()}requestDraw(){if(!(this.disposed||this.frameRequest!==null)){if(typeof requestAnimationFrame!="function"){this.draw();return}this.frameRequest=requestAnimationFrame(()=>{if(this.frameRequest=null,!this.disposed){if(this.hoverCanvas&&(this.hoverCanvas.hidden=!0),!this.drag?.moved&&!this.wheelMotion&&!this.touchMotion){this.draw();return}!this.motionFrame()&&(m.KiCadMotionWebGL||!this.bitmapMotionFrame())&&(this.hideMotion(),this.drawGeometry(!0)),this.dispatchEvent(new CustomEvent("kicad:viewframe"))}})}}displayTextLines(N){let re=String(N.text||"").split(`
`);if(!Number.isFinite(N.maxTextWidth))return re;let R=this.viewport.camera.zoom,$=this.overviewTextCache?.get(N);if($?.zoom===R&&$.text===N.text)return $.lines;let V=N.fontHeight||N.size||1.27,O=N.fontWidth&&V>0?N.fontWidth/V:1,C=N.maxTextWidth*R/O,j=[];if(N.maxTextWidth*R>=(N.minDisplayWidthPx||0)&&C>0){let B=this.ctx;B.save(),B.font=this.textFont(N),j=re.map(W=>{let K=we=>B.measureText(we)?.width;if(K(W)<=C)return W;if(!(K("\u2026")<=C))return"";let ge=Array.from(W),Ne=0,ne=ge.length;for(;Ne<ne;){let we=Math.ceil((Ne+ne)/2);K(ge.slice(0,we).join("")+"\u2026")<=C?Ne=we:ne=we-1}return ge.slice(0,Ne).join("")+"\u2026"}),B.restore()}return this.overviewTextCache||=new WeakMap,this.overviewTextCache.set(N,{zoom:R,text:N.text,lines:j}),j}textBounds(N){let re=this.viewport.camera,R=this.textBoundsCache.get(N);if(R&&R.zoom===re.zoom&&R.flipped===re.flipped&&R.quarterTurns===re.quarterTurns)return R.box;let $=this.ctx,V=N.fontHeight||N.size||1.27,O=N.fontWidth&&V>0?N.fontWidth/V:1,C=null,j=[],B=1/0,W=1/0,K=-1/0,ge=-1/0;$.save();try{$.font=this.textFont(N),$.textAlign=N.align||"center",$.textBaseline=N.baseline||"middle";let Ne=this.displayTextLines(N),ne=((N.angle||0)*(re.flipped?-1:1)+re.quarterTurns*90)*Math.PI/180,we=Math.cos(ne),xe=Math.sin(ne);for(let ke=0;ke<Ne.length;ke++){let Me=$.measureText(Ne[ke]);if(!Me||![Me.actualBoundingBoxLeft,Me.actualBoundingBoxRight,Me.actualBoundingBoxAscent,Me.actualBoundingBoxDescent].every(Number.isFinite))return j=null,null;let Ce=(ke-(Ne.length-1)/2)*V*re.zoom*(N.lineSpacing||1.5),tt=!!(N.mirrored??N.mirror)!=!!re.flipped,Ze=-(tt?Me.actualBoundingBoxRight:Me.actualBoundingBoxLeft)*O,Ye=(tt?Me.actualBoundingBoxLeft:Me.actualBoundingBoxRight)*O,vt=Ce-Me.actualBoundingBoxAscent,Rt=Ce+Me.actualBoundingBoxDescent;j.push({left:Ze,right:Ye,top:vt,bottom:Rt});for(let[Je,_t]of[[Ze,vt],[Ye,vt],[Ye,Rt],[Ze,Rt]]){let Et=re.screenDeltaToWorld({x:Je*we-_t*xe,y:Je*xe+_t*we}),gt=N.x+Et.x,Ht=N.y+Et.y;B=Math.min(B,gt),K=Math.max(K,gt),W=Math.min(W,Ht),ge=Math.max(ge,Ht)}}[B,W,K,ge].every(Number.isFinite)&&(C={x:B,y:W,w:K-B,h:ge-W})}finally{$.restore(),this.textBoundsCache.set(N,{zoom:re.zoom,flipped:re.flipped,quarterTurns:re.quarterTurns,box:C,rects:j})}return C}textFont(N){let re=this.embeddedFontSet?.family(N.fontFace),R=re?re+",sans-serif":N.fontFace?"sans-serif":'"Arial",sans-serif';return`${N.italic?"italic ":""}${N.bold?"bold ":""}${Math.max(1,N.minPixelSize||1,(N.fontHeight||N.size||1.27)*this.viewport.camera.zoom*4/3)}px ${R}`}inView(N,re){let R;if(N.type==="text"?R=this.textBounds(N):(R=this.geometryBounds.get(N),R===void 0&&(R=he(N),this.geometryBounds.set(N,R||null))),!R)return!0;let $=3/this.viewport.camera.zoom;return R.x+R.w>=re.x-$&&R.x<=re.x+re.w+$&&R.y+R.h>=re.y-$&&R.y<=re.y+re.h+$}draw(){this.motionTimer!==null&&(clearTimeout(this.motionTimer),this.motionTimer=null),this.wheelMotion=!1,this.hideMotion(),this.canUseMotionTexture()?this.motion&&(this.motion.saved=null):this.releaseMotion(),this.drawGeometry(),this.paintedCamera=this.hasSize?this.cameraState():null,this.paintPartHover(),this.dispatchEvent(new CustomEvent("kicad:viewframe"))}drawGeometry(N=!1,re=this.pixelRatio||1){if(this.disposed||!this.hasSize)return;let R=this.viewport.camera,$=this.ctx;if($.setTransform(1,0,0,1,0,0),$.fillStyle=this.background(),$.fillRect(0,0,this.canvas.width,this.canvas.height),$.setTransform(re,0,0,re,0,0),this.grid&&R.zoom>2){let Me=Number.isFinite(this.gridPitch)&&this.gridPitch>=.001&&this.gridPitch<=100?this.gridPitch:R.zoom>12?1:5;for(;Me*R.zoom<5;)Me*=10;let Ce=R.bbox;$.fillStyle=this.dark?"#2b3b46":"#d3d3c7";let tt=0;for(let Ze=Math.ceil(Ce.x/Me)*Me;Ze<Ce.x+Ce.w&&tt<2e4;Ze+=Me)for(let Ye=Math.ceil(Ce.y/Me)*Me;Ye<Ce.y+Ce.h&&tt++<2e4;Ye+=Me){let vt=R.world_to_screen({x:Ze,y:Ye});$.fillRect(vt.x,vt.y,1,1)}}if(this.paperVisible){let Me=this.design?.page||{width:297,height:210},Ce=R.world_to_screen({x:0,y:0}),tt=R.world_to_screen({x:Me.width,y:Me.height});$.save(),$.shadowColor="#00000055",$.shadowBlur=18,$.shadowOffsetY=4,$.fillStyle=this.paperColor(),$.fillRect(Math.min(Ce.x,tt.x),Ce.y,Math.abs(tt.x-Ce.x),tt.y-Ce.y),$.restore()}let V=R.bbox,O=3/R.zoom,C=[],j=[],B=this.renderPrimitives?[]:this.candidates({x:V.x-O,y:V.y-O,w:V.w+2*O,h:V.h+2*O}),W=N&&this.primitives.length>=2e4&&B.length>2800,K=W?Math.ceil(B.length/2800):1,ge=W&&this.selected?.kind==="footprint-hit"?this.selected.ownerUuid||this.selected.uuid:null,Ne=0,ne,we,xe=()=>{Ne&&($.stroke(),$.restore(),Ne=0)},ke=(Me,Ce)=>{let tt=Math.max(.65,(Me.width||.15)*R.zoom);Ne&&(ne!==Ce||we!==tt||Ne===256)&&xe(),Ne||($.save(),$.strokeStyle=ne=Ce,$.lineWidth=we=tt,$.lineCap="round",$.lineJoin="round",$.globalAlpha=1,$.setLineDash?.([]),$.beginPath());let Ze=R.world_to_screen(Me.points[0]),Ye=R.world_to_screen(Me.points[1]);$.moveTo(Ze.x,Ze.y),$.lineTo(Ye.x,Ye.y),Ne++};if(this.renderPrimitives)this.renderPrimitives($,R,this);else for(let Me=0;Me<B.length;Me++){let Ce=B[Me],tt=this.netPrimitives.has(Ce);if(W&&!tt&&Ce!==this.selected&&!(ge&&Ce.ownerUuid===ge)&&!Ce.frame&&Ce.layer!=="Edge.Cuts"&&(Me%K!==Math.floor(Me/K)%K||Ce.type==="text"||Ce.type==="image"||Ce.kind==="zone"||Ce.hole)||!this.geometryVisible(Ce)||!this.inView(Ce,V)||Ce.frame&&!this.paperVisible||!Ce.frame&&Ce.layer&&!this.visibleLayers.has(Ce.layer))continue;let Ze=this.netHighlight&&!Ce.frame&&!tt,Ye=this.focusedLayer&&!Ce.frame&&Ce.layer!==this.focusedLayer;if(Ye&&this.layerFocusMode==="isolate"&&!Ce.hole&&Ce.layer!=="Edge.Cuts"||Ze&&this.isolateNet&&!Ce.hole&&Ce.layer!=="Edge.Cuts")continue;let vt={color:Ze&&this.highlightMode!=="bright"&&!Ce.hole?this.dark?"#87919d":"#8b919a":Ce.kind==="via"?"#c5aa6c":tt&&!Ce.hole&&this.selectionColor!=="source"?this.pcb?"#ffe18b":this.dark?"#78d5ff":"#006ca8":this.netClassColors?.get(Ce)||null,opacity:Math.min(Ze&&!Ce.hole&&this.highlightMode!=="bright"&&Ce.layer!=="Edge.Cuts"?this.pcb?.045:.38:1,Ye&&!Ce.hole?.18:1)};if(this.pcb&&!this.netHighlight&&!Ye&&!Ce.frame&&!Ce.hole&&Ce.kind==="track"&&Ce.type==="line"&&Ce.points?.length===2&&!Ce.fill&&!Ce.lineStyle&&Ce.stroke!==!1&&(Ce.opacity===void 0||Ce.opacity===1)&&this.paint===ve.prototype.paint){ke(Ce,this.strokeColor(Ce,vt.color));continue}xe(),this.pcb&&this.netHighlight&&this.highlightMode!=="bright"?Ce.hole?j.push({p:Ce,style:vt}):tt?C.push({p:Ce,style:vt}):this.paint(Ce,vt):this.paint(Ce,vt)}xe();for(let{p:Me,style:Ce}of C)this.paint(Me,Ce);for(let{p:Me,style:Ce}of j)this.paint(Me,Ce);if(N||this.drawNetNames(),this.selected&&!this.netHighlight&&this.geometryVisible(this.selected)&&(!this.selected.layer||this.visibleLayers.has(this.selected.layer))&&(!this.focusedLayer||this.layerFocusMode!=="isolate"||this.selected.layer===this.focusedLayer)&&(!this.netHighlight||!this.isolateNet||this.netPrimitives.has(this.selected))){let Me=G([this.selected],!0);if(Me){let Ce=R.world_to_screen(Me);$.strokeStyle="#80f0b7",$.lineWidth=2,$.setLineDash([4,3]),$.strokeRect(Ce.x-4,Ce.y-4,(R.flipped?-1:1)*Me.w*R.zoom+8,Me.h*R.zoom+8),$.setLineDash([])}}}fillGraphic(N,re,R){let $=this.ctx;if(["hatch","reverse_hatch","cross_hatch"].includes(N.fill)){this.hatchPatterns||=new Map;let V=$.fillStyle,O=N.fill+"|"+V+"|"+(N.width||.15),C=this.hatchPatterns.get(O);if(!C){let j=document.createElement("canvas");j.width=j.height=16;let B=j.getContext("2d");if(B.strokeStyle=V,B.globalAlpha=.4,B.lineWidth=Math.max(.025,(N.width||.15)/2)*16/(Math.SQRT2*4),B.beginPath(),N.fill!=="reverse_hatch")for(let W of[-16,0,16])B.moveTo(W,0),B.lineTo(W+16,16);if(N.fill!=="hatch")for(let W of[-16,0,16])B.moveTo(W,16),B.lineTo(W+16,0);B.stroke(),C=$.createPattern(j,"repeat"),this.hatchPatterns.size>=32&&this.hatchPatterns.clear(),C&&this.hatchPatterns.set(O,C)}if(C){let j=Math.SQRT2*4,B=R?j/16:Math.max(4,j*this.viewport.camera.zoom)/16;C.setTransform?.({a:B,b:0,c:0,d:B,e:0,f:0}),$.fillStyle=C}}re?$.fill(re):$.fill()}strokeColor(N,re){let R=re||N.color||"#819baa";return N.hole?this.paperVisible?this.paperColor():this.background():re?R:!this.pcb&&!N.sourceColor?Y(R,this.dark):N.layer&&m.KiCadLayerColors?.reviewColorFor?m.KiCadLayerColors.reviewColorFor(N.layer,this.dark):R}paint(N,re={}){let R=this.ctx,$=this.viewport.camera;R.save();let V=this.strokeColor(N,re.color);R.strokeStyle=V,R.fillStyle=re.color?V:["color","hatch","reverse_hatch","cross_hatch"].includes(N.fill)&&N.fillColor?N.fillColor:N.fill==="background"?this.dark?"#32322a":"#ffffc2":V,R.globalAlpha=Math.max(0,Math.min(1,(this.netPrimitives.has(N)&&!N.hole?1:Number.isFinite(N.opacity)?N.opacity:1)*(re.opacity??1))),R.lineWidth=Math.max(.65,(N.width||.15)*$.zoom),this.netPrimitives.has(N)&&!N.hole&&(R.lineWidth+=1.5),R.lineCap="round",R.lineJoin="round";let O=Math.max(1,R.lineWidth),C={dash:[11,4],dot:[.2,4],dash_dot:[11,4,.2,4],dash_dot_dot:[11,4,.2,4,.2,4]}[N.lineStyle];if(R.setLineDash?.(C?C.map(j=>j*O):[]),N.type==="text"){let j=$.world_to_screen(N);R.translate(j.x,j.y),R.rotate(((N.angle||0)*($.flipped?-1:1)+$.quarterTurns*90)*Math.PI/180),!!(N.mirrored??N.mirror)!=!!$.flipped&&R.scale(-1,1),R.font=this.textFont(N),R.textAlign=N.align||"center",R.textBaseline=N.baseline||"middle";let B=N.fontHeight||N.size||1.27;N.fontWidth&&B>0&&R.scale(N.fontWidth/B,1);let W=this.displayTextLines(N);W.forEach((K,ge)=>R.fillText(K,0,(ge-(W.length-1)/2)*B*$.zoom*(N.lineSpacing||1.5))),R.restore();return}if(N.type==="image"){let j=this.imageResource(N);if(j.ready&&N.points?.length===4){let[B,W,,K]=N.points.map(ge=>$.world_to_screen(ge));R.transform((W.x-B.x)/N.pixelWidth,(W.y-B.y)/N.pixelWidth,(K.x-B.x)/N.pixelHeight,(K.y-B.y)/N.pixelHeight,B.x,B.y),R.drawImage(j.image,0,0)}R.restore();return}if(R.beginPath(),N.type==="arc"){let j=ee(N.start,N.mid,N.end);if(j){let B=$.world_to_screen(j),W=$.flipped?Math.PI-j.start:j.start,K=$.flipped?Math.PI-j.end:j.end;R.arc(B.x,B.y,j.r*$.zoom,W,K,$.flipped?!j.ccw:j.ccw)}else{let B=X(N);if(B.length){let W=$.world_to_screen(B[0]);R.moveTo(W.x,W.y);for(let K of B.slice(1)){let ge=$.world_to_screen(K);R.lineTo(ge.x,ge.y)}}}}else if(N.type==="circle"||N.type==="pad"&&N.r){let j=$.world_to_screen(N);R.arc(j.x,j.y,N.r*$.zoom,0,2*Math.PI)}else if(N.zoneCoordinates){let j=N.zoneCoordinates,B=$.world_to_screen({x:0,y:0}),W=$.worldDeltaToScreen({x:1,y:0}),K=$.worldDeltaToScreen({x:0,y:1});R.moveTo(B.x+j[0]*W.x+j[1]*K.x,B.y+j[0]*W.y+j[1]*K.y);for(let ge=2;ge<j.length;ge+=2)R.lineTo(B.x+j[ge]*W.x+j[ge+1]*K.x,B.y+j[ge]*W.y+j[ge+1]*K.y);R.closePath()}else{let j=X(N);if(j.length){let B=$.world_to_screen(j[0]);R.moveTo(B.x,B.y);for(let W of j.slice(1)){let K=$.world_to_screen(W);R.lineTo(K.x,K.y)}(N.type==="polygon"||N.type==="pad")&&R.closePath()}}N.fill&&this.fillGraphic(N,null,!1),!N.hole&&N.stroke!==!1&&R.stroke(),R.restore()}dispose(){if(!this.disposed){this.disposed=!0,this.bitmapMotion?.remove(),this.bitmapMotion=null,this.bitmapMotionState=null,this.paintedCamera=null,this.hoverCanvas?.remove(),this.hoverCanvas=null,this.hoverParts=null,this.hoveredPrimitive=null,this.embeddedFontSet?.dispose(),this.embeddedFontSet=null,this.fontSource=null,this.inheritedFonts=null,this.fontFaces=null,this.hatchPatterns?.clear(),this.releaseImages(),this.frameRequest!==null&&typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(this.frameRequest),this.frameRequest=null,this.motionTimer!==null&&clearTimeout(this.motionTimer),this.motionTimer=null,this.releaseMotion(),this.observer.disconnect();for(let N of this.handlers)N();this.handlers=[],this.primitives=[],this.design=null,this.document=null,this.selected=null,this.netHighlight=null,this.netPrimitives.clear(),this.netNames?.clear(),this.netClassColors?.clear(),this.layerSnapshot=null,this.canvas.width=this.canvas.height=1,this.canvas.remove()}}}function Ee(me,N,re,R){let $=Object.create(ve.prototype);Object.assign($,{ctx:me,viewport:{camera:N},pcb:!0,netPrimitives:new Set,pointCache:new WeakMap,pathCache:new WeakMap,pathCacheCount:0,pathCachePoints:0});for(let V of re)$.paint(V,{color:R})}m.KiCadOwnedCanvas={paintBoardPrimitives:Ee,netLabels:De,Camera:Ke,arcThrough:ee,bounds:G,hitPrimitive:Q,primitiveDistance:te,schematicColor:Y,objectTypes:qe,objectCategory:$e,objectVisible:Xe,canvasViewport:T,mount:(me,N)=>new ve(me,N)},typeof pm=="object"&&pm.exports&&(pm.exports=m.KiCadOwnedCanvas)})(globalThis)});var iS=$n((gF,fm)=>{(m=>{"use strict";function h(w){let S=null,A=null,T=null;function H(){S&&(S.hidden=!0)}function Y(ee,X,G="Release to place measurement point"){let ae=w.canvas,_e=ae.ownerDocument||m.document;S||(S=_e.createElement("div"),S.className="measurement-magnifier",S.setAttribute("role","img"),Object.assign(S.style,{position:"fixed",zIndex:"3000",pointerEvents:"none",width:"160px",padding:"4px",border:"2px solid #29abd0",borderRadius:"12px",background:"#14232f",color:"#fff",boxShadow:"0 4px 20px #0007"}),A=_e.createElement("canvas"),A.width=A.height=152,Object.assign(A.style,{display:"block",width:"152px",height:"152px",borderRadius:"7px"}),T=_e.createElement("small"),Object.assign(T.style,{display:"block",font:"11px system-ui",overflowWrap:"anywhere"}),S.append(A,T),_e.body.append(S));let J=ae.getBoundingClientRect();if(!J.width||!J.height)return H();let Q=A.getContext("2d");if(!Q)return H();let te=ee.clientX-J.left,he=ee.clientY-J.top,be=60,De=ae.width/J.width,Ke=ae.height/J.height;Q.fillStyle="#14232f",Q.fillRect(0,0,152,152),Q.drawImage(ae,(te-be/2)*De,(he-be/2)*Ke,be*De,be*Ke,0,0,152,152);let qe=X?w.viewport.camera.world_to_screen(X):{x:te,y:he},$e=76+(qe.x-te)*152/be,Xe=76+(qe.y-he)*152/be;Q.strokeStyle="#ffde75",Q.lineWidth=2,Q.beginPath(),Q.moveTo($e-9,Xe),Q.lineTo($e+9,Xe),Q.moveTo($e,Xe-9),Q.lineTo($e,Xe+9),Q.stroke(),Q.beginPath(),Q.arc($e,Xe,5,0,Math.PI*2),Q.stroke(),T.textContent=G,S.setAttribute("aria-label","Measurement magnifier: "+G),S.hidden=!1;let ve=m.innerWidth||_e.documentElement.clientWidth,Ee=m.innerHeight||_e.documentElement.clientHeight,me=S.getBoundingClientRect().height||190;S.style.left=Math.max(8,Math.min(ee.clientX-80,ve-168))+"px";let N=ee.clientY-me-32;S.style.top=Math.max(8,Math.min(N>=8?N:ee.clientY+32,Ee-me-8))+"px"}return{show:Y,hide:H,dispose(){S?.remove(),S=A=T=null}}}function p(w){let S=w.canvas,A=w.viewport.camera,T=new Map,H=S.style?.touchAction;S.style&&(S.style.touchAction="none");let Y=null,ee=!1,X=0,G=null,ae=null,_e=!1,J=()=>{let Xe=[...T.values()];return{x:Xe.reduce((ve,Ee)=>ve+Ee.x,0)/Xe.length,y:Xe.reduce((ve,Ee)=>ve+Ee.y,0)/Xe.length,d:Xe.length===2?Math.hypot(Xe[0].x-Xe[1].x,Xe[0].y-Xe[1].y):0}},Q=()=>{ae!==null&&(m.clearTimeout(ae),ae=null)},te=()=>S.classList.contains("ruler-mode")||S.classList.contains("area-mode"),he=Xe=>{if(!(Xe.pointerType!=="touch"||te()))if(Xe.preventDefault(),Xe.stopImmediatePropagation(),w.dismissTouchPicker?.(),T.set(Xe.pointerId,{x:Xe.clientX,y:Xe.clientY}),S.setPointerCapture?.(Xe.pointerId),Y=J(),Q(),T.size===1){ee=!1,X=0,_e=!1;let ve=Xe.clientX,Ee=Xe.clientY;ae=m.setTimeout(()=>{ae=null,!ee&&T.size===1&&(_e=!0,G=null,S.dispatchEvent(new MouseEvent("contextmenu",{bubbles:!0,clientX:ve,clientY:Ee,button:2})))},550)}else ee=!0},be=Xe=>{if(!T.has(Xe.pointerId))return;Xe.preventDefault(),Xe.stopImmediatePropagation(),T.set(Xe.pointerId,{x:Xe.clientX,y:Xe.clientY});let ve=J(),Ee=ve.x-Y.x,me=ve.y-Y.y;if(!Ee&&!me&&ve.d===Y.d)return;X+=Math.abs(Ee)+Math.abs(me),X>6&&(ee=!0,Q());let N=S.getBoundingClientRect(),re={x:ve.x-N.left,y:ve.y-N.top};if(A.center.x-=Ee/A.zoom*(A.flipped?-1:1),A.center.y-=me/A.zoom,ve.d&&Y.d){let R=A.screen_to_world(re);A.zoom=Math.max(.001,Math.min(1e4,A.zoom*ve.d/Y.d));let $=A.screen_to_world(re);A.center.x+=R.x-$.x,A.center.y+=R.y-$.y}Y=ve,w.touchMotion=!0,w.requestDraw()},De=Xe=>{S.hasPointerCapture?.(Xe)&&S.releasePointerCapture?.(Xe)},Ke=()=>{w.touchMotion&&(w.touchMotion=!1,w.requestDraw())},qe=Xe=>{if(T.has(Xe.pointerId)){if(Xe.preventDefault(),Xe.stopImmediatePropagation(),Q(),T.delete(Xe.pointerId),De(Xe.pointerId),T.size){Y=J(),ee=!0;return}if(Ke(),Y=null,!ee&&!_e&&Xe.type==="pointerup"){let ve={bubbles:!0,clientX:Xe.clientX,clientY:Xe.clientY,button:0},Ee=Xe.timeStamp||Date.now();if(w.touchNetPick?.(ve)){G=null;return}S.dispatchEvent(new MouseEvent("click",ve)),G&&Ee-G.time<350&&Math.hypot(Xe.clientX-G.x,Xe.clientY-G.y)<20?(S.dispatchEvent(new MouseEvent("dblclick",ve)),G=null):G={time:Ee,x:Xe.clientX,y:Xe.clientY}}else G=null}},$e=[["pointerdown",he],["pointermove",be],["pointerup",qe],["pointercancel",qe],["lostpointercapture",qe]];for(let[Xe,ve]of $e)S.addEventListener(Xe,ve,!0);return()=>{for(let[Xe,ve]of $e)S.removeEventListener(Xe,ve,!0);Q();for(let Xe of T.keys())De(Xe);T.clear(),Ke(),S.style&&(S.style.touchAction=H||"")}}if(m.KiCadTouchCanvas={attach:p,magnifier:h},m.KiCadAndroidTouch=m.KiCadTouchCanvas,typeof fm=="object"&&fm.exports&&(fm.exports=m.KiCadAndroidTouch),m.KiCadOwnedCanvas){let w=m.KiCadOwnedCanvas.mount;m.KiCadOwnedCanvas.mount=(...S)=>{let A=w(...S),T=p(A),H=A.dispose.bind(A);return A.dispose=()=>{T(),H()},A}}})(globalThis)});var Vi,Ul=Ui(()=>{Vi=new WeakMap});var nh,sh,rd,Hn,Ja,Bs,Qa=Ui(()=>{nh=m=>/\.kicad_(sch|pcb)$/i.test(m),sh=m=>/\.(gbr|ger|gerber|pho|art|gtl|gbl|gts|gbs|gto|gbo|gtp|gbp|gko|gm\d+|g\d+|drl|drd|xln|exc|excellon|xnc|ncd|tap|txt)$/i.test(m),rd=m=>/\.zip$/i.test(m),Hn=m=>/\.kicad_wks$/i.test(m),Ja=m=>nh(m)||Hn(m)||sh(m)||rd(m),Bs=m=>typeof m=="string"&&m.length>0&&m.length<=1e3&&!/[\\\x00-\x1f\x7f%?#:]/.test(m)&&m.split("/").every(h=>h&&h!=="."&&h!=="..")});function gm(m){if(typeof m!="string")throw new TypeError("Manufacturing source must be text.");if(m.length>hs.bytes)throw new Error("Manufacturing source exceeds 16 MiB.");let h=0;for(let p=0;p<m.length;p++){let w=m.charCodeAt(p);if(w===0)throw new Error("Binary manufacturing files are unsupported.");if(w<128?h++:w<2048?h+=2:w>=55296&&w<=56319&&m.charCodeAt(p+1)>=56320&&m.charCodeAt(p+1)<=57343?(h+=4,p++):h+=3,h>hs.bytes)throw new Error("Manufacturing source exceeds 16 MiB.")}}function js(m,h=0){let p=1/0,w=1/0,S=-1/0,A=-1/0;for(let T of m){let H=Hi(T.x),Y=Hi(T.y);p=Math.min(p,H-h),w=Math.min(w,Y-h),S=Math.max(S,H+h),A=Math.max(A,Y+h)}return p===1/0?null:{x:p,y:w,w:S-p,h:A-w}}function hv(m){return js(m.filter(Boolean).flatMap(h=>[{x:h.x,y:h.y},{x:h.x+h.w,y:h.y+h.h}]))}function ah(m,h,p){if(!(p>0))throw new Error("Aperture/tool dimensions must be positive.");return`M${zr(m+p)} ${zr(h)}A${zr(p)} ${zr(p)} 0 1 1 ${zr(m-p)} ${zr(h)}A${zr(p)} ${zr(p)} 0 1 1 ${zr(m+p)} ${zr(h)}Z`}function sS(m,h,p){let w=h.x-m.x,S=h.y-m.y,A=Math.hypot(w,S);if(A<1e-12)return ah(m.x,m.y,p);let T=-S/A*p,H=w/A*p;return`M${zr(m.x+T)} ${zr(m.y+H)}L${zr(h.x+T)} ${zr(h.y+H)}A${zr(p)} ${zr(p)} 0 0 0 ${zr(h.x-T)} ${zr(h.y-H)}L${zr(m.x-T)} ${zr(m.y-H)}A${zr(p)} ${zr(p)} 0 0 0 ${zr(m.x+T)} ${zr(m.y+H)}Z`}function id(m,h,p,w){let S=Math.hypot(m.x-p.x,m.y-p.y),A=Math.hypot(h.x-p.x,h.y-p.y);if(!(S>0)||Math.abs(S-A)>Math.max(.005,S*1e-6))throw new Error("Circular interpolation has inconsistent endpoint radii.");let T=Math.atan2(m.y-p.y,m.x-p.x),H=Math.atan2(h.y-p.y,h.x-p.x),Y=Math.hypot(m.x-h.x,m.y-h.y)<1e-9,ee=Y?mm:nS(w?T-H:H-T),X=w?0:1,G;if(Y){let _e={x:p.x*2-m.x,y:p.y*2-m.y};G=`A${zr(S)} ${zr(S)} 0 1 ${X} ${zr(_e.x)} ${zr(_e.y)}A${zr(S)} ${zr(S)} 0 1 ${X} ${zr(h.x)} ${zr(h.y)}`}else G=`A${zr(S)} ${zr(S)} 0 ${ee>Math.PI?1:0} ${X} ${zr(h.x)} ${zr(h.y)}`;let ae=[m,h];for(let _e of[0,Math.PI/2,Math.PI,Math.PI*1.5])(Y||nS(w?T-_e:_e-T)<=ee+1e-10)&&ae.push({x:p.x+S*Math.cos(_e),y:p.y+S*Math.sin(_e)});return{segment:G,bounds:js(ae),radius:S,sweep:ee,center:p}}function aS(m,h,p,w){let S=h.x-m.x,A=h.y-m.y,T=Math.hypot(S,A);if(!(p>0)||T<1e-12||T>p*2+1e-8)throw new Error("Invalid or ambiguous radius-defined route arc.");let H=Math.sqrt(Math.max(0,p*p-T*T/4)),Y=w?-1:1;return{x:(m.x+h.x)/2-Y*A/T*H,y:(m.y+h.y)/2+Y*S/T*H}}function us(m,{rotation:h=0,mirrorX:p=!1,mirrorY:w=!1,scale:S=1,x:A=0,y:T=0}={}){let H=h*Math.PI/180,Y=m.x*(p?-1:1)*S,ee=m.y*(w?-1:1)*S;return{x:Hi(A+Y*Math.cos(H)-ee*Math.sin(H)),y:Hi(T+Y*Math.sin(H)+ee*Math.cos(H))}}function Fl(m,h={}){let p=m.match(/[MLAZ]|[-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?/gi)||[],w=[],S=h.scale??1,A=!!h.mirrorX!=!!h.mirrorY;for(let T=0;T<p.length;){let H=p[T++];if(H==="Z"){w.push("Z");continue}if(H==="M"||H==="L"){let Y=us({x:Number(p[T++]),y:Number(p[T++])},h);w.push(`${H}${zr(Y.x)} ${zr(Y.y)}`)}else if(H==="A"){let Y=Number(p[T++])*S,ee=Number(p[T++])*S;T++;let X=p[T++],G=Number(p[T++]),ae=us({x:Number(p[T++]),y:Number(p[T++])},h);w.push(`A${zr(Y)} ${zr(ee)} 0 ${X} ${A?1-G:G} ${zr(ae.x)} ${zr(ae.y)}`)}else throw new Error("Unexpected internal CAM path command.")}return w.join("")}function oS(m){let h=[...m].sort((S,A)=>S.x-A.x||S.y-A.y),p=(S,A,T)=>(A.x-S.x)*(T.y-S.y)-(A.y-S.y)*(T.x-S.x),w=S=>{let A=[];for(let T of S){for(;A.length>1&&p(A.at(-2),A.at(-1),T)<=0;)A.pop();A.push(T)}return A};return[...w(h).slice(0,-1),...w(h.reverse()).slice(0,-1)]}function nd(m,h){let p=[],w=[],S=new Set,A=0,T=0;return{operations:p,warnings:w,warn:X=>{S.has(X)||(S.add(X),w.length<100&&w.push(X))},add:X=>{if(p.length>=hs.operations)throw new Error("Manufacturing geometry exceeds 200,000 operations.");if(A+=X.path.length,A>32*1024*1024)throw new Error("Manufacturing SVG geometry exceeds 32 MiB.");if(T+=JSON.stringify(X.metadata||{}).length,T>8*1024*1024)throw new Error("Manufacturing operation metadata exceeds 8 Mi characters.");let G={id:`${h||m}:${p.length+1}`,polarity:"dark",fill:!0,...X};return p.push(G),G},finish:(X={})=>({format:m,path:h,units:"mm",layers:[{id:h||m,name:X.fileFunction||h||m,operations:p}],warnings:w,bounds:hv(p.map(G=>G.bounds)),metadata:X})}}var hs,Hi,zr,ym,mm,nS,vm=Ui(()=>{hs=Object.freeze({bytes:16777216,commands:2e5,operations:2e5,segments:5e5,apertures:1024,repeats:1e4}),Hi=m=>{let h=Number(m);if(!Number.isFinite(h)||Math.abs(h)>1e6)throw new Error("CAM numeric value is invalid or exceeds the 1,000,000 mm coordinate bound.");return h},zr=m=>String(Math.round(Hi(m)*1e9)/1e9);ym=m=>m.map((h,p)=>`${p?"L":"M"}${zr(h.x)} ${zr(h.y)}`).join("")+"Z";mm=Math.PI*2,nS=m=>(m%mm+mm)%mm});function uv(){return Object.fromEntries(Object.keys(xm).map(m=>[m,0]))}function na(m,h,p){if(m[h]+=p,m[h]>xm[h]){let w=new Error(`Gerber compiled aperture ${h} budget exceeded.`);throw w.code="CAM_RESOURCE_LIMIT",w}}function uS(m,h,p=0,w=0,S=0){if(!Number.isInteger(h)||h<3||h>12)throw new Error("Polygon apertures require 3 to 12 vertices.");return Array.from({length:h},(A,T)=>{let H=(S+T*360/h)*Math.PI/180;return{x:p+m/2*Math.cos(H),y:w+m/2*Math.sin(H)}})}function lS(m,h,p){if(m.length>256)throw new Error("Aperture macro expression exceeds 256 characters.");let w=m.match(/\$\d+|(?:\d+(?:\.\d*)?|\.\d+)|[()+\-/xX]/g)||[];if(na(p,"expressionTokens",w.length),w.join("")!==m.replace(/\s/g,"")||w.length>128)throw new Error("Unsupported aperture macro expression.");let S=0,A=0;function T(){if(++A>32)throw new Error("Aperture macro expression nesting exceeds 32.");let X=w[S++],G;if(X==="+"||X==="-")G=(X==="-"?-1:1)*T();else if(X==="("){if(G=Y(),w[S++]!==")")throw new Error("Unclosed aperture macro expression.")}else if(X?.startsWith("$")){let ae=Number(X.slice(1));if(ae>500)throw new Error("Aperture macro variable limit exceeded.");G=h.get(ae)||0}else if(X!==void 0&&/^\d|^\./.test(X))G=Number(X);else throw new Error("Invalid aperture macro expression.");return A--,Hi(G)}function H(){let X=T();for(;["x","X","/"].includes(w[S]);){let G=w[S++],ae=T();if(G==="/"&&ae===0)throw new Error("Aperture macro division by zero.");X=Hi(G==="/"?X/ae:X*ae)}return X}function Y(){let X=H();for(;["+","-"].includes(w[S]);){let G=w[S++],ae=H();X=Hi(G==="+"?X+ae:X-ae)}return X}let ee=Y();if(S!==w.length)throw new Error("Invalid aperture macro expression tail.");return ee}function kD(m,h,p,w){if(m.length>512)throw new Error("Aperture macro exceeds 512 commands.");let S=new Map(h.map((T,H)=>[H+1,Hi(T)])),A=[];for(let T of m){if(na(w,"macroCommands",1),!T||/^0(?:\s|,|$)/.test(T))continue;T.length>128*1024&&na(w,"expressionTokens",xm.expressionTokens+1);let H=0;for(let Q=0;Q<T.length;Q++)T[Q]===","&&++H>4100&&na(w,"expressionTokens",xm.expressionTokens+1);let Y=/^\$(\d+)=(.+)$/.exec(T);if(Y){let Q=Number(Y[1]);if(Q>500)throw new Error("Aperture macro variable limit exceeded.");S.set(Q,lS(Y[2],S,w));continue}let ee=T.split(","),X=Number(ee.shift()),G=ee.map(Q=>lS(Q,S,w));if(![1,4,5,20,21,22].includes(X))throw new Error(`Aperture macro primitive ${X} is unsupported.`);if(G[0]!==1)throw new Error("Aperture macros with clear exposure are unsupported.");let ae,_e=0,J=Q=>Hi(Q*p);if(X===1){if(G.length!==4&&G.length!==5)throw new Error("Invalid macro circle.");let Q=zl(J(G[1]))/2;_e=G[4]||0;let te=us({x:J(G[2]),y:J(G[3])},{rotation:_e});ae=cS(te.x,te.y,Q)}else if(X===20){if(G.length!==7)throw new Error("Invalid macro vector line.");let Q=zl(J(G[1])),te={x:J(G[2]),y:J(G[3])},he={x:J(G[4]),y:J(G[5])},be=Math.hypot(he.x-te.x,he.y-te.y);if(!be)throw new Error("A zero-length macro vector line is unsupported.");let De=-(he.y-te.y)/be*Q/2,Ke=(he.x-te.x)/be*Q/2;_e=G[6],ae=oh([{x:te.x+De,y:te.y+Ke},{x:he.x+De,y:he.y+Ke},{x:he.x-De,y:he.y-Ke},{x:te.x-De,y:te.y-Ke}].map(qe=>us(qe,{rotation:_e})))}else if(X===21||X===22){if(G.length!==6)throw new Error("Invalid macro rectangle.");let Q=zl(J(G[1])),te=zl(J(G[2]));_e=G[5];let he=J(G[3])+(X===22?Q/2:0),be=J(G[4])+(X===22?te/2:0);ae=oh(hS(Q,te,he,be).map(De=>us(De,{rotation:_e})))}else if(X===5){if(G.length!==6)throw new Error("Invalid macro polygon.");ae=oh(uS(zl(J(G[4])),G[1],J(G[2]),J(G[3])).map(Q=>us(Q,{rotation:G[5]})))}else{let Q=G[1];if(!Number.isInteger(Q)||Q<3||Q>2e3||G.length!==Q*2+5)throw new Error("Invalid macro outline.");na(w,"points",Q+1);let te=Array.from({length:Q+1},(he,be)=>({x:J(G[2+be*2]),y:J(G[3+be*2])}));if(Math.hypot(te[0].x-te.at(-1).x,te[0].y-te.at(-1).y)>1e-9)throw new Error("Macro outline is not closed.");ae=oh(te.slice(0,-1).map(he=>us(he,{rotation:G.at(-1)})))}if(na(w,"parts",1),X!==4&&na(w,"points",ae.points?.length||1),na(w,"pathBytes",ae.path.length),A.push(ae),A.length>256)throw new Error("Aperture macro exceeds 256 primitives.")}if(!A.length)throw new Error("Aperture macro contains no drawable primitives.");return A}function dS(m,h,p,w,S=uv()){if(h.length>500)throw new Error("Aperture exceeds 500 parameters.");let A=h.map(Hi),T=ae=>zl(A[ae]*p),H,Y,ee;if(m==="C"){if(A.length<1||A.length>2)throw new Error("Invalid circular aperture parameters.");let ae=T(0)/2;H=[cS(0,0,ae)],Y={type:"circle",radius:ae},ee=ae*2}else if(m==="R"||m==="O"){if(A.length<2||A.length>3)throw new Error("Invalid rectangular/obround aperture parameters.");let ae=T(0),_e=T(1);if(ee=Math.min(ae,_e),m==="R"){let J=hS(ae,_e);H=[oh(J)],Y={type:"polygon",points:J}}else{let J=ee/2,Q={x:-(ae-ee)/2,y:-(_e-ee)/2},te={x:-Q.x,y:-Q.y};H=[{path:sS(Q,te,J),bounds:{x:-ae/2,y:-_e/2,w:ae,h:_e},capsule:{a:Q,b:te,radius:J}}],Math.abs(ae-_e)<1e-12&&(Y={type:"circle",radius:J})}}else if(m==="P"){if(A.length<2||A.length>4)throw new Error("Invalid polygon aperture parameters.");let ae=uS(T(0),A[1],0,0,A[2]||0);H=[oh(ae)],Y={type:"polygon",points:ae},ee=T(0)*Math.cos(Math.PI/A[1])}else{if(!w.has(m))throw new Error(`Aperture macro ${m} is not defined.`);return{template:m,parts:kD(w.get(m),h,p,S)}}let X=m==="C"?1:m==="P"?3:2,G=A[X]?zl(A[X]*p):0;if(G){if(G>=ee)throw new Error("Aperture hole is not contained inside its outer shape.");H[0].path+=ah(0,0,G/2)}na(S,"parts",H.length);for(let ae of H)na(S,"points",ae.points?.length||1),na(S,"pathBytes",ae.path.length);return{template:m,parts:H,stroke:G?null:Y,hole:G}}function pS(m,h){return m.parts.map(p=>{if(p.circle){let S=us(p.circle,h),A=p.circle.radius*h.scale;return{path:Fl(p.path,h),bounds:{x:S.x-A,y:S.y-A,w:A*2,h:A*2}}}if(p.points)return{path:Fl(p.path,h),bounds:js(p.points.map(S=>us(S,h)))};if(p.capsule)return{path:Fl(p.path,h),bounds:js([p.capsule.a,p.capsule.b].map(S=>us(S,h)),p.capsule.radius*h.scale)};let w=[{x:p.bounds.x,y:p.bounds.y},{x:p.bounds.x+p.bounds.w,y:p.bounds.y},{x:p.bounds.x+p.bounds.w,y:p.bounds.y+p.bounds.h},{x:p.bounds.x,y:p.bounds.y+p.bounds.h}].map(S=>us(S,h));return{path:Fl(p.path,h),bounds:js(w)}})}var xm,zl,cS,oh,hS,fS=Ui(()=>{vm();xm=Object.freeze({parts:16384,points:131072,pathBytes:8*1024*1024,macroCommands:32768,expressionTokens:524288});zl=m=>{let h=Hi(m);if(!(h>0))throw new Error("Aperture dimensions must be positive.");return h},cS=(m,h,p)=>({path:ah(m,h,p),bounds:{x:m-p,y:h-p,w:p*2,h:p*2},circle:{x:m,y:h,radius:p}}),oh=m=>({path:ym(m),bounds:js(m),points:m}),hS=(m,h,p=0,w=0)=>[{x:p-m/2,y:w-h/2},{x:p+m/2,y:w-h/2},{x:p+m/2,y:w+h/2},{x:p-m/2,y:w+h/2}]});function*OD(m){let h=0,p=0;for(;h<m.length;){if(/\s/.test(m[h])){h++;continue}let w=m[h]==="%",S=m.indexOf(w?"%":"*",h+(w?1:0));if(S<0)throw new Error("Unterminated Gerber command.");let A=m.slice(h+(w?1:0),S).trim();if(h=S+1,w&&A.startsWith("AM")){if(++p>hs.commands)throw new Error("Gerber command limit exceeded.");yield{extended:w,body:A};continue}let T=0;for(;T<A.length;){let H=w?A.indexOf("*",T):-1,Y=A.slice(T,H<0?A.length:H).trim();if(T=H<0?A.length:H+1,!!Y){if(++p>hs.commands)throw new Error("Gerber command limit exceeded.");yield{extended:w,body:Y}}}}}function mS(m,{path:h=""}={}){gm(m);let p=nd("gerber",h),w=new Map,S=new Map,A=uv(),T=Object.create(null),H=Object.create(null),Y=Object.create(null),ee=null,X=null,G=null,ae=null,_e=null,J="linear",Q=null,te="dark",he={rotation:0,scale:1,mirrorX:!1,mirrorY:!1},be=null,De=null,Ke=!1,qe=0,$e=(N,re)=>{if(!ee||!X)throw new Error("Gerber units and coordinate format must be declared before coordinates.");if(/^[+-]?(?:\d+\.\d*|\.\d+)$/.test(N))return Hi(Number(N)*ee);if(!/^[+-]?\d+$/.test(N))throw new Error("Invalid Gerber coordinate.");let R=N.startsWith("-")?-1:1,$=N.replace(/^[+-]/,""),V=X[re];if($.length>V.integer+V.decimal)throw new Error("Gerber coordinate exceeds its declared digit format.");let O=X.zeros==="T"?$.padEnd(V.integer+V.decimal,"0"):$.padStart(V.integer+V.decimal,"0");return Hi(R*Number(O)/10**V.decimal*ee)},Xe=(N,re,R={})=>{let $={...N,kind:re,polarity:te,metadata:{aperture:ae,apertureAttributes:{...w.get(ae)?.attributes},objectAttributes:{...Y},...R}};(be?be.buffer:p).add($)};function ve(){if(be){for(let N=0;N<be.x;N++)for(let re=0;re<be.y;re++)for(let R of be.buffer.operations){let{id:$,...V}=R,O=N*be.i,C=re*be.j;p.add({...V,path:O||C?Fl(V.path,{x:O,y:C}):V.path,bounds:{...V.bounds,x:V.bounds.x+O,y:V.bounds.y+C},metadata:{...V.metadata,repeat:{x:N,y:re}}})}be=null}}function Ee(){if(!De?.contour)return;let N=De.contour;if(N.edges&&Math.hypot(N.start.x-G.x,N.start.y-G.y)>1e-7)throw new Error("Gerber region contour is not closed.");N.edges&&(De.paths.push(N.path+"Z"),De.bounds.push(...N.bounds)),De.contour=null}function me(N,re,R){if(!Q)throw new Error("Gerber circular interpolation requires G74 or G75 quadrant mode.");let $=R.I===void 0?0:$e(R.I,"x"),V=R.J===void 0?0:$e(R.J,"y"),O=J==="clockwise";if(Q==="multi")return id(N,re,{x:N.x+$,y:N.y+V},O);let C=[];for(let j of[-1,1])for(let B of[-1,1])try{let W=id(N,re,{x:N.x+Math.abs($)*j,y:N.y+Math.abs(V)*B},O);W.sweep<=Math.PI/2+1e-6&&!C.some(K=>Math.hypot(K.center.x-W.center.x,K.center.y-W.center.y)<1e-8)&&C.push(W)}catch{}if(C.length!==1)throw new Error("Gerber single-quadrant arc has no unique valid center.");return C[0]}for(let N of OD(m)){let re=N.body;if(Ke)throw new Error("Gerber commands appear after M02.");if(!N.extended&&/^G0?4/.test(re))continue;if(N.extended&&re.startsWith("AM")){let K=0;for(let ne=0;ne<re.length;ne++)if(re[ne]==="*"&&++K>513)throw new Error("Aperture macro exceeds 512 commands.");let ge=re.split("*").map(ne=>ne.trim()).filter(Boolean),Ne=ge.shift().slice(2);if(!/^[A-Za-z_.$][A-Za-z0-9_.$]{0,99}$/.test(Ne)||S.has(Ne)||S.size>=hs.apertures)throw new Error("Invalid, duplicate or excessive Gerber aperture macro.");S.set(Ne,ge);continue}let R=re.replace(/\s/g,"");if(N.extended){let K;if(K=/^FS([LT])([AI])X(\d)(\d)Y(\d)(\d)$/.exec(R)){if(X||K[2]!=="A")throw new Error("Repeated or incremental Gerber format declarations are unsupported.");let ge={integer:Number(K[3]),decimal:Number(K[4])},Ne={integer:Number(K[5]),decimal:Number(K[6])};if([ge,Ne].some(ne=>ne.integer<1||ne.integer>6||ne.decimal<1||ne.decimal>7))throw new Error("Invalid Gerber digit format.");X={zeros:K[1],x:ge,y:Ne};continue}if(/^MO(MM|IN)$/.test(R)){let ge=R==="MOMM"?1:25.4;if(ee&&ee!==ge)throw new Error("Gerber unit changes within a file are unsupported.");ee=ge;continue}if(K=/^ADD(\d+)([A-Za-z_.$][A-Za-z0-9_.$]*)(?:,(.*))?$/.exec(R)){if(!ee)throw new Error("Gerber aperture declaration needs explicit units.");let ge=Number(K[1]);if(ge<10||w.has(ge)||w.size>=hs.apertures)throw new Error("Invalid, duplicate or excessive Gerber aperture.");if(K[3]){let Ne=0;for(let ne=0;ne<K[3].length;ne++)if(K[3][ne]==="X"&&++Ne>=500)throw new Error("Aperture exceeds 500 parameters.")}try{w.set(ge,{...dS(K[2],K[3]?K[3].split("X"):[],ee,S,A),attributes:{...H}})}catch(Ne){if(Ne.code==="CAM_RESOURCE_LIMIT")throw Ne;w.set(ge,{unsupported:Ne.message,attributes:{...H}})}continue}if(K=/^(TF|TA|TO)([^,]+)(?:,(.*))?$/.exec(re)){let ge=K[1]==="TF"?T:K[1]==="TA"?H:Y;if(Object.keys(ge).length>=128||re.length>4096)throw new Error("Gerber attributes exceed metadata limits.");ge[K[2]]=K[3]===void 0?[]:K[3].split(",");continue}if(K=/^TD(.*)$/.exec(R)){for(let ge of[H,Y])for(let Ne of Object.keys(ge))(!K[1]||Ne===K[1])&&delete ge[Ne];continue}if(/^LP[DC]$/.test(R)){if(De)throw new Error("Polarity changes inside a Gerber region are unsupported.");te=R==="LPD"?"dark":"clear";continue}if(K=/^LM(N|X|Y|XY)$/.exec(R)){he={...he,mirrorX:K[1].includes("X"),mirrorY:K[1].includes("Y")};continue}if(K=/^LR([+-]?(?:\d+(?:\.\d*)?|\.\d+))$/.exec(R)){he={...he,rotation:Hi(K[1])};continue}if(K=/^LS([+]?(?:\d+(?:\.\d*)?|\.\d+))$/.exec(R)){let ge=Hi(K[1]);if(!(ge>0))throw new Error("Invalid aperture scale.");he={...he,scale:ge};continue}if(R==="SR"){if(De)throw new Error("Step-repeat changes inside a region are unsupported.");ve();continue}if(K=/^SRX(\d+)Y(\d+)I([+-]?(?:\d+(?:\.\d*)?|\.\d+))J([+-]?(?:\d+(?:\.\d*)?|\.\d+))$/.exec(R)){if(De||be||!ee)throw new Error("Nested or invalid Gerber step-repeat state.");if(be={x:Number(K[1]),y:Number(K[2]),i:Hi(Number(K[3])*ee),j:Hi(Number(K[4])*ee),buffer:nd("gerber-repeat",h)},be.x<1||be.y<1||be.x*be.y>hs.repeats)throw new Error("Gerber step-repeat exceeds 10,000 copies.");continue}if(/^LN/.test(R)){T.LayerName=[re.slice(2)];continue}if(R==="IPPOS")continue;throw new Error(`Unsupported Gerber state command: ${R.slice(0,80)}.`)}if(/^M0?2$/.test(R)){if(De||be)throw new Error("Gerber ended inside a region or step-repeat block.");Ke=!0;continue}if(/^G0?36$/.test(R)){if(De)throw new Error("Nested Gerber regions are unsupported.");De={paths:[],bounds:[],contour:null};continue}if(/^G0?37$/.test(R)){if(!De)throw new Error("Gerber region end without a start.");Ee(),De.paths.length&&Xe({path:De.paths.join(""),bounds:hv(De.bounds)},"region"),De=null;continue}if(/^G0?74$/.test(R)){Q="single";continue}if(/^G0?75$/.test(R)){Q="multi";continue}if(/^G0?90$/.test(R))continue;if(/^G0?91$/.test(R))throw new Error("Incremental Gerber coordinates are unsupported.");let $=R.replace(/^G0?54/,""),V=[...$.matchAll(/([XYIJDG])([+-]?(?:\d+(?:\.\d*)?|\.\d+))/g)];if(!V.length||V.map(K=>K[0]).join("")!==$)throw new Error(`Unsupported Gerber command: ${R.slice(0,80)}.`);let O=Object.create(null);for(let K of V){if(O[K[1]]!==void 0)throw new Error("Duplicate Gerber coordinate/code word.");O[K[1]]=K[2]}if(O.G!==void 0){let K=Number(O.G);if(![1,2,3].includes(K))throw new Error(`Unsupported Gerber interpolation G${K}.`);J=K===1?"linear":K===2?"clockwise":"counterclockwise"}if(O.D!==void 0&&Number(O.D)>=10){if(["X","Y","I","J"].some(K=>O[K]!==void 0))throw new Error("Aperture selection cannot carry coordinates.");if(ae=Number(O.D),!w.has(ae))throw new Error("Selected Gerber aperture is undefined.");continue}if(O.D!==void 0&&(_e=Number(O.D),![1,2,3].includes(_e)))throw new Error("Invalid Gerber operation code.");if(!["X","Y"].some(K=>O[K]!==void 0)&&O.D===void 0)continue;if(!_e)throw new Error("Gerber coordinates have no operation code.");let j={x:O.X===void 0?G?.x:$e(O.X,"x"),y:O.Y===void 0?G?.y:$e(O.Y,"y")};if(!Number.isFinite(j.x)||!Number.isFinite(j.y))throw new Error("The first Gerber position must define both axes.");if(++qe>hs.segments)throw new Error("Gerber geometry segment limit exceeded.");if(_e===2){De&&(Ee(),De.contour={start:j,path:`M${zr(j.x)} ${zr(j.y)}`,bounds:[],edges:0}),G=j;continue}let B=w.get(ae);if(_e===3){if(De)throw new Error("A flash is not valid inside a Gerber region.");if(!B)throw new Error("Gerber flash needs a selected aperture.");if(B.unsupported)p.warn(`D${ae} omitted: ${B.unsupported}`);else for(let K of pS(B,{...he,x:j.x,y:j.y}))Xe(K,"flash");G=j;continue}if(!G)throw new Error("Gerber draw needs a starting position.");let W=J==="linear"?{segment:`L${zr(j.x)} ${zr(j.y)}`,bounds:js([G,j])}:me(G,j,O);if(De){if(!De.contour)throw new Error("A region contour needs an initial D02 move.");De.contour.path+=W.segment,De.contour.bounds.push(W.bounds),De.contour.edges++}else{if(!B)throw new Error("Gerber draw needs a selected aperture.");if(B.unsupported||!B.stroke)p.warn(`D${ae} draw omitted: ${B.unsupported||"unsupported swept aperture or aperture hole"}.`);else if(B.stroke.type==="circle"){let K=B.stroke.radius*2*he.scale,ge=W.bounds;Xe({path:`M${zr(G.x)} ${zr(G.y)}`+W.segment,fill:!1,width:K,bounds:{x:ge.x-K/2,y:ge.y-K/2,w:ge.w+K,h:ge.h+K}},"stroke")}else if(J==="linear"){let K=B.stroke.points.map(Ne=>us(Ne,he)),ge=oS(K.flatMap(Ne=>[{x:Ne.x+G.x,y:Ne.y+G.y},{x:Ne.x+j.x,y:Ne.y+j.y}]));Xe({path:ym(ge),bounds:js(ge)},"stroke")}else p.warn(`D${ae} circular draw omitted: non-circular swept apertures are unsupported.`)}G=j}if(De)throw new Error("Unclosed Gerber region.");if(be)throw new Error("Unclosed Gerber step-repeat block.");if(!ee||!X)throw new Error("Gerber units/format are missing; RS-274D without embedded apertures is unsupported.");return Ke||p.warn("Gerber M02 end marker is missing."),p.finish({inputUnits:ee===1?"mm":"inch",coordinateFormat:X,attributes:{...T},fileFunction:T[".FileFunction"]?.join(",")||T.LayerName?.join(",")})}var gS=Ui(()=>{vm();fS()});function dv(m){if(m==null)return null;let h=Array.isArray(m)?m:typeof m=="string"?m.split(":").map(Number):[m.integer,m.decimal];if(h.length!==2||h.some(p=>!Number.isInteger(p))||h[0]<1||h[0]>6||h[1]<1||h[1]>7)throw new TypeError("Excellon formatDigits must specify integer and decimal digit counts.");return{integer:h[0],decimal:h[1]}}function yS(m,h={}){gm(m);let{path:p=""}=h,w=nd("excellon",p),S=new Map,A=Object.create(null),T=Object.create(null),H=Object.create(null),Y=h.units===void 0?null:h.units==="mm"?1:h.units==="inch"?25.4:NaN;if(Number.isNaN(Y))throw new TypeError("Excellon units must be mm or inch.");let ee=Y,X=dv(h.formatDigits),G=h.zeroSuppression||null;if(G&&!["leading","trailing","none"].includes(G))throw new TypeError("Excellon zeroSuppression must be leading, trailing or none.");let ae=h.decimal===!0||h.coordinateFormat==="decimal"||/\.xnc$/i.test(p),_e=!1,J=!1,Q=!1,te=!1,he=null,be=null,De="drill",Ke=!1,qe="linear",$e=null,Xe=1;for(let B=0;B<m.length;B++)if(m.charCodeAt(B)===10&&++Xe>hs.commands)throw new Error("Excellon command limit exceeded.");let ve=m.split(/\r?\n/),Ee=B=>{if(ee&&ee!==B)throw new Error("Excellon units conflict with the header/options.");ee=B},me=B=>{if(X&&(X.integer!==B.integer||X.decimal!==B.decimal))throw new Error("Excellon digit format conflicts with the header/options.");X=B},N=B=>{if(G&&G!==B)throw new Error("Excellon zero suppression conflicts with the header/options.");G=B},re=B=>{if(!ee)throw new Error("Excellon units are missing; specify units explicitly.");if(/^[+-]?(?:\d+\.\d*|\.\d+)$/.test(B)||ae)return Hi(Number(B)*ee);if(!/^[+-]?\d+$/.test(B))throw new Error("Invalid Excellon coordinate.");if(Number(B)===0)return 0;if(!X)throw new Error("Ambiguous Excellon integer coordinates: specify formatDigits or use a declared decimal format.");let W=B.startsWith("-")?-1:1,K=B.replace(/^[+-]/,""),ge=X.integer+X.decimal;if(K.length>ge)throw new Error("Excellon coordinate exceeds its declared digit format.");if(K.length<ge&&(!G||G==="none"))throw new Error("Ambiguous Excellon omitted zeros: specify zeroSuppression.");let Ne=G==="trailing"?K.padEnd(ge,"0"):K.padStart(ge,"0");return Hi(W*Number(Ne)/10**X.decimal*ee)};function R(B){let W=[...B.matchAll(/([XYIJA])([+-]?(?:\d+(?:\.\d*)?|\.\d+))/g)];if(!W.length||W.map(ge=>ge[0]).join("")!==B)throw new Error(`Unsupported Excellon coordinate command: ${B.slice(0,80)}.`);let K=Object.create(null);for(let ge of W){if(K[ge[1]]!==void 0)throw new Error("Duplicate Excellon coordinate word.");K[ge[1]]=re(ge[2])}return K}function $(B,W=he){let K={x:B.X??W?.x,y:B.Y??W?.y};if(!Number.isFinite(K.x)||!Number.isFinite(K.y))throw new Error("The first Excellon position must define both axes.");return K}function V(){let B=S.get(be);if(!B)throw new Error("Excellon geometry requires a defined selected tool.");return B}function O(B,W,K){let ge=V();w.add({...B,kind:W,metadata:{tool:be,diameter:ge.diameter,line:K,toolAttributes:{...ge.attributes},objectAttributes:{...H}}}),ge.operations++}function C(B,W){let K=V().diameter/2;O({path:ah(B.x,B.y,K),bounds:{x:B.x-K,y:B.y-K,w:K*2,h:K*2}},"drill",W)}function j(B,W,K,ge,Ne="route"){let ne=V().diameter,we,xe;if(qe==="linear"||Ne==="slot")we=`L${zr(W.x)} ${zr(W.y)}`,xe=js([B,W]);else{let ke=qe==="clockwise",Me;if(K.I!==void 0||K.J!==void 0)Me={x:B.x+(K.I||0),y:B.y+(K.J||0)};else{let Ce=K.A??$e;if(!Ce)throw new Error("Excellon circular routing requires I/J offsets or an explicit A radius.");$e=Ce,Me=aS(B,W,Ce,ke)}({segment:we,bounds:xe}=id(B,W,Me,ke))}O({path:`M${zr(B.x)} ${zr(B.y)}`+we,fill:!1,width:ne,bounds:{x:xe.x-ne/2,y:xe.y-ne/2,w:xe.w+ne,h:xe.h+ne}},Ne,ge)}for(let B=0;B<ve.length;B++){let W=ve[B].trim();if(!W)continue;if(W.startsWith(";")){let ke;if((ke=/FILE_FORMAT\s*=\s*(\d+)\s*:\s*(\d+)/i.exec(W))&&me(dv([Number(ke[1]),Number(ke[2])])),/FORMAT=.*\/\s*decimal\s*\}/i.test(W)&&(ae=!0),ke=/#@!\s*(TF|TA|TO)([^,\s]+)(?:,(.*))?/.exec(W)){let Me=ke[1]==="TF"?A:ke[1]==="TA"?T:H;if(Object.keys(Me).length>128||W.length>4096)throw new Error("Excellon attributes exceed metadata limits.");Me[ke[2]]=ke[3]?.split(",")||[]}if(/#@!\s*TD/.test(W))for(let Me of[T,H])for(let Ce of Object.keys(Me))delete Me[Ce];continue}if(te)throw new Error("Excellon commands appear after M30.");let K=W.replace(/\s/g,""),ge;if(K==="M48"){if(J)throw new Error("Repeated Excellon header.");J=_e=!0;continue}if(!J)throw new Error("An Excellon M48 header is required in this beta.");if(K==="%"||K==="M95"){if(!_e)throw new Error("Unexpected Excellon header end.");_e=!1,Q=!0;continue}if(ge=/^(METRIC|INCH)(?:,(LZ|TZ))?(?:,(0+)\.(0+))?$/.exec(K)){if(!_e)throw new Error("Excellon unit declaration must be in its header.");Ee(ge[1]==="METRIC"?1:25.4),ge[2]&&N(ge[2]==="LZ"?"trailing":"leading"),ge[3]&&me(dv([ge[3].length,ge[4].length]));continue}if(K==="M71"||K==="M72"){Ee(K==="M71"?1:25.4);continue}if(K==="FMAT,2"||K==="VER,1"||K==="ICI,OFF"||K==="G90")continue;if(K==="G91"||K==="ICI,ON")throw new Error("Incremental Excellon coordinates are unsupported.");if(ge=/^T(\d+)C((?:\d+(?:\.\d*)?|\.\d+))(?:F[\d.]+)?(?:S[\d.]+)?$/.exec(K)){if(!_e||!ee)throw new Error("Excellon tools must be declared in a header with explicit units.");let ke=Number(ge[1]),Me=Hi(Number(ge[2])*ee);if(ke<1||ke>9999||S.has(ke)||S.size>=hs.apertures||!(Me>0))throw new Error("Invalid, duplicate or excessive Excellon tool.");S.set(ke,{diameter:Me,attributes:{...T},operations:0});continue}if(_e)throw new Error(`Unsupported Excellon header command: ${K.slice(0,80)}.`);if(K==="M30"){if(Ke)throw new Error("Excellon ended with the route tool down.");te=!0;continue}if(ge=/^T(\d+)$/.exec(K)){if(be=Number(ge[1])||null,be&&!S.has(be))throw new Error("Undefined Excellon tool selected.");continue}if(/^G0?5$/.test(K)){De="drill",Ke=!1,qe="linear";continue}if(K==="M15"){if(De!=="rout"||!he)throw new Error("Excellon tool down requires a route start.");V(),Ke=!0;continue}if(K==="M16"||K==="M17"){Ke=!1;continue}if(K.includes("G85")){if(Ke)throw new Error("G85 slot encountered while routing.");let ke=K.split("G85");if(ke.length!==2||!ke[1])throw new Error("Invalid Excellon G85 slot.");let Me=ke[0]?$(R(ke[0])):he;if(!Me)throw new Error("Excellon slot start is undefined.");let Ce=$(R(ke[1]),Me);j(Me,Ce,{},B+1,"slot"),he=Ce;continue}if(ge=/^R(\d+)(.*)$/.exec(K)){let ke=Number(ge[1]);if(De!=="drill"||!he||ke<1||ke>hs.repeats)throw new Error("Invalid or excessive Excellon repeat drill pattern.");let Me=R(ge[2]);if(Object.keys(Me).some(Ce=>!["X","Y"].includes(Ce)))throw new Error("Unsupported Excellon repeat fields.");for(let Ce=0;Ce<ke;Ce++)he={x:Hi(he.x+(Me.X||0)),y:Hi(he.y+(Me.Y||0))},C(he,B+1);continue}let Ne=K,ne=null;if((ge=/^G(0?[0123])(.*)$/.exec(K))&&(ne=Number(ge[1]),Ne=ge[2]),ne===0){if(De="rout",Ke)throw new Error("Rapid route movement with tool down is unsupported.");Ne&&(he=$(R(Ne)));continue}ne!==null&&(De="rout",qe=ne===1?"linear":ne===2?"clockwise":"counterclockwise");let we=R(Ne),xe=$(we);if(De==="drill"){if(["I","J","A"].some(ke=>we[ke]!==void 0))throw new Error("Unexpected arc fields in drill mode.");C(xe,B+1)}else{if(!Ke||!he)throw new Error("Excellon route segment requires tool down and a starting point.");j(he,xe,we,B+1)}he=xe}if(!Q||_e)throw new Error("Excellon header is incomplete.");if(!ee)throw new Error("Excellon units are missing.");return te||w.warn("Excellon M30 end marker is missing."),w.finish({inputUnits:ee===1?"mm":"inch",coordinateFormat:ae?"decimal":X,zeroSuppression:G,attributes:{...A},fileFunction:A[".FileFunction"]?.join(","),tools:[...S].map(([B,W])=>({id:B,diameter:W.diameter,operations:W.operations,attributes:{...W.attributes}}))})}var vS=Ui(()=>{vm()});function Co(m,h=""){if(typeof m!="string")return null;let p=m.slice(0,65536).replace(/^\uFEFF/,"");return/%\s*(?:FS[LT][AI]X\d\dY\d\d|MO(?:MM|IN)|ADD\d+)/.test(p)?"gerber":/(?:^|\n)\s*M48\s*(?:\r?\n|$)/.test(p)?"excellon":null}function pv(m,h={}){let p=h.format||Co(m,h.path);if(p==="gerber")return mS(m.replace(/^\uFEFF/,""),h);if(p==="excellon"||p==="xnc")return yS(m.replace(/^\uFEFF/,""),h);throw new Error("Source is not a recognized Gerber RS-274X or Excellon/XNC file.")}var sd=Ui(()=>{gS();vS()});var PF,fv,sa,lh,xS,Bl=Ui(()=>{PF=Vn(To(),1),fv=globalThis.KiCadDesignDiff,sa=fv.MAX_FILE_BYTES,lh=fv.MAX_PROJECT_BYTES,xS=fv.MAX_RENDER_PRIMITIVES});function vv(m,h){if(!(m instanceof URL)&&(typeof m!="string"||!m||m.length>8192))throw new TypeError("Supply a non-empty design URL.");let p=new URL(m,h);if(!["http:","https:"].includes(p.protocol)||p.username||p.password)throw new TypeError("Use an HTTP(S) design URL without embedded credentials.");return p}function ES(m){if(!["omit","same-origin"].includes(m))throw new TypeError("Credentials must be omit or same-origin.");return m}async function mv(m){try{await m.body?.cancel()}catch{}}async function ch(m,{signal:h,credentials:p="omit",limit:w=bm}={},S=!1){if(ES(p),!Number.isSafeInteger(w)||w<=0||w>bm)throw new TypeError("Invalid download limit.");h?.throwIfAborted();let A=await fetch(vv(m),{signal:h,credentials:p,referrerPolicy:"no-referrer"});if(h?.aborted&&(await mv(A),h.throwIfAborted()),!A.ok)throw await mv(A),new Error(`Design request failed (${A.status}).`);let T=()=>new Error(`Design exceeds the ${w===bm?"256 MiB":w+" byte"} download limit.`);if(Number(A.headers.get("content-length"))>w)throw await mv(A),T();if(!A.body?.getReader)throw new Error("Streaming downloads are unavailable; use loadSource.");let H=A.body.getReader(),Y=new TextDecoder,ee=0,X="",G=S?[]:null;try{for(;;){h?.throwIfAborted();let{done:_e,value:J}=await H.read();if(h?.throwIfAborted(),_e)break;if(ee+=J.byteLength,ee>w)throw T();S?G.push(J.slice()):X+=Y.decode(J,{stream:!0})}S||(X+=Y.decode())}finally{try{await H.cancel()}catch{}}let ae;if(S){ae=new Uint8Array(ee);let _e=0;for(let J of G)ae.set(J,_e),_e+=J.byteLength}return{source:X,bytes:ae,size:ee,type:A.headers.get("content-type")||"",url:A.url||String(m)}}async function xv(m,h={}){return(await ch(m,h,!0)).bytes}async function eo(m,h={}){return(await ch(m,h)).source}async function SS(m,{signal:h,credentials:p="omit"}={}){let{bytes:w}=await ch(m,{signal:h,credentials:p,limit:DD},!0),S="";for(let A=0;A<w.length;A+=32768)S+=String.fromCharCode(...w.subarray(A,A+32768));return{base64:btoa(S)}}function Em(m){return typeof m=="string"&&m.length>0&&m.length<=1e3&&!/[\\\x00-\x1f\x7f%?#:]/.test(m)&&m.split("/").every(h=>h&&h!=="."&&h!=="..")}function yv(m){try{return JSON.parse(m)}catch{throw new Error("Expected a valid project manifest or repository JSON response.")}}function wm(m,h){if(!m||typeof m!="object"||Array.isArray(m)||!Array.isArray(m.files)||!m.files.length||m.files.length>wS)throw new TypeError("A project manifest needs between 1 and 256 files.");let p=new Set,w=m.files.map(S=>{if(!S||!Em(S.path)||!_S(S.path)||typeof S.url!="string"||!S.url)throw new TypeError("Each manifest file needs a safe relative drawing/model path and HTTP(S) URL.");if(p.has(S.path))throw new TypeError("Project file paths must be unique.");return p.add(S.path),Object.freeze({path:S.path,url:vv(S.url,h).href})});if(!w.some(S=>Ro(S.path)))throw new TypeError("A project must contain a supported KiCad, manufacturing or ZIP drawing.");if(m.entry!==void 0&&(!Em(m.entry)||!w.some(S=>S.path===m.entry&&Ro(S.path))))throw new TypeError("The project entry must name a listed supported drawing.");if(m.worksheet!==void 0&&!w.some(S=>S.path===m.worksheet&&Hn(S.path)))throw new TypeError("The manifest worksheet must name a listed .kicad_wks file.");return{files:Object.freeze(w),...m.worksheet!==void 0?{worksheet:m.worksheet}:{},...m.entry!==void 0?{entry:m.entry}:{}}}async function Sm(m,h){let p=h.file||m.entry,w=p?m.files.find(T=>T.path===p&&Ro(T.path)):[...m.files].filter(T=>Ro(T.path)).sort((T,H)=>Number(/\.kicad_pcb$/i.test(H.path))-Number(/\.kicad_pcb$/i.test(T.path))||Number(Hn(T.path))-Number(Hn(H.path))||(T.path<H.path?-1:T.path>H.path?1:0))[0];if(!w)throw new Error("The requested project drawing is not listed.");let S=Object.freeze({...m,entry:w.path});if(rd(w.path))return{archive:await xv(w.url,h),path:w.path,project:S};if(h.metadataOnly)return{path:w.path,project:S};if(sh(w.path)){let T=[],H=0;for(let X of m.files.filter(G=>sh(G.path))){let G=await eo(X.url,{...h,limit:33554432});if(H+=new TextEncoder().encode(G).byteLength,H>128*1024*1024)throw new Error("Manufacturing project exceeds 128 MiB.");(!X.path.toLowerCase().endsWith(".txt")||Co(G,X.path))&&T.push({path:X.path,source:G})}let Y=T.find(X=>X.path===w.path)||(p?null:T[0]);if(!Y)throw new Error("The requested manufacturing entry was not recognized as Gerber or Excellon.");let ee=new Set(T.map(X=>X.path));return{files:T,path:Y.path,project:Object.freeze({...S,entry:Y.path,files:Object.freeze(m.files.filter(X=>!X.path.toLowerCase().endsWith(".txt")||ee.has(X.path)))})}}return{source:await eo(w.url,Hn(w.path)?{...h,limit:2*1024*1024}:h),path:w.path,project:S}}function UD(m,h){let p;try{p=m.pathname.split("/").filter(Boolean).map(decodeURIComponent)}catch{throw new TypeError("Invalid encoded GitHub path.")}if(p.length<2||p.slice(0,2).some(X=>!/^[A-Za-z0-9_.-]+$/.test(X)||[".",".."].includes(X)))throw new TypeError("Use a GitHub repository, tree or file link.");let[w,S]=p,A=`${w}/${S.replace(/\.git$/i,"")}`;if(!A.split("/")[1])throw new TypeError("Invalid GitHub repository.");if(p.length===2)return{repository:A,ref:h,path:"",type:"repo"};let T=p[2];if(!["blob","tree"].includes(T))throw new TypeError("Use a GitHub repository, tree or blob link.");let H=p.slice(3).join("/"),Y=h||p[3];if(typeof Y!="string"||!Y||Y.length>500||!/^[A-Za-z0-9_./-]+$/.test(Y)||Y.split("/").some(X=>!X||X==="."||X===".."))throw new TypeError("Invalid GitHub revision. Use the ref option for branches containing slashes.");if(!(H===Y||H.startsWith(Y+"/")))throw new TypeError("The explicit ref must match the GitHub URL.");let ee=H.slice(Y.length).replace(/^\//,"");if(ee&&!Em(ee)||T==="blob"&&!ee)throw new TypeError("Invalid GitHub design path.");return{repository:A,ref:Y,path:ee,type:T}}function gv(m,h,p){return`https://raw.githubusercontent.com/${m}/${h}/${p.split("/").map(encodeURIComponent).join("/")}`}async function FD(m,h){let p=UD(m,h.ref),w=`https://api.github.com/repos/${p.repository}`,S=_m,A=async ae=>{let _e=await ch(ae,{...h,credentials:"omit",limit:S});if(S-=_e.size,S<=0)throw new Error("GitHub metadata exceeds the 8 MiB budget.");let J=yv(_e.source);if(!J||typeof J!="object"||Array.isArray(J))throw new Error("Invalid GitHub response.");return J};if(!p.ref){let ae=await A(w);p.ref=ae.default_branch}if(typeof p.ref!="string"||!p.ref||p.ref.length>500||/[\x00-\x1f\x7f]/.test(p.ref))throw new Error("GitHub did not provide a valid default revision.");let T=await A(`${w}/commits/${encodeURIComponent(p.ref)}`);if(!bS(T.sha)||!bS(T.commit?.tree?.sha))throw new Error("GitHub did not provide an immutable commit/tree revision.");let H=T.sha;if(p.type==="blob"&&/\.json$/i.test(p.path)){let ae=gv(p.repository,H,p.path),_e=await ch(ae,{...h,limit:_m}),J=wm(yv(_e.source),_e.url);return Sm(J,h)}if(p.type==="blob"&&Ro(p.path)&&!h.file){let ae=gv(p.repository,H,p.path);return rd(p.path)?{archive:await xv(ae,h),path:p.path,project:null}:h.metadataOnly?{path:p.path,project:{entry:p.path,files:[{path:p.path,url:ae}]}}:{source:await eo(ae,Hn(p.path)?{...h,limit:2*1024*1024}:h),path:p.path,project:null}}let Y=await A(`${w}/git/trees/${T.commit.tree.sha}?recursive=1`);if(Y.truncated===!0)throw new Error("GitHub returned a truncated tree. Use a hosted project manifest for this repository.");if(Y.truncated!==!1||!Array.isArray(Y.tree))throw new Error("Invalid GitHub file listing.");let ee=p.path;if(p.type==="blob"){if(!/\.kicad_pro$/i.test(p.path))throw new TypeError("Choose a KiCad project, schematic or PCB link.");if(ee=p.path.split("/").slice(0,-1).join("/"),!Y.tree.some(ae=>ae.path===p.path&&ae.type==="blob"&&!["120000","160000"].includes(ae.mode)))throw new Error("The requested KiCad project is not present at this revision.")}let X=[];for(let ae of Y.tree)if(!(ae.type!=="blob"||!["100644","100755"].includes(ae.mode)||!Em(ae.path)||!_S(ae.path))&&!(ee&&!ae.path.startsWith(ee+"/"))&&(X.push(Object.freeze({path:ae.path,url:gv(p.repository,H,ae.path)})),X.length>wS))throw new Error("The project exceeds 256 supported files. Use a smaller project manifest.");if(!X.some(ae=>Ro(ae.path)))throw new Error("No supported KiCad or manufacturing drawings were found in this project.");let G;if(p.type==="blob"){let ae=p.path.replace(/\.kicad_pro$/i,"");G=[ae+".kicad_pcb",ae+".kicad_sch"].find(_e=>X.some(J=>J.path===_e))}return Sm({files:Object.freeze(X),entry:G,revision:H,repository:p.repository},h)}async function Mm(m,{baseURL:h,signal:p,ref:w,file:S,credentials:A="omit",metadataOnly:T=!1}={}){let H={signal:p,ref:w,file:S,credentials:ES(A),metadataOnly:T===!0};if(m&&typeof m=="object"&&!(m instanceof URL))return Sm(wm(m,h),H);let Y=vv(m,h);if(Y.hostname==="github.com"&&!Y.port&&Y.protocol==="https:")return FD(Y,H);if(Y.hostname==="gitlab.com"&&!Y.port&&Y.protocol==="https:"&&Y.pathname.includes("/-/blob/")&&(Y=new URL(Y.href.replace("/-/blob/","/-/raw/"))),/\.kicad_pro$/i.test(Y.pathname))throw new TypeError("A hosted .kicad_pro needs a project manifest listing its schematic and PCB URLs.");if(rd(Y.pathname))return{archive:await xv(Y,H),path:decodeURIComponent(Y.pathname.split("/").at(-1)),project:null};if(H.metadataOnly&&Ro(Y.pathname)){let G;try{G=decodeURIComponent(Y.pathname.split("/").at(-1))}catch{throw new TypeError("Invalid encoded design filename.")}let ae=wm({entry:G,files:[{path:G,url:Y.href}]},Y.href);return{path:G,project:ae}}let ee=await ch(Y,{...H,limit:/\.json$/i.test(Y.pathname)?_m:Hn(Y.pathname)?2*1024*1024:bm});if(/\.json$/i.test(Y.pathname)||/\bapplication\/(?:[a-z\d.+-]+\+)?json\b/i.test(ee.type)){if(ee.size>_m)throw new Error("Project manifest exceeds 8 MiB.");return Sm(wm(yv(ee.source),ee.url),H)}let X;try{X=decodeURIComponent(Y.pathname.split("/").at(-1))}catch{throw new TypeError("Invalid encoded design filename.")}return{source:ee.source,path:X||"drawing.kicad_pcb",project:null}}var bm,_m,DD,wS,Ro,_S,bS,Am=Ui(()=>{Qa();sd();Bl();bm=sa,_m=8*1024*1024,DD=8*1024*1024,wS=256,Ro=Ja,_S=m=>Ro(m)||/\.(wrl|glb)$/i.test(m),bS=m=>typeof m=="string"&&/^[a-f\d]{40}$/i.test(m)});function VD(m){let h=4294967295;for(let p of m)h=jD[(h^p)&255]^h>>>8;return(h^4294967295)>>>0}function HD(m){let h={};for(let[p,w]of Object.entries(zD)){let S=m[p]??w;if(!Number.isSafeInteger(S)||S<1||S>w)throw new TypeError(`ZIP ${p} must be an integer between 1 and ${w}.`);h[p]=S}return h}function GD(m,h){if(!(h&2048)&&m.some(S=>S>127))throw new Error("ZIP non-UTF-8 filenames are unsupported; use UTF-8 or ASCII filenames.");let p;try{p=BD.decode(m)}catch{throw new Error("ZIP filename is not valid UTF-8.")}let w=p.endsWith("/")?p.slice(0,-1):p;if(!w||w.length>1e3||/[\\\x00-\x1f\x7f%?#:]/.test(w)||w.startsWith("/")||w.split("/").some(S=>!S||S==="."||S===".."||/[. ]$/.test(S)||/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(S)))throw new Error("ZIP entry has an unsafe relative path.");return p}function MS(m,h,p){let w=h+p;for(;h<w;){if(h+4>w)throw new Error("ZIP extra field is truncated.");let S=m.getUint16(h,!0),A=m.getUint16(h+2,!0);if(h+=4,h+A>w)throw new Error("ZIP extra field is truncated.");if(S===1)throw new Error("ZIP64 archives are unsupported.");if(S===28789||S===25461)throw new Error("ZIP alternate Unicode filename metadata is unsupported; use UTF-8 names.");h+=A}}function WD(m,h){let p=new DataView(m.buffer,m.byteOffset,m.byteLength),w=(he,be)=>Number.isSafeInteger(he)&&he>=0&&be>=0&&he<=m.length-be,S=-1;for(let he=m.length-22;he>=Math.max(0,m.length-22-65535);he--)if(p.getUint32(he,!0)===101010256&&he+22+p.getUint16(he+20,!0)===m.length){S=he;break}if(S<0)throw new Error("ZIP end directory is missing or truncated.");let A=p.getUint16(S+4,!0),T=p.getUint16(S+6,!0),H=p.getUint16(S+8,!0),Y=p.getUint16(S+10,!0),ee=p.getUint32(S+12,!0),X=p.getUint32(S+16,!0);if(Y===65535||ee===4294967295||X===4294967295)throw new Error("ZIP64 archives are unsupported.");if(A||T||H!==Y)throw new Error("Multi-disk ZIP archives are unsupported.");if(!Y||Y>h.maxFiles)throw new Error(`ZIP must contain between 1 and ${h.maxFiles} entries.`);if(!w(X,ee)||X+ee!==S)throw new Error("ZIP central directory range is inconsistent.");let G=[],ae=new Set,_e=X,J=0;for(let he=0;he<Y;he++){if(!w(_e,46)||_e+46>S||p.getUint32(_e,!0)!==33639248)throw new Error("ZIP central directory entry is truncated.");let be=p.getUint16(_e+8,!0),De=p.getUint16(_e+10,!0),Ke=p.getUint32(_e+16,!0),qe=p.getUint32(_e+20,!0),$e=p.getUint32(_e+24,!0),Xe=p.getUint16(_e+28,!0),ve=p.getUint16(_e+30,!0),Ee=p.getUint16(_e+32,!0),me=p.getUint16(_e+34,!0),N=p.getUint32(_e+38,!0),re=p.getUint32(_e+42,!0),R=46+Xe+ve+Ee;if(!w(_e,R)||_e+R>S)throw new Error("ZIP central entry range is inconsistent.");if([qe,$e,re].includes(4294967295))throw new Error("ZIP64 archives are unsupported.");if(me)throw new Error("Multi-disk ZIP archives are unsupported.");if(be&-2063||be&1)throw new Error("Encrypted or unsupported ZIP flags.");if(![0,8].includes(De))throw new Error("ZIP supports only stored and deflate compression.");if(De===0&&(be&6||qe!==$e))throw new Error("Stored ZIP sizes or flags are inconsistent.");let $=m.subarray(_e+46,_e+46+Xe),V=GD($,be),O=V.replace(/\/$/,"").normalize("NFC").toLowerCase();if(ae.has(O))throw new Error("ZIP entry paths must be unique, including case and Unicode normalization.");ae.add(O);let C=N>>>16&61440,j=V.endsWith("/");if(C&&![32768,16384].includes(C))throw new Error("ZIP symlinks and special entries are unsupported.");if(C===16384&&!j||C===32768&&j||N&16&&!j)throw new Error("ZIP directory metadata is inconsistent.");if(j&&$e)throw new Error("ZIP directory contains unexpected data.");if(/\.(?:zip|zipx|jar|war|apk)$/i.test(V))throw new Error("Nested ZIP archives are unsupported.");if($e>h.maxFileBytes||J+$e>h.maxExpandedBytes||$e>Math.max(qe,1)*h.maxRatio)throw new Error("ZIP expanded size or compression ratio exceeds its limit.");if(J+=$e,MS(p,_e+46+Xe,ve),!w(re,30)||re+30>X||p.getUint32(re,!0)!==67324752)throw new Error("ZIP local file header is missing.");let B=p.getUint16(re+6,!0),W=p.getUint16(re+8,!0),K=p.getUint32(re+14,!0),ge=p.getUint32(re+18,!0),Ne=p.getUint32(re+22,!0),ne=p.getUint16(re+26,!0),we=p.getUint16(re+28,!0),xe=re+30+ne+we;if(B!==be||W!==De||ne!==Xe||!w(re,xe-re)||xe>X||!$.every((Me,Ce)=>m[re+30+Ce]===Me))throw new Error("ZIP local and central file headers disagree.");if(MS(p,re+30+ne,we),!w(xe,qe)||xe+qe>X)throw new Error("ZIP compressed data range is inconsistent.");let ke=xe+qe;if(be&8){if(K&&K!==Ke||ge&&ge!==qe||Ne&&Ne!==$e)throw new Error("ZIP descriptor local sizes disagree.");let Me=w(ke,4)&&p.getUint32(ke,!0)===134695760,Ce=ke+(Me?4:0);if(!w(Ce,12)||Ce+12>X||p.getUint32(Ce,!0)!==Ke||p.getUint32(Ce+4,!0)!==qe||p.getUint32(Ce+8,!0)!==$e)throw new Error("ZIP data descriptor is inconsistent.");ke=Ce+12}else if(K!==Ke||ge!==qe||Ne!==$e)throw new Error("ZIP local and central file sizes or CRC disagree.");G.push({path:V,directory:j,method:De,crc:Ke,size:$e,compressed:qe,offset:re,dataStart:xe,dataEnd:ke}),_e+=R}if(_e!==S)throw new Error("ZIP central directory length is inconsistent.");let Q=0;for(let he of[...G].sort((be,De)=>be.offset-De.offset)){if(he.offset!==Q)throw new Error("ZIP local entries overlap or contain unsupported padding/prefix data.");Q=he.dataEnd}if(Q!==X)throw new Error("ZIP data and central directory do not align.");let te=new Set(G.filter(he=>!he.directory).map(he=>he.path.normalize("NFC").toLowerCase()));for(let he of G){let be=he.path.split("/");for(let De=1;De<be.length;De++)if(te.has(be.slice(0,De).join("/").normalize("NFC").toLowerCase()))throw new Error("ZIP file and directory paths conflict.")}return G}async function XD(m,h,p){let w;try{w=new DecompressionStream("deflate-raw")}catch{throw new Error("This browser cannot decompress ZIP deflate data; use a current browser or unpack the files locally.")}let S=new Blob([m]).stream().pipeThrough(w),A=S.getReader(),T=()=>{A.cancel(p.reason).catch(()=>{})};p?.addEventListener("abort",T,{once:!0});let H=new Uint8Array(h),Y=0;try{for(;;){p?.throwIfAborted();let{value:ee,done:X}=await A.read();if(p?.throwIfAborted(),X)break;if(ee.byteLength>h-Y)throw new Error("ZIP inflated data exceeds its declared size.");H.set(ee,Y),Y+=ee.byteLength}if(Y!==h)throw new Error("ZIP inflated data does not match its declared size.");return H}finally{p?.removeEventListener("abort",T);try{await A.cancel()}catch{}}}async function jl(m,h={}){let p=HD(h),w=h.signal;w?.throwIfAborted();let S=m instanceof Uint8Array?m:m instanceof ArrayBuffer?new Uint8Array(m):null;if(!S)throw new TypeError("ZIP input must be an ArrayBuffer or Uint8Array.");if(S.byteLength>p.maxCompressedBytes)throw new Error("ZIP compressed input exceeds its limit.");let A=S.slice(),T=WD(A,p),H=[];for(let Y of T){w?.throwIfAborted();let ee=A.subarray(Y.dataStart,Y.dataStart+Y.compressed),X=Y.method===0?ee.slice():await XD(ee,Y.size,w);if(w?.throwIfAborted(),VD(X)!==Y.crc)throw new Error(`ZIP CRC check failed for ${Y.path}.`);if(X.length>=4&&X[0]===80&&X[1]===75&&(X[2]===3&&X[3]===4||X[2]===5&&X[3]===6))throw new Error("Nested ZIP archives are unsupported.");Y.directory||H.push({path:Y.path,bytes:X})}if(!H.length)throw new Error("ZIP contains no files.");return H}var zD,BD,jD,Tm=Ui(()=>{Bl();zD=Object.freeze({maxCompressedBytes:sa,maxExpandedBytes:lh,maxFileBytes:sa,maxFiles:256,maxRatio:1e3}),BD=new TextDecoder("utf-8",{fatal:!0}),jD=Uint32Array.from({length:256},(m,h)=>{for(let p=0;p<8;p++)h=h&1?3988292384^h>>>1:h>>>1;return h>>>0})});async function AS(m,{signal:h,lazyBoards:p=!1}={}){if(!m||!Number.isSafeInteger(m.length)||m.length<1||m.length>256)throw new Error("Choose between 1 and 256 files using an array or FileList.");let w=[],S=new Set,A=0;for(let T=0;T<m.length;T++){let H=m[T];h?.throwIfAborted();let Y=H.path||H.webkitRelativePath||H.name;if(!Bs(Y)||S.has(Y.normalize("NFC").toLowerCase()))throw new Error("File names must be unique safe relative paths.");S.add(Y.normalize("NFC").toLowerCase());let ee;if(typeof H.source=="string"){let X=0,G=H.source,ae=Math.min(32*1024*1024,128*1024*1024-A);if(G.length>ae)throw new Error("Files exceed the byte limit.");for(let _e=0;_e<G.length;_e++){let J=G.charCodeAt(_e);if(X+=J<128?1:J<2048?2:3,J>=55296&&J<=56319&&_e+1<G.length){let Q=G.charCodeAt(_e+1);Q>=56320&&Q<=57343&&(X++,_e++)}if(X>ae)throw new Error("Files exceed the byte limit.")}A+=X,w.push({path:Y,source:G});continue}else if(H.bytes instanceof Uint8Array)ee=H.bytes;else if(H.bytes instanceof ArrayBuffer)ee=new Uint8Array(H.bytes);else if(typeof H.arrayBuffer=="function"){if(!Number.isSafeInteger(H.size)||H.size<0||H.size>Math.min(32*1024*1024,128*1024*1024-A))throw new Error("File needs a known size within the byte limit.");if(p&&/\.kicad_pcb$/i.test(Y)){A+=H.size,w.push({path:Y,size:H.size,arrayBuffer:()=>H.arrayBuffer()});continue}if(ee=new Uint8Array(await H.arrayBuffer()),ee.byteLength!==H.size)throw new Error("File size changed while reading.")}else throw new TypeError("Files need source text, bytes or a browser File.");if(h?.throwIfAborted(),A+=ee.byteLength,ee.byteLength>32*1024*1024||A>128*1024*1024)throw new Error("Files exceed the 32 MiB per-file or 128 MiB total limit.");w.push({path:Y,bytes:ee})}return w}async function bv(m,{signal:h}={}){if(h?.throwIfAborted(),typeof m.source=="string")return m.source;let p=m.bytes;if(p instanceof ArrayBuffer&&(p=new Uint8Array(p)),!(p instanceof Uint8Array)){if(typeof m.arrayBuffer!="function"||!Number.isSafeInteger(m.size)||m.size<0||m.size>32*1024*1024)throw new Error("File needs a known size within the byte limit.");if(p=new Uint8Array(await m.arrayBuffer()),p.byteLength!==m.size)throw new Error("File size changed while reading.")}if(h?.throwIfAborted(),p.byteLength>32*1024*1024)throw new Error("File exceeds the 32 MiB limit.");return new TextDecoder("utf-8",{fatal:!0}).decode(p)}var TS=Ui(()=>{Qa()});function RS(m,h,p,w,S,A="layers"){let T=h("details","viewer-layers"),H=h("summary"),Y=h("div","viewer-layer-list");H.title=S,H.setAttribute("aria-label",S),H.append(p(A)),T.append(H,Y);let ee=(ae,_e)=>{let J=h("button");return J.type="button",J.textContent=ae,J.onclick=()=>{try{_e()}catch(Q){w(Q)}},J},X=ee("Close",()=>{T.open=!1,H.focus?.()});return X.setAttribute("aria-label","Close "+S.toLowerCase()),Y.append(X),{menu:T,summary:H,popup:Y,button:ee,select:(ae,_e,J)=>{let Q=h("label","inspection-field"),te=h("span"),he=h("select");te.textContent=ae,he.setAttribute("aria-label",ae);for(let[be,De]of _e){let Ke=h("option");Ke.value=be,Ke.textContent=De,he.append(Ke)}return he.onchange=()=>{try{J(he.value)}catch(be){w(be)}},Q.append(te,he),Y.append(Q),he}}}function PS(m,h,p,w){let S=RS(m,h,p,w,"Highlight settings","highlight"),A=S.select("Highlight style",[["dim","Dim context"],["bright","Bright only"],["isolate","Isolate selection"]],ee=>m.setHighlightStyle(ee)),T=S.select("Highlight color",[["accent","Accent color"],["source","Source colors"]],ee=>m.setHighlightStyle(m.highlightMode,{color:ee})),H=S.button("Clear selection",()=>m.clearSelection());S.popup.append(H);let Y=h("p","inspection-help");return Y.textContent="Style affects selected parts, pads and nets. Hidden layers remain hidden. Clear restores the surrounding design.",S.popup.append(Y),{...S,update(){S.menu.hidden=!["pcb","schematic","3d"].includes(m.view)||!m.renderer,A.value=m.highlightMode,T.value=m.highlightColor},dispose(){A.onchange=T.onchange=H.onclick=null}}}function IS(m,h,p,w){let S=RS(m,h,p,w,"Layers"),A=h("input"),T=h("div"),H=h("div","inspection-presets"),Y=new Map,ee=new Map,X=null,G=null;A.type="search",A.placeholder="Find a layer",A.setAttribute("aria-label","Find a layer"),S.popup.append(A,H);for(let[qe,$e]of[["all","All"],["overview","Overview"],["outline","Outline"],["none","None"],["front","Front"],["back","Back"],["copper","Copper"]]){let Xe=S.button($e,()=>m.setLayerPreset(qe));Xe.setAttribute("aria-pressed","false"),ee.set(qe,Xe),H.append(Xe)}let ae=S.button("Restore view",()=>m.restoreLayerView());H.append(ae);let _e=S.select("Layer focus mode",[["dim","Dim other layers"],["isolate","Isolate focused layer"]],qe=>{let $e=m.getLayerState();$e.focused&&m.focusLayer($e.focused,{mode:qe})}),J=h("div","inspection-presets"),Q=S.button("Fit focused layer",()=>m.fitFocusedLayer()),te=S.button("Clear layer focus",()=>m.clearLayerFocus());J.append(Q,te),S.popup.append(J);let he=h("p","inspection-help");he.setAttribute("role","status"),S.popup.append(he,T);let be=S.button("Reveal internal copper",()=>{m.setAppearance("translucent"),m.updateControls()});S.popup.append(be),A.oninput=()=>{let qe=(A.value||"").trim().toLowerCase();for(let[$e,Xe]of Y)Xe.node.hidden=!$e.toLowerCase().includes(qe)};function De(){let qe=m.getLayerState();S.menu.hidden=!qe.layers.length,S.menu.hidden&&(S.menu.open=!1);let $e=m.view+"|"+(m.path||"")+"|"+qe.layers.join("\0");if($e!==X||G!==m.design){X=$e,G=m.design;let ve=new Map;for(let Ee of m.design?.primitives||[])Ee.layer&&ve.set(Ee.layer,(ve.get(Ee.layer)||0)+1);Y.clear(),T.replaceChildren();for(let Ee of qe.layers){let me=h("div","layer-row"),N=h("label"),re=h("input"),R=h("span","layer-swatch"),$=h("span");me.title=Ee,re.type="checkbox",re.setAttribute("aria-label","Show layer "+Ee),$.textContent=Ee,R.style.background=globalThis.KiCadPCBRenderer?.colorFor?.(Ee)||"#819baa",re.onchange=()=>{try{let C=new Set(m.getLayerState().visible);re.checked?C.add(Ee):C.delete(Ee),m.setLayers([...C])}catch(C){w(C)}};let V=S.button("Focus",()=>m.focusLayer(Ee,{mode:_e.value}));V.setAttribute("aria-label","Focus layer "+Ee);let O=h("small");O.textContent=String(ve.get(Ee)||0),O.title="Saved drawing primitives on this layer",N.append(re,R,$,O),me.append(N,V),T.append(me),Y.set(Ee,{node:me,input:re,focus:V})}}for(let[ve,Ee]of ee)Ee.setAttribute("aria-pressed",String(qe.preset===ve)),Ee.hidden=["overview","outline"].includes(ve)&&m.view!=="pcb";let Xe=new Set(qe.visible);for(let[ve,Ee]of Y)Ee.input.checked=Xe.has(ve),Ee.focus.hidden=!qe.canFocus,Ee.focus.setAttribute("aria-pressed",String(qe.focused===ve)),Ee.node.setAttribute("data-focused",String(qe.focused===ve));_e.parentNode&&(_e.parentNode.hidden=!qe.canFocus),J.hidden=!qe.canFocus,Q.disabled=te.disabled=!qe.focused,ae.disabled=!qe.canRestore,_e.value=qe.focused?qe.focusMode:_e.value||"dim",he.textContent=qe.focused?qe.focused+" \xB7 "+(qe.focusMode==="isolate"?"isolated":"other layers dimmed"):m.view==="3d"?"Copper visibility. Internal layers are rendered in Translucent appearance.":"Select layers to show, or focus one layer. [ and ] cycle; Shift+F fits focus.",be.hidden=m.view!=="3d",A.oninput()}let Ke=qe=>{let $e=qe.target?.tagName?.toLowerCase();if(["input","textarea","select","button"].includes($e)||qe.target?.isContentEditable||qe.ctrlKey||qe.altKey||qe.metaKey)return;let Xe=m.getLayerState();if(Xe.canFocus)if(["[","]"].includes(qe.key)){qe.preventDefault();let ve=Xe.layers.indexOf(Xe.focused||m.renderer.activeLayer),Ee=qe.key==="]"?1:-1;m.focusLayer(Xe.layers[(ve+Ee+Xe.layers.length)%Xe.layers.length],{mode:_e.value||"dim"})}else qe.shiftKey&&qe.key.toLowerCase()==="f"&&(qe.preventDefault(),m.fitFocusedLayer())};return m.surface.addEventListener?.("keydown",Ke),{...S,list:T,filter:A,update:De,dispose(){m.surface.removeEventListener?.("keydown",Ke),A.oninput=_e.onchange=null,Y.clear()}}}var CS,NS=Ui(()=>{CS=`
.viewer-layers{position:static}.viewer-layer-list{right:8px;top:calc(var(--viewer-toolbar-height,48px) + 6px);width:min(330px,calc(100cqw - 20px));min-width:0;max-height:calc(100% - var(--viewer-toolbar-height,48px) - 14px);overflow:auto}
.inspection-presets{display:flex;flex-wrap:wrap;gap:4px;margin:8px 0}.viewer-toolbar .inspection-presets button,.viewer-toolbar .layer-row button{min-height:36px;border:1px solid var(--viewer-border);background:var(--viewer-bg)}
.viewer-toolbar .inspection-presets button[aria-pressed="true"]{background:var(--viewer-active);border-color:var(--viewer-accent)}
.viewer-layer-list .layer-row{display:flex;align-items:center;gap:5px;min-width:0}.viewer-layer-list .layer-row label{flex:1;min-width:0;white-space:normal;overflow-wrap:anywhere;min-height:36px}
.layer-swatch{width:12px;height:12px;flex:0 0 12px;border:1px solid var(--viewer-border);border-radius:3px}.layer-row[data-focused="true"]{background:var(--viewer-active);border-radius:5px}
.viewer-layer-list .inspection-field{display:flex;flex-wrap:wrap;align-items:center;gap:6px;white-space:normal;margin:8px 0}.viewer-layer-list select,.viewer-layer-list input[type="search"]{width:100%;min-width:0;min-height:36px;padding:7px;border:1px solid var(--viewer-border);border-radius:5px;background:var(--viewer-bg);color:var(--viewer-ink);font:12px system-ui}.viewer-layer-list input[type="search"]{height:auto}.inspection-help{font:11px/1.5 system-ui;color:var(--viewer-muted);white-space:normal;margin:8px 0}
@media(pointer:coarse){.viewer-layer-list .layer-row label,.viewer-toolbar .inspection-presets button,.viewer-toolbar .layer-row button,.viewer-layer-list select{min-height:44px}}
`});function LS(m){let h=m.host.ownerDocument,p=(Ze,Ye)=>{let vt=h.createElement(Ze);return Ye&&(vt.className=Ye),vt},w=Ze=>{let Ye=p("span","viewer-icon");return Ye.setAttribute("aria-hidden","true"),Ye.innerHTML='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round"><path d="'+YD[Ze]+'"/></svg>',Ye},S=p("style");S.textContent=qD+WE+CS+KD;let A=p("div","viewer-toolbar");A.setAttribute("role","toolbar"),A.setAttribute("aria-label","Drawing viewer controls");let T=p("div","viewer-picker"),H=p("select"),Y=p("span","viewer-name");H.setAttribute("aria-label","Project drawing"),H.title="Choose a project drawing",T.append(w("drawing"),H,Y);let ee=p("div","viewer-views");ee.setAttribute("role","group"),ee.setAttribute("aria-label","Drawing view");let X=p("div","viewer-actions"),G=Ze=>ke(Ze.message,!0),ae=(Ze,Ye,vt,Rt="")=>{let Je=p("button");if(Je.type="button",Je.title=Ye,Je.setAttribute("aria-label",Ye),Je.append(w(Ze)),Rt){let _t=p("span");_t.textContent=Rt,Je.append(_t)}return Je.onclick=()=>{Promise.resolve().then(vt).catch(G)},Je},_e=ae("layout","PCB layout",()=>m.setView("pcb"),"Layout"),J=ae("cube","3D view",()=>m.setView("3d"),"3D");ee.append(_e,J);let Q=ae("fit","Fit drawing",()=>m.fit());Q.className="viewer-fit";let te=ae("fit","Fit page",()=>{re.open=!1,m.fitPage()},"Page"),he=ae("moon","Switch to dark theme",()=>m.setTheme(m.theme==="light"?"dark":"light")),be=IS(m,p,w,G),De=PS(m,p,w,G),Ke=be.menu,qe=be.list,$e=be.filter,Xe=be.summary,ve=ae("notes","Rendering notes",()=>xe()),Ee=p("span","viewer-note-count");Ee.hidden=!0,ve.append(Ee),ve.setAttribute("aria-expanded","false");let me=ae("ruler","Measure distance",()=>m.setMeasuring(!m.renderer?.measuring)),N=ae("inspect","Inspect properties and parts",()=>{re.open=!1,Ke.open=!1,De.menu.open=!1,xe(!1),m.setInspectorOpen(!m.inspector.isOpen())});N.setAttribute("aria-expanded","false");let re=p("details","viewer-more"),R=p("summary"),$=p("div","viewer-more-panel");R.textContent="More",R.title="More viewer tools",R.setAttribute("aria-label","More viewer tools"),$.append(te,me,N,he,De.menu,Ke,ve),re.append(R,$),X.append(Q,re),A.append(T,ee,X);let V=h.defaultView?.ResizeObserver||globalThis.ResizeObserver,O=V?new V(()=>{let Ze=A.getBoundingClientRect().height;m.root.style.setProperty("--viewer-toolbar-height",Ze+"px")}):null;O?.observe(A);let C=XE(m,G),j=m.status;j.className="viewer-notes",j.hidden=!0,j.tabIndex=0,j.setAttribute("aria-label","Rendering notes");let B=[],W=!1,K=null,ge=null,Ne,ne=[],we=new Map;function xe(Ze=!W){W=!!Ze,j.hidden=!W,W&&(Ke.open=!1,De.menu.open=!1),W&&m.inspector?.toggle(!1),ve.setAttribute("aria-expanded",String(W))}function ke(Ze,Ye=!1){B=(Array.isArray(Ze)?Ze:Ze?[Ze]:[]).map(String).filter(Boolean),j.textContent=B.length?B.join(`

`):"No rendering notes for this drawing.",j.setAttribute("data-error",String(Ye)),Ee.textContent=String(B.length),Ee.hidden=!B.length,ve.title=B.length?"Rendering notes ("+B.length+")":"Rendering notes",Ye&&xe(!0)}function Me(Ze){Ze!==ge&&(ge=Ze,m.root.setAttribute("data-theme",Ze),he.replaceChildren(w(Ze==="dark"?"sun":"moon")),he.title=Ze==="dark"?"Switch to light theme":"Switch to dark theme",he.setAttribute("aria-label",he.title))}function Ce(){C.update(),C.panel.parentNode!==$&&$.append(C.panel),H.hidden=!m.project,Y.hidden=!!m.project,Y.textContent=m.path?.split("/").at(-1)||"KiCad viewer",Y.title=m.path||"Read-only KiCad viewer";let Ze=m.getFiles().filter(Ye=>!/\.(wrl|glb)$/i.test(Ye.path)).map(Ye=>Ye.path);(Ne!==m.project||Ze.length!==ne.length||Ze.some((Ye,vt)=>Ye!==ne[vt]))&&(Ne=m.project,ne=Ze,H.replaceChildren(...Ze.map(Ye=>{let vt=p("option");return vt.value=Ye,vt.textContent=Ye,vt}))),H.value=m.path||"",_e.hidden=J.hidden=ee.hidden=m.kind!=="pcb",_e.setAttribute("aria-pressed",String(m.view==="pcb")),J.setAttribute("aria-pressed",String(m.view==="3d")),Q.disabled=!m.renderer,te.hidden=!m.renderer||!["pcb","schematic"].includes(m.view),me.hidden=m.view!=="manufacturing",me.setAttribute("aria-pressed",String(!!m.renderer?.measuring)),be.update(),De.update(),Me(m.theme)}be.menu.ontoggle=()=>{be.menu.open&&(De.menu.open=!1,xe(!1),m.inspector.toggle(!1))},De.menu.ontoggle=()=>{De.menu.open&&(be.menu.open=!1,xe(!1),m.inspector.toggle(!1))},H.onchange=()=>m.openFile(H.value).catch(G);let tt=Ze=>{Ze.key==="Escape"&&(xe(!1),Ke.open=!1,De.menu.open=!1,re.open=!1)};return m.surface.addEventListener?.("keydown",tt),{style:S,toolbar:A,fileSelect:H,layoutButton:_e,threeButton:J,fitButton:Q,moreMenu:re,themeButton:he,layersMenu:Ke,layerList:qe,notesButton:ve,measureButton:me,inspectorButton:N,layerFilter:$e,update:Ce,setTheme:Me,setStatus:ke,toggleNotes:xe,dispose(){C.dispose(),be.menu.ontoggle=De.menu.ontoggle=null,be.dispose(),De.dispose(),O?.disconnect(),m.surface.removeEventListener?.("keydown",tt);for(let Ze of[_e,J,Q,te,he,ve,me,N])Ze.onclick=null;H.onchange=$e.oninput=null}}}var YD,qD,KD,kS=Ui(()=>{NS();lv();YD={drawing:"M5 3h10l4 4v14H5zM14 3v5h5M8 12h8M8 16h5",layout:"M4 4h16v16H4zM8 4v5h5V4M4 14h7v6M16 12h4",cube:"m12 3 9 5v8l-9 5-9-5V8zM3 8l9 5 9-5M12 13v8M7 5.8l9 5",fit:"M8 3H3v5M16 3h5v5M21 16v5h-5M8 21H3v-5M8 8h8v8H8z",moon:"M20.8 13A9 9 0 0 1 11 3.2 9 9 0 1 0 20.8 13z",sun:"M12 3V1M12 23v-2M3 12H1M23 12h-2M4.2 4.2l1.4 1.4M18.4 18.4l1.4 1.4M4.2 19.8l1.4-1.4M18.4 5.6l1.4-1.4M16 12a4 4 0 1 1-8 0 4 4 0 0 1 8 0",highlight:"m9 3 1.5 4.5L15 9l-4.5 1.5L9 15l-1.5-4.5L3 9l4.5-1.5zM18 14l1 3 3 1-3 1-1 3-1-3-3-1 3-1z",layers:"m12 3 10 5-10 5L2 8zM3 13l9 5 9-5M3 18l9 5 9-5",inspect:"M4 3h16v18H4zM9 3v18M12 7h5M12 11h5M12 15h3",ruler:"M3 17 17 3l4 4L7 21zM13 7l4 4M9 11l3 3M5 15l3 3",notes:"M12 8v5M12 17h.01M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0"},qD=`
:host{--viewer-bg:#f4f7fa;--viewer-bar:#ffffff;--viewer-ink:#253445;--viewer-muted:#657588;--viewer-border:#dbe3eb;--viewer-hover:#edf3f8;--viewer-accent:#176b83;--viewer-active:#e6f3f5;--viewer-shadow:0 8px 28px #172c4220;display:flex;position:relative;flex-direction:column;font:12px/1.4 system-ui,-apple-system,"Segoe UI",sans-serif}
:host([data-theme="dark"]){--viewer-bg:#111a24;--viewer-bar:#182330;--viewer-ink:#e1eaf3;--viewer-muted:#99aabd;--viewer-border:#324254;--viewer-hover:#253548;--viewer-accent:#77d4df;--viewer-active:#23434d;--viewer-shadow:0 8px 28px #0005}
*{box-sizing:border-box}[hidden]{display:none!important}
select option{background:var(--viewer-bar);color:var(--viewer-ink)}select option:disabled{color:var(--viewer-muted)}select{color-scheme:light}:host([data-theme="dark"]) select{color-scheme:dark}
.viewer-toolbar{display:flex;align-items:center;gap:10px;flex:0 0 auto;min-height:48px;padding:7px 10px;background:var(--viewer-bar);color:var(--viewer-ink);border-bottom:1px solid var(--viewer-border);z-index:10;min-width:0}
.viewer-picker{display:flex;align-items:center;gap:8px;min-width:0;flex:1 1 160px;max-width:340px;color:var(--viewer-muted)}
.viewer-picker>.viewer-icon{flex:0 0 auto}.viewer-picker select{width:100%;min-width:0;max-width:100%;appearance:auto;padding:5px 3px;border:0;background:transparent;color:var(--viewer-ink);font:600 12px/1.4 system-ui;overflow:hidden;text-overflow:ellipsis;cursor:pointer}
.viewer-picker select{color-scheme:light}.viewer-picker select option{background:#ffffff;color:#253445}:host([data-theme="dark"]) .viewer-picker select{color-scheme:dark}:host([data-theme="dark"]) .viewer-picker select option{background:#182330;color:#e1eaf3}
.viewer-name{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--viewer-ink);font-weight:600}
.viewer-views{display:flex;align-items:center;gap:2px;flex:0 0 auto;padding:3px;border:1px solid var(--viewer-border);border-radius:9px;background:var(--viewer-bg)}
.viewer-toolbar button,.viewer-toolbar summary{display:inline-flex;align-items:center;justify-content:center;gap:6px;min-width:32px;min-height:32px;padding:6px;border:0;border-radius:6px;background:transparent;color:var(--viewer-muted);font:600 11px/1 system-ui;cursor:pointer;list-style:none;white-space:nowrap}
.viewer-toolbar button:hover,.viewer-toolbar summary:hover{color:var(--viewer-ink);background:var(--viewer-hover)}
.viewer-toolbar button:disabled{opacity:.38;cursor:default}
.viewer-toolbar button[aria-pressed="true"]{color:var(--viewer-accent);background:var(--viewer-active);box-shadow:0 1px 3px #1023350b}
.viewer-views button{padding:6px 9px;min-height:28px}
.viewer-actions{display:flex;align-items:center;gap:3px;flex:0 0 auto;margin-left:auto}
.viewer-toolbar button:focus-visible,.viewer-toolbar select:focus-visible,.viewer-toolbar summary:focus-visible,.viewer-notes:focus-visible{outline:2px solid var(--viewer-accent);outline-offset:2px}
.viewer-icon{display:inline-flex;width:17px;height:17px;align-items:center;justify-content:center;pointer-events:none}
.viewer-icon svg{width:100%;height:100%;display:block}.viewer-layers{position:relative}.viewer-layers summary::-webkit-details-marker{display:none}
.viewer-layer-list{position:absolute;right:0;top:calc(100% + 9px);min-width:190px;max-height:min(300px,65vh);overflow:auto;padding:10px;border:1px solid var(--viewer-border);border-radius:9px;background:var(--viewer-bar);color:var(--viewer-ink);box-shadow:var(--viewer-shadow)}
.viewer-layer-list label{display:flex;align-items:center;gap:8px;min-height:30px;white-space:nowrap;cursor:pointer}.viewer-layer-list input{width:15px;height:15px;margin:0;accent-color:var(--viewer-accent)}
.viewer-notes{position:absolute;right:10px;top:56px;z-index:11;width:min(420px,calc(100% - 20px));max-height:calc(100% - 70px);overflow:auto;margin:0;padding:14px;border:1px solid var(--viewer-border);border-radius:9px;background:var(--viewer-bar);color:var(--viewer-ink);box-shadow:var(--viewer-shadow);font:12px/1.65 system-ui;white-space:pre-line;overflow-wrap:anywhere}
.viewer-notes[data-error="true"]{border-color:#b46d4a}.viewer-note-count{display:inline-flex;align-items:center;justify-content:center;min-width:15px;height:15px;padding:0 3px;border-radius:5px;background:#9b692116;color:#9a6521;font-size:9px;font-variant-numeric:tabular-nums}:host([data-theme="dark"]) .viewer-note-count{background:#dba35222;color:#f0c384}
@container (max-width:540px){.viewer-toolbar{gap:6px;padding-inline:7px}.viewer-picker{flex-basis:80px}.viewer-picker>.viewer-icon{display:none}.viewer-views button{padding-inline:7px}.viewer-views .viewer-icon{display:none}.viewer-actions{gap:0}}
@container (max-width:360px){.viewer-toolbar{gap:3px;padding-inline:5px}.viewer-toolbar button,.viewer-toolbar summary{min-width:29px;padding:5px}.viewer-picker{flex-basis:45px}.viewer-views{padding:2px}.viewer-views button{padding-inline:6px}.viewer-note-count{min-width:12px;padding:0 2px}}
@container (max-width:240px){.viewer-toolbar{flex-wrap:wrap}.viewer-picker{flex:1 1 28px}}
@media(pointer:coarse){.viewer-toolbar button,.viewer-toolbar summary{min-height:36px}.viewer-toolbar{min-height:52px}.viewer-notes{top:60px}}
@container (max-width:540px){
 .viewer-toolbar{flex-wrap:wrap;align-content:center;gap:4px 6px;padding:6px}
 .viewer-picker{flex:1 0 100%;max-width:none;min-height:32px}
 .viewer-picker select{font-size:16px;min-height:36px}
 .viewer-actions{flex:1 1 160px;flex-wrap:wrap;justify-content:flex-end;gap:2px}
 .viewer-toolbar button,.viewer-toolbar summary{min-width:40px;min-height:40px}
 .viewer-views button{min-height:40px}
 .viewer-notes{top:calc(var(--viewer-toolbar-height,96px) + 8px);max-height:calc(100% - var(--viewer-toolbar-height,96px) - 16px)}
 .viewer-layers{position:static}.viewer-layer-list{position:absolute;left:8px;right:8px;top:calc(var(--viewer-toolbar-height,96px) + 6px);min-width:0;max-height:calc(100% - var(--viewer-toolbar-height,96px) - 14px);overscroll-behavior:contain}
 .viewer-layer-list label{min-height:44px;white-space:normal;overflow-wrap:anywhere}
 .viewer-layer-list input{width:20px;height:20px;flex-shrink:0}
 .viewer-layer-list input[type=search]{width:100%;font-size:16px!important}
}
@media(pointer:coarse){.viewer-toolbar button,.viewer-toolbar summary{min-width:44px;min-height:44px}.viewer-views button{min-height:44px}.viewer-picker select{font-size:16px;min-height:44px}.viewer-layer-list label{min-height:44px}}
`,KD=`
.viewer-toolbar{flex-wrap:nowrap;align-content:center;gap:4px;min-height:36px;height:36px;padding:2px 5px}
.viewer-picker{flex:1 1 80px;max-width:none;min-height:0;overflow:hidden;gap:3px}.viewer-picker>.viewer-icon{display:none}.viewer-picker select{font:600 11px/1.2 system-ui;min-height:30px;padding:2px;max-width:100%}.viewer-name{font-size:11px}
.viewer-views{padding:1px;gap:1px;border-radius:6px}.viewer-views button,.viewer-toolbar button,.viewer-toolbar summary{box-sizing:border-box;min-width:30px;min-height:30px;height:30px;padding:4px;font:600 11px/1 system-ui}.viewer-views button{padding-inline:4px}.viewer-views .viewer-icon{display:inline-flex}.viewer-actions{flex:0 0 auto;flex-wrap:nowrap;gap:2px;margin-left:0}
.viewer-more{position:static}.viewer-more>summary{gap:2px}.viewer-more>summary::-webkit-details-marker{display:none}.viewer-more[open]>summary{color:var(--viewer-accent);background:var(--viewer-active)}
.viewer-more-panel{position:absolute;z-index:12;right:5px;top:calc(var(--viewer-toolbar-height,36px) + 3px);display:grid;gap:3px;width:min(252px,calc(100cqw - 10px));max-height:calc(100% - var(--viewer-toolbar-height,36px) - 8px);overflow:auto;overscroll-behavior:contain;padding:6px;border:1px solid var(--viewer-border);border-radius:7px;background:var(--viewer-bar);color:var(--viewer-ink);box-shadow:var(--viewer-shadow)}
.viewer-more-panel>button,.viewer-more-panel>.viewer-layers>summary{justify-content:flex-start;width:100%;min-height:30px;height:auto}.viewer-more-panel>button::after,.viewer-more-panel>.viewer-layers>summary::after{content:attr(aria-label);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.viewer-more-panel>.viewer-layers{position:static}.viewer-more-panel .viewer-layer-list{position:static;inset:auto;width:100%;min-width:0;max-height:180px;overflow:auto;margin:3px 0;box-shadow:none}.viewer-more-panel .viewer-navigation{position:static;inset:auto;width:100%;max-width:none;max-height:none;overflow:visible;box-shadow:none}.viewer-more-panel .viewer-navigation button{min-width:0;min-height:30px}
:host([data-inset="true"]) .viewer-picker,:host([data-inset="true"]) .viewer-fit{display:none!important}
@container (max-width:360px){.viewer-views button span:not(.viewer-icon){display:none}.viewer-views button{min-width:30px;padding:4px}.viewer-views .viewer-icon{display:inline-flex}}
@media(pointer:coarse){.viewer-toolbar{min-height:36px;height:36px}.viewer-toolbar button,.viewer-toolbar summary,.viewer-views button,.viewer-picker select{min-width:30px;min-height:30px;height:30px;font-size:11px}.viewer-more-panel .viewer-navigation button{min-height:30px}}
`});function OS(m,h){if(typeof m!="number"||!Number.isFinite(m)||m<240||m>480)throw new TypeError("Inspector width must be 240 to 480 pixels.");let p=Number.isFinite(h)&&h>0?h:m+16;return Math.round(Math.min(m,Math.max(0,p-16)))}function US(m,h){let p=m.host.ownerDocument.createElement("div");p.className="inspector-resize",p.tabIndex=0,p.setAttribute("role","separator"),p.setAttribute("aria-orientation","vertical"),p.setAttribute("aria-label","Resize inspector"),p.setAttribute("aria-valuemin","240"),p.setAttribute("aria-valuemax","480"),h.append(p);let w=310,S=310,A=null,T=!1,H=()=>({open:!h.hidden,preferredWidth:w,width:S}),Y=()=>{if(T)return;S=OS(w,m.root?.clientWidth||m.host.clientWidth);let he=m.root?.clientHeight||m.host.clientHeight;h.setAttribute("data-short",String(Number.isFinite(he)&&he>0&&he<=420)),h.style.setProperty?.("--viewer-panel-width",S+"px"),p.setAttribute("aria-valuenow",String(w)),p.setAttribute("aria-valuetext",w+" pixels")},ee=he=>(OS(he),w=he,Y(),m.emit?.("panelchange",H()),H()),X=he=>{if(!A||he?.pointerId!==void 0&&he.pointerId!==A.id)return;let be=A.id;A=null,p.hasPointerCapture?.(be)&&p.releasePointerCapture?.(be)},J={pointerdown:he=>{he.button!==0||A||(A={id:he.pointerId,x:he.clientX,width:w},p.setPointerCapture?.(he.pointerId),he.preventDefault(),he.stopPropagation())},pointermove:he=>{!A||A.id!==he.pointerId||(ee(Math.max(240,Math.min(480,A.width+A.x-he.clientX))),he.stopPropagation())},pointerup:X,pointercancel:X,lostpointercapture:X,keydown:he=>{if(he.ctrlKey||he.altKey||he.metaKey||!["ArrowLeft","ArrowRight","Home","End","Escape"].includes(he.key))return;if(he.key==="Escape"){X();return}let be=he.shiftKey?64:16;ee(he.key==="Home"?240:he.key==="End"?480:Math.max(240,Math.min(480,w+(he.key==="ArrowLeft"?be:-be)))),he.preventDefault(),he.stopPropagation()}};for(let[he,be]of Object.entries(J))p.addEventListener?.(he,be);let Q=m.host.ownerDocument.defaultView?.ResizeObserver||globalThis.ResizeObserver,te=Q&&m.root?new Q(Y):null;return te?.observe(m.root),Y(),{handle:p,sync:Y,setWidth:ee,getState:H,dispose(){if(!T){X(),T=!0,te?.disconnect();for(let[he,be]of Object.entries(J))p.removeEventListener?.(he,be);p.remove()}}}}var DS,FS=Ui(()=>{DS=`
.viewer-inspector{top:calc(var(--viewer-toolbar-height,48px) + 8px);width:var(--viewer-panel-width,310px);max-height:calc(100% - var(--viewer-toolbar-height,48px) - 16px);overscroll-behavior:contain}
.inspector-resize{position:absolute;top:0;bottom:0;left:0;width:7px;z-index:2;cursor:ew-resize;touch-action:none}
.inspector-resize:hover,.inspector-resize:focus-visible{background:var(--viewer-accent);opacity:.7;outline:none}
.inspector-tabs{flex-shrink:0}
.inspector-heading{flex-shrink:0}.viewer-inspector .inspector-body{overflow:auto;overscroll-behavior:contain}.inspector-fields dd{min-width:0}.inspector-options summary{cursor:pointer;min-height:32px;display:list-item;font:600 11px system-ui;padding:8px 0}.inspector-options summary:focus-visible{outline:2px solid var(--viewer-accent)}.inspector-options label{display:flex;gap:7px;align-items:center;min-height:32px}
@container(max-width:580px){.viewer-inspector{top:auto;right:8px;width:calc(100% - 16px);max-height:min(65%,calc(100% - var(--viewer-toolbar-height,96px) - 16px))}.inspector-resize{display:none}}
.viewer-inspector[data-short="true"]{overflow:auto}.viewer-inspector[data-short="true"] .inspector-body{flex:0 0 auto;min-height:60px}.viewer-inspector[data-short="true"] .inspector-footer{flex-shrink:0}
`});function JD(m,h){let p=h==="pcb"?ba(m,"component_classes").flatMap(w=>ba(w,"class").map(S=>S[1])):ba(m,"property").filter(w=>qi(w[1])==="Component Class").map(w=>w[2]);return ds(p.slice(0,64).map(w=>qi(w)).filter(w=>typeof w=="string"&&w.length<=4096))}function Im(m,{kind:h,path:p="",design:w,connectivity:S}={}){let A=[],T=new Map,H=new Map,Y=new Map,ee=new Map,X=[];S?.warnings&&X.push(...S.warnings.slice(0,1e3));let G=new Map,ae=0,_e=ba(m,h==="pcb"?"footprint":"symbol");for(let V of _e.slice(0,wv)){aa(V)&&G.set(aa(V),0),ae++;for(let O of V)Po(O)==="pad"&&ae++<Vs&&aa(O)&&G.set(aa(O),0)}for(let V of m||[])["segment","arc","via","zone"].includes(Po(V))&&ae++<Vs&&aa(V)&&G.set(aa(V),0);for(let V of(w?.primitives||[]).slice(0,Rm))V.uuid&&!V.frame&&G.set(V.uuid,0);let J=Array.isArray(m)?[m]:[],Q=[0];for(;J.length;){let V=J.length-1,O=J[V];if(Q[V]>=O.length){J.pop();continue}let C=O[Q[V]++];if(Array.isArray(C))if(["uuid","tstamp"].includes(Po(C))){let j=String(qi(C[1])||""),B=G.get(j);B!==void 0&&G.set(j,B+1)}else Q[J.length]=0,J.push(C)}let te=new Set;for(let[V,O]of G)O>1&&te.add(V);G.clear(),te.size&&X.push(`${te.size} duplicated saved UUIDs: ambiguous object lookup and owner-group highlighting are disabled.`),(ae>Vs||h==="manufacturing"&&(w?.camLayers||[]).reduce((V,O)=>V+(O.operations?.length||0),0)>Vs)&&X.push("Object lookup is limited to 500,000 saved records.");let he=0;function be(V,O){let C=[],j=new Set;for(let B of V)for(let W of B)if(!(j.has(W)||O&&W.ownerUuid!==O)){if(he>=ZD)return X.includes("Inspection membership is limited to 3,000,000 geometry references.")||X.push("Inspection membership is limited to 3,000,000 geometry references."),C;j.add(W),C.push(W),he++}return C}let De=0,Ke=V=>De++>=Vs?(X.includes("Object lookup is limited to 500,000 saved records.")||X.push("Object lookup is limited to 500,000 saved records."),V):(T.set(V.id,V),V.uuid&&H.set(V.uuid,te.has(V.uuid)||H.has(V.uuid)?null:V),V);(w?.primitives?.length||0)>Rm&&X.push("Inspection geometry lookup is limited to the first 1,500,000 primitives.");for(let V of(w?.primitives||[]).slice(0,Rm))if(!V.frame){if(V.uuid&&!te.has(V.uuid)){let O=Y.get(V.uuid)||[];O.push(V),Y.set(V.uuid,O)}if(V.ownerUuid&&!te.has(V.ownerUuid)){let O=ee.get(V.ownerUuid)||[];O.push(V),ee.set(V.ownerUuid,O)}}let qe=new Map(ba(m,"net").map(V=>[qi(V[1]),Ci(qi(V[2]))])),$e=V=>{let O=to(V,"net");return O?Ci(qi(O[2])??(typeof qi(O[1])=="string"?qi(O[1]):qe.get(qi(O[1])))):""},Xe=(V,O)=>V&&!te.has(V)?S?.objectClasses?.get((p||"drawing.kicad_sch")+"/"+O+":uuid:"+V):void 0,ve=V=>V&&!te.has(V)?be([Y.get(V)||[],ee.get(V)||[]]):[];if(h==="pcb"||h==="schematic"){let V=_e;V.length>wv&&X.push("Part search is limited to the first 50,000 saved parts.");for(let[O,C]of V.slice(0,wv).entries()){if(De>=Vs)break;let j=aa(C),B=_v(C),W=ve(j),K=hh(C),ge=ba(C,"property"),Ne=Me=>Ci(qi(ge.find(Ce=>qi(Ce[1])===Me)?.[2])),ne=Ke({id:`${p}#${j||"part-"+O}`,uuid:j,type:"part",reference:Ne("Reference")||zS(C,"reference"),value:Ne("Value")||zS(C,"value"),footprint:h==="pcb"?Ci(qi(C[1])):Ne("Footprint"),schematicUuid:h==="pcb"&&Ci(oa(C,"path")).split("/").filter(Boolean).at(-1)||"",symbol:h==="schematic"?Ci(oa(C,"lib_id")):"",layer:Ci(oa(C,"layer")),position:K,rotation:la(to(C,"at")?.[3]),fields:B,primitives:W,pads:[],layers:ds(W.map(Me=>Me.layer)),path:p}),we=JD(C,h),xe=Xe(j,"symbol");if(we.length&&(ne.savedComponentClasses=we),xe?.length&&(ne.classAssignments=xe),ba(C,"property").length>Pm&&(ne.note="Only the first 64 saved fields are shown."),te.has(j)&&(ne.note="Saved UUID is duplicated; part-group highlighting is disabled."),A.push(ne),h!=="pcb")continue;let ke=ba(C,"pad");for(let[Me,Ce]of ke.entries()){let tt=aa(Ce),Ze=tt&&!te.has(tt)?be([Y.get(tt)||[]],j):[],Ye=Ze.find(Ht=>Ht.kind==="pad"),vt=hh(Ce),Rt=(ne.rotation||0)*Math.PI/180,Je=Ye?.padCenter||(K&&vt?{x:K.x+vt.x*Math.cos(Rt)+vt.y*Math.sin(Rt),y:K.y-vt.x*Math.sin(Rt)+vt.y*Math.cos(Rt)}:null),_t=to(Ce,"drill"),Et=qi(_t?.[1])==="oval",gt=Ke({id:`${p}#${tt||"pad-"+O+"-"+Me}`,uuid:tt,type:"pad",part:ne,number:Ci(qi(Ce[1])),name:Ci(oa(Ce,"pinfunction")),pinType:Ci(oa(Ce,"pintype")),padType:Ci(qi(Ce[2])),shape:Ci(qi(Ce[3])),net:$e(Ce),position:Je,localPosition:vt,rotation:la(to(Ce,"at")?.[3]),size:$D(Ce),drill:_t?{x:la(_t[Et?2:1]),y:la(_t[Et?3:1])}:null,layers:ds(Ze.map(Ht=>Ht.layer).concat((to(Ce,"layers")||[]).slice(1).map(Ht=>Ci(qi(Ht))))),primitives:Ze,fields:_v(Ce),path:p});if(ne.pads.push(gt),De>=Vs)break}}for(let O of m||[]){let C=Po(O);if(BS.includes(C)){let B=to(O,"polyline"),W=aa(O)||(C==="rule_area"&&B?aa(B):"");if(W&&!te.has(W)&&Ke({id:p+"#"+W,uuid:W,type:C,reference:C==="rule_area"?"Rule area":"Directive label",classAssignments:Xe(W,C),position:hh(O),primitives:ve(W),fields:_v(O),layers:[],path:p}),De>=Vs)break;continue}if(!["segment","arc","via","zone"].includes(Po(O)))continue;let j=aa(O);if(j&&(Ke({id:`${p}#${j}`,uuid:j,type:Po(O),net:$e(O),layer:Ci(oa(O,"layer")),layers:ds((Y.get(j)||[]).map(B=>B.layer)),position:hh(O)||hh(O,"start"),end:hh(O,"end"),width:la(oa(O,"width")),size:la(oa(O,"size")),drill:la(oa(O,"drill")),primitives:Y.get(j)||[],path:p}),De>=Vs))break}}else if(h==="manufacturing")e:for(let V of w?.camLayers||[])for(let O of V.operations||[]){if(De>=Vs)break e;if(Ke({id:O.id,type:"manufacturing",operation:O.kind,polarity:O.polarity,layer:V.id,width:O.width,bounds:O.bounds,metadata:O.metadata||{},layers:[V.id],primitives:[],path:V.id}),De>=Vs)break}function Ee(V){if(!V)return null;let O=Ci(V.uuid||V.id),C=Ci(V.ownerUuid||V.parent?.uuid),j=H.get(O)||T.get(O);if(j?.type==="pad"||j&&!["pad","pin","pin-marker","pin-name","pin-number"].includes(V.kind))return j;let B=C&&H.get(C)||(j?.type==="part"?j:null);if(B?.type==="part"&&V.pinNumber!==void 0){let W=B.pads.filter(Ne=>Ne.number===String(V.pinNumber));if(W.length===1)return W[0];let K=B.primitives.filter(Ne=>Ne.pinNumber===String(V.pinNumber)&&Ne.ownerUuid===B.uuid),ge=K.find(Ne=>Ne.kind==="pin")||K[0];return{id:`${B.id}:pin:${V.pinNumber}`,type:"pin",part:B,number:Ci(V.pinNumber),name:Ci(V.pinName||ge?.pinName),pinType:Ci(ge?.pinType),position:ge?.connectPoint||V.connectPoint,primitives:K,layers:[],fields:[],path:p}}return B?.type==="part"?B:j||{id:O,type:V.kind||V.type||"object",reference:Ci(V.reference||V.ref),value:Ci(V.value),layer:Ci(V.layer),net:Ci(V.netName||V.net),number:Ci(V.pinNumber),name:Ci(V.pinName),position:V.connectPoint||null,layers:ds((Y.get(O)||[]).map(W=>W.layer)),fields:[],primitives:Y.get(O)||[],metadata:V,path:p}}let me=new Map;if(h==="pcb"){for(let V of T.values())if(V.net&&V.primitives?.length){let O=me.get(V.net)||{name:V.net,primitives:[]};for(let C of V.primitives)O.primitives.push(C);me.set(V.net,O)}}let N=new Set((w?.primitives||[]).slice(0,Rm)),re=S?S.nets.slice(0,Vs).map(V=>({...V,name:V.displayName||V.name,type:"net",net:V.displayName||V.name,primitives:V.primitives.filter(O=>N.has(O)&&!te.has(O.uuid)),layers:ds(V.primitives.map(O=>O.layer)),fields:[],path:p})):[...me.values()].map((V,O)=>({...V,id:p+"#net-"+O,type:"net",net:V.name,layers:ds(V.primitives.map(C=>C.layer)),fields:[],path:p})),R=new Map;for(let V of re)for(let O of V.primitives)R.set(O,R.has(O)&&R.get(O)!==V?null:V);return{parts:A,warnings:X,nets:re,netFor:V=>{let O=new Set((V?.primitives||[]).map(C=>R.get(C)).filter(Boolean));return O.size===1?[...O][0]:null},resolve:Ee,find:V=>T.get(V)||H.get(V)||null}}function jS(m,h="",p=0,w=[]){if(!m||p>3||w.length>=Pm)return w;for(let[S,A]of Object.entries(m)){if(w.length>=Pm)break;let T=h?`${h} \xB7 ${S}`:S;A&&typeof A=="object"&&!Array.isArray(A)?jS(A,T,p+1,w):A!=null&&w.push({name:Ci(T),value:Ci(Array.isArray(A)?A.join(", "):A)})}return w}function QD(m){if(!m)return[];let h=[],p=(A,T)=>{T!==""&&T!==void 0&&T!==null&&h.push({name:A,value:Ci(T)})},w=m.type==="part"?m:m.part;w&&(p("Reference",w.reference),p("Value",w.value),p("Footprint",w.footprint),p("Symbol",w.symbol)),["pad","pin"].includes(m.type)&&(p(m.type==="pad"?"Pad number":"Pin number",m.number),p("Pin name",m.name),p("Pin type",m.pinType),p("Pad type",m.padType),p("Shape",m.shape),p("Size",Sv(m.size)),p("Drill size",Sv(m.drill))),p("Saved component classes",w?.savedComponentClasses?.join(", "));let S=m.classAssignments||w?.classAssignments;return p("Sheet-local net classes",uh(S,"net").join(", ")),p("Component classes from rule areas",uh(S,"component").join(", ")),p("Directive UUIDs",ds((S||[]).map(A=>A.directiveUuid)).join(", ")),p("Rule area UUIDs",ds((S||[]).map(A=>A.ruleAreaUuid)).join(", ")),BS.includes(m.type)&&m.type!=="rule_area"&&h.push(...m.fields||[]),p("Net",m.net),m.type==="net"&&p("Objects",m.primitives.length),p("Layer",m.layer),p("Position",Ev(m.position)),p("End position",Ev(m.end)),m.rotation!==void 0&&p(m.type==="pad"?"Saved pad angle":"Rotation",`${Io(m.rotation)}\xB0`),typeof m.width=="number"&&p("Width",`${Io(m.width)} mm`),typeof m.size=="number"&&p("Diameter",`${Io(m.size)} mm`),typeof m.drill=="number"&&p("Drill",`${Io(m.drill)} mm`),m.type==="manufacturing"&&(p("Operation",m.operation),p("Polarity",m.polarity),m.bounds&&(p("Bounds origin",Ev(m.bounds)),p("Bounds size",Sv({x:m.bounds.w,y:m.bounds.h}))),h.push(...jS(m.metadata))),p("Source",m.path),p("Saved UUID",m.uuid),h}function VS(m){let h=m.host.ownerDocument,p=(et,St,At)=>{let Wt=h.createElement(et);return St&&(Wt.className=St),At!==void 0&&(Wt.textContent=At),Wt},w=p("style","",eU+DS),S=p("aside","viewer-inspector");S.hidden=!0,S.setAttribute("aria-label","Drawing inspector");let A=p("header","inspector-heading"),T=p("span"),H=p("small","","INSPECT"),Y=p("strong","","Properties");T.append(H,Y);let ee=(et,St)=>{let At=p("button","",et);return At.type="button",At.title=et,At.setAttribute("aria-label",et),At.onclick=St,At},X=ee("Clear selection",()=>m.clearSelection()),G=ee("Close inspector",()=>ne(!1));G.textContent="\xD7",A.append(T,X,G);let ae=p("div","inspector-tabs");ae.setAttribute("role","tablist"),ae.setAttribute("aria-label","Inspection sections");let _e=ee("Properties",()=>we("properties")),J=ee("Parts",()=>we("parts"));_e.setAttribute("role","tab"),J.setAttribute("role","tab");let Q=ee("Nets",()=>we("nets"));Q.setAttribute("role","tab"),ae.append(_e,J,Q);let te=p("section","inspector-body"),he=p("section","inspector-body"),be=p("input","inspector-search");be.type="search",be.placeholder="Find reference, value, footprint or class",be.setAttribute("aria-label","Find a part");let De=p("p","inspector-help"),Ke=p("div","inspector-results");De.setAttribute("role","status"),he.append(be,De,Ke);let qe=p("section","inspector-body"),$e=p("input","inspector-search"),Xe=p("p","inspector-help"),ve=p("div","inspector-results");$e.type="search",$e.placeholder="Find net name",$e.setAttribute("aria-label","Find a net"),qe.append($e,Xe,ve);let Ee=p("footer","inspector-footer"),me=p("label"),N=p("input");N.type="checkbox",N.setAttribute("aria-label","Show saved PCB pad and net labels"),N.disabled=!0,me.title="Saved PCB net and pad names appear at close zoom.",me.append(N,p("span","","Pad / net labels at close zoom"));let re=p("label"),R=p("input");R.type="checkbox",R.checked=!0,R.setAttribute("aria-label","Highlight entire net on selection"),re.append(R,p("span","","Highlight entire net"));let $=p("label"),V=p("input");V.type="checkbox",V.checked=m.inspectOnSelect!==!1,V.setAttribute("aria-label","Open properties on selection"),V.onchange=()=>m.setInspectOnSelect(V.checked),$.append(V,p("span","","Open properties on selection")),Ee.append($,re,me,p("div","","READ ONLY \xB7 Saved source properties")),S.append(A,ae,te,he,qe,Ee);let O=Im(null,{}),C=null,j="properties",B=!1,W=!1,K="",ge=[],Ne=US(m,S);function ne(et=!B){B=!!et,S.hidden=!B,Ne.sync(),m.inspectorButton?.setAttribute("aria-expanded",String(B)),m.emit?.("panelchange",Ne.getState())}function we(et){j=et,te.hidden=et!=="properties",he.hidden=et!=="parts",qe.hidden=et!=="nets",Q.setAttribute("aria-selected",String(et==="nets")),_e.setAttribute("aria-selected",String(et==="properties")),J.setAttribute("aria-selected",String(et==="parts"))}function xe(et){te.append(p("h3","inspector-section",et))}function ke(et){let St=p("dl","inspector-fields");for(let At of et.slice(0,128))St.append(p("dt","",At.name),p("dd","",At.value));te.append(St)}function Me(){let et=te.scrollTop||0,St=m.surface?.activeElement,At=St&&te.contains?.(St)?St.getAttribute?.("aria-label"):null;try{Ce()}finally{At&&[...te.querySelectorAll?.("button")||[]].find(Wt=>Wt.getAttribute("aria-label")===At)?.focus?.({preventScroll:!0}),te.scrollTop=et}}function Ce(){if(lt.layerSection=null,K="",ge=[],te.replaceChildren(),X.disabled=!C,Y.textContent=C?C.type==="pad"||C.type==="pin"?`${C.part?.reference||""} ${C.type} ${C.number}`.trim():C.reference||C.part?.reference||C.operation||C.type:"Properties",!C){te.append(p("p","inspector-help","Select an object in the drawing to inspect its saved properties, or use Parts to find a component."));return}let et=O.netFor(C);et&&!C.net&&(C={...C,net:et.name}),Y.textContent=C.type==="net"?"Net \xB7 "+C.name:["segment","arc","via","zone"].includes(C.type)?(C.type==="segment"?"Track":C.type)+(C.net?" \xB7 "+C.net:""):Y.textContent;let St=C.type==="net"?C:R.checked&&C.type!=="part"?et:null;St&&te.append(p("p","inspector-help",`Full net highlighted \xB7 ${St.name} \xB7 ${St.primitives.length} copper/drawing primitives`)),ke(QD(C)),["pcb","schematic"].includes(m.kind)&&typeof m.openInset=="function"&&te.append(ee("Open contextual preview",()=>{m.openInset().catch(ft=>{m.disposed||m.chrome.setStatus(ft.message,!0)})})),et&&C.type!=="net"&&te.append(ee("Highlight net "+et.name,()=>Je(et.id,{locate:!1})));let At=C.type==="part"?C:C.part,Wt=C.classAssignments||At?.classAssignments,nr=[...uh(Wt||et?.classAssignments,"net").map(ft=>["net",ft]),...ds([...At?.savedComponentClasses||[],...uh(Wt,"component")]).map(ft=>["component",ft])];for(let[ft,Bt]of nr.slice(0,24))te.append(ee("Highlight "+ft+" class "+Bt,()=>vt(ft,Bt)));let pt=C.type==="part"?C:C.part;if(pt){C.type!=="part"&&te.append(ee(m.view==="3d"?"Highlight part and pads":"Locate part and pads",()=>Rt(pt,!0)));let ft=pt.fields.filter(Bt=>!["Reference","Value","Footprint"].includes(Bt.name));if(ft.length&&(xe("Supplied fields"),ke(ft)),pt.note&&te.append(p("p","inspector-help",pt.note)),pt.pads.length){xe(`Pads \xB7 ${pt.pads.length}`);let Bt=p("div","inspector-pad-list");for(let Yt of pt.pads.slice(0,100)){let kr=ee(`Pad ${Yt.number}${Yt.net?" \xB7 "+Yt.net:""}`,()=>Rt(Yt,!0));kr.disabled=!Yt.primitives.length,Bt.append(kr)}te.append(Bt),pt.pads.length>100&&te.append(p("p","inspector-help","Showing the first 100 pads."))}}tt()}function tt(){if(!C)return;let et=m.getLayers(),St=ds((C.layers||[]).concat(C.part?.layers||[])),At=m.view+"|"+St.join("\0");if(At===K&&lt.layerSection){for(let{layer:ft,input:Bt}of ge)Bt.checked=m.renderer?.visibleLayers?.has(ft)||!1;return}if(lt.layerSection&&lt.layerSection.remove(),lt.layerSection=null,ge=[],K=At,!St.length)return;let Wt=p("div"),nr=p("h3","inspector-section","Object layers"),pt=p("div","inspector-layers");for(let ft of St){let Bt=p("label"),Yt=p("input");Yt.type="checkbox",Yt.checked=m.renderer?.visibleLayers?.has(ft)||!1,Yt.disabled=!["pcb","manufacturing"].includes(m.view)||!et.includes(ft),Yt.setAttribute("aria-label",`Show layer ${ft}`),ge.push({layer:ft,input:Yt}),Yt.onchange=()=>{let kr=new Set(m.renderer.visibleLayers);Yt.checked?kr.add(ft):kr.delete(ft),m.setLayers([...kr])},Bt.append(Yt,p("span","",ft)),pt.append(Bt)}Wt.append(nr,pt),te.append(Wt),lt.layerSection=Wt}function Ze(){let et=be.value?.trim().toLowerCase().slice(0,200)||"",St=O.parts.filter(At=>[At.reference,At.value,At.footprint,...At.savedComponentClasses||[],...uh(At.classAssignments,"component")].join(" ").toLowerCase().includes(et));De.textContent=`${St.length} ${St.length===1?"part":"parts"}${St.length>Cm?" \xB7 showing first 100":""}${O.warnings.length?" \xB7 bounded source index":""}`,Ke.replaceChildren(...St.slice(0,Cm).map(At=>{let Wt=ee(`Select ${At.reference||At.uuid||"part"}`,()=>Rt(At,!0));return Wt.replaceChildren(p("strong","",At.reference||"Unreferenced part"),p("small","",[At.value,At.footprint].filter(Boolean).join(" \xB7 "))),Wt.disabled=!At.uuid||!At.primitives.length||O.find(At.uuid)!==At,Wt})),O.parts.length||(De.textContent=m.kind==="manufacturing"?"CAM files contain manufacturing objects, not a component list.":"No saved parts are available in this drawing.")}function Ye(et,St=!1){let At=et?.part||et,Wt=et?.type==="net"?et:R.checked&&et?.type!=="part"?O.netFor(et):null,nr=Wt?.primitives||(et?.type==="pad"||et?.type==="pin"?et.primitives:At?.primitives)||[];if(m.view==="3d"&&et?.type==="class"){m.renderer?.setSelection?.({uuids:ds(et.records.map(pt=>pt.uuid))});return}if(m.view==="3d"){m.renderer?.setSelectionStyle?m.renderer.setSelectionStyle({mode:m.highlightMode||"dim",color:m.highlightColor||"source"}):m.renderer?.setSelectionDim?.(m.highlightMode!=="bright"),m.renderer?.setSelection?.(Wt?{netNames:[Wt.name]}:et?{uuids:ds([O.find(At.uuid)===At?At.uuid:"",...(At.pads||[]).filter(pt=>O.find(pt.uuid)===pt).map(pt=>pt.uuid),O.find(et.uuid)===et?et.uuid:""])}:{}),St&&!Wt&&At?.type==="part"&&O.find(At.uuid)===At&&m.renderer?.focusPart?.(At.uuid);return}if(m.view!=="manufacturing"){if(m.renderer?.setNetHighlight?.(et&&nr.length?{primitives:nr}:null,{mode:m.highlightMode||"dim",selectionColor:m.highlightColor||"source"}),St&&et?.primitives?.length&&m.renderer?.viewport?.camera){let pt=globalThis.KiCadOwnedCanvas?.bounds(et.primitives);if(pt){let ft=Math.max(1,Math.max(pt.w,pt.h)*.15);m.renderer.viewport.camera.bbox={x:pt.x-ft,y:pt.y-ft,w:Math.max(pt.w,1)+ft*2,h:Math.max(pt.h,1)+ft*2}}}m.renderer?.draw?.()}}function vt(et,St){let At=et==="net"?O.nets.filter(nr=>nr.classAssignments?.some(pt=>pt.name===St)):O.parts.filter(nr=>nr.savedComponentClasses?.includes(St)||nr.classAssignments?.some(pt=>pt.type==="component"&&pt.name===St)),Wt=[...new Set(At.flatMap(nr=>nr.primitives))];return Wt.length?(C={type:"class",reference:St,records:At,primitives:Wt,path:m.path},m.renderer&&(m.renderer.selected=null),Ye(C),Me(),!0):!1}function Rt(et,St=!1){if(!et)return!1;if(m.view==="3d")return Et({uuid:et.uuid,ownerUuid:et.part?.uuid,kind:et.type,pinNumber:et.number},{locate:St}),m.emit("select",{item:{uuid:et.uuid,ownerUuid:et.part?.uuid,reference:et.reference||et.part?.reference,kind:et.type},path:m.path,view:m.view}),!0;let At=et.primitives?.find(nr=>!nr.hidden&&nr.kind!=="drill")||et.primitives?.[0];if(!At)return!1;St&&Ye(et,!0);let Wt={uuid:et.uuid,ownerUuid:et.part?.uuid,reference:et.reference||et.part?.reference,kind:et.type,pinNumber:et.number};return m.renderer?.select?m.renderer.select({primitive:At,context:Wt}):m.handleSelection({item:Wt}),!0}function Je(et,{locate:St=!1}={}){let At=O.nets.find(pt=>pt.id===et),Wt=O.nets.filter(pt=>pt.name===et),nr=At||(Wt.length===1?Wt[0]:null);return!nr?.primitives.length||!["pcb","schematic","3d"].includes(m.view)?!1:(C=nr,m.renderer.selected=null,Ye(nr,St),Me(),m.inspectOnSelect!==!1&&(we("properties"),ne(!0)),m.emit("select",{item:{kind:"net",id:nr.id,netName:nr.name},path:m.path,view:m.view}),!0)}function _t(){let et=$e.value?.trim().toLowerCase().slice(0,200)||"",St=O.nets.filter(At=>(At.name+" "+uh(At.classAssignments,"net").join(" ")).toLowerCase().includes(et));Xe.textContent=St.length+" nets"+(St.length>Cm?" \xB7 showing first 100":"")+(m.kind==="schematic"?" \xB7 per-file saved connectivity":""),ve.replaceChildren(...St.slice(0,Cm).map(At=>{let Wt=ee("Select net "+At.name,()=>Je(At.id,{locate:!0}));return Wt.disabled=!At.primitives.length,Wt}))}function Et(et,{locate:St=!0}={}){C=O.resolve(et),Ye(C,St&&m.view==="3d"),Me(),C&&m.inspectOnSelect!==!1&&(we("properties"),ne(!0))}let gt=et=>{et.key==="Escape"&&B&&(ne(!1),m.inspectorButton?.focus?.())};m.surface.addEventListener?.("keydown",gt),be.oninput=Ze,$e.oninput=_t,R.onchange=()=>{Ye(C),Me()};function Ht(){Ye(C),_t(),R.disabled=!["pcb","schematic","3d"].includes(m.view),N.disabled=m.view!=="pcb"||typeof m.renderer?.setNetNames!="function",N.checked=W&&!N.disabled,N.disabled||(m.renderer.setNetNames(O.nets),m.renderer.showNetNames=W,m.renderer.draw?.())}N.onchange=()=>{W=N.checked,Ht()};let lt={style:w,panel:S,search:be,results:Ke,resultCount:De,clearButton:X,closeButton:G,propertiesTab:_e,partsTab:J,properties:te,partsPanel:he,netsTab:Q,netSearch:$e,netResults:ve,netToggle:R,layerSection:null,sizing:Ne,toggle:ne,select:Et,refreshLayers:tt,syncRenderer:Ht,labelToggle:N,autoInspect:V,refreshHighlight(){Ye(C)},setModel(et){O=et,C=null,te.scrollTop=0,be.value="",$e.value="",Ze(),_t(),Me()},resetSelection(){C=null,Me()},getSelectionPosition(){let et=C?.position;if(!et||![et.x,et.y].every(Number.isFinite))return null;let St=C.type==="segment"?C.end:null;return{x:St&&Number.isFinite(St.x)?(et.x+St.x)/2:et.x,y:St&&Number.isFinite(St.y)?(et.y+St.y)/2:et.y,layer:C.layer||C.layers?.find(At=>/^(F|B|In\d+)\.Cu$/.test(At))||null}},getSelection(){if(!C)return null;let et=C.type==="net"?C:O.netFor(C);return{kind:C.type,...C.uuid?{uuid:C.uuid}:{},...C.id?{id:C.id}:{},...C.part?.uuid?{ownerUuid:C.part.uuid}:{},...et?.name||C.net?{netName:et?.name||C.net}:{},...["pad","pin"].includes(C.type)?{pinNumber:C.number}:{}}},selectObject(et,{locate:St=!1,pinNumber:At}={}){let Wt=O.find(et);return Wt?.type==="part"&&At!==void 0&&(Wt=O.resolve({uuid:Wt.uuid,ownerUuid:Wt.uuid,kind:"pin",pinNumber:At})),Wt?Rt(Wt,St):!1},getParts(){return O.parts.map(et=>({id:et.id,uuid:et.uuid,reference:et.reference,value:et.value,footprint:et.footprint,layer:et.layer,schematicUuid:et.schematicUuid,...et.savedComponentClasses?.length?{savedComponentClasses:[...et.savedComponentClasses]}:{},...et.classAssignments?.length?{classAssignments:[...et.classAssignments]}:{}}))},selectPart(et,{locate:St=!0}={}){let At=O.find(et);return At?.type==="part"&&At.uuid&&O.find(At.uuid)===At?Rt(At,St):!1},getNets(){return O.nets.map(et=>({id:et.id,name:et.name,layers:[...et.layers],count:et.primitives.length,...et.classAssignments?.length?{classAssignments:[...et.classAssignments]}:{}}))},selectNet:Je,selectClass:vt,partGeometry(et){let St=O.find(et);return St?.type==="part"&&St.uuid===et?St.primitives:[]},partIdentity(et){let St=O.resolve(et),At=St?.type==="part"?St:St?.part;return At?.uuid&&O.find(At.uuid)===At?At.uuid:null},isOpen(){return B},getWarnings(){return[...O?.warnings||[]]},dispose(){Ne.dispose(),m.surface.removeEventListener?.("keydown",gt),be.oninput=$e.oninput=R.onchange=N.onchange=V.onchange=null;for(let et of[X,G,_e,J,Q])et.onclick=null;O=null,C=null,S.remove()}};return we(j),Me(),Ze(),lt}var wv,Vs,Pm,Cm,Rm,ZD,qi,Po,ba,to,oa,aa,Ci,la,hh,_v,zS,$D,ds,BS,uh,Io,Ev,Sv,eU,HS=Ui(()=>{FS();Bl();wv=5e4,Vs=5e5,Pm=64,Cm=100,Rm=xS,ZD=3e6,qi=m=>m&&typeof m=="object"&&!Array.isArray(m)?m.quoted:m,Po=m=>Array.isArray(m)?qi(m[0]):"",ba=(m,h)=>Array.isArray(m)?m.filter(p=>Po(p)===h):[],to=(m,h)=>Array.isArray(m)?m.find(p=>Po(p)===h):void 0,oa=(m,h)=>qi(to(m,h)?.[1]),aa=m=>String(oa(m,"uuid")||oa(m,"tstamp")||""),Ci=m=>m==null?"":String(m).slice(0,4096),la=m=>{let h=Number(qi(m));return Number.isFinite(h)?h:void 0},hh=(m,h="at")=>{let p=to(m,h);if(!p)return null;let w=la(p[1]),S=la(p[2]);return w===void 0||S===void 0?null:{x:w,y:S}},_v=m=>ba(m,"property").slice(0,Pm).map(h=>({name:Ci(qi(h[1])),value:Ci(qi(h[2]))})),zS=(m,h)=>Ci(qi(ba(m,"fp_text").find(p=>qi(p[1])===h)?.[2])),$D=m=>{let h=to(m,"size");return h?{x:la(h[1]),y:la(h[2])}:null},ds=m=>[...new Set(m.filter(Boolean))],BS=["rule_area","netclass_flag","directive_label"],uh=(m,h)=>ds((m||[]).filter(p=>p.type===h).map(p=>p.name));Io=m=>Number.isFinite(m)?String(Math.round(m*1e6)/1e6):"",Ev=m=>m&&Number.isFinite(m.x)&&Number.isFinite(m.y)?`${Io(m.x)}, ${Io(m.y)} mm`:"",Sv=m=>m&&Number.isFinite(m.x)&&Number.isFinite(m.y)?`${Io(m.x)} \xD7 ${Io(m.y)} mm`:"";eU=`
.viewer-inspector{position:absolute;z-index:9;top:58px;right:10px;bottom:10px;width:310px;max-width:calc(100% - 20px);display:flex;flex-direction:column;overflow:hidden;border:1px solid var(--viewer-border);border-radius:12px;background:var(--viewer-bar);color:var(--viewer-ink);box-shadow:var(--viewer-shadow);font:12px/1.45 system-ui}
.viewer-inspector[hidden]{display:none!important}.inspector-heading{display:flex;align-items:center;gap:6px;padding:12px 12px 10px;border-bottom:1px solid var(--viewer-border)}.inspector-heading>span{min-width:0;flex:1}.inspector-heading small{display:block;color:var(--viewer-muted);font:700 9px/1.4 system-ui;letter-spacing:.1em}.inspector-heading strong{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:14px}.viewer-inspector button{border:1px solid transparent;border-radius:5px;background:transparent;color:var(--viewer-muted);font:600 11px system-ui;padding:5px 7px;cursor:pointer}.viewer-inspector button:hover{background:var(--viewer-hover);color:var(--viewer-ink)}.viewer-inspector button:disabled{opacity:.4;cursor:default}.viewer-inspector button:focus-visible,.viewer-inspector input:focus-visible{outline:2px solid var(--viewer-accent);outline-offset:2px}
.inspector-tabs{display:flex;gap:3px;padding:6px 10px;background:var(--viewer-bg);border-bottom:1px solid var(--viewer-border)}.inspector-tabs button{flex:1;min-height:29px}.inspector-tabs button[aria-selected=true]{background:var(--viewer-bar);color:var(--viewer-accent);box-shadow:0 1px 3px #0001}.inspector-body{overflow:auto;flex:1;min-height:0;padding:12px}.inspector-body[hidden]{display:none}.inspector-fields{display:grid;grid-template-columns:minmax(65px,auto) minmax(0,1fr);gap:7px 14px;margin:0}.inspector-fields dt{color:var(--viewer-muted);font-size:10px}.inspector-fields dd{margin:0;overflow-wrap:anywhere;font-size:11px;font-variant-numeric:tabular-nums;white-space:pre-wrap}.inspector-section{margin:16px 0 8px;color:var(--viewer-muted);font-size:9px;letter-spacing:.07em;text-transform:uppercase}.inspector-help{margin:0 0 10px;color:var(--viewer-muted);font-size:11px;line-height:1.6}.inspector-search{width:100%;margin:0 0 10px;padding:8px 9px;border:1px solid var(--viewer-border);border-radius:7px;background:var(--viewer-bg);color:var(--viewer-ink);font:12px system-ui}.inspector-results{display:flex;flex-direction:column;gap:3px}.inspector-results button{display:block;width:100%;text-align:left;border:1px solid var(--viewer-border);padding:8px}.inspector-results button strong{color:var(--viewer-ink);font-size:12px}.inspector-results button small{display:block;margin-top:2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font:10px/1.4 system-ui}.inspector-pad-list{display:flex;flex-wrap:wrap;gap:4px}.inspector-pad-list button{border-color:var(--viewer-border);font-variant-numeric:tabular-nums}.inspector-layers{display:flex;flex-direction:column;gap:5px}.inspector-layers label{display:flex;align-items:center;gap:6px;font:11px system-ui}.inspector-layers input{accent-color:var(--viewer-accent)}.inspector-footer{border-top:1px solid var(--viewer-border);padding:7px 12px;color:var(--viewer-muted);font-size:9px;letter-spacing:.02em}
@container (max-width:580px){.viewer-inspector{width:min(340px,calc(100% - 20px));max-height:calc(100% - 68px);bottom:10px;top:auto}.inspector-body{max-height:52vh}.inspector-heading{padding:10px 12px}.inspector-fields{gap:6px 10px}}
@container (max-width:580px){.viewer-inspector{top:auto;bottom:8px;right:8px;width:calc(100% - 16px);max-width:none;max-height:min(65%,calc(100% - var(--viewer-toolbar-height,96px) - 16px));overflow:auto;overscroll-behavior:contain}.inspector-body{flex:1 0 120px;min-height:120px;max-height:none;overscroll-behavior:contain}.inspector-search{font-size:16px;min-height:44px}.viewer-inspector button{min-height:40px}.inspector-heading{flex-shrink:0}.inspector-tabs,.inspector-footer{flex-shrink:0}.inspector-footer label{display:flex;align-items:center;gap:7px;min-height:36px}.inspector-footer input{width:18px;height:18px}.inspector-fields{grid-template-columns:minmax(65px,auto) minmax(0,1fr)}}
@media(pointer:coarse){.viewer-inspector button{min-height:44px}.inspector-layers label{min-height:44px}.inspector-layers input{width:20px;height:20px}.inspector-footer label{min-height:40px}}
`});var Av={};Ol(Av,{loadThree:()=>rU});function rU(){return Promise.resolve(tU)}var tU,Tv=Ui(()=>{tU=(()=>{var m=Object.create,h=Object.defineProperty,p=Object.getOwnPropertyDescriptor,w=Object.getOwnPropertyNames,S=Object.getPrototypeOf,A=Object.prototype.hasOwnProperty,T=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),H=(e,t)=>{for(var r in t)h(e,r,{get:t[r],enumerable:!0})},Y=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of w(t))!A.call(e,n)&&n!==r&&h(e,n,{get:()=>t[n],enumerable:!(i=p(t,n))||i.enumerable});return e},ee=(e,t,r)=>(r=e!=null?m(S(e)):{},Y(t||!e||!e.__esModule?h(r,"default",{value:e,enumerable:!0}):r,e)),X=e=>Y(h({},"__esModule",{value:!0}),e),G=T((e,t)=>{(r=>{"use strict";let i=y=>({quoted:String(y??"")}),n=y=>{let b=Number(y);if(!Number.isFinite(b)||Math.abs(b)>1e8)throw Error("Invalid legacy schematic coordinate.");return Math.round(b*.0254*1e8)/1e8},s=y=>[...y.matchAll(/"((?:\\.|[^"\\])*)"|([^\s]+)/g)].map(b=>b[1]!==void 0?b[1].replace(/\\(["\\])/g,"$1"):b[2]),a=(y,b,x=0)=>["at",n(y),n(b),x],o=(y=50,b=!1)=>["effects",["font",["size",n(y),n(y)]],...b?["hide"]:[]];function l(y){if(typeof y!="string"||new TextEncoder().encode(y).length>8388608)throw Error("Legacy schematic/library exceeds its size limit.");let b=y.replace(/^\uFEFF/,"").split(/\r?\n/);if(b.length>15e4)throw Error("Legacy schematic/library exceeds its line limit.");return b}function c(y,b,x){let g,v=1,_=!1,E=!1,M=0,P=[];for(let k=b;k<x;k++){let z=y[k].trim();if(!z)continue;if(z==="EndData"&&_&&!E){E=!0;continue}if(_&&!E){if(!/^[0-9a-f]{2}(?:\s+[0-9a-f]{2})*$/i.test(z))throw Error("Invalid saved bitmap bytes.");let Z=z.match(/[0-9a-f]{2}/gi);if(M+=Z.length,M>4*1024*1024)throw Error("Saved bitmap exceeds its 4 MiB limit.");for(let se=0;se<Z.length;se+=8192)P.push(String.fromCharCode(...Z.slice(se,se+8192).map(ce=>parseInt(ce,16))));continue}let[D,I,L]=s(z);D==="Pos"&&I!==void 0&&L!==void 0&&(g=a(I,L)),D==="Scale"&&I!==void 0&&(v=Number(I)),D==="Data"&&!_&&(_=!0)}if(!g||!P.length||!E||!Number.isFinite(v)||v<=0)throw Error("Invalid saved bitmap placement or data.");return["image",g,["scale",v],["uuid",i("legacy-bitmap-"+b)],["data",i(btoa(P.join("")))]]}function u(y,b){let x=new Map,g=0;if(!Array.isArray(y))return x;if(y.length>16)throw Error("Too many legacy symbol libraries.");for(let v of y){let _=typeof v=="string"?v:v?.content;if(typeof _!="string")continue;if(g+=_.length,g>16*1024*1024)throw Error("Legacy symbol libraries exceed their combined limit.");let E=null,M=[],P=!1,k=new Map;for(let z of l(_)){let D=s(z),I=D[0];if(!I||I[0]==="#")continue;if(I==="DEF"){E=D,M=[],k=new Map;continue}if(!E)continue;if(I==="ALIAS"){M.push(...D.slice(1));continue}if(I==="DRAW"){P=!0;continue}if(I==="ENDDRAW"){P=!1;continue}if(I==="ENDDEF"){let ce=E[1],fe=["symbol",i(ce),...E[9]==="P"?[["power"]]:[],...E[5]==="N"?[["pin_numbers","hide"]]:[],...E[6]==="N"?[["pin_names","hide"]]:[],...k.values()];for(let ze of[ce,...M])x.has(ze)||x.set(ze,fe);E=null;continue}if(!P)continue;let L=(ce,fe,ze)=>{let Fe=ce+"_"+fe;k.has(Fe)||k.set(Fe,["symbol",i(E[1]+"_"+Fe)]),k.get(Fe).push(ze)},Z=ce=>["stroke",["width",Math.max(n(ce||6),.01)]],se=ce=>["fill",["type",ce==="F"?"outline":ce==="f"?"background":"none"]];if(I==="S")L(D[5],D[6],["rectangle",["start",n(D[1]),n(D[2])],["end",n(D[3]),n(D[4])],Z(D[7]),se(D[8])]);else if(I==="C")L(D[4],D[5],["circle",["center",n(D[1]),n(D[2])],["radius",n(D[3])],Z(D[6]),se(D[7])]);else if(I==="P"){let ce=Number(D[1]);if(!Number.isInteger(ce)||ce<2||ce>1e4||D.length<5+2*ce)throw Error("Invalid legacy library polyline.");L(D[2],D[3],["polyline",["pts",...Array.from({length:ce},(fe,ze)=>["xy",n(D[5+ze*2]),n(D[6+ze*2])])],Z(D[4]),se(D[5+ce*2])])}else if(I==="A"){let ce=n(D[1]),fe=n(D[2]),ze=n(D[3]),Fe=Number(D[4])*Math.PI/1800,Pe=Number(D[5])*Math.PI/1800-Fe;for(;Pe<0;)Pe+=Math.PI*2;let ue=Te=>[ce+ze*Math.cos(Te),fe+ze*Math.sin(Te)];L(D[6],D[7],["arc",["start",...ue(Fe)],["mid",...ue(Fe+Pe/2)],["end",...ue(Fe+Pe)],Z(D[8]),se(D[9])])}else if(I==="X"){let ce={I:"input",O:"output",B:"bidirectional",T:"tri_state",P:"passive",U:"unspecified",W:"power_in",w:"power_out",C:"open_collector",E:"open_emitter",N:"no_connect"},fe={R:0,U:90,L:180,D:270}[D[6]],ze={"":"line",I:"inverted",C:"clock",CI:"inverted_clock",L:"input_low",CL:"clock_low",V:"output_low",F:"edge_clock_high",X:"non_logic"},Fe=D[12]||"",Pe=Fe.includes("N"),ue=ze[Fe.replace(/N/g,"")];if(fe===void 0||!ue){b("Unsupported legacy pin orientation/style omitted: "+D[1]);continue}L(D[9],D[10],["pin",ce[D[11]]||"unspecified",ue,a(D[3],D[4],fe),["length",n(D[5])],["name",i(D[1]),o(D[8])],["number",i(D[2]),o(D[7])],...Pe?["hide"]:[]])}else b(I==="T"?"Legacy library text is omitted; convert a copy in KiCad for complete typography.":"Unsupported legacy library graphic "+I+" omitted.")}}return x}function d(y,b={}){let x=l(y);if(!/^EESchema Schematic File Version [24]\b/.test(x[0]))throw Error("Only legacy Eeschema v2/v4 schematics are supported.");let g=new Set(["Restricted legacy schematic preview: only recognized saved records and supplied cache-library graphics are rendered. Convert a separate copy in KiCad for a complete modern preview."]),v=D=>{g.size<200&&g.add(D)},_=u(b.libraries,v),E=["kicad_sch",["version",Number(x[0].match(/\d+$/)[0])],["legacy_source",i(x[0])]],M=["lib_symbols"],P=[],k=(D,I,L,Z,se=50,ce=!1,fe=0)=>["property",i(D),i(I),a(L,Z,fe),o(se,ce)];function z(D,I){let L=[],Z=D;for(;Z<x.length&&x[Z]!==I;Z++)L.push(s(x[Z]));if(Z===x.length)throw Error("Incomplete legacy schematic "+I+" block.");return{records:L,end:Z}}for(let D=1;D<x.length;D++){let I=s(x[D]),L=I[0];if(!(!L||L[0]==="#")){if(L==="$Descr"){E.push(["paper",i(I[1])]);continue}if(/^Comment[1-9]$/.test(L)){let Z=E.find(se=>Array.isArray(se)&&se[0]==="title_block");Z||(Z=["title_block"],E.push(Z)),Z.push(["comment",Number(L.slice(7)),i(I[1])]);continue}if(["Title","Date","Rev","Comp"].includes(L)){let Z=E.find(se=>Array.isArray(se)&&se[0]==="title_block");Z||(Z=["title_block"],E.push(Z)),Z.push([{Title:"title",Date:"date",Rev:"rev",Comp:"company"}[L],i(I[1])]);continue}if(L==="Wire"||L==="Entry"){let Z=s(x[++D]||"");if(Z.length!==4)throw Error("Invalid legacy wire record.");if(L==="Entry"){v("Legacy bus-entry geometry omitted.");continue}E.push([I[1]==="Bus"?"bus":"wire",["pts",["xy",n(Z[0]),n(Z[1])],["xy",n(Z[2]),n(Z[3])]]]);continue}if(L==="Connection"||L==="NoConn"){E.push([L==="Connection"?"junction":"no_connect",a(I[2],I[3])]);continue}if(L==="Text"){let Z=x[++D]??"",se={Label:"label",GLabel:"global_label",HLabel:"hierarchical_label",Notes:"text"}[I[1]];if(!se){v("Unsupported legacy text record "+I[1]+" omitted.");continue}let ce=[0,90,180,270],fe=ce[Number(I[4])];if(fe===void 0){v("Unsupported legacy text orientation omitted.");continue}let ze={Input:"input",Output:"output",BiDi:"bidirectional",TriState:"tri_state",UnSpc:"passive"}[I[6]];!["text","label"].includes(se)&&!ze&&v("Unknown legacy label shape "+I[6]+"; passive outline used."),E.push([se,i(Z.replace(/\\n/g,`
`)),a(I[2],I[3],fe),o(I[5]),...se==="text"||se==="label"?[]:[["shape",ze||"passive"]]]);continue}if(L==="$Sheet"){let Z=z(D+1,"$EndSheet");D=Z.end;let se=Z.records,ce=se.find(Fe=>Fe[0]==="S"),fe=se.find(Fe=>Fe[0]==="U");if(!ce)throw Error("Legacy sheet has no bounds.");let ze=["sheet",a(ce[1],ce[2]),["size",n(ce[3]),n(ce[4])],["uuid",i(fe?.[1]||"legacy-sheet-"+D)]];for(let Fe of se.filter(Pe=>/^F\d+$/.test(Pe[0])))if(Fe[0]==="F0"||Fe[0]==="F1")ze.push(k(Fe[0]==="F0"?"Sheetname":"Sheetfile",Fe[1],ce[1],ce[2],Fe[2]));else{let Pe=Fe[3],ue={L:180,R:0,U:90,D:270}[Pe];ze.push(["pin",i(Fe[1]),{I:"input",O:"output",B:"bidirectional",T:"tri_state",U:"passive"}[Fe[2]]||"passive",a(Fe[4],Fe[5],ue??0),o(Fe[6])])}E.push(ze);continue}if(L==="$Comp"){let Z=z(D+1,"$EndComp");D=Z.end;let se=Z.records,ce=se.find(Ie=>Ie[0]==="L"),fe=se.find(Ie=>Ie[0]==="U"),ze=se.find(Ie=>Ie[0]==="P");if(!ce||!ze)throw Error("Incomplete legacy component.");let Fe=ce[1],Pe=se.find(Ie=>Ie.length===4&&Ie.every(Re=>/^-?\d+$/.test(Re)))?.map(Number)||[1,0,0,-1],ue=null;for(let Ie of[0,90,180,270])for(let Re of["","x","y"]){let Be=Ie*Math.PI/180,Se=Math.round(Math.cos(Be)),U=Math.round(Math.sin(Be)),ie=Re==="y"?-1:1,Ae=Re==="x"?-1:1,Ue=[ie*Se,-ie*U,-Ae*U,-Ae*Se];Pe.every((Ge,nt)=>Ge===Ue[nt])&&(ue={angle:Ie,mirror:Re})}if(!ue){v("Legacy component "+Fe+" has an unsupported orientation and is omitted.");continue}let Te=["symbol",["lib_id",i(Fe)],a(ze[1],ze[2],ue.angle),["unit",Number(fe?.[1]||1)],["convert",Number(fe?.[2]||1)],["uuid",i(fe?.[3]||"legacy-component-"+D)],...ue.mirror?[["mirror",ue.mirror]]:[]];for(let Ie of se.filter(Re=>Re[0]==="F")){let Re=["Reference","Value","Footprint","Datasheet"][Number(Ie[1])]||Ie[11]||"Field"+Ie[1];Te.push(k(Re,Ie[2],Ie[4],Ie[5],Ie[6],Ie[7]!=="0000",(((Ie[3]==="V"?90:0)-ue.angle)%180+180)%180))}let de=_.get(Fe)||_.get(Fe.split(":").pop());de?P.includes(Fe)||(M.push(["symbol",i(Fe),...de.slice(2)]),P.push(Fe)):v("Missing saved legacy library definition for "+Fe+": symbol body and pins omitted; fields remain visible."),E.push(Te);continue}if(L==="$Bitmap"){let Z=x.indexOf("$EndBitmap",D+1);if(Z<0){v("Legacy bitmap omitted: missing block terminator.");break}try{E.push(c(x,D+1,Z))}catch(se){v("Legacy bitmap omitted: "+se.message)}D=Z}}}if(!x.some(D=>D==="$EndSCHEMATC"))throw Error("Incomplete legacy schematic terminator.");return E.push(M,...[...g].map(D=>["legacy_diagnostic",i(D)])),E}function f(y){let b=l(y),x=[],g=!1;for(let v of b)if(v==="$Sheet")g=!0;else if(v==="$EndSheet")g=!1;else if(g){let _=s(v);_[0]==="F1"&&x.push(_[1])}return x}r.KiCadLegacy={parse:d,sheetFiles:f},typeof t=="object"&&t.exports&&(t.exports=r.KiCadLegacy)})(globalThis)}),ae=T((e,t)=>{(r=>{"use strict";let i=()=>268435456,n=new Set(["symbol","sheet","wire","bus","bus_entry","label","global_label","hierarchical_label","junction","no_connect","text","text_box","polyline","rectangle","circle","arc","image","rule_area","netclass_flag","directive_label"]),s=new Set(["footprint","segment","arc","via","zone","gr_line","gr_rect","gr_circle","gr_arc","gr_poly","gr_curve","gr_text","gr_text_box","gr_bitmap","dimension","target"]),a=new Set(["uuid","tstamp","filled_polygon","fill_segments"]),o=/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?$/;function l(de){if(typeof de!="string")throw new TypeError("KiCad source must be a string.");if(!/[^\x00-\x7f]/.test(de))return de.length;let Ie=de.length;for(let Re=0;Re<de.length;Re++){let Be=de.charCodeAt(Re);if(!(Be<128)){if(Be<2048){Ie++;continue}if(Be>=55296&&Be<=56319&&Re+1<de.length){let Se=de.charCodeAt(Re+1);if(Se>=56320&&Se<=57343){Ie+=2,Re++;continue}}Ie+=2}}return Ie}let c=de=>de===32||de>=9&&de<=13||de>127&&/\s/.test(String.fromCharCode(de));function u(de){if(!Array.isArray(de)||de.length!==4||de.some(ie=>!ie||!Number.isFinite(ie.x)||!Number.isFinite(ie.y)))throw Error("Bezier requires four finite control points.");let Ie=[{...de[0]}],Re=[de],Be=.005**2,Se=(ie,Ae,Ue)=>{let Ge=Ue.x-Ae.x,nt=Ue.y-Ae.y,Qe=Ge*Ge+nt*nt,ct=Qe?Math.max(0,Math.min(1,((ie.x-Ae.x)*Ge+(ie.y-Ae.y)*nt)/Qe)):0;return(ie.x-Ae.x-ct*Ge)**2+(ie.y-Ae.y-ct*nt)**2},U=(ie,Ae)=>({x:ie.x/2+Ae.x/2,y:ie.y/2+Ae.y/2});for(;Re.length;){let[ie,Ae,Ue,Ge]=Re.pop();if(Math.max(Se(Ae,ie,Ge),Se(Ue,ie,Ge))<=Be){if(Ie.length>=2049)throw Error("Bezier exceeds the bounded tessellation budget.");Ie.push({...Ge})}else{let nt=U(ie,Ae),Qe=U(Ae,Ue),ct=U(Ue,Ge),ye=U(nt,Qe),dt=U(Qe,ct),xt=U(ye,dt);if(Re.length>32||[nt,Qe,ct,ye,dt,xt].some(Dt=>!Number.isFinite(Dt.x)||!Number.isFinite(Dt.y)))throw Error("Bezier exceeds the bounded tessellation budget.");Re.push([xt,dt,ct,Ge],[ie,nt,ye,xt])}}return Ie}let d=new Set(["version","generator","generator_version","uuid","paper","title_block","property","sheet","symbol","footprint","module","sheet_instances","legacy_source","legacy_diagnostic"]),f=new Set([...d,"embedded_files"]),y=new Set(["property","uuid","path","instances"]);function b(de,Ie={}){if(typeof de!="string")throw new TypeError("KiCad source must be a string.");if(/^\s*PCBNEW-BOARD/.test(de))throw Error("Legacy .brd boards are detected but this drawing format is not yet rendered. Open and save a separate .kicad_pcb copy in KiCad.");if(/^\s*EESchema Schematic File Version [24]\b/.test(de)){let Qe=r.KiCadLegacy||(typeof t=="object"&&t.exports?G():null);if(!Qe)throw Error("Legacy schematic adapter is unavailable; reload the extension.");return Qe.parse(de,Ie)}if(de.length>268435456||de.length>268435456/3&&l(de)>268435456)throw new Error("KiCad file exceeds browser parser size limits.");let Re=[],Be=[],Se=/\(xy[ \t]+([-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?)[ \t]+([-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?)[ \t]*\)/y,U=0,ie=0,Ae=0,Ue=()=>Re.length===3&&Re[0][0]==="kicad_pcb"&&Re[1][0]==="zone"&&Re[2][0]==="filled_polygon";function Ge(Qe){let ct=Qe+4,ye=0,dt=new Float64Array(128);for(;ct<de.length;){for(;c(de.charCodeAt(ct));)ct++;if(de.charCodeAt(ct)===41)return ye<6?null:(ie+=1+ye*2,nt(["pts",ye===dt.length?dt:dt.slice(0,ye)]),ct+1);Se.lastIndex=ct;let xt=Se.exec(de);if(!xt)return null;let Dt=Number(xt[1]),We=Number(xt[2]);if(!Number.isFinite(Dt)||!Number.isFinite(We))throw new Error("Invalid numeric KiCad value.");if(ie+6+ye*2>12e6)throw new Error("KiCad file has too many S-expression nodes.");if(ye===dt.length){let mt=new Float64Array(dt.length*2);mt.set(dt),dt=mt}dt[ye++]=Dt,dt[ye++]=We,ct=Se.lastIndex}return null}let nt=Qe=>{if(++ie>12e6)throw new Error("KiCad file has too many S-expression nodes.");Ae||(Re.at(-1)||Be).push(Qe)};for(;U<de.length;){let Qe=de[U];if(c(de.charCodeAt(U))){U++;continue}if((Qe==="<"||Qe===">")&&/^(?:<{7,}|>{7,})(?:\s|$)/.test(de.slice(U,U+120)))throw new Error("Unresolved Git merge conflict at line "+de.slice(0,U).split(`
`).length+". Resolve the conflict in a separate copy before viewing.");if(Qe===";"){for(;U<de.length&&de[U]!==`
`;)U++;continue}if(Qe==="("){if(Re.length>=96)throw new Error("KiCad S-expression is too deep.");if(Ie.compactCopper&&!Ie.metadataOnly&&de.startsWith("(pts",U)&&c(de.charCodeAt(U+4))&&Ue()){let xt=Ge(U);if(xt!==null){U=xt;continue}}if(!Ie.metadataOnly&&Re.length&&de.startsWith("(xy",U)){Se.lastIndex=U;let xt=Se.exec(de);if(xt){let Dt=Number(xt[1]),We=Number(xt[2]);if(!Number.isFinite(Dt)||!Number.isFinite(We))throw new Error("Invalid numeric KiCad value.");ie+=3,nt(["xy",Dt,We]),U=Se.lastIndex;continue}}if(Ie.metadataOnly&&!Ae){let xt=null;if(Re.length===1?xt=Ie.includeEmbeddedFonts?f:d:Re.length===2&&["symbol","footprint","module"].includes(Re.at(-1)?.[0])?xt=y:Re.at(-1)?.[0]==="property"&&(xt=new Set),xt){let Dt=U+1;for(;Dt<de.length&&c(de.charCodeAt(Dt));)Dt++;let We=Dt;for(;We<de.length&&!c(de.charCodeAt(We))&&!["(",")",";"].includes(de[We]);)We++;xt.has(de.slice(Dt,We))||(Ae=Re.length+1)}}let dt=[];nt(dt),Re.push(dt),U++;continue}if(Qe===")"){if(!Re.length)throw new Error("Unexpected closing parenthesis in KiCad file.");let dt=Re.pop();if(!Ae&&dt.length>0&&dt.length<=4){let xt=dt.slice(),Dt=Re.at(-1)||Be;Dt[Dt.length-1]=xt}Ae&&Re.length<Ae&&(Ae=0),U++;continue}if(!Re.length)throw new Error("Expected a KiCad S-expression.");if(Qe==='"'){let dt=null,xt=++U,Dt=!1,We="";for(;U<de.length;){let mt=de[U++];if(mt==='"'){if(Dt=!0,!Ae){let it=de.slice(xt,U-1);dt?(dt.push(it),We=dt.join("")):We=it}break}if(mt==="\\"){if(U>=de.length)throw new Error("Unterminated KiCad escape sequence.");let it=de[U++];if(!Ae){dt??=[],dt.push(de.slice(xt,U-2));let st={n:`
`,r:"\r",t:"	",'"':'"',"\\":"\\"}[it];dt.push(st===void 0?"\\"+it:st)}xt=U}}if(!Dt)throw new Error("Unterminated quoted KiCad string.");nt(Ae?null:{quoted:We});continue}let ct=U;for(;U<de.length;){let dt=de.charCodeAt(U);if(dt===40||dt===41||dt===59||dt===34||c(dt))break;U++}if(ct===U)throw new Error("Unexpected KiCad source character.");if(Ae){nt(null);continue}let ye=de.slice(ct,U);if(o.test(ye)){let dt=Number(ye);if(!Number.isFinite(dt))throw new Error("Invalid numeric KiCad value.");nt(dt)}else nt(ye==="xy"?"xy":ye)}if(Re.length||Be.length!==1||!Array.isArray(Be[0]))throw new Error("Incomplete KiCad S-expression.");return Be[0]}let x=de=>de&&typeof de=="object"&&!Array.isArray(de)?de.quoted:de,g=de=>Array.isArray(de)?String(x(de[0])):"",v=(de,Ie)=>de.filter(Re=>Array.isArray(Re)&&g(Re)===Ie),_=(de,Ie)=>de.find(Re=>Array.isArray(Re)&&g(Re)===Ie),E=(de,Ie)=>x(_(de,Ie)?.[1]);function M(de){let Ie=_(de,"polyline"),Re=Ie&&_(Ie,"pts");if(!Re||Re.length<4||Re.length>4097)return null;let Be=[];for(let ie of Re.slice(1)){let Ae=x(ie?.[1]),Ue=x(ie?.[2]);if(!Array.isArray(ie)||g(ie)!=="xy"||!Number.isFinite(Ae)||!Number.isFinite(Ue))return null;let Ge=Be.at(-1);(Ge?.x!==Ae||Ge.y!==Ue)&&Be.push({x:Ae,y:Ue})}if(Be[0].x===Be.at(-1).x&&Be[0].y===Be.at(-1).y&&Be.pop(),Be.length<3)return null;let Se=Be[0],U=0;for(let ie=1;ie<Be.length-1;ie++){let Ae=Be[ie],Ue=Be[ie+1];U+=(Ae.x-Se.x)*(Ue.y-Se.y)-(Ae.y-Se.y)*(Ue.x-Se.x)}return Number.isFinite(U)&&U!==0?Be:null}function P(de){for(let Ie of["at","start","center","end","xy"]){let Re=_(de,Ie);if(Re&&Number.isFinite(x(Re[1]))&&Number.isFinite(x(Re[2])))return{x:x(Re[1]),y:x(Re[2])}}for(let Ie of["pts","polygon"]){let Re=_(de,Ie),Be=Re&&_(Ie==="polygon"&&_(Re,"pts")||Re,"xy");if(Be&&Number.isFinite(x(Be[1]))&&Number.isFinite(x(Be[2])))return{x:x(Be[1]),y:x(Be[2])}}return null}function k(de,Ie){let Re=[];for(let ie of v(de,"property"))ie.length>=3&&Re.push([String(x(ie[1])),String(x(ie[2]))]);if(Ie==="footprint")for(let[ie,Ae]of[["reference","Reference"],["value","Value"]]){let Ue=v(de,"fp_text").find(Ge=>x(Ge[1])===ie);Ue&&Ue.length>=3&&!Re.some(([Ge])=>Ge===Ae)&&Re.push([Ae,String(x(Ue[2]))])}for(let ie of["lib_id","layer","width","drill","size","unit"]){let Ae=_(de,ie);Ae&&Re.push([ie,Ae.slice(1).map(x).join(", ")])}let Be=_(de,"layers");Be&&Re.push(["Layers",Be.slice(1).map(x).join(", ")]);let Se=_(de,"net");Se&&Re.push(["Net",String(x(Se[2]??Se[1]))]);let U=_(de,"at");return U&&Number.isFinite(x(U[3]))&&Re.push(["Angle",String(x(U[3]))]),["label","global_label","hierarchical_label","text","gr_text","gr_text_box"].includes(Ie)&&Re.push(["Text",String(x(de[1]??""))]),Ie==="pad"&&(Re.push(["Number",String(x(de[1]??""))]),Re.push(["Type",String(x(de[2]??""))]),Re.push(["Shape",String(x(de[3]??""))])),Object.fromEntries(Re)}function z(de){return Array.isArray(de)?de.filter(Ie=>!Array.isArray(Ie)||!a.has(g(Ie))).map(z):de&&typeof de=="object"?["quoted",de.quoted]:de}function D(de){let Ie=2166136261;for(let Re=0;Re<de.length;Re++)Ie=Math.imul(Ie^de.charCodeAt(Re),16777619);return(Ie>>>0).toString(16).padStart(8,"0")}function I(de,Ie,Re,Be){let Se=E(de,"uuid")??E(de,"tstamp")??(Ie==="rule_area"&&_(de,"polyline")?E(_(de,"polyline"),"uuid"):void 0);if(Se!=null&&String(Se))return{key:`uuid:${Se}`,uuid:String(Se)};let U=Ie==="pad"?Re.Number:Ie==="sheet"?Re.Sheetfile:Ie==="symbol"||Ie==="footprint"?Re.Reference:void 0;return{key:U?`fallback:${String(U)}`:`fallback:${D(typeof Be=="function"?Be():Be)}`,uuid:null}}function L(de,Ie,Re,Be){return Ie==="pad"?`${Be||"Footprint"} pad ${Re.Number||""}`.trim():Re.Reference||Re.Sheetname||Re["Sheet name"]||Re.Text||(Ie==="footprint"?String(x(de[1]??"Footprint")):Ie==="symbol"?Re.lib_id||"symbol":Ie==="netclass_flag"||Ie==="directive_label"?"Directive label":Ie==="rule_area"?"Rule area":Ie.replace(/_/g," "))}function Z(de,Ie){if(!de||!Ie?.position)return null;let Re=Number(x(_(Ie.form,"at")?.[3]??0)),Be=(Number.isFinite(Re)?Re:0)*Math.PI/180,Se=Math.cos(Be),U=Math.sin(Be),ie=Ie.position.x+de.x*Se+de.y*U,Ae=Ie.position.y-de.x*U+de.y*Se,Ue=Ge=>Math.round(Ge*1e6)/1e6;return{x:Ue(ie),y:Ue(Ae)}}function se(de,Ie,Re=null,Be=null,Se=!1){let U=g(Ie),ie=k(Ie,U),Ae=P(U==="rule_area"&&_(Ie,"polyline")||Ie),Ue=U==="pad"?Z(Ae,Re):Ae,Ge,nt=()=>Ge??=JSON.stringify([z(Ie),Ue,typeof Be=="function"?Be():Be]);Se||(ie["Source fingerprint"]=D(nt()));let Qe=I(Ie,U,ie,nt),ct=`${Re?`${Re.scope}/`:`${de}/`}${U}:${Qe.key}`,ye=L(Ie,U,ie,Re?.label);return{key:ct,scope:ct,signature:Se?null:nt(),metadata:{uuid:Qe.uuid,position:Ue,properties:ie},path:de,kind:U,label:ye,form:Ie}}function ce(de,Ie,Re=null,{forConnectivity:Be=!1,parseOnly:Se=!1,compactCopper:U=!1}={},ie){let Ae=ie||b(Ie,{compactCopper:U});Re?.(Ae);let Ue=g(Ae);if(Ue!=="kicad_sch"&&Ue!=="kicad_pcb")throw new Error("Expected a KiCad schematic or board.");if(Se)return[];let Ge=Ue==="kicad_sch"?n:s,nt=new Map;if(Ue==="kicad_sch"){let ct=_(Ae,"lib_symbols");if(ct)for(let ye of v(ct,"symbol")){let dt=x(ye[1]);typeof dt=="string"&&nt.set(dt,Be?ye:JSON.stringify(z(ye)))}}let Qe=[];for(let ct of Ae){if(!Array.isArray(ct)||!Ge.has(g(ct)))continue;let ye=g(ct)==="symbol"?nt.get(String(E(ct,"lib_name")??E(ct,"lib_id"))):null,dt=se(de,ct,null,Be&&ye?()=>JSON.stringify(z(ye)):ye,Be);if(Qe.push(dt),Ue==="kicad_pcb"&&dt.kind==="footprint")for(let xt of v(ct,"pad"))Qe.push(se(de,xt,{form:ct,position:dt.metadata.position,scope:dt.scope,label:dt.label},null,Be))}return Qe}function fe(de,Ie={}){return b(de,{...Ie,metadataOnly:!0}).filter((Re,Be)=>Be===0||Array.isArray(Re)&&(Ie.includeEmbeddedFonts?f:d).has(Re[0])).map(Re=>Array.isArray(Re)&&["symbol","footprint","module"].includes(Re[0])?Re.filter((Be,Se)=>Se===0||Array.isArray(Be)&&y.has(Be[0])):Re)}let ze=new WeakMap;function Fe(de,{forConnectivity:Ie=!1,compactCopper:Re=!1}={}){let Be=new Map,Se=ue(de,(ie,Ae)=>Be.set(ie.path,Ae),null,{forConnectivity:Ie,parseOnly:Ie,compactCopper:Ie&&Re}),U=Object.freeze({});return ze.set(U,{files:de.map(ie=>({path:ie.path,content:ie.content})),parsed:Be,records:Ie?null:Se,forConnectivity:Ie}),U}function Pe(de,Ie,Re){let Be=ze.get(de);if(!Be||!Be.parsed.has(Ie))throw new Error("Prepared KiCad file is unavailable.");if(Re!==void 0&&!Be.files.some(Se=>Se.path===Ie&&Se.content===Re))throw new Error("Prepared KiCad file differs from source.");return Be.parsed.get(Ie)}function ue(de,Ie=null,Re=null,{forConnectivity:Be=!1,parseOnly:Se=!1,compactCopper:U=!1}={}){if(Re){let Ge=ze.get(Re);if(!Ge||!Array.isArray(de)||de.length!==Ge.files.length||de.some((nt,Qe)=>nt?.path!==Ge.files[Qe].path||nt?.content!==Ge.files[Qe].content))throw new Error("Prepared KiCad project differs from source.");if(Ge.forConnectivity!==Be||!Ge.records){let nt=[];for(let Qe of de)for(let ct of ce(Qe.path,Qe.content,ye=>Ie?.(Qe,ye),{forConnectivity:Be},Ge.parsed.get(Qe.path)))nt.push(ct);return nt}for(let nt of de)Ie?.(nt,Ge.parsed.get(nt.path));return Ge.records.map(nt=>({...nt}))}if(!Array.isArray(de)||de.length>128)throw new Error("Too many KiCad files to compare.");let ie=new Set,Ae=[],Ue=0;for(let Ge of de){if(!Ge||typeof Ge.path!="string"||typeof Ge.content!="string"||!/\.kicad_(?:sch|pcb)$/i.test(Ge.path)||ie.has(Ge.path))throw new Error("Invalid or duplicate KiCad file entry.");ie.add(Ge.path);let nt=l(Ge.content);if(Ue+=nt,nt>268435456||Ue>536870912)throw new Error("KiCad project exceeds browser comparison size limits.");for(let Qe of ce(Ge.path,Ge.content,ct=>Ie?.(Ge,ct),{forConnectivity:Be,parseOnly:Se,compactCopper:U}))Ae.push(Qe)}return Ae}function Te(de,Ie){let Re=ue(de),Be=ue(Ie),Se=new Map;for(let Ue of Re)Se.has(Ue.key)||Se.set(Ue.key,{before:[],after:[]}),Se.get(Ue.key).before.push(Ue);for(let Ue of Be)Se.has(Ue.key)||Se.set(Ue.key,{before:[],after:[]}),Se.get(Ue.key).after.push(Ue);let U=[],ie={added:0,removed:0,modified:0},Ae=(Ue,Ge,nt,Qe,ct)=>{U.push({id:ct,path:Ue.path,kind:Ue.kind,label:Ue.label,status:Ge,before:nt?.metadata??null,after:Qe?.metadata??null}),ie[Ge]++};for(let[Ue,Ge]of Se){let nt=[...Ge.before],Qe=[...Ge.after];for(let ye=nt.length-1;ye>=0;ye--){let dt=Qe.findIndex(xt=>xt.signature===nt[ye].signature);dt>=0&&(nt.splice(ye,1),Qe.splice(dt,1))}nt.sort((ye,dt)=>ye.signature.localeCompare(dt.signature)),Qe.sort((ye,dt)=>ye.signature.localeCompare(dt.signature));let ct=Math.max(nt.length,Qe.length);for(let ye=0;ye<ct;ye++){let dt=nt[ye]||null,xt=Qe[ye]||null;Ae(xt||dt,dt&&xt?"modified":dt?"removed":"added",dt,xt,ct>1?`${Ue}#${ye+1}`:Ue)}}return U.sort((Ue,Ge)=>Ue.path.localeCompare(Ge.path)||Ue.id.localeCompare(Ge.id)||Ue.status.localeCompare(Ge.status)),{changes:U,counts:ie}}r.KiCadDesignDiff={compareProjects:Te,projectObjects:ue,parse:b,parseMetadata:fe,sourceByteLimit:i,sourceByteLength:l,prepareProject:Fe,preparedFile:Pe,cubicBezierPoints:u,MAX_FILES:128,MAX_FILE_BYTES:268435456,MAX_PROJECT_BYTES:536870912,MAX_RENDER_PRIMITIVES:15e5,ruleAreaPoints:M},typeof t=="object"&&t.exports&&(t.exports=r.KiCadDesignDiff)})(typeof globalThis=="object"?globalThis:e)}),_e=T((e,t)=>{(r=>{"use strict";let i=g=>g&&typeof g=="object"&&!Array.isArray(g)?g.quoted:g,n=g=>Array.isArray(g)?String(i(g[0])):"",s=(g,v)=>Array.isArray(g)?g.filter(_=>Array.isArray(_)&&n(_)===v):[],a=(g,v)=>s(g,v)[0],o=(g,v)=>i(a(g,v)?.[1]),l=(g,v)=>typeof i(g)=="number"&&Number.isFinite(i(g))?i(g):v,c=(g,v,_)=>{let E=a(a(g,v),"xyz");return E?[l(E[1],NaN),l(E[2],NaN),l(E[3],NaN)]:[..._]},u=g=>typeof g=="string"&&g.length>0&&g.length<=500&&!/[\\\u0000-\u001f\u007f?%]/.test(g)&&!/^[a-z][a-z\d+.-]*:/i.test(g)&&!g.startsWith("/");function d(g,v){if(typeof v=="string"&&(v=v.replace(/\\/g,"/")),!u(g)||!/\.kicad_pcb$/i.test(g)||!u(v))return null;let _=g.split("/");if(_.some(k=>!k||k==="."||k===".."))return null;let E=v.replace(/^(?:\$\{KIPRJMOD\}|\$\(KIPRJMOD\))\//,"");if(E.includes("$(")||E.includes("${")||E.includes("}"))return null;let M=_.slice(0,-1);for(let k of E.split("/"))if(!(!k||k==="."))if(k===".."){if(!M.length)return null;M.pop()}else M.push(k);let P=M.join("/");return P.length<=500&&u(P)?P:null}function f(g){if(n(g)!=="kicad_pcb")throw new Error("Expected a saved KiCad PCB.");let v=new Set(["at","layer","uuid","tstamp","model","embedded_files"]),_=["kicad_pcb"];for(let E of g){if(n(E)==="embedded_files"&&_.push(E),n(E)!=="footprint")continue;let M=["footprint"];if(_.push(M),!!E.some(P=>n(P)==="model"))for(let P of E){let k=n(P);v.has(k)?M.push(P):(k==="property"&&i(P[1])==="Reference"||k==="fp_text"&&i(P[1])==="reference")&&M.push(P.slice(0,3))}}return _}function y(g,v,_=r.KiCadDesignDiff?.parse,E=[]){if(typeof _!="function")throw new Error("KiCad S-expression parser is unavailable.");return b(_(g),v,E)}function b(g,v,_=[]){if(n(g)!=="kicad_pcb")throw new Error("Expected a saved KiCad PCB.");let E=[],M=[],P=se=>{M.length<48&&M.push(se)},k=Array.isArray(_)?_.slice(0,2e3).filter(se=>u(se)&&se.split("/").every(ce=>ce&&ce!=="."&&ce!=="..")):[];function z(se,ce){let fe=d(v,se),ze=/^(?:\$\{(?:KICAD\d+_3DMODEL_DIR|KISYS3DMOD)\}|\$\((?:KICAD\d+_3DMODEL_DIR|KISYS3DMOD)\))[\\/]/,Fe=typeof se=="string"&&ze.test(se)?se.replace(ze,"").replace(/\\/g,"/"):null,Pe=fe||Fe;if(fe&&(!k.length||k.includes(fe)))return fe;if(Array.isArray(_)&&_.length>=2e3)return fe||P(`${ce}: model discovery is incomplete; library recovery is unavailable: ${String(se).slice(0,100)}`),fe;if(fe){let ue=k.filter(Te=>Te.toLowerCase()===fe.toLowerCase());if(ue.length===1)return P(`${ce}: model path casing corrected to ${ue[0]}`),ue[0];if(ue.length>1)return P(`${ce}: model path casing is ambiguous: ${fe}`),null}if(Pe&&u(Pe)&&Pe.split("/").every(ue=>ue&&ue!=="."&&ue!=="..")){let ue=Fe?k.filter(de=>de===Fe||de.endsWith("/"+Fe)):[];if(ue.length===1)return ue[0];if(ue.length>1)return P(`${ce}: model library path matches multiple repository files: ${Fe}`),null;if(Fe){let de=Fe.toLowerCase(),Ie=k.filter(Re=>Re.toLowerCase()===de||Re.toLowerCase().endsWith("/"+de));if(Ie.length===1)return P(`${ce}: model path casing corrected to ${Ie[0]}`),Ie[0];if(Ie.length>1)return P(`${ce}: model path casing is ambiguous: ${Fe}`),null}let Te=Pe.replace(/\.(?:step|stp|wrl|vrml)$/i,"");if(Te!==Pe){let de=k.filter(Ie=>{let Re=Ie.replace(/\.(?:step|stp|wrl|vrml)$/i,"");return Re!==Ie&&(Re.toLowerCase()===Te.toLowerCase()||Fe&&Re.toLowerCase().endsWith("/"+Te.toLowerCase()))});if(de.length===1)return P(`${ce}: using repository model alternative ${de[0]} for ${se}`),de[0];if(de.length>1)return P(`${ce}: model alternatives are ambiguous: ${Pe}`),null}}return fe||(!Fe||!u(Fe)||Fe.split("/").some(ue=>!ue||ue==="."||ue==="..")||P(`${ce}: library model is not included in this project: ${Fe}. Include the model files with the project to load them offline or in the browser.`),null)}function D(se){let ce=new Map;for(let fe of s(a(se,"embedded_files"),"file")){let ze=o(fe,"name");if(!(!u(ze)||ze.split("/").some(Fe=>!Fe||Fe==="."||Fe===".."))){if(ce.has(ze)){ce.set(ze,null),P(`Duplicate embedded model name: ${ze}`);continue}ce.set(ze,fe)}}return ce}let I=D(g),L=new WeakMap;function Z(se){if(!se)return null;if(L.has(se))return L.get(se);let ce=a(se,"data"),fe=0;for(let Pe=1;Pe<(ce?.length||0)&&fe<=11200002;Pe++)fe+=String(i(ce[Pe])).length;let ze=fe&&fe<=11200002?ce.slice(1).map(i).join(""):"",Fe=ze.startsWith("|")&&ze.endsWith("|")?{base64:ze.slice(1,-1),checksum:String(o(se,"checksum")||"")}:null;return L.set(se,Fe),Fe}for(let[se,ce]of s(g,"footprint").entries()){let fe=s(ce,"model");if(!fe.length)continue;let ze=s(ce,"property").find(U=>i(U[1])==="Reference"),Fe=s(ce,"fp_text").find(U=>i(U[1])==="reference"),Pe=String(i(ze?.[2])||i(Fe?.[2])||`REF${se+1}`),ue=o(ce,"uuid")||o(ce,"tstamp")||`component-${Pe}`,Te=a(ce,"at"),de=l(Te?.[1],NaN),Ie=l(Te?.[2],NaN),Re=l(Te?.[3],0),Be=String(o(ce,"layer")||"F.Cu");if(![de,Ie,Re].every(Number.isFinite)||!["F.Cu","B.Cu"].includes(Be)){P(`${Pe}: footprint placement or side is unsupported.`);continue}let Se;for(let U of fe){if(E.length>=2048)return P("Only the first 2048 footprint model references are loaded."),{models:E,diagnostics:M};let ie=i(U[1]),Ae=typeof ie=="string"&&ie.startsWith("kicad-embed://")?ie.slice(14):null;Ae!==null&&(Se??=D(ce));let Ue=Ae!==null?Z(Se.has(Ae)?Se.get(Ae):I.get(Ae)):null;if(Ae!==null&&!Ue){P(`${Pe}: embedded model is missing or ambiguous: ${Ae}`);continue}let Ge=Ae!==null?ie:z(ie,Pe);if(!Ge){P(`${Pe}: model path is not a repository-relative file: ${String(ie).slice(0,100)}`);continue}let nt=/\.([a-z\d]+)$/i.exec(Ge)?.[1]?.toLowerCase();if(!["wrl","vrml","glb","step","stp"].includes(nt)){P(`${Pe}: ${nt==="step"||nt==="stp"?"STEP":"model format"} is not supported in the browser: ${Ge}`);continue}let Qe=a(U,"hide");if(Qe&&i(Qe[1])!=="no"&&i(Qe[1])!==!1)continue;let ct=c(U,"offset",[0,0,0]),ye=c(U,"scale",[1,1,1]),dt=c(U,"rotate",[0,0,0]);if(ct.some(xt=>!Number.isFinite(xt)||Math.abs(xt)>1e4)||ye.some(xt=>!Number.isFinite(xt)||xt<=0||xt>1e3)||dt.some(xt=>!Number.isFinite(xt)||Math.abs(xt)>3600)){P(`${Pe}: model transform is invalid: ${Ge}`);continue}E.push({path:Ge,format:nt,footprintId:String(ue),reference:Pe,footprint:{x:de,y:Ie,angle:Re,layer:Be},offset:ct,scale:ye,rotate:dt,...Ue?{embeddedAsset:Ue,assetKey:`embedded:${Se.has(Ae)?se:"board"}:${Ae}`}:{}})}}return{models:E,diagnostics:M}}function x(g,v,_,E){let M=g.footprint.layer==="B.Cu",P=g.footprint.angle*Math.PI/180,[k,z,D]=g.offset,I=M?-z:z,L=["glb","step","stp"].includes(g.format)?1:2.54;return{position:[g.footprint.x-v+k*Math.cos(P)-I*Math.sin(P),_-g.footprint.y+k*Math.sin(P)+I*Math.cos(P),(M?-1:1)*(E/2+D)],footprintAngle:P,modelRotation:[(M?180:0)-g.rotate[0],(M?1:-1)*g.rotate[1],(M?1:-1)*g.rotate[2]].map(Z=>Z*Math.PI/180),scale:g.scale.map(Z=>Z*L)}}r.KiCadRepoModels={collect:y,collectParsed:b,modelSource:f,resolveModelPath:d,modelPose:x},typeof t=="object"&&t.exports&&(t.exports=r.KiCadRepoModels)})(typeof globalThis=="object"?globalThis:e)}),J=T((e,t)=>{(function(r){typeof t<"u"&&typeof e=="object"?t.exports=r():typeof define<"u"&&define.amd?define(["fzstd",r]):(typeof self<"u"?self:this).fzstd=r()})(function(){var r={},i=ArrayBuffer,n=Uint8Array,s=Uint16Array,a=Int16Array,o=Uint32Array,l=Int32Array,c=function(ue,Te,de){if(n.prototype.slice)return n.prototype.slice.call(ue,Te,de);(Te==null||Te<0)&&(Te=0),(de==null||de>ue.length)&&(de=ue.length);var Ie=new n(de-Te);return Ie.set(ue.subarray(Te,de)),Ie},u=function(ue,Te,de,Ie){if(n.prototype.fill)return n.prototype.fill.call(ue,Te,de,Ie);for((de==null||de<0)&&(de=0),(Ie==null||Ie>ue.length)&&(Ie=ue.length);de<Ie;++de)ue[de]=Te;return ue},d=function(ue,Te,de,Ie){if(n.prototype.copyWithin)return n.prototype.copyWithin.call(ue,Te,de,Ie);for((de==null||de<0)&&(de=0),(Ie==null||Ie>ue.length)&&(Ie=ue.length);de<Ie;)ue[Te++]=ue[de++]};r.ZstdErrorCode={InvalidData:0,WindowSizeTooLarge:1,InvalidBlockType:2,FSEAccuracyTooHigh:3,DistanceTooFarBack:4,UnexpectedEOF:5};var f=["invalid zstd data","window size too large (>2046MB)","invalid block type","FSE accuracy too high","match distance too far back","unexpected EOF"],y=function(ue,Te,de){var Ie=Error(Te||f[ue]);if(Ie.code=ue,Error.captureStackTrace&&Error.captureStackTrace(Ie,y),!de)throw Ie;return Ie},b=function(ue,Te,de){for(var Ie=0,Re=0;Ie<de;++Ie)Re|=ue[Te++]<<(Ie<<3);return Re},x=function(ue,Te){return(ue[Te]|ue[Te+1]<<8|ue[Te+2]<<16|ue[Te+3]<<24)>>>0},g=function(ue,Te){var de=ue[0]|ue[1]<<8|ue[2]<<16;if(de==3126568&&ue[3]==253){var Ie=ue[4],Re=Ie>>5&1,Be=Ie>>2&1,Se=3&Ie,U=Ie>>6;8&Ie&&y(0);var ie=6-Re,Ae=Se==3?4:Se,Ue=b(ue,ie,Ae),Ge=U?1<<U:Re,nt=b(ue,ie+=Ae,Ge)+(U==1&&256),Qe=nt;if(!Re){var ct=1<<10+(ue[5]>>3);Qe=ct+(ct>>3)*(7&ue[5])}Qe>2145386496&&y(1);var ye=new n((Te==1?nt||Qe:Te?0:Qe)+12);return ye[0]=1,ye[4]=4,ye[8]=8,{b:ie+Ge,y:0,l:0,d:Ue,w:Te&&Te!=1?Te:ye.subarray(12),e:Qe,o:new l(ye.buffer,0,3),u:nt,c:Be,m:Math.min(131072,Qe)}}if((de>>4|ue[3]<<20)==25481893)return x(ue,4)+8;y(0)},v=function(ue){for(var Te=0;1<<Te<=ue;++Te);return Te-1},_=function(ue,Te,de){var Ie=4+(Te<<3),Re=5+(15&ue[Te]);Re>de&&y(3);for(var Be=1<<Re,Se=Be,U=-1,ie=-1,Ae=-1,Ue=Be,Ge=new i(512+(Be<<2)),nt=new a(Ge,0,256),Qe=new s(Ge,0,256),ct=new s(Ge,512,Be),ye=512+(Be<<1),dt=new n(Ge,ye,Be),xt=new n(Ge,ye+Be);U<255&&Se>0;){var Dt=v(Se+1),We=Ie>>3,mt=(1<<Dt+1)-1,it=(ue[We]|ue[We+1]<<8|ue[We+2]<<16)>>(7&Ie)&mt,st=(1<<Dt)-1,oe=mt-Se-1,F=it&st;if(F<oe?(Ie+=Dt,it=F):(Ie+=Dt+1,it>st&&(it-=oe)),nt[++U]=--it,it==-1?(Se+=it,dt[--Ue]=U):Se-=it,!it)do{var le=Ie>>3;ie=(ue[le]|ue[le+1]<<8)>>(7&Ie)&3,Ie+=2,U+=ie}while(ie==3)}(U>255||Se)&&y(0);for(var pe=0,Le=(Be>>1)+(Be>>3)+3,He=Be-1,at=0;at<=U;++at){var rt=nt[at];if(rt<1)Qe[at]=-rt;else for(Ae=0;Ae<rt;++Ae){dt[pe]=at;do pe=pe+Le&He;while(pe>=Ue)}}for(pe&&y(0),Ae=0;Ae<Be;++Ae){var ht=Qe[dt[Ae]]++,Tt=xt[Ae]=Re-v(ht);ct[Ae]=(ht<<Tt)-Be}return[Ie+7>>3,{b:Re,s:dt,n:xt,t:ct}]},E=function(ue,Te){var de=0,Ie=-1,Re=new n(292),Be=ue[Te],Se=Re.subarray(0,256),U=Re.subarray(256,268),ie=new s(Re.buffer,268);if(Be<128){var Ae=_(ue,Te+1,6),Ue=Ae[1],Ge=Ae[0]<<3,nt=ue[Te+=Be];nt||y(0);for(var Qe=0,ct=0,ye=Ue.b,dt=ye,xt=(++Te<<3)-8+v(nt);!((xt-=ye)<Ge);){var Dt=xt>>3;if(Se[++Ie]=Ue.s[Qe+=(ue[Dt]|ue[Dt+1]<<8)>>(7&xt)&(1<<ye)-1],(xt-=dt)<Ge)break;Se[++Ie]=Ue.s[ct+=(ue[Dt=xt>>3]|ue[Dt+1]<<8)>>(7&xt)&(1<<dt)-1],ye=Ue.n[Qe],Qe=Ue.t[Qe],dt=Ue.n[ct],ct=Ue.t[ct]}++Ie>255&&y(0)}else{for(Ie=Be-127;de<Ie;de+=2){var We=ue[++Te];Se[de]=We>>4,Se[de+1]=15&We}++Te}var mt=0;for(de=0;de<Ie;++de)(F=Se[de])>11&&y(0),mt+=F&&1<<F-1;var it=v(mt)+1,st=1<<it,oe=st-mt;for(oe&oe-1&&y(0),Se[Ie++]=v(oe)+1,de=0;de<Ie;++de){var F;++U[Se[de]=(F=Se[de])&&it+1-F]}var le=new n(st<<1),pe=le.subarray(0,st),Le=le.subarray(st);for(ie[it]=0,de=it;de>0;--de){var He=ie[de];u(Le,de,He,ie[de-1]=He+U[de]*(1<<it-de))}for(ie[0]!=st&&y(0),de=0;de<Ie;++de){var at=Se[de];if(at){var rt=ie[at];u(pe,de,rt,ie[at]=rt+(1<<it-at))}}return[Te,{n:Le,b:it,s:pe}]},M=_(new n([81,16,99,140,49,198,24,99,12,33,196,24,99,102,102,134,70,146,4]),0,6)[1],P=_(new n([33,20,196,24,99,140,33,132,16,66,8,33,132,16,66,8,33,68,68,68,68,68,68,68,68,36,9]),0,6)[1],k=_(new n([32,132,16,66,102,70,68,68,68,68,36,73,2]),0,5)[1],z=function(ue,Te){for(var de=ue.length,Ie=new l(de),Re=0;Re<de;++Re)Ie[Re]=Te,Te+=1<<ue[Re];return Ie},D=new n(new l([0,0,0,0,16843009,50528770,134678020,202050057,269422093]).buffer,0,36),I=z(D,0),L=new n(new l([0,0,0,0,0,0,0,0,16843009,50528770,117769220,185207048,252579084,16]).buffer,0,53),Z=z(L,3),se=function(ue,Te,de){var Ie=ue.length,Re=Te.length,Be=ue[Ie-1],Se=(1<<de.b)-1,U=-de.b;Be||y(0);for(var ie=0,Ae=de.b,Ue=(Ie<<3)-8+v(Be)-Ae,Ge=-1;Ue>U&&Ge<Re;){var nt=Ue>>3;Te[++Ge]=de.s[ie=(ie<<Ae|(ue[nt]|ue[nt+1]<<8|ue[nt+2]<<16)>>(7&Ue))&Se],Ue-=Ae=de.n[ie]}Ue==U&&Ge+1==Re||y(0)},ce=function(ue,Te,de){var Ie=6,Re=Te.length+3>>2,Be=Re<<1,Se=Re+Be;se(ue.subarray(Ie,Ie+=ue[0]|ue[1]<<8),Te.subarray(0,Re),de),se(ue.subarray(Ie,Ie+=ue[2]|ue[3]<<8),Te.subarray(Re,Be),de),se(ue.subarray(Ie,Ie+=ue[4]|ue[5]<<8),Te.subarray(Be,Se),de),se(ue.subarray(Ie),Te.subarray(Se),de)},fe=function(ue,Te,de){var Ie,Re=Te.b,Be=ue[Re],Se=Be>>1&3;Te.l=1&Be;var U=Be>>3|ue[Re+1]<<5|ue[Re+2]<<13,ie=(Re+=3)+U;if(Se==1)return Re>=ue.length?void 0:(Te.b=Re+1,de?(u(de,ue[Re],Te.y,Te.y+=U),de):u(new n(U),ue[Re]));if(!(ie>ue.length)){if(Se==0)return Te.b=ie,de?(de.set(ue.subarray(Re,ie),Te.y),Te.y+=U,de):c(ue,Re,ie);if(Se==2){var Ae=ue[Re],Ue=3&Ae,Ge=Ae>>2&3,nt=Ae>>4,Qe=0,ct=0;Ue<2?1&Ge?nt|=ue[++Re]<<4|(2&Ge&&ue[++Re]<<12):nt=Ae>>3:(ct=Ge,Ge<2?(nt|=(63&ue[++Re])<<4,Qe=ue[Re]>>6|ue[++Re]<<2):Ge==2?(nt|=ue[++Re]<<4|(3&ue[++Re])<<12,Qe=ue[Re]>>2|ue[++Re]<<6):(nt|=ue[++Re]<<4|(63&ue[++Re])<<12,Qe=ue[Re]>>6|ue[++Re]<<2|ue[++Re]<<10)),++Re;var ye=de?de.subarray(Te.y,Te.y+Te.m):new n(Te.m),dt=ye.length-nt;if(Ue==0)ye.set(ue.subarray(Re,Re+=nt),dt);else if(Ue==1)u(ye,ue[Re++],dt);else{var xt=Te.h;if(Ue==2){var Dt=E(ue,Re);Qe+=Re-(Re=Dt[0]),Te.h=xt=Dt[1]}else xt||y(0);(ct?ce:se)(ue.subarray(Re,Re+=Qe),ye.subarray(dt),xt)}var We=ue[Re++];if(We){We==255?We=32512+(ue[Re++]|ue[Re++]<<8):We>127&&(We=We-128<<8|ue[Re++]);var mt=ue[Re++];3&mt&&y(0);for(var it=[P,k,M],st=2;st>-1;--st){var oe=mt>>2+(st<<1)&3;if(oe==1){var F=new n([0,0,ue[Re++]]);it[st]={s:F.subarray(2,3),n:F.subarray(0,1),t:new s(F.buffer,0,1),b:0}}else oe==2?(Re=(Ie=_(ue,Re,9-(1&st)))[0],it[st]=Ie[1]):oe==3&&(Te.t||y(0),it[st]=Te.t[st])}var le=Te.t=it,pe=le[0],Le=le[1],He=le[2],at=ue[ie-1];at||y(0);var rt=(ie<<3)-8+v(at)-He.b,ht=rt>>3,Tt=0,Mt=(ue[ht]|ue[ht+1]<<8)>>(7&rt)&(1<<He.b)-1,Ut=(ue[ht=(rt-=Le.b)>>3]|ue[ht+1]<<8)>>(7&rt)&(1<<Le.b)-1,Kt=(ue[ht=(rt-=pe.b)>>3]|ue[ht+1]<<8)>>(7&rt)&(1<<pe.b)-1;for(++We;--We;){var fr=He.s[Mt],er=He.n[Mt],Zt=pe.s[Kt],Gt=pe.n[Kt],Er=Le.s[Ut],ut=Le.n[Ut],zt=1<<Er,It=zt+((ue[ht=(rt-=Er)>>3]|ue[ht+1]<<8|ue[ht+2]<<16|ue[ht+3]<<24)>>>(7&rt)&zt-1);ht=(rt-=L[Zt])>>3;var Ct=Z[Zt]+((ue[ht]|ue[ht+1]<<8|ue[ht+2]<<16)>>(7&rt)&(1<<L[Zt])-1);ht=(rt-=D[fr])>>3;var rr=I[fr]+((ue[ht]|ue[ht+1]<<8|ue[ht+2]<<16)>>(7&rt)&(1<<D[fr])-1);if(ht=(rt-=er)>>3,Mt=He.t[Mt]+((ue[ht]|ue[ht+1]<<8)>>(7&rt)&(1<<er)-1),ht=(rt-=Gt)>>3,Kt=pe.t[Kt]+((ue[ht]|ue[ht+1]<<8)>>(7&rt)&(1<<Gt)-1),ht=(rt-=ut)>>3,Ut=Le.t[Ut]+((ue[ht]|ue[ht+1]<<8)>>(7&rt)&(1<<ut)-1),It>3)Te.o[2]=Te.o[1],Te.o[1]=Te.o[0],Te.o[0]=It-=3;else{var $t=It-(rr!=0);$t?(It=$t==3?Te.o[0]-1:Te.o[$t],$t>1&&(Te.o[2]=Te.o[1]),Te.o[1]=Te.o[0],Te.o[0]=It):It=Te.o[0]}for(st=0;st<rr;++st)ye[Tt+st]=ye[dt+st];dt+=rr;var xr=(Tt+=rr)-It;if(xr<0){var cr=-xr,yr=Te.e+xr;for(cr>Ct&&(cr=Ct),st=0;st<cr;++st)ye[Tt+st]=Te.w[yr+st];Tt+=cr,Ct-=cr,xr=0}for(st=0;st<Ct;++st)ye[Tt+st]=ye[xr+st];Tt+=Ct}if(Tt!=dt)for(;dt<ye.length;)ye[Tt++]=ye[dt++];else Tt=ye.length;de?Te.y+=Tt:ye=c(ye,0,Tt)}else if(de){if(Te.y+=nt,dt)for(st=0;st<nt;++st)ye[st]=ye[dt+st]}else dt&&(ye=c(ye,dt));return Te.b=ie,ye}y(2)}},ze=function(ue,Te){if(ue.length==1)return ue[0];for(var de=new n(Te),Ie=0,Re=0;Ie<ue.length;++Ie){var Be=ue[Ie];de.set(Be,Re),Re+=Be.length}return de};function Fe(ue,Te){for(var de=[],Ie=+!Te,Re=0,Be=0;ue.length;){var Se=g(ue,Ie||Te);if(typeof Se=="object"){for(Ie?(Te=null,Se.w.length==Se.u&&(de.push(Te=Se.w),Be+=Se.u)):(de.push(Te),Se.e=0);!Se.l;){var U=fe(ue,Se,Te);U||y(5),Te?Se.e=Se.y:(de.push(U),Be+=U.length,d(Se.w,0,U.length),Se.w.set(U,Se.w.length-U.length))}Re=Se.b+4*Se.c}else Re=Se;ue=ue.subarray(Re)}return ze(de,Be)}r.decompress=Fe;var Pe=(function(){function ue(Te){this.ondata=Te,this.c=[],this.l=0,this.z=0}return ue.prototype.push=function(Te,de){if(typeof this.s=="number"){var Ie=Math.min(Te.length,this.s);Te=Te.subarray(Ie),this.s-=Ie}var Re=Te.length+this.l;if(!this.s){if(de){if(!Re)return void this.ondata(new n(0),!0);Re<5&&y(5)}else if(Re<18)return this.c.push(Te),void(this.l=Re);if(this.l&&(this.c.push(Te),Te=ze(this.c,Re),this.c=[],this.l=0),typeof(this.s=g(Te))=="number")return this.push(Te,de)}if(typeof this.s!="number"){if(Re<(this.z||3))return de&&y(5),this.c.push(Te),void(this.l=Re);if(this.l&&(this.c.push(Te),Te=ze(this.c,Re),this.c=[],this.l=0),!this.z&&Re<(this.z=2&Te[this.s.b]?4:3+(Te[this.s.b]>>3|Te[this.s.b+1]<<5|Te[this.s.b+2]<<13)))return de&&y(5),this.c.push(Te),void(this.l=Re);for(this.z=0;;){var Be=fe(Te,this.s);if(!Be){de&&y(5);var Se=Te.subarray(this.s.b);return this.s.b=0,this.c.push(Se),void(this.l+=Se.length)}if(this.ondata(Be,!1),d(this.s.w,0,Be.length),this.s.w.set(Be,this.s.w.length-Be.length),this.s.l){var U=Te.subarray(this.s.b);return this.s=4*this.s.c,void this.push(U,de)}}}else de&&y(5)},ue})();return r.Decompress=Pe,r})}),Q=T((e,t)=>{(r=>{"use strict";function i(d,{maxBytes:f=8388608,padded:y=!1,host:b=r}={}){if(!Number.isSafeInteger(f)||f<0||f>8388608||typeof d!="string"||d.length>112e5)throw Error("Invalid or oversized model base64.");let x=d.length,g=d.endsWith("==")?2:d.endsWith("=")?1:0;if(x%4===1||(g||y)&&x%4!==0)throw Error("Invalid model base64 padding.");let v=x-g;for(let k=0;k<v;k++){let z=d.charCodeAt(k);if(!(z>=65&&z<=90||z>=97&&z<=122||z>=48&&z<=57||z===43||z===47))throw Error("Invalid model base64.")}let _=Math.floor(x*3/4)-g;if(_>f)throw Error("Model base64 exceeds its decoded byte limit.");let E=b.Uint8Array?.fromBase64;if(typeof E=="function")return E.call(b.Uint8Array,d);let M=b.atob(d),P=new Uint8Array(_);for(let k=0;k<_;k++)P[k]=M.charCodeAt(k);return P}function n(d,f=!1){let y=(1n<<64n)-1n,b=0x87c37b91114253d5n,x=0x4cf5ad432745937fn,g=(I,L)=>(I<<L|I>>64n-L)&y,v=(I,L)=>{let Z=0n;for(let se=0;se<L;se++)Z|=BigInt(d[I+se]||0)<<BigInt(se*8);return Z},_=I=>(I^=I>>33n,I=I*0xff51afd7ed558ccdn&y,I^=I>>33n,I=I*0xc4ceb9fe1a85ec53n&y,I^I>>33n),E=0xabba2345n,M=E,P=new DataView(d.buffer,d.byteOffset,d.byteLength),k=d.length-d.length%16;for(let I=0;I<k;I+=16){let L=P.getBigUint64(I,!0),Z=P.getBigUint64(I+8,!0);L=g(L*b&y,31n)*x&y,E^=L,E=(g(E,27n)+M)*5n+0x52dce729n&y,Z=g(Z*x&y,33n)*b&y,M^=Z,M=(g(M,31n)+E)*5n+0x38495ab5n&y}let z=f?Math.ceil(d.length/4)*4:d.length,D=z%16;return D>8&&(M^=g(v(k+8,D-8)*x&y,33n)*b&y),D&&(E^=g(v(k,Math.min(8,D))*b&y,31n)*x&y),E^=BigInt(z),M^=BigInt(z),E=E+M&y,M=M+E&y,E=_(E),M=_(M),E=E+M&y,M=M+E&y,E.toString(16).padStart(16,"0")+M.toString(16).padStart(16,"0")}function s(d){let f=new DataView(d.buffer,d.byteOffset,d.byteLength);if(d.length<6||f.getUint32(0,!0)!==4247762216)throw Error("Embedded model is not Zstandard.");let y=d[4],b=!!(y&32),x=y>>>6;if(y&24)throw Error("Unsupported Zstandard frame flags.");let g=5;if(!b){let M=d[g++];if(2**(10+(M>>>3))*(1+(M&7)/8)>8388608)throw Error("Embedded model window exceeds 8 MiB.")}if([0,1,2,4][y&3])throw Error("Embedded model requires a Zstandard dictionary.");let v=x?[0,2,4,8][x]:b?1:0;if(!v||g+v>d.length)throw Error("Embedded model has no bounded content size.");let _=0;for(let M=0;M<v;M++)_+=d[g++]*2**(8*M);if(x===1&&(_+=256),!Number.isSafeInteger(_)||_<=0||_>8388608)throw Error("Embedded model exceeds 8 MiB.");let E=!1;for(;!E;){if(g+3>d.length)throw Error("Truncated embedded model block.");let M=d[g]|d[g+1]<<8|d[g+2]<<16;g+=3,E=!!(M&1);let P=M>>>1&3,k=M>>>3;if(P===3||k>131072)throw Error("Invalid embedded model block.");if(g+=P===1?1:k,g>d.length)throw Error("Truncated embedded model block.")}if(y&4&&(g+=4),g!==d.length)throw Error("Embedded model has trailing or missing frame data.");return _}async function a(d,f=r.fzstd?.decompress,y=8388608){let b=d?.base64,x=i(b,{padded:!0});if(x.length>8388608)throw Error("Compressed embedded model exceeds 8 MiB.");let g=s(x);if(g>y)throw Error("Embedded asset exceeds its allocation budget.");if(typeof f!="function")throw Error("Embedded model decoder unavailable.");let v=f(x,new Uint8Array(g));if(!(v instanceof Uint8Array)||v.length!==g)throw Error("Embedded model size mismatch.");if(/^[a-f0-9]{64}$/i.test(d.checksum||"")){let _=new Uint8Array(await r.crypto.subtle.digest("SHA-256",v));if(Array.from(_,E=>E.toString(16).padStart(2,"0")).join("")!==d.checksum.toLowerCase())throw Error("Embedded model checksum mismatch.")}else if(/^[a-f0-9]{32}$/i.test(d.checksum||"")){let _=d.checksum.toLowerCase();if(n(v)!==_&&n(v,!0)!==_)throw Error("Embedded model checksum mismatch.")}else throw Error("Embedded model checksum is missing or unsupported.");return v}function o(d){let f=new DataView(d.buffer,d.byteOffset,d.byteLength),y=new Set;if(f.byteLength<12||![65536,1330926671,1953658213].includes(f.getUint32(0)))return y;let b=f.getUint16(4);if(b>256||12+b*16>f.byteLength)return y;for(let x=12;x<12+b*16;x+=16){if(f.getUint32(x)!==1851878757)continue;let g=f.getUint32(x+8),v=f.getUint32(x+12);if(v<6||g+v>f.byteLength)break;let _=f.getUint16(g+2),E=g+f.getUint16(g+4);if(_>2048||E<g+6+_*12||E>g+v)break;let M=new TextDecoder("utf-16be");for(let P=0;P<_;P++){let k=g+6+P*12,z=f.getUint16(k),D=f.getUint16(k+6);if(![0,3].includes(z)||![1,4,6,16].includes(D))continue;let I=f.getUint16(k+8),L=E+f.getUint16(k+10);if(!I||I>512||I%2||L+I>g+v)continue;let Z=M.decode(d.subarray(L,L+I)).trim().toLowerCase();Z&&!Z.includes("\0")&&y.add(Z)}break}return y}function l(d){let f=new DataView(d.buffer,d.byteOffset,d.byteLength),y=f.getUint16(4);for(let b=12;b<12+y*16;b+=16){if(f.getUint32(b)!==1751474532)continue;let x=f.getUint32(b+8),g=f.getUint32(b+12);if(g<46||x+g>d.length)break;let v=f.getUint16(x+44);return{weight:v&1?"bold":"normal",style:v&2?"italic":"normal"}}return{weight:"normal",style:"normal"}}let c=0;function u(d,f,y,b,x=r,g){if(!d?.length||!f.size||typeof x.FontFace!="function"||!x.document?.fonts)return null;let v=++c,_=new Map,E=[],M=new Set,P=x.document.fonts,k=!1,z=8*1024*1024,D;async function I(){for(let L of d){if(await new Promise(Z=>setTimeout(Z,0)),k||z<=0)return;try{if(D??=g?await g():x.fzstd?.decompress,k)return;let Z=await a(L,D,Math.min(z,2*1024*1024));if(k)return;z-=Z.length;let se=[...o(Z)].filter(fe=>f.has(fe));if(!se.length)continue;let ce=l(Z);for(let fe of se){let ze=JSON.stringify([fe,ce.weight,ce.style]);if(M.has(ze))continue;let Fe=_.get(fe)||"kivi-embedded-"+v+"-"+_.size,Pe=await new x.FontFace(Fe,Z,ce).load();if(k)return;P.add(Pe),E.push(Pe),M.add(ze),_.set(fe,Fe)}}catch(Z){k||b?.(L.name,Z.message)}}!k&&E.length&&y()}return I(),{family(L){return typeof L=="string"?_.get(L.trim().toLowerCase()):void 0},dispose(){k=!0;for(let L of E)P.delete(L);E.length=0,_.clear()}}}r.KiCadEmbeddedFonts={mount:u,fontNames:o},r.KiCadEmbeddedModels={decode:a,decodeBase64:i,frameSize:s,murmur:n,MAX_BYTES:8388608,fontNames:o,mountFonts:u},typeof t=="object"&&t.exports&&(t.exports=r.KiCadEmbeddedModels)})(typeof globalThis=="object"?globalThis:e)}),te=T((e,t)=>{(r=>{"use strict";function i(a){if(a?.success!==!0||!Array.isArray(a.meshes)||!a.meshes.length||a.meshes.length>512)throw new Error("STEP did not produce a supported mesh.");let o=0,l=0,c=0;return a.meshes.map((u,d)=>{let f=u.attributes?.position?.array,y=u.index?.array,b=u.attributes?.normal?.array;if(!Array.isArray(f)||f.length%3||!f.length||!Array.isArray(y)||y.length%3||!y.length)throw new Error("STEP returned invalid mesh arrays.");if(o+=f.length/3,l+=y.length/3,o>5e5||l>5e5)throw new Error("STEP tessellation exceeds 500,000 vertices or triangles.");if(f.some(L=>!Number.isFinite(L)||Math.abs(L)>1e6)||y.some(L=>!Number.isSafeInteger(L)||L<0||L>=f.length/3))throw new Error("STEP mesh coordinates or indices are invalid.");if(b&&(!Array.isArray(b)||b.length!==f.length||b.some(L=>!Number.isFinite(L))))throw new Error("STEP returned invalid mesh normals.");let x=Array.isArray(u.color)&&u.color.length===3&&u.color.every(L=>Number.isFinite(L)&&L>=0&&L<=1)?u.color:[.65,.68,.7],g=u.brep_faces;if(g!==void 0&&(!Array.isArray(g)||g.length>y.length/3))throw new Error("STEP returned invalid face ranges.");let v=[x],_=new Map([[JSON.stringify(x),0]]),E=new Uint8Array(y.length/3).fill(255),M=Math.min(8,1024-c-(a.meshes.length-d-1));for(let L of g||[]){let Z=L?.first,se=L?.last;if(!Number.isSafeInteger(Z)||!Number.isSafeInteger(se)||Z<0||se<Z||se>=E.length)throw new Error("STEP returned invalid face ranges.");let ce=Array.isArray(L.color)&&L.color.length===3&&L.color.every(Fe=>Number.isFinite(Fe)&&Fe>=0&&Fe<=1),fe=ce?JSON.stringify(L.color):null,ze=ce?_.get(fe):0;if(ze===void 0){if(v.length>=M)throw new Error("STEP face colours exceed the bounded material budget.");ze=v.length,v.push(L.color),_.set(fe,ze)}for(let Fe=Z;Fe<=se;Fe++){if(E[Fe]!==255)throw new Error("STEP returned overlapping face ranges.");E[Fe]=ze}}let P=new Uint32Array(v.length);for(let L=0;L<E.length;L++)E[L]===255&&(E[L]=0),P[E[L]]+=3;let k=[],z=new Uint32Array(v.length),D=0;for(let L=0;L<v.length;L++)z[L]=D,P[L]&&(k.push({start:D,count:P[L],color:v[L]}),D+=P[L]);c+=k.length;let I=new Uint32Array(y.length);for(let L=0;L<E.length;L++){let Z=z[E[L]];z[E[L]]+=3,I[Z]=y[L*3],I[Z+1]=y[L*3+1],I[Z+2]=y[L*3+2]}return{positions:new Float32Array(f),normals:b?new Float32Array(b):null,index:I,color:x,groups:k}})}async function n(a,o=r.Worker,l=r,c){let u=await l.fetch(a,{credentials:"omit",redirect:"error",signal:c});if(!u.ok)throw new Error("Bundled STEP worker could not be read.");let d=await u.arrayBuffer();if(d.byteLength>256*1024)throw new Error("Bundled STEP worker exceeds 256 KiB.");let f=l.URL.createObjectURL(new l.Blob([d],{type:"text/javascript"}));try{return new o(f)}finally{l.URL.revokeObjectURL(f)}}class s{constructor(o,l=r.Worker){this.url=o,this.WorkerType=l,this.worker=null,this.queue=Promise.resolve(),this.disposed=!1,this.pending=null,this.loadingAbort=null,this.initialized=!1,this.wasmUrl=r.KiCadVSCodeContext?.stepWasmUrl}decode(o){let l=()=>this.run(o),c=this.queue.then(l,l);return this.queue=c.catch(()=>{}),c}async run(o){if(this.disposed)throw new Error("STEP decoder is closed.");if(!(o instanceof Uint8Array)||!o.byteLength||o.byteLength>8*1024*1024)throw new Error("STEP input exceeds 8 MiB or is empty.");if(!this.worker){this.initialized=!1;let l=new AbortController;this.loadingAbort=l;let c=setTimeout(()=>l.abort(),1e4);try{this.worker=r.KiCadVSCodeContext?.stepWorkerUrl?await n(r.KiCadVSCodeContext.stepWorkerUrl,this.WorkerType,r,l.signal):new this.WorkerType(this.url)}catch(u){throw new Error("STEP worker is unavailable: "+u.message)}finally{clearTimeout(c),this.loadingAbort=null}if(this.disposed)throw this.worker.terminate(),this.worker=null,new Error("STEP decoder is closed.")}return new Promise((l,c)=>{let u=(x,g)=>{clearTimeout(f),this.pending=null,this.worker&&(this.worker.onmessage=this.worker.onerror=null),x?c(x):l(g)},d=x=>{this.worker?.terminate(),this.worker=null,this.initialized=!1,u(new Error(x))},f,y=this.initialized,b=(x,g)=>{clearTimeout(f),f=setTimeout(()=>d(g),x)};b(this.initialized?3e4:6e4,this.initialized?"STEP conversion timed out after 30 seconds.":"STEP initialization timed out after 60 seconds."),this.pending=()=>d("STEP decoder is closed."),this.worker.onmessage=x=>{if(x.data?.stage==="kernel-ready"){y||(y=!0,this.initialized=!0,b(3e4,"STEP conversion timed out after 30 seconds."));return}this.initialized=x.data?.ok===!0,this.initialized?u(null,x.data.meshes):u(new Error(x.data?.error||"STEP conversion failed."))},this.worker.onerror=()=>d("STEP worker failed.");try{let x=o.slice();this.worker.postMessage({bytes:x,reportStages:!0,...this.wasmUrl?{wasmUrl:this.wasmUrl}:{}},[x.buffer])}catch{d("STEP worker could not accept input.")}})}dispose(){this.disposed=!0,this.loadingAbort?.abort(),this.pending?.(),this.worker?.terminate(),this.worker=null}}r.KiCadStepDecoder={meshes:i,Client:s,bundledWorker:n},typeof t=="object"&&t.exports&&(t.exports=r.KiCadStepDecoder)})(typeof globalThis=="object"?globalThis:e)}),he=T((e,t)=>{(r=>{"use strict";let i={"F.Cu":["#c83434",1],"B.Cu":["#4d7fc4",1],"In1.Cu":["#7fc87f",1],"In2.Cu":["#ce7d2c",1],"In3.Cu":["#4fcbcb",1],"In4.Cu":["#db628b",1],"In5.Cu":["#a7a5c6",1],"In6.Cu":["#28ccd9",1],"In7.Cu":["#e8b2a7",1],"In8.Cu":["#f2eda1",1],"In9.Cu":["#8dcb81",1],"In10.Cu":["#ed7c33",1],"In11.Cu":["#5bc3eb",1],"In12.Cu":["#f76f8e",1],"In13.Cu":["#a7a5c6",1],"In14.Cu":["#28ccd9",1],"In15.Cu":["#e8b2a7",1],"In16.Cu":["#f2eda1",1],"In17.Cu":["#ed7c33",1],"In18.Cu":["#5bc3eb",1],"In19.Cu":["#f76f8e",1],"In20.Cu":["#a7a5c6",1],"In21.Cu":["#28ccd9",1],"In22.Cu":["#e8b2a7",1],"In23.Cu":["#f2eda1",1],"In24.Cu":["#ed7c33",1],"In25.Cu":["#5bc3eb",1],"In26.Cu":["#f76f8e",1],"In27.Cu":["#a7a5c6",1],"In28.Cu":["#28ccd9",1],"In29.Cu":["#e8b2a7",1],"In30.Cu":["#f2eda1",1],"F.Adhes":["#840084",1],"B.Adhes":["#000084",1],"F.Paste":["#b4a09a",.9],"B.Paste":["#00c2c2",.9],"F.SilkS":["#f2eda1",1],"B.SilkS":["#e8b2a7",1],"F.Mask":["#d864ff",.4],"B.Mask":["#02ffee",.4],"F.Fab":["#afafaf",1],"B.Fab":["#585d84",1],"F.CrtYd":["#ff26e2",1],"B.CrtYd":["#26e9ff",1],"Edge.Cuts":["#d0d2cd",1],Margin:["#ff26e2",1],"Dwgs.User":["#c2c2c2",1],"Cmts.User":["#5994dc",1],"Eco1.User":["#b4dbd2",1],"Eco2.User":["#d8c852",1],"User.1":["#c2c2c2",1],"User.2":["#5994dc",1],"User.3":["#b4dbd2",1],"User.4":["#d8c852",1],"User.5":["#c2c2c2",1],"User.6":["#5994dc",1],"User.7":["#b4dbd2",1],"User.8":["#d8c852",1],"User.9":["#e8b2a7",1],"User.10":["#5994dc",1],"User.11":["#b4dbd2",1],"User.12":["#d8c852",1],"User.13":["#c2c2c2",1],"User.14":["#5994dc",1],"User.15":["#b4dbd2",1],"User.16":["#d8c852",1],"User.17":["#c2c2c2",1],"User.18":["#5994dc",1],"User.19":["#b4dbd2",1],"User.20":["#d8c852",1],"User.21":["#c2c2c2",1],"User.22":["#5994dc",1],"User.23":["#b4dbd2",1],"User.24":["#d8c852",1],"User.25":["#c2c2c2",1],"User.26":["#5994dc",1],"User.27":["#b4dbd2",1],"User.28":["#d8c852",1],"User.29":["#c2c2c2",1],"User.30":["#5994dc",1],"User.31":["#b4dbd2",1],"User.32":["#d8c852",1],"User.33":["#c2c2c2",1],"User.34":["#5994dc",1],"User.35":["#b4dbd2",1],"User.36":["#d8c852",1],"User.37":["#c2c2c2",1],"User.38":["#5994dc",1],"User.39":["#b4dbd2",1],"User.40":["#d8c852",1],"User.41":["#c2c2c2",1],"User.42":["#5994dc",1],"User.43":["#b4dbd2",1],"User.44":["#d8c852",1],"User.45":["#c2c2c2",1]};for(let f of Object.values(i))Object.freeze(f);Object.freeze(i);let n=f=>i[String(f)]?.[0]||"#c2c2c2",s=f=>i[String(f)]?.[1]??1,a=f=>{let y=n(f),b=s(f);return b===1?y:`rgba(${parseInt(y.slice(1,3),16)},${parseInt(y.slice(3,5),16)},${parseInt(y.slice(5,7),16)},${b})`},o=Object.freeze({"F.Cu":"#fa6f68","B.Cu":"#63a5ff","F.SilkS":"#e8dcae","B.SilkS":"#b5c8df","F.Fab":"#b2bbc9","B.Fab":"#8d9ab0","F.CrtYd":"#c59be0","B.CrtYd":"#7bc6cf","Edge.Cuts":"#d6deea","F.Mask":"#b197d7","B.Mask":"#77bdb5","F.Paste":"#d2afa0","B.Paste":"#98c9ce"}),l=Object.freeze({"F.Cu":"#b9474c","B.Cu":"#3268ae","F.SilkS":"#766126","B.SilkS":"#596a87","F.Fab":"#647086","B.Fab":"#606c83","F.CrtYd":"#8c519e","B.CrtYd":"#257b85","Edge.Cuts":"#465368","F.Mask":"#9279b8","B.Mask":"#4d968a","F.Paste":"#9d796a","B.Paste":"#448b93"});function c(f,y=!0){let b=(y?o:l)[String(f)]||n(f),x=s(f);return x===1?b:`rgba(${parseInt(b.slice(1,3),16)},${parseInt(b.slice(3,5),16)},${parseInt(b.slice(5,7),16)},${x})`}function u(f){let y=String(f||"").toLowerCase(),b=/bottom|\bbot\b/.test(y),x=b?"B.":"F.";if(/drill|plated/.test(y))return null;if(/outline|profile/.test(y))return"Edge.Cuts";if(/copper/.test(y)){if(/inner|inr/.test(y)){let g=/copper,\s*l(\d+),\s*inr/.exec(y),v=/inner copper\s*(\d+)/.exec(y),_=g?Number(g[1])-1:v?Number(v[1]):0;return _>=1&&_<=30?"In"+_+".Cu":null}return x+"Cu"}return/mask/.test(y)?x+"Mask":/silk|legend/.test(y)?x+"SilkS":/paste/.test(y)?x+"Paste":null}let d=Object.freeze({entries:i,hexFor:n,opacityFor:s,colorFor:a,reviewColorFor:c,fabricationLayer:u});r.KiCadLayerColors=d,typeof t=="object"&&t.exports&&(t.exports=d)})(globalThis)}),be={};H(be,{mountBoard3D:()=>KO,mountResultScene:()=>xO,mountSavedResult3D:()=>MO,objectVisibilityPolicy:()=>C0});function De(e=512){if(!Number.isInteger(e)||e<0||e>4096)throw new TypeError("Choose a bounded geometry cache size.");let t=new Map,r=0,i=0;return{get(n,s){if(t.has(n))return r++,t.get(n);let a=s();return t.size<e?t.set(n,a):i++,a},clear(){t.clear()},stats(){return{entries:t.size,hits:r,uncached:i}}}}function Ke(e,t=r=>r.assetKey||r.path){let r=new Map,i=new Map;for(let n of e){let s=t(n);r.set(s,(r.get(s)||0)+1)}return{get(n,s){let a=t(n);return i.has(a)||i.set(a,Promise.resolve().then(s)),i.get(a)},isLastUse(n){return r.get(t(n))===1},release(n){let s=t(n),a=(r.get(s)||0)-1;a>0?r.set(s,a):(r.delete(s),i.delete(s))},clear(){r.clear(),i.clear()},stats:()=>({templates:i.size,remainingAssets:r.size})}}var qe={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4},$e={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Xe=(e,t)=>{if(!Number.isSafeInteger(e)||e<0)throw Error("Invalid GLB "+t+".");return e},ve=e=>{throw Object.assign(Error("Linked model "+e+" exceeds its decoded memory budget; saved footprint proxies and identities are retained."),{code:"MODEL_ALLOCATION_BUDGET"})},Ee="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function me(e,t){if(e.bufferView!==void 0){let o=t(e.bufferView);return{length:o.length,at:l=>o[l]}}let r=/^data:([^;,]+);base64,/i.exec(e.uri||"");if(!r)throw Error("Embedded model image has no supported bounded header.");let i=e.uri,n=r[0].length,s=i.length-n,a=i.endsWith("==")?2:i.endsWith("=")?1:0;if(s%4||s<4)throw Error("Invalid embedded image base64.");for(let o=n;o<i.length-a;o++)if(Ee.indexOf(i[o])<0)throw Error("Invalid embedded image base64.");return{length:s*3/4-a,at(o){let l=Math.floor(o/3)*4+n,c=o%3,u=Ee.indexOf(i[l+c]),d=Ee.indexOf(i[l+c+1]);return c===0?(u<<2|d>>4)&255:c===1?(u<<4|d>>2)&255:(u<<6|d)&255}}}function N(e){let t=e.length,r=e.at,i=s=>r(s)*256+r(s+1),n=s=>r(s)*16777216+r(s+1)*65536+r(s+2)*256+r(s+3);if(t>=24&&r(0)===137&&r(1)===80&&r(2)===78&&r(3)===71&&r(4)===13&&r(5)===10&&r(6)===26&&r(7)===10){if(n(8)!==13||n(12)!==1229472850)throw Error("Invalid embedded PNG header.");let s=n(16),a=n(20);if(!s||!a)throw Error("Invalid embedded PNG dimensions.");return{width:s,height:a}}if(t>=4&&r(0)===255&&r(1)===216){let s=2;for(;s<t;){if(r(s++)!==255)throw Error("Invalid embedded JPEG marker.");for(;s<t&&r(s)===255;)s++;if(s>=t)break;let a=r(s++);if(a===0||a===218||a===217)break;if(a===1||a>=208&&a<=216)continue;if(s+2>t)break;let o=i(s);if(o<2||s+o>t)throw Error("Invalid embedded JPEG segment.");if(a>=192&&a<=207&&![196,200,204].includes(a)){if(o<8)throw Error("Invalid embedded JPEG frame.");let l=i(s+3),c=i(s+5),u=r(s+7);if(!c||!l||!u||o<8+3*u)throw Error("Invalid embedded JPEG dimensions.");return{width:c,height:l}}s+=o}throw Error("Embedded JPEG has no bounded frame dimensions.")}throw Error("Embedded model image format has no bounded PNG/JPEG dimension preflight; saved footprint proxies are retained.")}function re(e,t,r,{maxAccessorBytes:i=67108864,maxTextureBytes:n=33554432,maxTextureDimension:s=8192}={}){for(let[x,g]of[[i,"accessor budget"],[n,"texture budget"],[s,"texture dimension"]])if(!Number.isSafeInteger(x)||x<1)throw TypeError("Invalid GLB "+g+".");let a=null,o=r;for(;o<t.length;){if(o+8>t.length)throw Error("Truncated GLB chunk.");let x=new DataView(t.buffer,t.byteOffset+o,8),g=x.getUint32(0,!0),v=x.getUint32(4,!0);if(o+=8,g>t.length-o)throw Error("Truncated GLB chunk.");if(v===5130562){if(a)throw Error("Duplicate GLB binary chunk.");a=t.subarray(o,o+g)}o+=g}let l=e.buffers||[],c=e.bufferViews||[];function u(x){Xe(x,"buffer view index");let g=c[x];if(!g)throw Error("GLB references an invalid buffer view.");let v=l[Xe(g.buffer,"buffer index")];if(!v)throw Error("GLB references an invalid buffer.");let _=Xe(g.byteOffset??0,"buffer offset"),E=Xe(g.byteLength,"buffer length"),M=Xe(v.byteLength,"buffer length");if(!Number.isSafeInteger(_+E)||_+E>M)throw Error("GLB buffer view exceeds its declared buffer.");if(!v.uri&&(!a||M>a.length))throw Error("GLB buffer exceeds its binary chunk.");return{view:g,start:_,length:E,buffer:v}}let d=x=>{let{buffer:g,start:v,length:_}=u(x);if(g.uri)throw Error("Embedded image buffer uses an unsupported nested data URI.");return a.subarray(v,v+_)},f=0;for(let x=0;x<c.length;x++)f+=u(x).length,(!Number.isSafeInteger(f)||f>i+n)&&ve("buffer view expansion");let y=0;for(let x of e.accessors||[]){let g=Xe(x.count,"accessor count"),v=qe[x.componentType],_=$e[x.type];if(!g||!Number.isInteger(x.componentType)||!v||!Object.hasOwn(qe,x.componentType)||!_||!Object.hasOwn($e,x.type))throw Error("Invalid GLB accessor component type, shape or count.");let E=x.type.startsWith("MAT")?Number(x.type.at(-1)):1,M=_/E,P=E>1?E*Math.ceil(M*v/4)*4:_*v,k=P,z=Xe(x.byteOffset??0,"accessor offset");if(z%v)throw Error("Misaligned GLB accessor offset.");if(x.bufferView!==void 0){let I=u(x.bufferView);if(k=I.view.byteStride??P,!Number.isSafeInteger(k)||k<P||k%v||I.view.byteStride!==void 0&&(k<4||k>252||k%4))throw Error("Invalid GLB accessor stride.");let L=(g-1)*k+P;if(!Number.isSafeInteger(L)||z+L>I.length)throw Error("GLB accessor exceeds its buffer view.")}else if(z)throw Error("GLB accessor without a buffer view has an offset.");let D=g*k;if(x.sparse){let I=x.sparse,L=Xe(I.count,"sparse count"),Z=qe[I.indices?.componentType];if(!L||L>g||![5121,5123,5125].includes(I.indices?.componentType)||!I.values)throw Error("Invalid GLB sparse accessor.");for(let[se,ce,fe]of[[I.indices,L*Z,Z],[I.values,L*P,v]]){let ze=u(se.bufferView),Fe=Xe(se.byteOffset??0,"sparse offset");if(Fe%fe||Fe+ce>ze.length)throw Error("GLB sparse accessor exceeds its buffer view.")}D+=g*_*v}y+=D,(!Number.isSafeInteger(y)||y>i)&&ve("accessor expansion")}let b=0;for(let x of e.images||[]){let{width:g,height:v}=N(me(x,d));(g>s||v>s)&&ve("image dimensions"),b+=Math.ceil(g*v*4*4/3),(!Number.isSafeInteger(b)||b>n)&&ve("image pixels")}return{accessorBytes:y,textureBytes:b}}var R=(e,t)=>e||t>512?1:3,$=()=>Object.assign(Error("Linked model graph exceeds the bounded assembly node budget; saved footprint proxies and identities are retained."),{code:"MODEL_GRAPH_BUDGET"});function V(e){if(!Number.isSafeInteger(e)||e<1)throw TypeError("Choose a positive model node budget.");let t=new WeakMap,r=0,i=0,n=0;function s(a){if(t.has(a))return t.get(a);let o=[a],l=0;for(;o.length;){let c=o.pop();if(++l>e)throw $();for(let u of c.children||[]){if(l+o.length>=e)throw $();o.push(u)}}return t.set(a,l),l}return{limit:e,checkTemplate(a,o=0){try{let l=s(a);if(r+l+o>e)throw $();return l}catch(l){throw l.code==="MODEL_GRAPH_BUDGET"&&i++,l}},rejectPreflight(){i++},admit(a,o,l){let c=s(a)+o;if(r+c>e)throw n++,$();let u=l();return r+=c,u},stats:()=>({limit:e,admittedNodes:r,rejectedTemplates:i,rejectedOccurrences:n})}}function O(e,t,r){if(e.byteLength<20)throw Error("GLB has an external dependency or invalid header");let i=new DataView(e.buffer,e.byteOffset,e.byteLength),n=i.getUint32(12,!0);if(i.getUint32(0,!0)!==1179937895||i.getUint32(4,!0)!==2||i.getUint32(8,!0)!==e.byteLength||i.getUint32(16,!0)!==1313821514||n>e.byteLength-20)throw Error("GLB has an external dependency or invalid header");let s=JSON.parse(new TextDecoder().decode(e.subarray(20,20+n)));for(let d of[s.buffers||[],s.images||[]])for(let f of d)if(f.uri&&!/^data:/i.test(f.uri))throw Error("GLB has an external dependency or invalid header");re(s,e,20+n,r);let a=s.nodes||[],o=s.scenes||[],l=s.meshes||[],c=o.length;if(a.length>t||c>t)throw $();let u=[];for(let d of o){for(let f of d.nodes||[]){if(c+u.length>=t)throw $();u.push(f)}for(;u.length;){let f=u.pop(),y=a[f];if(!Number.isInteger(f)||!y)throw Error("GLB references an invalid node.");let b=1;if(y.mesh!==void 0){let x=l[y.mesh];if(!x||!Array.isArray(x.primitives))throw Error("GLB references an invalid mesh.");x.primitives.length>1&&(b+=x.primitives.length)}if(y.camera!==void 0&&b++,y.extensions?.KHR_lights_punctual&&(b+=2),c+=b,c>t)throw $();for(let x of y.children||[]){if(c+u.length>=t)throw $();u.push(x)}}}return c}var C={};H(C,{ACESFilmicToneMapping:()=>Cr,AddEquation:()=>gt,AddOperation:()=>Dr,AdditiveAnimationBlendMode:()=>sg,AdditiveBlending:()=>Rt,AgXToneMapping:()=>Ur,AlphaFormat:()=>Qm,AlwaysCompare:()=>Tx,AlwaysDepth:()=>Jt,AlwaysStencilFunc:()=>og,AmbientLight:()=>wy,AnimationAction:()=>T1,AnimationClip:()=>bc,AnimationLoader:()=>C2,AnimationMixer:()=>tC,AnimationObjectGroup:()=>Q2,AnimationUtils:()=>S2,ArcCurve:()=>Sb,ArrayCamera:()=>w1,ArrowHelper:()=>EC,AttachedBindMode:()=>fi,Audio:()=>S1,AudioAnalyser:()=>H2,AudioContext:()=>_y,AudioListener:()=>B2,AudioLoader:()=>U2,AxesHelper:()=>SC,BackSide:()=>tt,BasicDepthPacking:()=>vx,BasicShadowMap:()=>we,BatchedMesh:()=>yb,Bone:()=>Ep,BooleanKeyframeTrack:()=>el,Box2:()=>cC,Box3:()=>Xi,Box3Helper:()=>wC,BoxGeometry:()=>Da,BoxHelper:()=>bC,BufferAttribute:()=>ui,BufferGeometry:()=>Hr,BufferGeometryLoader:()=>m1,ByteType:()=>Sa,Cache:()=>Ba,Camera:()=>gp,CameraHelper:()=>xC,CanvasTexture:()=>Fp,CapsuleGeometry:()=>Pb,CatmullRomCurve3:()=>Mb,CineonToneMapping:()=>Yr,CircleGeometry:()=>Ib,ClampToEdgeWrapping:()=>ei,Clock:()=>Ey,Color:()=>or,ColorKeyframeTrack:()=>fy,ColorManagement:()=>li,CompressedArrayTexture:()=>YT,CompressedCubeTexture:()=>qT,CompressedTexture:()=>Up,CompressedTextureLoader:()=>R2,ConeGeometry:()=>ty,ConstantAlphaFactor:()=>Gi,ConstantColorFactor:()=>ii,Controls:()=>z1,CubeCamera:()=>Qx,CubeReflectionMapping:()=>br,CubeRefractionMapping:()=>wi,CubeTexture:()=>jh,CubeTextureLoader:()=>P2,CubeUVReflectionMapping:()=>vi,CubicBezierCurve:()=>Kg,CubicBezierCurve3:()=>Tb,CubicInterpolant:()=>r1,CullFaceBack:()=>ge,CullFaceFront:()=>Ne,CullFaceFrontBack:()=>ne,CullFaceNone:()=>K,Curve:()=>Ks,CurvePath:()=>Rb,CustomBlending:()=>Et,CustomToneMapping:()=>Or,CylinderGeometry:()=>eu,Cylindrical:()=>oC,Data3DTexture:()=>pg,DataArrayTexture:()=>Jd,DataTexture:()=>ys,DataTextureLoader:()=>I2,DataUtils:()=>_T,DecrementStencilOp:()=>EA,DecrementWrapStencilOp:()=>MA,DefaultLoadingManager:()=>s1,DepthFormat:()=>Uo,DepthStencilFormat:()=>no,DepthTexture:()=>zp,DetachedBindMode:()=>Mi,DirectionalLight:()=>$p,DirectionalLightHelper:()=>vC,DiscreteInterpolant:()=>i1,DodecahedronGeometry:()=>Nb,DoubleSide:()=>Ze,DstAlphaFactor:()=>Yt,DstColorFactor:()=>Gr,DynamicCopyUsage:()=>zA,DynamicDrawUsage:()=>Cx,DynamicReadUsage:()=>DA,EdgesGeometry:()=>tu,EllipseCurve:()=>Bp,EqualCompare:()=>Ex,EqualDepth:()=>qt,EqualStencilFunc:()=>RA,EquirectangularReflectionMapping:()=>an,EquirectangularRefractionMapping:()=>Rn,Euler:()=>Ys,EventDispatcher:()=>ha,ExtrudeGeometry:()=>Kp,FileLoader:()=>Ps,Float16BufferAttribute:()=>CT,Float32BufferAttribute:()=>hr,FloatType:()=>es,Fog:()=>rb,FogExp2:()=>tb,FramebufferTexture:()=>XT,FrontSide:()=>Ce,Frustum:()=>qh,GLBufferAttribute:()=>aC,GLSL1:()=>jA,GLSL3:()=>cg,GreaterCompare:()=>Sx,GreaterDepth:()=>ar,GreaterEqualCompare:()=>Ax,GreaterEqualDepth:()=>gr,GreaterEqualStencilFunc:()=>LA,GreaterStencilFunc:()=>IA,GridHelper:()=>gC,Group:()=>Wi,HalfFloatType:()=>Ts,HemisphereLight:()=>a1,HemisphereLightHelper:()=>mC,IcosahedronGeometry:()=>zb,ImageBitmapLoader:()=>v1,ImageLoader:()=>su,ImageUtils:()=>Ox,IncrementStencilOp:()=>_A,IncrementWrapStencilOp:()=>SA,InstancedBufferAttribute:()=>qo,InstancedBufferGeometry:()=>f1,InstancedInterleavedBuffer:()=>sC,InstancedMesh:()=>Mp,Int16BufferAttribute:()=>AT,Int32BufferAttribute:()=>TT,Int8BufferAttribute:()=>ET,IntType:()=>Do,InterleavedBuffer:()=>Vh,InterleavedBufferAttribute:()=>cc,Interpolant:()=>xc,InterpolateDiscrete:()=>Gl,InterpolateLinear:()=>Wl,InterpolateSmooth:()=>qd,InvertStencilOp:()=>AA,KeepStencilOp:()=>Bo,KeyframeTrack:()=>Zs,LOD:()=>ob,LatheGeometry:()=>ey,Layers:()=>sp,LessCompare:()=>_x,LessDepth:()=>sr,LessEqualCompare:()=>lg,LessEqualDepth:()=>Xt,LessEqualStencilFunc:()=>PA,LessStencilFunc:()=>CA,Light:()=>fo,LightProbe:()=>d1,Line:()=>ua,Line3:()=>hC,LineBasicMaterial:()=>tn,LineCurve:()=>Zg,LineCurve3:()=>Cb,LineDashedMaterial:()=>Qb,LineLoop:()=>Lp,LineSegments:()=>Fn,LinearFilter:()=>Pi,LinearInterpolant:()=>py,LinearMipMapLinearFilter:()=>Xn,LinearMipMapNearestFilter:()=>gd,LinearMipmapLinearFilter:()=>Fi,LinearMipmapNearestFilter:()=>Wn,LinearSRGBColorSpace:()=>kn,LinearToneMapping:()=>Si,LinearTransfer:()=>Ih,Loader:()=>mn,LoaderUtils:()=>Va,LoadingManager:()=>my,LoopOnce:()=>fx,LoopPingPong:()=>gx,LoopRepeat:()=>mx,LuminanceAlphaFormat:()=>rg,LuminanceFormat:()=>tg,MOUSE:()=>B,Material:()=>bn,MaterialLoader:()=>p1,MathUtils:()=>$d,Matrix2:()=>lC,Matrix3:()=>si,Matrix4:()=>Ir,MaxEquation:()=>St,Mesh:()=>qr,MeshBasicMaterial:()=>en,MeshDepthMaterial:()=>cy,MeshDistanceMaterial:()=>hy,MeshLambertMaterial:()=>$b,MeshMatcapMaterial:()=>Jb,MeshNormalMaterial:()=>ly,MeshPhongMaterial:()=>oy,MeshPhysicalMaterial:()=>vs,MeshStandardMaterial:()=>is,MeshToonMaterial:()=>Zb,MinEquation:()=>et,MirroredRepeatWrapping:()=>Ri,MixOperation:()=>Br,MultiplyBlending:()=>_t,MultiplyOperation:()=>mr,NearestFilter:()=>oi,NearestMipMapLinearFilter:()=>As,NearestMipMapNearestFilter:()=>ps,NearestMipmapLinearFilter:()=>Qn,NearestMipmapNearestFilter:()=>Pn,NeutralToneMapping:()=>ni,NeverCompare:()=>wx,NeverDepth:()=>jt,NeverStencilFunc:()=>TA,NoBlending:()=>Ye,NoColorSpace:()=>Ta,NoToneMapping:()=>hi,NormalAnimationBlendMode:()=>Kd,NormalBlending:()=>vt,NotEqualCompare:()=>Mx,NotEqualDepth:()=>Ar,NotEqualStencilFunc:()=>NA,NumberKeyframeTrack:()=>tl,Object3D:()=>mi,ObjectLoader:()=>O2,ObjectSpaceNormalMap:()=>bx,OctahedronGeometry:()=>sy,OneFactor:()=>Wt,OneMinusConstantAlphaFactor:()=>yt,OneMinusConstantColorFactor:()=>ur,OneMinusDstAlphaFactor:()=>kr,OneMinusDstColorFactor:()=>Qr,OneMinusSrcAlphaFactor:()=>Bt,OneMinusSrcColorFactor:()=>pt,OrthographicCamera:()=>wc,PCFShadowMap:()=>xe,PCFSoftShadowMap:()=>ke,PMREMGenerator:()=>of,Path:()=>mc,PerspectiveCamera:()=>cn,Plane:()=>Ua,PlaneGeometry:()=>vc,PlaneHelper:()=>_C,PointLight:()=>Zp,PointLightHelper:()=>pC,Points:()=>Dp,PointsMaterial:()=>$h,PolarGridHelper:()=>yC,PolyhedronGeometry:()=>gc,PositionalAudio:()=>V2,PropertyBinding:()=>zi,PropertyMixer:()=>A1,QuadraticBezierCurve:()=>$g,QuadraticBezierCurve3:()=>Jg,Quaternion:()=>pn,QuaternionKeyframeTrack:()=>rl,QuaternionLinearInterpolant:()=>n1,RED_GREEN_RGTC2_Format:()=>Xd,RED_RGTC1_Format:()=>ng,REVISION:()=>j,RGBADepthPacking:()=>xx,RGBAFormat:()=>Ln,RGBAIntegerFormat:()=>wd,RGBA_ASTC_10x10_Format:()=>Bd,RGBA_ASTC_10x5_Format:()=>Ud,RGBA_ASTC_10x6_Format:()=>Fd,RGBA_ASTC_10x8_Format:()=>zd,RGBA_ASTC_12x10_Format:()=>jd,RGBA_ASTC_12x12_Format:()=>Vd,RGBA_ASTC_4x4_Format:()=>Rd,RGBA_ASTC_5x4_Format:()=>Pd,RGBA_ASTC_5x5_Format:()=>Id,RGBA_ASTC_6x5_Format:()=>Nd,RGBA_ASTC_6x6_Format:()=>Ld,RGBA_ASTC_8x5_Format:()=>kd,RGBA_ASTC_8x6_Format:()=>Od,RGBA_ASTC_8x8_Format:()=>Dd,RGBA_BPTC_Format:()=>Rh,RGBA_ETC2_EAC_Format:()=>Cd,RGBA_PVRTC_2BPPV1_Format:()=>Md,RGBA_PVRTC_4BPPV1_Format:()=>Sd,RGBA_S3TC_DXT1_Format:()=>Ah,RGBA_S3TC_DXT3_Format:()=>Th,RGBA_S3TC_DXT5_Format:()=>Ch,RGBDepthPacking:()=>vA,RGBFormat:()=>eg,RGBIntegerFormat:()=>yA,RGB_BPTC_SIGNED_Format:()=>Hd,RGB_BPTC_UNSIGNED_Format:()=>Gd,RGB_ETC1_Format:()=>Ad,RGB_ETC2_Format:()=>Td,RGB_PVRTC_2BPPV1_Format:()=>Ed,RGB_PVRTC_4BPPV1_Format:()=>_d,RGB_S3TC_DXT1_Format:()=>Mh,RGDepthPacking:()=>xA,RGFormat:()=>ig,RGIntegerFormat:()=>bd,RawShaderMaterial:()=>ay,Ray:()=>Wo,Raycaster:()=>ou,RectAreaLight:()=>h1,RedFormat:()=>xd,RedIntegerFormat:()=>Sh,ReinhardToneMapping:()=>Vr,RenderTarget:()=>Dx,RepeatWrapping:()=>Wr,ReplaceStencilOp:()=>wA,ReverseSubtractEquation:()=>lt,RingGeometry:()=>Bb,SIGNED_RED_GREEN_RGTC2_Format:()=>Yd,SIGNED_RED_RGTC1_Format:()=>Wd,SRGBColorSpace:()=>xi,SRGBTransfer:()=>Ii,Scene:()=>Yo,ShaderChunk:()=>ai,ShaderLib:()=>$s,ShaderMaterial:()=>ln,ShadowMaterial:()=>Kb,Shape:()=>Fa,ShapeGeometry:()=>jb,ShapePath:()=>MC,ShapeUtils:()=>za,ShortType:()=>Eh,Skeleton:()=>Fg,SkeletonHelper:()=>dC,SkinnedMesh:()=>Ug,Source:()=>Vo,Sphere:()=>on,SphereGeometry:()=>po,Spherical:()=>Ty,SphericalHarmonics3:()=>u1,SplineCurve:()=>Qg,SpotLight:()=>xy,SpotLightHelper:()=>uC,Sprite:()=>kg,SpriteMaterial:()=>yp,SrcAlphaFactor:()=>ft,SrcAlphaSaturateFactor:()=>Zr,SrcColorFactor:()=>nr,StaticCopyUsage:()=>FA,StaticDrawUsage:()=>Nh,StaticReadUsage:()=>OA,StereoCamera:()=>F2,StreamCopyUsage:()=>BA,StreamDrawUsage:()=>kA,StreamReadUsage:()=>UA,StringKeyframeTrack:()=>il,SubtractEquation:()=>Ht,SubtractiveBlending:()=>Je,TOUCH:()=>W,TangentSpaceNormalMap:()=>so,TetrahedronGeometry:()=>Vb,Texture:()=>Qi,TextureLoader:()=>gy,TextureUtils:()=>PC,TorusGeometry:()=>Hb,TorusKnotGeometry:()=>Gb,Triangle:()=>ka,TriangleFanDrawMode:()=>Zd,TriangleStripDrawMode:()=>ag,TrianglesDrawMode:()=>yx,TubeGeometry:()=>Wb,UVMapping:()=>Rr,Uint16BufferAttribute:()=>Rg,Uint32BufferAttribute:()=>Pg,Uint8BufferAttribute:()=>ST,Uint8ClampedBufferAttribute:()=>MT,Uniform:()=>rC,UniformsGroup:()=>nC,UniformsLib:()=>vr,UniformsUtils:()=>Rs,UnsignedByteType:()=>Ji,UnsignedInt248Type:()=>io,UnsignedInt5999Type:()=>Jm,UnsignedIntType:()=>Aa,UnsignedShort4444Type:()=>yd,UnsignedShort5551Type:()=>vd,UnsignedShortType:()=>Ma,VSMShadowMap:()=>Me,Vector2:()=>Ft,Vector3:()=>je,Vector4:()=>_i,VectorKeyframeTrack:()=>nl,VideoTexture:()=>WT,WebGL3DRenderTarget:()=>dT,WebGLArrayRenderTarget:()=>uT,WebGLCoordinateSystem:()=>ca,WebGLCubeRenderTarget:()=>eb,WebGLMultipleRenderTargets:()=>IC,WebGLRenderTarget:()=>In,WebGLRenderer:()=>df,WebGLUtils:()=>fw,WebGPUCoordinateSystem:()=>Lh,WireframeGeometry:()=>Xb,WrapAroundEnding:()=>Ph,ZeroCurvatureEnding:()=>Fo,ZeroFactor:()=>At,ZeroSlopeEnding:()=>zo,ZeroStencilOp:()=>bA,createCanvasElement:()=>Ix});var j="171",B={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},W={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},K=0,ge=1,Ne=2,ne=3,we=0,xe=1,ke=2,Me=3,Ce=0,tt=1,Ze=2,Ye=0,vt=1,Rt=2,Je=3,_t=4,Et=5,gt=100,Ht=101,lt=102,et=103,St=104,At=200,Wt=201,nr=202,pt=203,ft=204,Bt=205,Yt=206,kr=207,Gr=208,Qr=209,Zr=210,ii=211,ur=212,Gi=213,yt=214,jt=0,Jt=1,sr=2,Xt=3,qt=4,gr=5,ar=6,Ar=7,mr=0,Br=1,Dr=2,hi=0,Si=1,Vr=2,Yr=3,Cr=4,Or=5,Ur=6,ni=7,fi="attached",Mi="detached",Rr=300,br=301,wi=302,an=303,Rn=304,vi=306,Wr=1e3,ei=1001,Ri=1002,oi=1003,Pn=1004,ps=1004,Qn=1005,As=1005,Pi=1006,Wn=1007,gd=1007,Fi=1008,Xn=1008,Ji=1009,Sa=1010,Eh=1011,Ma=1012,Do=1013,Aa=1014,es=1015,Ts=1016,yd=1017,vd=1018,io=1020,Jm=35902,Qm=1021,eg=1022,Ln=1023,tg=1024,rg=1025,Uo=1026,no=1027,xd=1028,Sh=1029,ig=1030,bd=1031,yA=1032,wd=1033,Mh=33776,Ah=33777,Th=33778,Ch=33779,_d=35840,Ed=35841,Sd=35842,Md=35843,Ad=36196,Td=37492,Cd=37496,Rd=37808,Pd=37809,Id=37810,Nd=37811,Ld=37812,kd=37813,Od=37814,Dd=37815,Ud=37816,Fd=37817,zd=37818,Bd=37819,jd=37820,Vd=37821,Rh=36492,Hd=36494,Gd=36495,ng=36283,Wd=36284,Xd=36285,Yd=36286,fx=2200,mx=2201,gx=2202,Gl=2300,Wl=2301,qd=2302,Fo=2400,zo=2401,Ph=2402,Kd=2500,sg=2501,yx=0,ag=1,Zd=2,vx=3200,xx=3201,vA=3202,xA=3203,so=0,bx=1,Ta="",xi="srgb",kn="srgb-linear",Ih="linear",Ii="srgb",bA=0,Bo=7680,wA=7681,_A=7682,EA=7683,SA=34055,MA=34056,AA=5386,TA=512,CA=513,RA=514,PA=515,IA=516,NA=517,LA=518,og=519,wx=512,_x=513,Ex=514,lg=515,Sx=516,Mx=517,Ax=518,Tx=519,Nh=35044,Cx=35048,kA=35040,OA=35045,DA=35049,UA=35041,FA=35046,zA=35050,BA=35042,jA="100",cg="300 es",ca=2e3,Lh=2001,ha=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let r=this._listeners;r[e]===void 0&&(r[e]=[]),r[e].indexOf(t)===-1&&r[e].push(t)}hasEventListener(e,t){if(this._listeners===void 0)return!1;let r=this._listeners;return r[e]!==void 0&&r[e].indexOf(t)!==-1}removeEventListener(e,t){if(this._listeners===void 0)return;let r=this._listeners[e];if(r!==void 0){let i=r.indexOf(t);i!==-1&&r.splice(i,1)}}dispatchEvent(e){if(this._listeners===void 0)return;let t=this._listeners[e.type];if(t!==void 0){e.target=this;let r=t.slice(0);for(let i=0,n=r.length;i<n;i++)r[i].call(this,e);e.target=null}}},On=["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"],Rx=1234567,jo=Math.PI/180,Xl=180/Math.PI;function fs(){let e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,r=Math.random()*4294967295|0,i=Math.random()*4294967295|0;return(On[e&255]+On[e>>8&255]+On[e>>16&255]+On[e>>24&255]+"-"+On[t&255]+On[t>>8&255]+"-"+On[t>>16&15|64]+On[t>>24&255]+"-"+On[r&63|128]+On[r>>8&255]+"-"+On[r>>16&255]+On[r>>24&255]+On[i&255]+On[i>>8&255]+On[i>>16&255]+On[i>>24&255]).toLowerCase()}function Jr(e,t,r){return Math.max(t,Math.min(r,e))}function hg(e,t){return(e%t+t)%t}function VA(e,t,r,i,n){return i+(e-t)*(n-i)/(r-t)}function HA(e,t,r){return e!==t?(r-e)/(t-e):0}function kh(e,t,r){return(1-r)*e+r*t}function GA(e,t,r,i){return kh(e,t,1-Math.exp(-r*i))}function WA(e,t=1){return t-Math.abs(hg(e,t*2)-t)}function XA(e,t,r){return e<=t?0:e>=r?1:(e=(e-t)/(r-t),e*e*(3-2*e))}function YA(e,t,r){return e<=t?0:e>=r?1:(e=(e-t)/(r-t),e*e*e*(e*(e*6-15)+10))}function qA(e,t){return e+Math.floor(Math.random()*(t-e+1))}function KA(e,t){return e+Math.random()*(t-e)}function ZA(e){return e*(.5-Math.random())}function $A(e){e!==void 0&&(Rx=e);let t=Rx+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function JA(e){return e*jo}function QA(e){return e*Xl}function eT(e){return(e&e-1)===0&&e!==0}function tT(e){return Math.pow(2,Math.ceil(Math.log(e)/Math.LN2))}function rT(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))}function iT(e,t,r,i,n){let s=Math.cos,a=Math.sin,o=s(r/2),l=a(r/2),c=s((t+i)/2),u=a((t+i)/2),d=s((t-i)/2),f=a((t-i)/2),y=s((i-t)/2),b=a((i-t)/2);switch(n){case"XYX":e.set(o*u,l*d,l*f,o*c);break;case"YZY":e.set(l*f,o*u,l*d,o*c);break;case"ZXZ":e.set(l*d,l*f,o*u,o*c);break;case"XZX":e.set(o*u,l*b,l*y,o*c);break;case"YXY":e.set(l*y,o*u,l*b,o*c);break;case"ZYZ":e.set(l*b,l*y,o*u,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+n)}}function Yn(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw new Error("Invalid component type.")}}function ti(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(e*4294967295);case Uint16Array:return Math.round(e*65535);case Uint8Array:return Math.round(e*255);case Int32Array:return Math.round(e*2147483647);case Int16Array:return Math.round(e*32767);case Int8Array:return Math.round(e*127);default:throw new Error("Invalid component type.")}}var $d={DEG2RAD:jo,RAD2DEG:Xl,generateUUID:fs,clamp:Jr,euclideanModulo:hg,mapLinear:VA,inverseLerp:HA,lerp:kh,damp:GA,pingpong:WA,smoothstep:XA,smootherstep:YA,randInt:qA,randFloat:KA,randFloatSpread:ZA,seededRandom:$A,degToRad:JA,radToDeg:QA,isPowerOfTwo:eT,ceilPowerOfTwo:tT,floorPowerOfTwo:rT,setQuaternionFromProperEuler:iT,normalize:ti,denormalize:Yn},Ft=class GS{constructor(t=0,r=0){GS.prototype.isVector2=!0,this.x=t,this.y=r}get width(){return this.x}set width(t){this.x=t}get height(){return this.y}set height(t){this.y=t}set(t,r){return this.x=t,this.y=r,this}setScalar(t){return this.x=t,this.y=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setComponent(t,r){switch(t){case 0:this.x=r;break;case 1:this.y=r;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y)}copy(t){return this.x=t.x,this.y=t.y,this}add(t){return this.x+=t.x,this.y+=t.y,this}addScalar(t){return this.x+=t,this.y+=t,this}addVectors(t,r){return this.x=t.x+r.x,this.y=t.y+r.y,this}addScaledVector(t,r){return this.x+=t.x*r,this.y+=t.y*r,this}sub(t){return this.x-=t.x,this.y-=t.y,this}subScalar(t){return this.x-=t,this.y-=t,this}subVectors(t,r){return this.x=t.x-r.x,this.y=t.y-r.y,this}multiply(t){return this.x*=t.x,this.y*=t.y,this}multiplyScalar(t){return this.x*=t,this.y*=t,this}divide(t){return this.x/=t.x,this.y/=t.y,this}divideScalar(t){return this.multiplyScalar(1/t)}applyMatrix3(t){let r=this.x,i=this.y,n=t.elements;return this.x=n[0]*r+n[3]*i+n[6],this.y=n[1]*r+n[4]*i+n[7],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this}clamp(t,r){return this.x=Jr(this.x,t.x,r.x),this.y=Jr(this.y,t.y,r.y),this}clampScalar(t,r){return this.x=Jr(this.x,t,r),this.y=Jr(this.y,t,r),this}clampLength(t,r){let i=this.length();return this.divideScalar(i||1).multiplyScalar(Jr(i,t,r))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(t){return this.x*t.x+this.y*t.y}cross(t){return this.x*t.y-this.y*t.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(t){let r=Math.sqrt(this.lengthSq()*t.lengthSq());if(r===0)return Math.PI/2;let i=this.dot(t)/r;return Math.acos(Jr(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){let r=this.x-t.x,i=this.y-t.y;return r*r+i*i}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,r){return this.x+=(t.x-this.x)*r,this.y+=(t.y-this.y)*r,this}lerpVectors(t,r,i){return this.x=t.x+(r.x-t.x)*i,this.y=t.y+(r.y-t.y)*i,this}equals(t){return t.x===this.x&&t.y===this.y}fromArray(t,r=0){return this.x=t[r],this.y=t[r+1],this}toArray(t=[],r=0){return t[r]=this.x,t[r+1]=this.y,t}fromBufferAttribute(t,r){return this.x=t.getX(r),this.y=t.getY(r),this}rotateAround(t,r){let i=Math.cos(r),n=Math.sin(r),s=this.x-t.x,a=this.y-t.y;return this.x=s*i-a*n+t.x,this.y=s*n+a*i+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},si=class WS{constructor(t,r,i,n,s,a,o,l,c){WS.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],t!==void 0&&this.set(t,r,i,n,s,a,o,l,c)}set(t,r,i,n,s,a,o,l,c){let u=this.elements;return u[0]=t,u[1]=n,u[2]=o,u[3]=r,u[4]=s,u[5]=l,u[6]=i,u[7]=a,u[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(t){let r=this.elements,i=t.elements;return r[0]=i[0],r[1]=i[1],r[2]=i[2],r[3]=i[3],r[4]=i[4],r[5]=i[5],r[6]=i[6],r[7]=i[7],r[8]=i[8],this}extractBasis(t,r,i){return t.setFromMatrix3Column(this,0),r.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(t){let r=t.elements;return this.set(r[0],r[4],r[8],r[1],r[5],r[9],r[2],r[6],r[10]),this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,r){let i=t.elements,n=r.elements,s=this.elements,a=i[0],o=i[3],l=i[6],c=i[1],u=i[4],d=i[7],f=i[2],y=i[5],b=i[8],x=n[0],g=n[3],v=n[6],_=n[1],E=n[4],M=n[7],P=n[2],k=n[5],z=n[8];return s[0]=a*x+o*_+l*P,s[3]=a*g+o*E+l*k,s[6]=a*v+o*M+l*z,s[1]=c*x+u*_+d*P,s[4]=c*g+u*E+d*k,s[7]=c*v+u*M+d*z,s[2]=f*x+y*_+b*P,s[5]=f*g+y*E+b*k,s[8]=f*v+y*M+b*z,this}multiplyScalar(t){let r=this.elements;return r[0]*=t,r[3]*=t,r[6]*=t,r[1]*=t,r[4]*=t,r[7]*=t,r[2]*=t,r[5]*=t,r[8]*=t,this}determinant(){let t=this.elements,r=t[0],i=t[1],n=t[2],s=t[3],a=t[4],o=t[5],l=t[6],c=t[7],u=t[8];return r*a*u-r*o*c-i*s*u+i*o*l+n*s*c-n*a*l}invert(){let t=this.elements,r=t[0],i=t[1],n=t[2],s=t[3],a=t[4],o=t[5],l=t[6],c=t[7],u=t[8],d=u*a-o*c,f=o*l-u*s,y=c*s-a*l,b=r*d+i*f+n*y;if(b===0)return this.set(0,0,0,0,0,0,0,0,0);let x=1/b;return t[0]=d*x,t[1]=(n*c-u*i)*x,t[2]=(o*i-n*a)*x,t[3]=f*x,t[4]=(u*r-n*l)*x,t[5]=(n*s-o*r)*x,t[6]=y*x,t[7]=(i*l-c*r)*x,t[8]=(a*r-i*s)*x,this}transpose(){let t,r=this.elements;return t=r[1],r[1]=r[3],r[3]=t,t=r[2],r[2]=r[6],r[6]=t,t=r[5],r[5]=r[7],r[7]=t,this}getNormalMatrix(t){return this.setFromMatrix4(t).invert().transpose()}transposeIntoArray(t){let r=this.elements;return t[0]=r[0],t[1]=r[3],t[2]=r[6],t[3]=r[1],t[4]=r[4],t[5]=r[7],t[6]=r[2],t[7]=r[5],t[8]=r[8],this}setUvTransform(t,r,i,n,s,a,o){let l=Math.cos(s),c=Math.sin(s);return this.set(i*l,i*c,-i*(l*a+c*o)+a+t,-n*c,n*l,-n*(-c*a+l*o)+o+r,0,0,1),this}scale(t,r){return this.premultiply(ug.makeScale(t,r)),this}rotate(t){return this.premultiply(ug.makeRotation(-t)),this}translate(t,r){return this.premultiply(ug.makeTranslation(t,r)),this}makeTranslation(t,r){return t.isVector2?this.set(1,0,t.x,0,1,t.y,0,0,1):this.set(1,0,t,0,1,r,0,0,1),this}makeRotation(t){let r=Math.cos(t),i=Math.sin(t);return this.set(r,-i,0,i,r,0,0,0,1),this}makeScale(t,r){return this.set(t,0,0,0,r,0,0,0,1),this}equals(t){let r=this.elements,i=t.elements;for(let n=0;n<9;n++)if(r[n]!==i[n])return!1;return!0}fromArray(t,r=0){for(let i=0;i<9;i++)this.elements[i]=t[i+r];return this}toArray(t=[],r=0){let i=this.elements;return t[r]=i[0],t[r+1]=i[1],t[r+2]=i[2],t[r+3]=i[3],t[r+4]=i[4],t[r+5]=i[5],t[r+6]=i[6],t[r+7]=i[7],t[r+8]=i[8],t}clone(){return new this.constructor().fromArray(this.elements)}},ug=new si;function Px(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}var nT={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function Yl(e,t){return new nT[e](t)}function Oh(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}function Ix(){let e=Oh("canvas");return e.style.display="block",e}var Nx={};function ql(e){e in Nx||(Nx[e]=!0,console.warn(e))}function sT(e,t,r){return new Promise(function(i,n){function s(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:n();break;case e.TIMEOUT_EXPIRED:setTimeout(s,r);break;default:i()}}setTimeout(s,r)})}function aT(e){let t=e.elements;t[2]=.5*t[2]+.5*t[3],t[6]=.5*t[6]+.5*t[7],t[10]=.5*t[10]+.5*t[11],t[14]=.5*t[14]+.5*t[15]}function oT(e){let t=e.elements;t[11]===-1?(t[10]=-t[10]-1,t[14]=-t[14]):(t[10]=-t[10],t[14]=-t[14]+1)}var Lx=new si().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),kx=new si().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function lT(){let e={enabled:!0,workingColorSpace:kn,spaces:{},convert:function(n,s,a){return this.enabled===!1||s===a||!s||!a||(this.spaces[s].transfer===Ii&&(n.r=Ca(n.r),n.g=Ca(n.g),n.b=Ca(n.b)),this.spaces[s].primaries!==this.spaces[a].primaries&&(n.applyMatrix3(this.spaces[s].toXYZ),n.applyMatrix3(this.spaces[a].fromXYZ)),this.spaces[a].transfer===Ii&&(n.r=Kl(n.r),n.g=Kl(n.g),n.b=Kl(n.b))),n},fromWorkingColorSpace:function(n,s){return this.convert(n,this.workingColorSpace,s)},toWorkingColorSpace:function(n,s){return this.convert(n,s,this.workingColorSpace)},getPrimaries:function(n){return this.spaces[n].primaries},getTransfer:function(n){return n===Ta?Ih:this.spaces[n].transfer},getLuminanceCoefficients:function(n,s=this.workingColorSpace){return n.fromArray(this.spaces[s].luminanceCoefficients)},define:function(n){Object.assign(this.spaces,n)},_getMatrix:function(n,s,a){return n.copy(this.spaces[s].toXYZ).multiply(this.spaces[a].fromXYZ)},_getDrawingBufferColorSpace:function(n){return this.spaces[n].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(n=this.workingColorSpace){return this.spaces[n].workingColorSpaceConfig.unpackColorSpace}},t=[.64,.33,.3,.6,.15,.06],r=[.2126,.7152,.0722],i=[.3127,.329];return e.define({[kn]:{primaries:t,whitePoint:i,transfer:Ih,toXYZ:Lx,fromXYZ:kx,luminanceCoefficients:r,workingColorSpaceConfig:{unpackColorSpace:xi},outputColorSpaceConfig:{drawingBufferColorSpace:xi}},[xi]:{primaries:t,whitePoint:i,transfer:Ii,toXYZ:Lx,fromXYZ:kx,luminanceCoefficients:r,outputColorSpaceConfig:{drawingBufferColorSpace:xi}}}),e}var li=lT();function Ca(e){return e<.04045?e*.0773993808:Math.pow(e*.9478672986+.0521327014,2.4)}function Kl(e){return e<.0031308?e*12.92:1.055*Math.pow(e,.41666)-.055}var Zl,Ox=class{static getDataURL(e){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let t;if(e instanceof HTMLCanvasElement)t=e;else{Zl===void 0&&(Zl=Oh("canvas")),Zl.width=e.width,Zl.height=e.height;let r=Zl.getContext("2d");e instanceof ImageData?r.putImageData(e,0,0):r.drawImage(e,0,0,e.width,e.height),t=Zl}return t.width>2048||t.height>2048?(console.warn("THREE.ImageUtils.getDataURL: Image converted to jpg for performance reasons",e),t.toDataURL("image/jpeg",.6)):t.toDataURL("image/png")}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){let t=Oh("canvas");t.width=e.width,t.height=e.height;let r=t.getContext("2d");r.drawImage(e,0,0,e.width,e.height);let i=r.getImageData(0,0,e.width,e.height),n=i.data;for(let s=0;s<n.length;s++)n[s]=Ca(n[s]/255)*255;return r.putImageData(i,0,0),t}else if(e.data){let t=e.data.slice(0);for(let r=0;r<t.length;r++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[r]=Math.floor(Ca(t[r]/255)*255):t[r]=Ca(t[r]);return{data:t,width:e.width,height:e.height}}else return console.warn("THREE.ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}},cT=0,Vo=class{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:cT++}),this.uuid=fs(),this.data=e,this.dataReady=!0,this.version=0}set needsUpdate(e){e===!0&&this.version++}toJSON(e){let t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];let r={uuid:this.uuid,url:""},i=this.data;if(i!==null){let n;if(Array.isArray(i)){n=[];for(let s=0,a=i.length;s<a;s++)i[s].isDataTexture?n.push(dg(i[s].image)):n.push(dg(i[s]))}else n=dg(i);r.url=n}return t||(e.images[this.uuid]=r),r}};function dg(e){return typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap?Ox.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(console.warn("THREE.Texture: Unable to serialize Texture."),{})}var hT=0,Qi=class Nm extends ha{constructor(t=Nm.DEFAULT_IMAGE,r=Nm.DEFAULT_MAPPING,i=ei,n=ei,s=Pi,a=Fi,o=Ln,l=Ji,c=Nm.DEFAULT_ANISOTROPY,u=Ta){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:hT++}),this.uuid=fs(),this.name="",this.source=new Vo(t),this.mipmaps=[],this.mapping=r,this.channel=0,this.wrapS=i,this.wrapT=n,this.magFilter=s,this.minFilter=a,this.anisotropy=c,this.format=o,this.internalFormat=null,this.type=l,this.offset=new Ft(0,0),this.repeat=new Ft(1,1),this.center=new Ft(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new si,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=u,this.userData={},this.version=0,this.onUpdate=null,this.isRenderTargetTexture=!1,this.pmremVersion=0}get image(){return this.source.data}set image(t=null){this.source.data=t}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}clone(){return new this.constructor().copy(this)}copy(t){return this.name=t.name,this.source=t.source,this.mipmaps=t.mipmaps.slice(0),this.mapping=t.mapping,this.channel=t.channel,this.wrapS=t.wrapS,this.wrapT=t.wrapT,this.magFilter=t.magFilter,this.minFilter=t.minFilter,this.anisotropy=t.anisotropy,this.format=t.format,this.internalFormat=t.internalFormat,this.type=t.type,this.offset.copy(t.offset),this.repeat.copy(t.repeat),this.center.copy(t.center),this.rotation=t.rotation,this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrix.copy(t.matrix),this.generateMipmaps=t.generateMipmaps,this.premultiplyAlpha=t.premultiplyAlpha,this.flipY=t.flipY,this.unpackAlignment=t.unpackAlignment,this.colorSpace=t.colorSpace,this.userData=JSON.parse(JSON.stringify(t.userData)),this.needsUpdate=!0,this}toJSON(t){let r=t===void 0||typeof t=="string";if(!r&&t.textures[this.uuid]!==void 0)return t.textures[this.uuid];let i={metadata:{version:4.6,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(t).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(i.userData=this.userData),r||(t.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(t){if(this.mapping!==Rr)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case Wr:t.x=t.x-Math.floor(t.x);break;case ei:t.x=t.x<0?0:1;break;case Ri:Math.abs(Math.floor(t.x)%2)===1?t.x=Math.ceil(t.x)-t.x:t.x=t.x-Math.floor(t.x);break}if(t.y<0||t.y>1)switch(this.wrapT){case Wr:t.y=t.y-Math.floor(t.y);break;case ei:t.y=t.y<0?0:1;break;case Ri:Math.abs(Math.floor(t.y)%2)===1?t.y=Math.ceil(t.y)-t.y:t.y=t.y-Math.floor(t.y);break}return this.flipY&&(t.y=1-t.y),t}set needsUpdate(t){t===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(t){t===!0&&this.pmremVersion++}};Qi.DEFAULT_IMAGE=null,Qi.DEFAULT_MAPPING=Rr,Qi.DEFAULT_ANISOTROPY=1;var _i=class XS{constructor(t=0,r=0,i=0,n=1){XS.prototype.isVector4=!0,this.x=t,this.y=r,this.z=i,this.w=n}get width(){return this.z}set width(t){this.z=t}get height(){return this.w}set height(t){this.w=t}set(t,r,i,n){return this.x=t,this.y=r,this.z=i,this.w=n,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this.w=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setW(t){return this.w=t,this}setComponent(t,r){switch(t){case 0:this.x=r;break;case 1:this.y=r;break;case 2:this.z=r;break;case 3:this.w=r;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w!==void 0?t.w:1,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this.w+=t,this}addVectors(t,r){return this.x=t.x+r.x,this.y=t.y+r.y,this.z=t.z+r.z,this.w=t.w+r.w,this}addScaledVector(t,r){return this.x+=t.x*r,this.y+=t.y*r,this.z+=t.z*r,this.w+=t.w*r,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this.w-=t,this}subVectors(t,r){return this.x=t.x-r.x,this.y=t.y-r.y,this.z=t.z-r.z,this.w=t.w-r.w,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this}applyMatrix4(t){let r=this.x,i=this.y,n=this.z,s=this.w,a=t.elements;return this.x=a[0]*r+a[4]*i+a[8]*n+a[12]*s,this.y=a[1]*r+a[5]*i+a[9]*n+a[13]*s,this.z=a[2]*r+a[6]*i+a[10]*n+a[14]*s,this.w=a[3]*r+a[7]*i+a[11]*n+a[15]*s,this}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this.w/=t.w,this}divideScalar(t){return this.multiplyScalar(1/t)}setAxisAngleFromQuaternion(t){this.w=2*Math.acos(t.w);let r=Math.sqrt(1-t.w*t.w);return r<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=t.x/r,this.y=t.y/r,this.z=t.z/r),this}setAxisAngleFromRotationMatrix(t){let r,i,n,s,a=t.elements,o=a[0],l=a[4],c=a[8],u=a[1],d=a[5],f=a[9],y=a[2],b=a[6],x=a[10];if(Math.abs(l-u)<.01&&Math.abs(c-y)<.01&&Math.abs(f-b)<.01){if(Math.abs(l+u)<.1&&Math.abs(c+y)<.1&&Math.abs(f+b)<.1&&Math.abs(o+d+x-3)<.1)return this.set(1,0,0,0),this;r=Math.PI;let v=(o+1)/2,_=(d+1)/2,E=(x+1)/2,M=(l+u)/4,P=(c+y)/4,k=(f+b)/4;return v>_&&v>E?v<.01?(i=0,n=.707106781,s=.707106781):(i=Math.sqrt(v),n=M/i,s=P/i):_>E?_<.01?(i=.707106781,n=0,s=.707106781):(n=Math.sqrt(_),i=M/n,s=k/n):E<.01?(i=.707106781,n=.707106781,s=0):(s=Math.sqrt(E),i=P/s,n=k/s),this.set(i,n,s,r),this}let g=Math.sqrt((b-f)*(b-f)+(c-y)*(c-y)+(u-l)*(u-l));return Math.abs(g)<.001&&(g=1),this.x=(b-f)/g,this.y=(c-y)/g,this.z=(u-l)/g,this.w=Math.acos((o+d+x-1)/2),this}setFromMatrixPosition(t){let r=t.elements;return this.x=r[12],this.y=r[13],this.z=r[14],this.w=r[15],this}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this.w=Math.min(this.w,t.w),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this.w=Math.max(this.w,t.w),this}clamp(t,r){return this.x=Jr(this.x,t.x,r.x),this.y=Jr(this.y,t.y,r.y),this.z=Jr(this.z,t.z,r.z),this.w=Jr(this.w,t.w,r.w),this}clampScalar(t,r){return this.x=Jr(this.x,t,r),this.y=Jr(this.y,t,r),this.z=Jr(this.z,t,r),this.w=Jr(this.w,t,r),this}clampLength(t,r){let i=this.length();return this.divideScalar(i||1).multiplyScalar(Jr(i,t,r))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z+this.w*t.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,r){return this.x+=(t.x-this.x)*r,this.y+=(t.y-this.y)*r,this.z+=(t.z-this.z)*r,this.w+=(t.w-this.w)*r,this}lerpVectors(t,r,i){return this.x=t.x+(r.x-t.x)*i,this.y=t.y+(r.y-t.y)*i,this.z=t.z+(r.z-t.z)*i,this.w=t.w+(r.w-t.w)*i,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z&&t.w===this.w}fromArray(t,r=0){return this.x=t[r],this.y=t[r+1],this.z=t[r+2],this.w=t[r+3],this}toArray(t=[],r=0){return t[r]=this.x,t[r+1]=this.y,t[r+2]=this.z,t[r+3]=this.w,t}fromBufferAttribute(t,r){return this.x=t.getX(r),this.y=t.getY(r),this.z=t.getZ(r),this.w=t.getW(r),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}},Dx=class extends ha{constructor(e=1,t=1,r={}){super(),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=1,this.scissor=new _i(0,0,e,t),this.scissorTest=!1,this.viewport=new _i(0,0,e,t);let i={width:e,height:t,depth:1};r=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Pi,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1},r);let n=new Qi(i,r.mapping,r.wrapS,r.wrapT,r.magFilter,r.minFilter,r.format,r.type,r.anisotropy,r.colorSpace);n.flipY=!1,n.generateMipmaps=r.generateMipmaps,n.internalFormat=r.internalFormat,this.textures=[];let s=r.count;for(let a=0;a<s;a++)this.textures[a]=n.clone(),this.textures[a].isRenderTargetTexture=!0;this.depthBuffer=r.depthBuffer,this.stencilBuffer=r.stencilBuffer,this.resolveDepthBuffer=r.resolveDepthBuffer,this.resolveStencilBuffer=r.resolveStencilBuffer,this.depthTexture=r.depthTexture,this.samples=r.samples}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}setSize(e,t,r=1){if(this.width!==e||this.height!==t||this.depth!==r){this.width=e,this.height=t,this.depth=r;for(let i=0,n=this.textures.length;i<n;i++)this.textures[i].image.width=e,this.textures[i].image.height=t,this.textures[i].image.depth=r;this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let r=0,i=e.textures.length;r<i;r++)this.textures[r]=e.textures[r].clone(),this.textures[r].isRenderTargetTexture=!0;let t=Object.assign({},e.texture.image);return this.texture.source=new Vo(t),this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,e.depthTexture!==null&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}},In=class extends Dx{constructor(e=1,t=1,r={}){super(e,t,r),this.isWebGLRenderTarget=!0}},Jd=class extends Qi{constructor(e=null,t=1,r=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:r,depth:i},this.magFilter=oi,this.minFilter=oi,this.wrapR=ei,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},uT=class extends In{constructor(e=1,t=1,r=1,i={}){super(e,t,i),this.isWebGLArrayRenderTarget=!0,this.depth=r,this.texture=new Jd(null,e,t,r),this.texture.isRenderTargetTexture=!0}},pg=class extends Qi{constructor(e=null,t=1,r=1,i=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:r,depth:i},this.magFilter=oi,this.minFilter=oi,this.wrapR=ei,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},dT=class extends In{constructor(e=1,t=1,r=1,i={}){super(e,t,i),this.isWebGL3DRenderTarget=!0,this.depth=r,this.texture=new pg(null,e,t,r),this.texture.isRenderTargetTexture=!0}},pn=class{constructor(e=0,t=0,r=0,i=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=r,this._w=i}static slerpFlat(e,t,r,i,n,s,a){let o=r[i+0],l=r[i+1],c=r[i+2],u=r[i+3],d=n[s+0],f=n[s+1],y=n[s+2],b=n[s+3];if(a===0){e[t+0]=o,e[t+1]=l,e[t+2]=c,e[t+3]=u;return}if(a===1){e[t+0]=d,e[t+1]=f,e[t+2]=y,e[t+3]=b;return}if(u!==b||o!==d||l!==f||c!==y){let x=1-a,g=o*d+l*f+c*y+u*b,v=g>=0?1:-1,_=1-g*g;if(_>Number.EPSILON){let M=Math.sqrt(_),P=Math.atan2(M,g*v);x=Math.sin(x*P)/M,a=Math.sin(a*P)/M}let E=a*v;if(o=o*x+d*E,l=l*x+f*E,c=c*x+y*E,u=u*x+b*E,x===1-a){let M=1/Math.sqrt(o*o+l*l+c*c+u*u);o*=M,l*=M,c*=M,u*=M}}e[t]=o,e[t+1]=l,e[t+2]=c,e[t+3]=u}static multiplyQuaternionsFlat(e,t,r,i,n,s){let a=r[i],o=r[i+1],l=r[i+2],c=r[i+3],u=n[s],d=n[s+1],f=n[s+2],y=n[s+3];return e[t]=a*y+c*u+o*f-l*d,e[t+1]=o*y+c*d+l*u-a*f,e[t+2]=l*y+c*f+a*d-o*u,e[t+3]=c*y-a*u-o*d-l*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,r,i){return this._x=e,this._y=t,this._z=r,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){let r=e._x,i=e._y,n=e._z,s=e._order,a=Math.cos,o=Math.sin,l=a(r/2),c=a(i/2),u=a(n/2),d=o(r/2),f=o(i/2),y=o(n/2);switch(s){case"XYZ":this._x=d*c*u+l*f*y,this._y=l*f*u-d*c*y,this._z=l*c*y+d*f*u,this._w=l*c*u-d*f*y;break;case"YXZ":this._x=d*c*u+l*f*y,this._y=l*f*u-d*c*y,this._z=l*c*y-d*f*u,this._w=l*c*u+d*f*y;break;case"ZXY":this._x=d*c*u-l*f*y,this._y=l*f*u+d*c*y,this._z=l*c*y+d*f*u,this._w=l*c*u-d*f*y;break;case"ZYX":this._x=d*c*u-l*f*y,this._y=l*f*u+d*c*y,this._z=l*c*y-d*f*u,this._w=l*c*u+d*f*y;break;case"YZX":this._x=d*c*u+l*f*y,this._y=l*f*u+d*c*y,this._z=l*c*y-d*f*u,this._w=l*c*u-d*f*y;break;case"XZY":this._x=d*c*u-l*f*y,this._y=l*f*u-d*c*y,this._z=l*c*y+d*f*u,this._w=l*c*u+d*f*y;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+s)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let r=t/2,i=Math.sin(r);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(r),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,r=t[0],i=t[4],n=t[8],s=t[1],a=t[5],o=t[9],l=t[2],c=t[6],u=t[10],d=r+a+u;if(d>0){let f=.5/Math.sqrt(d+1);this._w=.25/f,this._x=(c-o)*f,this._y=(n-l)*f,this._z=(s-i)*f}else if(r>a&&r>u){let f=2*Math.sqrt(1+r-a-u);this._w=(c-o)/f,this._x=.25*f,this._y=(i+s)/f,this._z=(n+l)/f}else if(a>u){let f=2*Math.sqrt(1+a-r-u);this._w=(n-l)/f,this._x=(i+s)/f,this._y=.25*f,this._z=(o+c)/f}else{let f=2*Math.sqrt(1+u-r-a);this._w=(s-i)/f,this._x=(n+l)/f,this._y=(o+c)/f,this._z=.25*f}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let r=e.dot(t)+1;return r<Number.EPSILON?(r=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=r):(this._x=0,this._y=-e.z,this._z=e.y,this._w=r)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=r),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Jr(this.dot(e),-1,1)))}rotateTowards(e,t){let r=this.angleTo(e);if(r===0)return this;let i=Math.min(1,t/r);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let r=e._x,i=e._y,n=e._z,s=e._w,a=t._x,o=t._y,l=t._z,c=t._w;return this._x=r*c+s*a+i*l-n*o,this._y=i*c+s*o+n*a-r*l,this._z=n*c+s*l+r*o-i*a,this._w=s*c-r*a-i*o-n*l,this._onChangeCallback(),this}slerp(e,t){if(t===0)return this;if(t===1)return this.copy(e);let r=this._x,i=this._y,n=this._z,s=this._w,a=s*e._w+r*e._x+i*e._y+n*e._z;if(a<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,a=-a):this.copy(e),a>=1)return this._w=s,this._x=r,this._y=i,this._z=n,this;let o=1-a*a;if(o<=Number.EPSILON){let f=1-t;return this._w=f*s+t*this._w,this._x=f*r+t*this._x,this._y=f*i+t*this._y,this._z=f*n+t*this._z,this.normalize(),this}let l=Math.sqrt(o),c=Math.atan2(l,a),u=Math.sin((1-t)*c)/l,d=Math.sin(t*c)/l;return this._w=s*u+this._w*d,this._x=r*u+this._x*d,this._y=i*u+this._y*d,this._z=n*u+this._z*d,this._onChangeCallback(),this}slerpQuaternions(e,t,r){return this.copy(e).slerp(t,r)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),r=Math.random(),i=Math.sqrt(1-r),n=Math.sqrt(r);return this.set(i*Math.sin(e),i*Math.cos(e),n*Math.sin(t),n*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},je=class YS{constructor(t=0,r=0,i=0){YS.prototype.isVector3=!0,this.x=t,this.y=r,this.z=i}set(t,r,i){return i===void 0&&(i=this.z),this.x=t,this.y=r,this.z=i,this}setScalar(t){return this.x=t,this.y=t,this.z=t,this}setX(t){return this.x=t,this}setY(t){return this.y=t,this}setZ(t){return this.z=t,this}setComponent(t,r){switch(t){case 0:this.x=r;break;case 1:this.y=r;break;case 2:this.z=r;break;default:throw new Error("index is out of range: "+t)}return this}getComponent(t){switch(t){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+t)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(t){return this.x=t.x,this.y=t.y,this.z=t.z,this}add(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this}addScalar(t){return this.x+=t,this.y+=t,this.z+=t,this}addVectors(t,r){return this.x=t.x+r.x,this.y=t.y+r.y,this.z=t.z+r.z,this}addScaledVector(t,r){return this.x+=t.x*r,this.y+=t.y*r,this.z+=t.z*r,this}sub(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this}subScalar(t){return this.x-=t,this.y-=t,this.z-=t,this}subVectors(t,r){return this.x=t.x-r.x,this.y=t.y-r.y,this.z=t.z-r.z,this}multiply(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this}multiplyScalar(t){return this.x*=t,this.y*=t,this.z*=t,this}multiplyVectors(t,r){return this.x=t.x*r.x,this.y=t.y*r.y,this.z=t.z*r.z,this}applyEuler(t){return this.applyQuaternion(Ux.setFromEuler(t))}applyAxisAngle(t,r){return this.applyQuaternion(Ux.setFromAxisAngle(t,r))}applyMatrix3(t){let r=this.x,i=this.y,n=this.z,s=t.elements;return this.x=s[0]*r+s[3]*i+s[6]*n,this.y=s[1]*r+s[4]*i+s[7]*n,this.z=s[2]*r+s[5]*i+s[8]*n,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){let r=this.x,i=this.y,n=this.z,s=t.elements,a=1/(s[3]*r+s[7]*i+s[11]*n+s[15]);return this.x=(s[0]*r+s[4]*i+s[8]*n+s[12])*a,this.y=(s[1]*r+s[5]*i+s[9]*n+s[13])*a,this.z=(s[2]*r+s[6]*i+s[10]*n+s[14])*a,this}applyQuaternion(t){let r=this.x,i=this.y,n=this.z,s=t.x,a=t.y,o=t.z,l=t.w,c=2*(a*n-o*i),u=2*(o*r-s*n),d=2*(s*i-a*r);return this.x=r+l*c+a*d-o*u,this.y=i+l*u+o*c-s*d,this.z=n+l*d+s*u-a*c,this}project(t){return this.applyMatrix4(t.matrixWorldInverse).applyMatrix4(t.projectionMatrix)}unproject(t){return this.applyMatrix4(t.projectionMatrixInverse).applyMatrix4(t.matrixWorld)}transformDirection(t){let r=this.x,i=this.y,n=this.z,s=t.elements;return this.x=s[0]*r+s[4]*i+s[8]*n,this.y=s[1]*r+s[5]*i+s[9]*n,this.z=s[2]*r+s[6]*i+s[10]*n,this.normalize()}divide(t){return this.x/=t.x,this.y/=t.y,this.z/=t.z,this}divideScalar(t){return this.multiplyScalar(1/t)}min(t){return this.x=Math.min(this.x,t.x),this.y=Math.min(this.y,t.y),this.z=Math.min(this.z,t.z),this}max(t){return this.x=Math.max(this.x,t.x),this.y=Math.max(this.y,t.y),this.z=Math.max(this.z,t.z),this}clamp(t,r){return this.x=Jr(this.x,t.x,r.x),this.y=Jr(this.y,t.y,r.y),this.z=Jr(this.z,t.z,r.z),this}clampScalar(t,r){return this.x=Jr(this.x,t,r),this.y=Jr(this.y,t,r),this.z=Jr(this.z,t,r),this}clampLength(t,r){let i=this.length();return this.divideScalar(i||1).multiplyScalar(Jr(i,t,r))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(t){return this.x*t.x+this.y*t.y+this.z*t.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(t){return this.normalize().multiplyScalar(t)}lerp(t,r){return this.x+=(t.x-this.x)*r,this.y+=(t.y-this.y)*r,this.z+=(t.z-this.z)*r,this}lerpVectors(t,r,i){return this.x=t.x+(r.x-t.x)*i,this.y=t.y+(r.y-t.y)*i,this.z=t.z+(r.z-t.z)*i,this}cross(t){return this.crossVectors(this,t)}crossVectors(t,r){let i=t.x,n=t.y,s=t.z,a=r.x,o=r.y,l=r.z;return this.x=n*l-s*o,this.y=s*a-i*l,this.z=i*o-n*a,this}projectOnVector(t){let r=t.lengthSq();if(r===0)return this.set(0,0,0);let i=t.dot(this)/r;return this.copy(t).multiplyScalar(i)}projectOnPlane(t){return fg.copy(this).projectOnVector(t),this.sub(fg)}reflect(t){return this.sub(fg.copy(t).multiplyScalar(2*this.dot(t)))}angleTo(t){let r=Math.sqrt(this.lengthSq()*t.lengthSq());if(r===0)return Math.PI/2;let i=this.dot(t)/r;return Math.acos(Jr(i,-1,1))}distanceTo(t){return Math.sqrt(this.distanceToSquared(t))}distanceToSquared(t){let r=this.x-t.x,i=this.y-t.y,n=this.z-t.z;return r*r+i*i+n*n}manhattanDistanceTo(t){return Math.abs(this.x-t.x)+Math.abs(this.y-t.y)+Math.abs(this.z-t.z)}setFromSpherical(t){return this.setFromSphericalCoords(t.radius,t.phi,t.theta)}setFromSphericalCoords(t,r,i){let n=Math.sin(r)*t;return this.x=n*Math.sin(i),this.y=Math.cos(r)*t,this.z=n*Math.cos(i),this}setFromCylindrical(t){return this.setFromCylindricalCoords(t.radius,t.theta,t.y)}setFromCylindricalCoords(t,r,i){return this.x=t*Math.sin(r),this.y=i,this.z=t*Math.cos(r),this}setFromMatrixPosition(t){let r=t.elements;return this.x=r[12],this.y=r[13],this.z=r[14],this}setFromMatrixScale(t){let r=this.setFromMatrixColumn(t,0).length(),i=this.setFromMatrixColumn(t,1).length(),n=this.setFromMatrixColumn(t,2).length();return this.x=r,this.y=i,this.z=n,this}setFromMatrixColumn(t,r){return this.fromArray(t.elements,r*4)}setFromMatrix3Column(t,r){return this.fromArray(t.elements,r*3)}setFromEuler(t){return this.x=t._x,this.y=t._y,this.z=t._z,this}setFromColor(t){return this.x=t.r,this.y=t.g,this.z=t.b,this}equals(t){return t.x===this.x&&t.y===this.y&&t.z===this.z}fromArray(t,r=0){return this.x=t[r],this.y=t[r+1],this.z=t[r+2],this}toArray(t=[],r=0){return t[r]=this.x,t[r+1]=this.y,t[r+2]=this.z,t}fromBufferAttribute(t,r){return this.x=t.getX(r),this.y=t.getY(r),this.z=t.getZ(r),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let t=Math.random()*Math.PI*2,r=Math.random()*2-1,i=Math.sqrt(1-r*r);return this.x=i*Math.cos(t),this.y=r,this.z=i*Math.sin(t),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}},fg=new je,Ux=new pn,Xi=class{constructor(e=new je(1/0,1/0,1/0),t=new je(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,r=e.length;t<r;t+=3)this.expandByPoint(Ws.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,r=e.count;t<r;t++)this.expandByPoint(Ws.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,r=e.length;t<r;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){let r=Ws.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(r),this.max.copy(e).add(r),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);let r=e.geometry;if(r!==void 0){let n=r.getAttribute("position");if(t===!0&&n!==void 0&&e.isInstancedMesh!==!0)for(let s=0,a=n.count;s<a;s++)e.isMesh===!0?e.getVertexPosition(s,Ws):Ws.fromBufferAttribute(n,s),Ws.applyMatrix4(e.matrixWorld),this.expandByPoint(Ws);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),Qd.copy(e.boundingBox)):(r.boundingBox===null&&r.computeBoundingBox(),Qd.copy(r.boundingBox)),Qd.applyMatrix4(e.matrixWorld),this.union(Qd)}let i=e.children;for(let n=0,s=i.length;n<s;n++)this.expandByObject(i[n],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Ws),Ws.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,r;return e.normal.x>0?(t=e.normal.x*this.min.x,r=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,r=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,r+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,r+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,r+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,r+=e.normal.z*this.min.z),t<=-e.constant&&r>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Dh),ep.subVectors(this.max,Dh),$l.subVectors(e.a,Dh),Jl.subVectors(e.b,Dh),Ql.subVectors(e.c,Dh),ao.subVectors(Jl,$l),oo.subVectors(Ql,Jl),Ho.subVectors($l,Ql);let t=[0,-ao.z,ao.y,0,-oo.z,oo.y,0,-Ho.z,Ho.y,ao.z,0,-ao.x,oo.z,0,-oo.x,Ho.z,0,-Ho.x,-ao.y,ao.x,0,-oo.y,oo.x,0,-Ho.y,Ho.x,0];return!mg(t,$l,Jl,Ql,ep)||(t=[1,0,0,0,1,0,0,0,1],!mg(t,$l,Jl,Ql,ep))?!1:(tp.crossVectors(ao,oo),t=[tp.x,tp.y,tp.z],mg(t,$l,Jl,Ql,ep))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Ws).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Ws).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(Ra[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Ra[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Ra[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Ra[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Ra[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Ra[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Ra[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Ra[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Ra),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}},Ra=[new je,new je,new je,new je,new je,new je,new je,new je],Ws=new je,Qd=new Xi,$l=new je,Jl=new je,Ql=new je,ao=new je,oo=new je,Ho=new je,Dh=new je,ep=new je,tp=new je,Go=new je;function mg(e,t,r,i,n){for(let s=0,a=e.length-3;s<=a;s+=3){Go.fromArray(e,s);let o=n.x*Math.abs(Go.x)+n.y*Math.abs(Go.y)+n.z*Math.abs(Go.z),l=t.dot(Go),c=r.dot(Go),u=i.dot(Go);if(Math.max(-Math.max(l,c,u),Math.min(l,c,u))>o)return!1}return!0}var pT=new Xi,Uh=new je,gg=new je,on=class{constructor(e=new je,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){let r=this.center;t!==void 0?r.copy(t):pT.setFromPoints(e).getCenter(r);let i=0;for(let n=0,s=e.length;n<s;n++)i=Math.max(i,r.distanceToSquared(e[n]));return this.radius=Math.sqrt(i),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){let t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){let r=this.center.distanceToSquared(e);return t.copy(e),r>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Uh.subVectors(e,this.center);let t=Uh.lengthSq();if(t>this.radius*this.radius){let r=Math.sqrt(t),i=(r-this.radius)*.5;this.center.addScaledVector(Uh,i/r),this.radius+=i}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(gg.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Uh.copy(e.center).add(gg)),this.expandByPoint(Uh.copy(e.center).sub(gg))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}},Pa=new je,yg=new je,rp=new je,lo=new je,vg=new je,ip=new je,xg=new je,Wo=class{constructor(e=new je,t=new je(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,Pa)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);let r=t.dot(this.direction);return r<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,r)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){let t=Pa.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Pa.copy(this.origin).addScaledVector(this.direction,t),Pa.distanceToSquared(e))}distanceSqToSegment(e,t,r,i){yg.copy(e).add(t).multiplyScalar(.5),rp.copy(t).sub(e).normalize(),lo.copy(this.origin).sub(yg);let n=e.distanceTo(t)*.5,s=-this.direction.dot(rp),a=lo.dot(this.direction),o=-lo.dot(rp),l=lo.lengthSq(),c=Math.abs(1-s*s),u,d,f,y;if(c>0)if(u=s*o-a,d=s*a-o,y=n*c,u>=0)if(d>=-y)if(d<=y){let b=1/c;u*=b,d*=b,f=u*(u+s*d+2*a)+d*(s*u+d+2*o)+l}else d=n,u=Math.max(0,-(s*d+a)),f=-u*u+d*(d+2*o)+l;else d=-n,u=Math.max(0,-(s*d+a)),f=-u*u+d*(d+2*o)+l;else d<=-y?(u=Math.max(0,-(-s*n+a)),d=u>0?-n:Math.min(Math.max(-n,-o),n),f=-u*u+d*(d+2*o)+l):d<=y?(u=0,d=Math.min(Math.max(-n,-o),n),f=d*(d+2*o)+l):(u=Math.max(0,-(s*n+a)),d=u>0?n:Math.min(Math.max(-n,-o),n),f=-u*u+d*(d+2*o)+l);else d=s>0?-n:n,u=Math.max(0,-(s*d+a)),f=-u*u+d*(d+2*o)+l;return r&&r.copy(this.origin).addScaledVector(this.direction,u),i&&i.copy(yg).addScaledVector(rp,d),f}intersectSphere(e,t){Pa.subVectors(e.center,this.origin);let r=Pa.dot(this.direction),i=Pa.dot(Pa)-r*r,n=e.radius*e.radius;if(i>n)return null;let s=Math.sqrt(n-i),a=r-s,o=r+s;return o<0?null:a<0?this.at(o,t):this.at(a,t)}intersectsSphere(e){return this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let r=-(this.origin.dot(e.normal)+e.constant)/t;return r>=0?r:null}intersectPlane(e,t){let r=this.distanceToPlane(e);return r===null?null:this.at(r,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let r,i,n,s,a,o,l=1/this.direction.x,c=1/this.direction.y,u=1/this.direction.z,d=this.origin;return l>=0?(r=(e.min.x-d.x)*l,i=(e.max.x-d.x)*l):(r=(e.max.x-d.x)*l,i=(e.min.x-d.x)*l),c>=0?(n=(e.min.y-d.y)*c,s=(e.max.y-d.y)*c):(n=(e.max.y-d.y)*c,s=(e.min.y-d.y)*c),r>s||n>i||((n>r||isNaN(r))&&(r=n),(s<i||isNaN(i))&&(i=s),u>=0?(a=(e.min.z-d.z)*u,o=(e.max.z-d.z)*u):(a=(e.max.z-d.z)*u,o=(e.min.z-d.z)*u),r>o||a>i)||((a>r||r!==r)&&(r=a),(o<i||i!==i)&&(i=o),i<0)?null:this.at(r>=0?r:i,t)}intersectsBox(e){return this.intersectBox(e,Pa)!==null}intersectTriangle(e,t,r,i,n){vg.subVectors(t,e),ip.subVectors(r,e),xg.crossVectors(vg,ip);let s=this.direction.dot(xg),a;if(s>0){if(i)return null;a=1}else if(s<0)a=-1,s=-s;else return null;lo.subVectors(this.origin,e);let o=a*this.direction.dot(ip.crossVectors(lo,ip));if(o<0)return null;let l=a*this.direction.dot(vg.cross(lo));if(l<0||o+l>s)return null;let c=-a*lo.dot(xg);return c<0?null:this.at(c/s,n)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},Ir=class Mv{constructor(t,r,i,n,s,a,o,l,c,u,d,f,y,b,x,g){Mv.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],t!==void 0&&this.set(t,r,i,n,s,a,o,l,c,u,d,f,y,b,x,g)}set(t,r,i,n,s,a,o,l,c,u,d,f,y,b,x,g){let v=this.elements;return v[0]=t,v[4]=r,v[8]=i,v[12]=n,v[1]=s,v[5]=a,v[9]=o,v[13]=l,v[2]=c,v[6]=u,v[10]=d,v[14]=f,v[3]=y,v[7]=b,v[11]=x,v[15]=g,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new Mv().fromArray(this.elements)}copy(t){let r=this.elements,i=t.elements;return r[0]=i[0],r[1]=i[1],r[2]=i[2],r[3]=i[3],r[4]=i[4],r[5]=i[5],r[6]=i[6],r[7]=i[7],r[8]=i[8],r[9]=i[9],r[10]=i[10],r[11]=i[11],r[12]=i[12],r[13]=i[13],r[14]=i[14],r[15]=i[15],this}copyPosition(t){let r=this.elements,i=t.elements;return r[12]=i[12],r[13]=i[13],r[14]=i[14],this}setFromMatrix3(t){let r=t.elements;return this.set(r[0],r[3],r[6],0,r[1],r[4],r[7],0,r[2],r[5],r[8],0,0,0,0,1),this}extractBasis(t,r,i){return t.setFromMatrixColumn(this,0),r.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this}makeBasis(t,r,i){return this.set(t.x,r.x,i.x,0,t.y,r.y,i.y,0,t.z,r.z,i.z,0,0,0,0,1),this}extractRotation(t){let r=this.elements,i=t.elements,n=1/ec.setFromMatrixColumn(t,0).length(),s=1/ec.setFromMatrixColumn(t,1).length(),a=1/ec.setFromMatrixColumn(t,2).length();return r[0]=i[0]*n,r[1]=i[1]*n,r[2]=i[2]*n,r[3]=0,r[4]=i[4]*s,r[5]=i[5]*s,r[6]=i[6]*s,r[7]=0,r[8]=i[8]*a,r[9]=i[9]*a,r[10]=i[10]*a,r[11]=0,r[12]=0,r[13]=0,r[14]=0,r[15]=1,this}makeRotationFromEuler(t){let r=this.elements,i=t.x,n=t.y,s=t.z,a=Math.cos(i),o=Math.sin(i),l=Math.cos(n),c=Math.sin(n),u=Math.cos(s),d=Math.sin(s);if(t.order==="XYZ"){let f=a*u,y=a*d,b=o*u,x=o*d;r[0]=l*u,r[4]=-l*d,r[8]=c,r[1]=y+b*c,r[5]=f-x*c,r[9]=-o*l,r[2]=x-f*c,r[6]=b+y*c,r[10]=a*l}else if(t.order==="YXZ"){let f=l*u,y=l*d,b=c*u,x=c*d;r[0]=f+x*o,r[4]=b*o-y,r[8]=a*c,r[1]=a*d,r[5]=a*u,r[9]=-o,r[2]=y*o-b,r[6]=x+f*o,r[10]=a*l}else if(t.order==="ZXY"){let f=l*u,y=l*d,b=c*u,x=c*d;r[0]=f-x*o,r[4]=-a*d,r[8]=b+y*o,r[1]=y+b*o,r[5]=a*u,r[9]=x-f*o,r[2]=-a*c,r[6]=o,r[10]=a*l}else if(t.order==="ZYX"){let f=a*u,y=a*d,b=o*u,x=o*d;r[0]=l*u,r[4]=b*c-y,r[8]=f*c+x,r[1]=l*d,r[5]=x*c+f,r[9]=y*c-b,r[2]=-c,r[6]=o*l,r[10]=a*l}else if(t.order==="YZX"){let f=a*l,y=a*c,b=o*l,x=o*c;r[0]=l*u,r[4]=x-f*d,r[8]=b*d+y,r[1]=d,r[5]=a*u,r[9]=-o*u,r[2]=-c*u,r[6]=y*d+b,r[10]=f-x*d}else if(t.order==="XZY"){let f=a*l,y=a*c,b=o*l,x=o*c;r[0]=l*u,r[4]=-d,r[8]=c*u,r[1]=f*d+x,r[5]=a*u,r[9]=y*d-b,r[2]=b*d-y,r[6]=o*u,r[10]=x*d+f}return r[3]=0,r[7]=0,r[11]=0,r[12]=0,r[13]=0,r[14]=0,r[15]=1,this}makeRotationFromQuaternion(t){return this.compose(fT,t,mT)}lookAt(t,r,i){let n=this.elements;return ms.subVectors(t,r),ms.lengthSq()===0&&(ms.z=1),ms.normalize(),co.crossVectors(i,ms),co.lengthSq()===0&&(Math.abs(i.z)===1?ms.x+=1e-4:ms.z+=1e-4,ms.normalize(),co.crossVectors(i,ms)),co.normalize(),np.crossVectors(ms,co),n[0]=co.x,n[4]=np.x,n[8]=ms.x,n[1]=co.y,n[5]=np.y,n[9]=ms.y,n[2]=co.z,n[6]=np.z,n[10]=ms.z,this}multiply(t){return this.multiplyMatrices(this,t)}premultiply(t){return this.multiplyMatrices(t,this)}multiplyMatrices(t,r){let i=t.elements,n=r.elements,s=this.elements,a=i[0],o=i[4],l=i[8],c=i[12],u=i[1],d=i[5],f=i[9],y=i[13],b=i[2],x=i[6],g=i[10],v=i[14],_=i[3],E=i[7],M=i[11],P=i[15],k=n[0],z=n[4],D=n[8],I=n[12],L=n[1],Z=n[5],se=n[9],ce=n[13],fe=n[2],ze=n[6],Fe=n[10],Pe=n[14],ue=n[3],Te=n[7],de=n[11],Ie=n[15];return s[0]=a*k+o*L+l*fe+c*ue,s[4]=a*z+o*Z+l*ze+c*Te,s[8]=a*D+o*se+l*Fe+c*de,s[12]=a*I+o*ce+l*Pe+c*Ie,s[1]=u*k+d*L+f*fe+y*ue,s[5]=u*z+d*Z+f*ze+y*Te,s[9]=u*D+d*se+f*Fe+y*de,s[13]=u*I+d*ce+f*Pe+y*Ie,s[2]=b*k+x*L+g*fe+v*ue,s[6]=b*z+x*Z+g*ze+v*Te,s[10]=b*D+x*se+g*Fe+v*de,s[14]=b*I+x*ce+g*Pe+v*Ie,s[3]=_*k+E*L+M*fe+P*ue,s[7]=_*z+E*Z+M*ze+P*Te,s[11]=_*D+E*se+M*Fe+P*de,s[15]=_*I+E*ce+M*Pe+P*Ie,this}multiplyScalar(t){let r=this.elements;return r[0]*=t,r[4]*=t,r[8]*=t,r[12]*=t,r[1]*=t,r[5]*=t,r[9]*=t,r[13]*=t,r[2]*=t,r[6]*=t,r[10]*=t,r[14]*=t,r[3]*=t,r[7]*=t,r[11]*=t,r[15]*=t,this}determinant(){let t=this.elements,r=t[0],i=t[4],n=t[8],s=t[12],a=t[1],o=t[5],l=t[9],c=t[13],u=t[2],d=t[6],f=t[10],y=t[14],b=t[3],x=t[7],g=t[11],v=t[15];return b*(+s*l*d-n*c*d-s*o*f+i*c*f+n*o*y-i*l*y)+x*(+r*l*y-r*c*f+s*a*f-n*a*y+n*c*u-s*l*u)+g*(+r*c*d-r*o*y-s*a*d+i*a*y+s*o*u-i*c*u)+v*(-n*o*u-r*l*d+r*o*f+n*a*d-i*a*f+i*l*u)}transpose(){let t=this.elements,r;return r=t[1],t[1]=t[4],t[4]=r,r=t[2],t[2]=t[8],t[8]=r,r=t[6],t[6]=t[9],t[9]=r,r=t[3],t[3]=t[12],t[12]=r,r=t[7],t[7]=t[13],t[13]=r,r=t[11],t[11]=t[14],t[14]=r,this}setPosition(t,r,i){let n=this.elements;return t.isVector3?(n[12]=t.x,n[13]=t.y,n[14]=t.z):(n[12]=t,n[13]=r,n[14]=i),this}invert(){let t=this.elements,r=t[0],i=t[1],n=t[2],s=t[3],a=t[4],o=t[5],l=t[6],c=t[7],u=t[8],d=t[9],f=t[10],y=t[11],b=t[12],x=t[13],g=t[14],v=t[15],_=d*g*c-x*f*c+x*l*y-o*g*y-d*l*v+o*f*v,E=b*f*c-u*g*c-b*l*y+a*g*y+u*l*v-a*f*v,M=u*x*c-b*d*c+b*o*y-a*x*y-u*o*v+a*d*v,P=b*d*l-u*x*l-b*o*f+a*x*f+u*o*g-a*d*g,k=r*_+i*E+n*M+s*P;if(k===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let z=1/k;return t[0]=_*z,t[1]=(x*f*s-d*g*s-x*n*y+i*g*y+d*n*v-i*f*v)*z,t[2]=(o*g*s-x*l*s+x*n*c-i*g*c-o*n*v+i*l*v)*z,t[3]=(d*l*s-o*f*s-d*n*c+i*f*c+o*n*y-i*l*y)*z,t[4]=E*z,t[5]=(u*g*s-b*f*s+b*n*y-r*g*y-u*n*v+r*f*v)*z,t[6]=(b*l*s-a*g*s-b*n*c+r*g*c+a*n*v-r*l*v)*z,t[7]=(a*f*s-u*l*s+u*n*c-r*f*c-a*n*y+r*l*y)*z,t[8]=M*z,t[9]=(b*d*s-u*x*s-b*i*y+r*x*y+u*i*v-r*d*v)*z,t[10]=(a*x*s-b*o*s+b*i*c-r*x*c-a*i*v+r*o*v)*z,t[11]=(u*o*s-a*d*s-u*i*c+r*d*c+a*i*y-r*o*y)*z,t[12]=P*z,t[13]=(u*x*n-b*d*n+b*i*f-r*x*f-u*i*g+r*d*g)*z,t[14]=(b*o*n-a*x*n-b*i*l+r*x*l+a*i*g-r*o*g)*z,t[15]=(a*d*n-u*o*n+u*i*l-r*d*l-a*i*f+r*o*f)*z,this}scale(t){let r=this.elements,i=t.x,n=t.y,s=t.z;return r[0]*=i,r[4]*=n,r[8]*=s,r[1]*=i,r[5]*=n,r[9]*=s,r[2]*=i,r[6]*=n,r[10]*=s,r[3]*=i,r[7]*=n,r[11]*=s,this}getMaxScaleOnAxis(){let t=this.elements,r=t[0]*t[0]+t[1]*t[1]+t[2]*t[2],i=t[4]*t[4]+t[5]*t[5]+t[6]*t[6],n=t[8]*t[8]+t[9]*t[9]+t[10]*t[10];return Math.sqrt(Math.max(r,i,n))}makeTranslation(t,r,i){return t.isVector3?this.set(1,0,0,t.x,0,1,0,t.y,0,0,1,t.z,0,0,0,1):this.set(1,0,0,t,0,1,0,r,0,0,1,i,0,0,0,1),this}makeRotationX(t){let r=Math.cos(t),i=Math.sin(t);return this.set(1,0,0,0,0,r,-i,0,0,i,r,0,0,0,0,1),this}makeRotationY(t){let r=Math.cos(t),i=Math.sin(t);return this.set(r,0,i,0,0,1,0,0,-i,0,r,0,0,0,0,1),this}makeRotationZ(t){let r=Math.cos(t),i=Math.sin(t);return this.set(r,-i,0,0,i,r,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(t,r){let i=Math.cos(r),n=Math.sin(r),s=1-i,a=t.x,o=t.y,l=t.z,c=s*a,u=s*o;return this.set(c*a+i,c*o-n*l,c*l+n*o,0,c*o+n*l,u*o+i,u*l-n*a,0,c*l-n*o,u*l+n*a,s*l*l+i,0,0,0,0,1),this}makeScale(t,r,i){return this.set(t,0,0,0,0,r,0,0,0,0,i,0,0,0,0,1),this}makeShear(t,r,i,n,s,a){return this.set(1,i,s,0,t,1,a,0,r,n,1,0,0,0,0,1),this}compose(t,r,i){let n=this.elements,s=r._x,a=r._y,o=r._z,l=r._w,c=s+s,u=a+a,d=o+o,f=s*c,y=s*u,b=s*d,x=a*u,g=a*d,v=o*d,_=l*c,E=l*u,M=l*d,P=i.x,k=i.y,z=i.z;return n[0]=(1-(x+v))*P,n[1]=(y+M)*P,n[2]=(b-E)*P,n[3]=0,n[4]=(y-M)*k,n[5]=(1-(f+v))*k,n[6]=(g+_)*k,n[7]=0,n[8]=(b+E)*z,n[9]=(g-_)*z,n[10]=(1-(f+x))*z,n[11]=0,n[12]=t.x,n[13]=t.y,n[14]=t.z,n[15]=1,this}decompose(t,r,i){let n=this.elements,s=ec.set(n[0],n[1],n[2]).length(),a=ec.set(n[4],n[5],n[6]).length(),o=ec.set(n[8],n[9],n[10]).length();this.determinant()<0&&(s=-s),t.x=n[12],t.y=n[13],t.z=n[14],Xs.copy(this);let l=1/s,c=1/a,u=1/o;return Xs.elements[0]*=l,Xs.elements[1]*=l,Xs.elements[2]*=l,Xs.elements[4]*=c,Xs.elements[5]*=c,Xs.elements[6]*=c,Xs.elements[8]*=u,Xs.elements[9]*=u,Xs.elements[10]*=u,r.setFromRotationMatrix(Xs),i.x=s,i.y=a,i.z=o,this}makePerspective(t,r,i,n,s,a,o=ca){let l=this.elements,c=2*s/(r-t),u=2*s/(i-n),d=(r+t)/(r-t),f=(i+n)/(i-n),y,b;if(o===ca)y=-(a+s)/(a-s),b=-2*a*s/(a-s);else if(o===Lh)y=-a/(a-s),b=-a*s/(a-s);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return l[0]=c,l[4]=0,l[8]=d,l[12]=0,l[1]=0,l[5]=u,l[9]=f,l[13]=0,l[2]=0,l[6]=0,l[10]=y,l[14]=b,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(t,r,i,n,s,a,o=ca){let l=this.elements,c=1/(r-t),u=1/(i-n),d=1/(a-s),f=(r+t)*c,y=(i+n)*u,b,x;if(o===ca)b=(a+s)*d,x=-2*d;else if(o===Lh)b=s*d,x=-1*d;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return l[0]=2*c,l[4]=0,l[8]=0,l[12]=-f,l[1]=0,l[5]=2*u,l[9]=0,l[13]=-y,l[2]=0,l[6]=0,l[10]=x,l[14]=-b,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(t){let r=this.elements,i=t.elements;for(let n=0;n<16;n++)if(r[n]!==i[n])return!1;return!0}fromArray(t,r=0){for(let i=0;i<16;i++)this.elements[i]=t[i+r];return this}toArray(t=[],r=0){let i=this.elements;return t[r]=i[0],t[r+1]=i[1],t[r+2]=i[2],t[r+3]=i[3],t[r+4]=i[4],t[r+5]=i[5],t[r+6]=i[6],t[r+7]=i[7],t[r+8]=i[8],t[r+9]=i[9],t[r+10]=i[10],t[r+11]=i[11],t[r+12]=i[12],t[r+13]=i[13],t[r+14]=i[14],t[r+15]=i[15],t}},ec=new je,Xs=new Ir,fT=new je(0,0,0),mT=new je(1,1,1),co=new je,np=new je,ms=new je,Fx=new Ir,zx=new pn,Ys=class qS{constructor(t=0,r=0,i=0,n=qS.DEFAULT_ORDER){this.isEuler=!0,this._x=t,this._y=r,this._z=i,this._order=n}get x(){return this._x}set x(t){this._x=t,this._onChangeCallback()}get y(){return this._y}set y(t){this._y=t,this._onChangeCallback()}get z(){return this._z}set z(t){this._z=t,this._onChangeCallback()}get order(){return this._order}set order(t){this._order=t,this._onChangeCallback()}set(t,r,i,n=this._order){return this._x=t,this._y=r,this._z=i,this._order=n,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(t){return this._x=t._x,this._y=t._y,this._z=t._z,this._order=t._order,this._onChangeCallback(),this}setFromRotationMatrix(t,r=this._order,i=!0){let n=t.elements,s=n[0],a=n[4],o=n[8],l=n[1],c=n[5],u=n[9],d=n[2],f=n[6],y=n[10];switch(r){case"XYZ":this._y=Math.asin(Jr(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-u,y),this._z=Math.atan2(-a,s)):(this._x=Math.atan2(f,c),this._z=0);break;case"YXZ":this._x=Math.asin(-Jr(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(o,y),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-d,s),this._z=0);break;case"ZXY":this._x=Math.asin(Jr(f,-1,1)),Math.abs(f)<.9999999?(this._y=Math.atan2(-d,y),this._z=Math.atan2(-a,c)):(this._y=0,this._z=Math.atan2(l,s));break;case"ZYX":this._y=Math.asin(-Jr(d,-1,1)),Math.abs(d)<.9999999?(this._x=Math.atan2(f,y),this._z=Math.atan2(l,s)):(this._x=0,this._z=Math.atan2(-a,c));break;case"YZX":this._z=Math.asin(Jr(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-u,c),this._y=Math.atan2(-d,s)):(this._x=0,this._y=Math.atan2(o,y));break;case"XZY":this._z=Math.asin(-Jr(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(f,c),this._y=Math.atan2(o,s)):(this._x=Math.atan2(-u,y),this._y=0);break;default:console.warn("THREE.Euler: .setFromRotationMatrix() encountered an unknown order: "+r)}return this._order=r,i===!0&&this._onChangeCallback(),this}setFromQuaternion(t,r,i){return Fx.makeRotationFromQuaternion(t),this.setFromRotationMatrix(Fx,r,i)}setFromVector3(t,r=this._order){return this.set(t.x,t.y,t.z,r)}reorder(t){return zx.setFromEuler(this),this.setFromQuaternion(zx,t)}equals(t){return t._x===this._x&&t._y===this._y&&t._z===this._z&&t._order===this._order}fromArray(t){return this._x=t[0],this._y=t[1],this._z=t[2],t[3]!==void 0&&(this._order=t[3]),this._onChangeCallback(),this}toArray(t=[],r=0){return t[r]=this._x,t[r+1]=this._y,t[r+2]=this._z,t[r+3]=this._order,t}_onChange(t){return this._onChangeCallback=t,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}};Ys.DEFAULT_ORDER="XYZ";var sp=class{constructor(){this.mask=1}set(e){this.mask=(1<<e|0)>>>0}enable(e){this.mask|=1<<e|0}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e|0}disable(e){this.mask&=~(1<<e|0)}disableAll(){this.mask=0}test(e){return(this.mask&e.mask)!==0}isEnabled(e){return(this.mask&(1<<e|0))!==0}},gT=0,Bx=new je,tc=new pn,Ia=new Ir,ap=new je,Fh=new je,yT=new je,vT=new pn,jx=new je(1,0,0),Vx=new je(0,1,0),Hx=new je(0,0,1),Gx={type:"added"},xT={type:"removed"},rc={type:"childadded",child:null},bg={type:"childremoved",child:null},mi=class Lm extends ha{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:gT++}),this.uuid=fs(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Lm.DEFAULT_UP.clone();let t=new je,r=new Ys,i=new pn,n=new je(1,1,1);function s(){i.setFromEuler(r,!1)}function a(){r.setFromQuaternion(i,void 0,!1)}r._onChange(s),i._onChange(a),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:t},rotation:{configurable:!0,enumerable:!0,value:r},quaternion:{configurable:!0,enumerable:!0,value:i},scale:{configurable:!0,enumerable:!0,value:n},modelViewMatrix:{value:new Ir},normalMatrix:{value:new si}}),this.matrix=new Ir,this.matrixWorld=new Ir,this.matrixAutoUpdate=Lm.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Lm.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new sp,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(t){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(t),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(t){return this.quaternion.premultiply(t),this}setRotationFromAxisAngle(t,r){this.quaternion.setFromAxisAngle(t,r)}setRotationFromEuler(t){this.quaternion.setFromEuler(t,!0)}setRotationFromMatrix(t){this.quaternion.setFromRotationMatrix(t)}setRotationFromQuaternion(t){this.quaternion.copy(t)}rotateOnAxis(t,r){return tc.setFromAxisAngle(t,r),this.quaternion.multiply(tc),this}rotateOnWorldAxis(t,r){return tc.setFromAxisAngle(t,r),this.quaternion.premultiply(tc),this}rotateX(t){return this.rotateOnAxis(jx,t)}rotateY(t){return this.rotateOnAxis(Vx,t)}rotateZ(t){return this.rotateOnAxis(Hx,t)}translateOnAxis(t,r){return Bx.copy(t).applyQuaternion(this.quaternion),this.position.add(Bx.multiplyScalar(r)),this}translateX(t){return this.translateOnAxis(jx,t)}translateY(t){return this.translateOnAxis(Vx,t)}translateZ(t){return this.translateOnAxis(Hx,t)}localToWorld(t){return this.updateWorldMatrix(!0,!1),t.applyMatrix4(this.matrixWorld)}worldToLocal(t){return this.updateWorldMatrix(!0,!1),t.applyMatrix4(Ia.copy(this.matrixWorld).invert())}lookAt(t,r,i){t.isVector3?ap.copy(t):ap.set(t,r,i);let n=this.parent;this.updateWorldMatrix(!0,!1),Fh.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Ia.lookAt(Fh,ap,this.up):Ia.lookAt(ap,Fh,this.up),this.quaternion.setFromRotationMatrix(Ia),n&&(Ia.extractRotation(n.matrixWorld),tc.setFromRotationMatrix(Ia),this.quaternion.premultiply(tc.invert()))}add(t){if(arguments.length>1){for(let r=0;r<arguments.length;r++)this.add(arguments[r]);return this}return t===this?(console.error("THREE.Object3D.add: object can't be added as a child of itself.",t),this):(t&&t.isObject3D?(t.removeFromParent(),t.parent=this,this.children.push(t),t.dispatchEvent(Gx),rc.child=t,this.dispatchEvent(rc),rc.child=null):console.error("THREE.Object3D.add: object not an instance of THREE.Object3D.",t),this)}remove(t){if(arguments.length>1){for(let i=0;i<arguments.length;i++)this.remove(arguments[i]);return this}let r=this.children.indexOf(t);return r!==-1&&(t.parent=null,this.children.splice(r,1),t.dispatchEvent(xT),bg.child=t,this.dispatchEvent(bg),bg.child=null),this}removeFromParent(){let t=this.parent;return t!==null&&t.remove(this),this}clear(){return this.remove(...this.children)}attach(t){return this.updateWorldMatrix(!0,!1),Ia.copy(this.matrixWorld).invert(),t.parent!==null&&(t.parent.updateWorldMatrix(!0,!1),Ia.multiply(t.parent.matrixWorld)),t.applyMatrix4(Ia),t.removeFromParent(),t.parent=this,this.children.push(t),t.updateWorldMatrix(!1,!0),t.dispatchEvent(Gx),rc.child=t,this.dispatchEvent(rc),rc.child=null,this}getObjectById(t){return this.getObjectByProperty("id",t)}getObjectByName(t){return this.getObjectByProperty("name",t)}getObjectByProperty(t,r){if(this[t]===r)return this;for(let i=0,n=this.children.length;i<n;i++){let s=this.children[i].getObjectByProperty(t,r);if(s!==void 0)return s}}getObjectsByProperty(t,r,i=[]){this[t]===r&&i.push(this);let n=this.children;for(let s=0,a=n.length;s<a;s++)n[s].getObjectsByProperty(t,r,i);return i}getWorldPosition(t){return this.updateWorldMatrix(!0,!1),t.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Fh,t,yT),t}getWorldScale(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Fh,vT,t),t}getWorldDirection(t){this.updateWorldMatrix(!0,!1);let r=this.matrixWorld.elements;return t.set(r[8],r[9],r[10]).normalize()}raycast(){}traverse(t){t(this);let r=this.children;for(let i=0,n=r.length;i<n;i++)r[i].traverse(t)}traverseVisible(t){if(this.visible===!1)return;t(this);let r=this.children;for(let i=0,n=r.length;i<n;i++)r[i].traverseVisible(t)}traverseAncestors(t){let r=this.parent;r!==null&&(t(r),r.traverseAncestors(t))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(t){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||t)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,t=!0);let r=this.children;for(let i=0,n=r.length;i<n;i++)r[i].updateMatrixWorld(t)}updateWorldMatrix(t,r){let i=this.parent;if(t===!0&&i!==null&&i.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),r===!0){let n=this.children;for(let s=0,a=n.length;s<a;s++)n[s].updateWorldMatrix(!1,!0)}}toJSON(t){let r=t===void 0||typeof t=="string",i={};r&&(t={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},i.metadata={version:4.6,type:"Object",generator:"Object3D.toJSON"});let n={};n.uuid=this.uuid,n.type=this.type,this.name!==""&&(n.name=this.name),this.castShadow===!0&&(n.castShadow=!0),this.receiveShadow===!0&&(n.receiveShadow=!0),this.visible===!1&&(n.visible=!1),this.frustumCulled===!1&&(n.frustumCulled=!1),this.renderOrder!==0&&(n.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(n.userData=this.userData),n.layers=this.layers.mask,n.matrix=this.matrix.toArray(),n.up=this.up.toArray(),this.matrixAutoUpdate===!1&&(n.matrixAutoUpdate=!1),this.isInstancedMesh&&(n.type="InstancedMesh",n.count=this.count,n.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(n.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(n.type="BatchedMesh",n.perObjectFrustumCulled=this.perObjectFrustumCulled,n.sortObjects=this.sortObjects,n.drawRanges=this._drawRanges,n.reservedRanges=this._reservedRanges,n.visibility=this._visibility,n.active=this._active,n.bounds=this._bounds.map(o=>({boxInitialized:o.boxInitialized,boxMin:o.box.min.toArray(),boxMax:o.box.max.toArray(),sphereInitialized:o.sphereInitialized,sphereRadius:o.sphere.radius,sphereCenter:o.sphere.center.toArray()})),n.maxInstanceCount=this._maxInstanceCount,n.maxVertexCount=this._maxVertexCount,n.maxIndexCount=this._maxIndexCount,n.geometryInitialized=this._geometryInitialized,n.geometryCount=this._geometryCount,n.matricesTexture=this._matricesTexture.toJSON(t),this._colorsTexture!==null&&(n.colorsTexture=this._colorsTexture.toJSON(t)),this.boundingSphere!==null&&(n.boundingSphere={center:n.boundingSphere.center.toArray(),radius:n.boundingSphere.radius}),this.boundingBox!==null&&(n.boundingBox={min:n.boundingBox.min.toArray(),max:n.boundingBox.max.toArray()}));function s(o,l){return o[l.uuid]===void 0&&(o[l.uuid]=l.toJSON(t)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?n.background=this.background.toJSON():this.background.isTexture&&(n.background=this.background.toJSON(t).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(n.environment=this.environment.toJSON(t).uuid);else if(this.isMesh||this.isLine||this.isPoints){n.geometry=s(t.geometries,this.geometry);let o=this.geometry.parameters;if(o!==void 0&&o.shapes!==void 0){let l=o.shapes;if(Array.isArray(l))for(let c=0,u=l.length;c<u;c++){let d=l[c];s(t.shapes,d)}else s(t.shapes,l)}}if(this.isSkinnedMesh&&(n.bindMode=this.bindMode,n.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(s(t.skeletons,this.skeleton),n.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){let o=[];for(let l=0,c=this.material.length;l<c;l++)o.push(s(t.materials,this.material[l]));n.material=o}else n.material=s(t.materials,this.material);if(this.children.length>0){n.children=[];for(let o=0;o<this.children.length;o++)n.children.push(this.children[o].toJSON(t).object)}if(this.animations.length>0){n.animations=[];for(let o=0;o<this.animations.length;o++){let l=this.animations[o];n.animations.push(s(t.animations,l))}}if(r){let o=a(t.geometries),l=a(t.materials),c=a(t.textures),u=a(t.images),d=a(t.shapes),f=a(t.skeletons),y=a(t.animations),b=a(t.nodes);o.length>0&&(i.geometries=o),l.length>0&&(i.materials=l),c.length>0&&(i.textures=c),u.length>0&&(i.images=u),d.length>0&&(i.shapes=d),f.length>0&&(i.skeletons=f),y.length>0&&(i.animations=y),b.length>0&&(i.nodes=b)}return i.object=n,i;function a(o){let l=[];for(let c in o){let u=o[c];delete u.metadata,l.push(u)}return l}}clone(t){return new this.constructor().copy(this,t)}copy(t,r=!0){if(this.name=t.name,this.up.copy(t.up),this.position.copy(t.position),this.rotation.order=t.rotation.order,this.quaternion.copy(t.quaternion),this.scale.copy(t.scale),this.matrix.copy(t.matrix),this.matrixWorld.copy(t.matrixWorld),this.matrixAutoUpdate=t.matrixAutoUpdate,this.matrixWorldAutoUpdate=t.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=t.matrixWorldNeedsUpdate,this.layers.mask=t.layers.mask,this.visible=t.visible,this.castShadow=t.castShadow,this.receiveShadow=t.receiveShadow,this.frustumCulled=t.frustumCulled,this.renderOrder=t.renderOrder,this.animations=t.animations.slice(),this.userData=JSON.parse(JSON.stringify(t.userData)),r===!0)for(let i=0;i<t.children.length;i++){let n=t.children[i];this.add(n.clone())}return this}};mi.DEFAULT_UP=new je(0,1,0),mi.DEFAULT_MATRIX_AUTO_UPDATE=!0,mi.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;var qs=new je,Na=new je,wg=new je,La=new je,ic=new je,nc=new je,Wx=new je,_g=new je,Eg=new je,Sg=new je,Mg=new _i,Ag=new _i,Tg=new _i,ka=class dh{constructor(t=new je,r=new je,i=new je){this.a=t,this.b=r,this.c=i}static getNormal(t,r,i,n){n.subVectors(i,r),qs.subVectors(t,r),n.cross(qs);let s=n.lengthSq();return s>0?n.multiplyScalar(1/Math.sqrt(s)):n.set(0,0,0)}static getBarycoord(t,r,i,n,s){qs.subVectors(n,r),Na.subVectors(i,r),wg.subVectors(t,r);let a=qs.dot(qs),o=qs.dot(Na),l=qs.dot(wg),c=Na.dot(Na),u=Na.dot(wg),d=a*c-o*o;if(d===0)return s.set(0,0,0),null;let f=1/d,y=(c*l-o*u)*f,b=(a*u-o*l)*f;return s.set(1-y-b,b,y)}static containsPoint(t,r,i,n){return this.getBarycoord(t,r,i,n,La)===null?!1:La.x>=0&&La.y>=0&&La.x+La.y<=1}static getInterpolation(t,r,i,n,s,a,o,l){return this.getBarycoord(t,r,i,n,La)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(s,La.x),l.addScaledVector(a,La.y),l.addScaledVector(o,La.z),l)}static getInterpolatedAttribute(t,r,i,n,s,a){return Mg.setScalar(0),Ag.setScalar(0),Tg.setScalar(0),Mg.fromBufferAttribute(t,r),Ag.fromBufferAttribute(t,i),Tg.fromBufferAttribute(t,n),a.setScalar(0),a.addScaledVector(Mg,s.x),a.addScaledVector(Ag,s.y),a.addScaledVector(Tg,s.z),a}static isFrontFacing(t,r,i,n){return qs.subVectors(i,r),Na.subVectors(t,r),qs.cross(Na).dot(n)<0}set(t,r,i){return this.a.copy(t),this.b.copy(r),this.c.copy(i),this}setFromPointsAndIndices(t,r,i,n){return this.a.copy(t[r]),this.b.copy(t[i]),this.c.copy(t[n]),this}setFromAttributeAndIndices(t,r,i,n){return this.a.fromBufferAttribute(t,r),this.b.fromBufferAttribute(t,i),this.c.fromBufferAttribute(t,n),this}clone(){return new this.constructor().copy(this)}copy(t){return this.a.copy(t.a),this.b.copy(t.b),this.c.copy(t.c),this}getArea(){return qs.subVectors(this.c,this.b),Na.subVectors(this.a,this.b),qs.cross(Na).length()*.5}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return dh.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,r){return dh.getBarycoord(t,this.a,this.b,this.c,r)}getInterpolation(t,r,i,n,s){return dh.getInterpolation(t,this.a,this.b,this.c,r,i,n,s)}containsPoint(t){return dh.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return dh.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,r){let i=this.a,n=this.b,s=this.c,a,o;ic.subVectors(n,i),nc.subVectors(s,i),_g.subVectors(t,i);let l=ic.dot(_g),c=nc.dot(_g);if(l<=0&&c<=0)return r.copy(i);Eg.subVectors(t,n);let u=ic.dot(Eg),d=nc.dot(Eg);if(u>=0&&d<=u)return r.copy(n);let f=l*d-u*c;if(f<=0&&l>=0&&u<=0)return a=l/(l-u),r.copy(i).addScaledVector(ic,a);Sg.subVectors(t,s);let y=ic.dot(Sg),b=nc.dot(Sg);if(b>=0&&y<=b)return r.copy(s);let x=y*c-l*b;if(x<=0&&c>=0&&b<=0)return o=c/(c-b),r.copy(i).addScaledVector(nc,o);let g=u*b-y*d;if(g<=0&&d-u>=0&&y-b>=0)return Wx.subVectors(s,n),o=(d-u)/(d-u+(y-b)),r.copy(n).addScaledVector(Wx,o);let v=1/(g+x+f);return a=x*v,o=f*v,r.copy(i).addScaledVector(ic,a).addScaledVector(nc,o)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}},Xx={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},ho={h:0,s:0,l:0},op={h:0,s:0,l:0};function Cg(e,t,r){return r<0&&(r+=1),r>1&&(r-=1),r<.16666666666666666?e+(t-e)*6*r:r<.5?t:r<.6666666666666666?e+(t-e)*6*(.6666666666666666-r):e}var or=class{constructor(e,t,r){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,r)}set(e,t,r){if(t===void 0&&r===void 0){let i=e;i&&i.isColor?this.copy(i):typeof i=="number"?this.setHex(i):typeof i=="string"&&this.setStyle(i)}else this.setRGB(e,t,r);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=xi){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,li.toWorkingColorSpace(this,t),this}setRGB(e,t,r,i=li.workingColorSpace){return this.r=e,this.g=t,this.b=r,li.toWorkingColorSpace(this,i),this}setHSL(e,t,r,i=li.workingColorSpace){if(e=hg(e,1),t=Jr(t,0,1),r=Jr(r,0,1),t===0)this.r=this.g=this.b=r;else{let n=r<=.5?r*(1+t):r+t-r*t,s=2*r-n;this.r=Cg(s,n,e+1/3),this.g=Cg(s,n,e),this.b=Cg(s,n,e-1/3)}return li.toWorkingColorSpace(this,i),this}setStyle(e,t=xi){function r(n){n!==void 0&&parseFloat(n)<1&&console.warn("THREE.Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let n,s=i[1],a=i[2];switch(s){case"rgb":case"rgba":if(n=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return r(n[4]),this.setRGB(Math.min(255,parseInt(n[1],10))/255,Math.min(255,parseInt(n[2],10))/255,Math.min(255,parseInt(n[3],10))/255,t);if(n=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return r(n[4]),this.setRGB(Math.min(100,parseInt(n[1],10))/100,Math.min(100,parseInt(n[2],10))/100,Math.min(100,parseInt(n[3],10))/100,t);break;case"hsl":case"hsla":if(n=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(a))return r(n[4]),this.setHSL(parseFloat(n[1])/360,parseFloat(n[2])/100,parseFloat(n[3])/100,t);break;default:console.warn("THREE.Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){let n=i[1],s=n.length;if(s===3)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(s===6)return this.setHex(parseInt(n,16),t);console.warn("THREE.Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=xi){let r=Xx[e.toLowerCase()];return r!==void 0?this.setHex(r,t):console.warn("THREE.Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=Ca(e.r),this.g=Ca(e.g),this.b=Ca(e.b),this}copyLinearToSRGB(e){return this.r=Kl(e.r),this.g=Kl(e.g),this.b=Kl(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=xi){return li.fromWorkingColorSpace(Dn.copy(this),e),Math.round(Jr(Dn.r*255,0,255))*65536+Math.round(Jr(Dn.g*255,0,255))*256+Math.round(Jr(Dn.b*255,0,255))}getHexString(e=xi){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=li.workingColorSpace){li.fromWorkingColorSpace(Dn.copy(this),t);let r=Dn.r,i=Dn.g,n=Dn.b,s=Math.max(r,i,n),a=Math.min(r,i,n),o,l,c=(a+s)/2;if(a===s)o=0,l=0;else{let u=s-a;switch(l=c<=.5?u/(s+a):u/(2-s-a),s){case r:o=(i-n)/u+(i<n?6:0);break;case i:o=(n-r)/u+2;break;case n:o=(r-i)/u+4;break}o/=6}return e.h=o,e.s=l,e.l=c,e}getRGB(e,t=li.workingColorSpace){return li.fromWorkingColorSpace(Dn.copy(this),t),e.r=Dn.r,e.g=Dn.g,e.b=Dn.b,e}getStyle(e=xi){li.fromWorkingColorSpace(Dn.copy(this),e);let t=Dn.r,r=Dn.g,i=Dn.b;return e!==xi?`color(${e} ${t.toFixed(3)} ${r.toFixed(3)} ${i.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(r*255)},${Math.round(i*255)})`}offsetHSL(e,t,r){return this.getHSL(ho),this.setHSL(ho.h+e,ho.s+t,ho.l+r)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,r){return this.r=e.r+(t.r-e.r)*r,this.g=e.g+(t.g-e.g)*r,this.b=e.b+(t.b-e.b)*r,this}lerpHSL(e,t){this.getHSL(ho),e.getHSL(op);let r=kh(ho.h,op.h,t),i=kh(ho.s,op.s,t),n=kh(ho.l,op.l,t);return this.setHSL(r,i,n),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){let t=this.r,r=this.g,i=this.b,n=e.elements;return this.r=n[0]*t+n[3]*r+n[6]*i,this.g=n[1]*t+n[4]*r+n[7]*i,this.b=n[2]*t+n[5]*r+n[8]*i,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}},Dn=new or;or.NAMES=Xx;var bT=0,bn=class extends ha{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:bT++}),this.uuid=fs(),this.name="",this.type="Material",this.blending=vt,this.side=Ce,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=ft,this.blendDst=Bt,this.blendEquation=gt,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new or(0,0,0),this.blendAlpha=0,this.depthFunc=Xt,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=og,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Bo,this.stencilZFail=Bo,this.stencilZPass=Bo,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let r=e[t];if(r===void 0){console.warn(`THREE.Material: parameter '${t}' has value of undefined.`);continue}let i=this[t];if(i===void 0){console.warn(`THREE.Material: '${t}' is not a property of THREE.${this.type}.`);continue}i&&i.isColor?i.set(r):i&&i.isVector3&&r&&r.isVector3?i.copy(r):this[t]=r}}toJSON(e){let t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});let r={metadata:{version:4.6,type:"Material",generator:"Material.toJSON"}};r.uuid=this.uuid,r.type=this.type,this.name!==""&&(r.name=this.name),this.color&&this.color.isColor&&(r.color=this.color.getHex()),this.roughness!==void 0&&(r.roughness=this.roughness),this.metalness!==void 0&&(r.metalness=this.metalness),this.sheen!==void 0&&(r.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(r.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(r.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(r.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(r.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(r.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(r.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(r.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(r.shininess=this.shininess),this.clearcoat!==void 0&&(r.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(r.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(r.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(r.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(r.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,r.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.dispersion!==void 0&&(r.dispersion=this.dispersion),this.iridescence!==void 0&&(r.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(r.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(r.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(r.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(r.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(r.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(r.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(r.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(r.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(r.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(r.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(r.lightMap=this.lightMap.toJSON(e).uuid,r.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(r.aoMap=this.aoMap.toJSON(e).uuid,r.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(r.bumpMap=this.bumpMap.toJSON(e).uuid,r.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(r.normalMap=this.normalMap.toJSON(e).uuid,r.normalMapType=this.normalMapType,r.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(r.displacementMap=this.displacementMap.toJSON(e).uuid,r.displacementScale=this.displacementScale,r.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(r.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(r.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(r.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(r.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(r.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(r.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(r.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(r.combine=this.combine)),this.envMapRotation!==void 0&&(r.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(r.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(r.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(r.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(r.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(r.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(r.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(r.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(r.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(r.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(r.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(r.size=this.size),this.shadowSide!==null&&(r.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(r.sizeAttenuation=this.sizeAttenuation),this.blending!==vt&&(r.blending=this.blending),this.side!==Ce&&(r.side=this.side),this.vertexColors===!0&&(r.vertexColors=!0),this.opacity<1&&(r.opacity=this.opacity),this.transparent===!0&&(r.transparent=!0),this.blendSrc!==ft&&(r.blendSrc=this.blendSrc),this.blendDst!==Bt&&(r.blendDst=this.blendDst),this.blendEquation!==gt&&(r.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(r.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(r.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(r.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(r.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(r.blendAlpha=this.blendAlpha),this.depthFunc!==Xt&&(r.depthFunc=this.depthFunc),this.depthTest===!1&&(r.depthTest=this.depthTest),this.depthWrite===!1&&(r.depthWrite=this.depthWrite),this.colorWrite===!1&&(r.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(r.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==og&&(r.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(r.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(r.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Bo&&(r.stencilFail=this.stencilFail),this.stencilZFail!==Bo&&(r.stencilZFail=this.stencilZFail),this.stencilZPass!==Bo&&(r.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(r.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(r.rotation=this.rotation),this.polygonOffset===!0&&(r.polygonOffset=!0),this.polygonOffsetFactor!==0&&(r.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(r.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(r.linewidth=this.linewidth),this.dashSize!==void 0&&(r.dashSize=this.dashSize),this.gapSize!==void 0&&(r.gapSize=this.gapSize),this.scale!==void 0&&(r.scale=this.scale),this.dithering===!0&&(r.dithering=!0),this.alphaTest>0&&(r.alphaTest=this.alphaTest),this.alphaHash===!0&&(r.alphaHash=!0),this.alphaToCoverage===!0&&(r.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(r.premultipliedAlpha=!0),this.forceSinglePass===!0&&(r.forceSinglePass=!0),this.wireframe===!0&&(r.wireframe=!0),this.wireframeLinewidth>1&&(r.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!=="round"&&(r.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!=="round"&&(r.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(r.flatShading=!0),this.visible===!1&&(r.visible=!1),this.toneMapped===!1&&(r.toneMapped=!1),this.fog===!1&&(r.fog=!1),Object.keys(this.userData).length>0&&(r.userData=this.userData);function i(n){let s=[];for(let a in n){let o=n[a];delete o.metadata,s.push(o)}return s}if(t){let n=i(e.textures),s=i(e.images);n.length>0&&(r.textures=n),s.length>0&&(r.images=s)}return r}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;let t=e.clippingPlanes,r=null;if(t!==null){let i=t.length;r=new Array(i);for(let n=0;n!==i;++n)r[n]=t[n].clone()}return this.clippingPlanes=r,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){e===!0&&this.version++}onBuild(){console.warn("Material: onBuild() has been removed.")}},en=class extends bn{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new or(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Ys,this.combine=mr,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},Oa=wT();function wT(){let e=new ArrayBuffer(4),t=new Float32Array(e),r=new Uint32Array(e),i=new Uint32Array(512),n=new Uint32Array(512);for(let l=0;l<256;++l){let c=l-127;c<-27?(i[l]=0,i[l|256]=32768,n[l]=24,n[l|256]=24):c<-14?(i[l]=1024>>-c-14,i[l|256]=1024>>-c-14|32768,n[l]=-c-1,n[l|256]=-c-1):c<=15?(i[l]=c+15<<10,i[l|256]=c+15<<10|32768,n[l]=13,n[l|256]=13):c<128?(i[l]=31744,i[l|256]=64512,n[l]=24,n[l|256]=24):(i[l]=31744,i[l|256]=64512,n[l]=13,n[l|256]=13)}let s=new Uint32Array(2048),a=new Uint32Array(64),o=new Uint32Array(64);for(let l=1;l<1024;++l){let c=l<<13,u=0;for(;(c&8388608)===0;)c<<=1,u-=8388608;c&=-8388609,u+=947912704,s[l]=c|u}for(let l=1024;l<2048;++l)s[l]=939524096+(l-1024<<13);for(let l=1;l<31;++l)a[l]=l<<23;a[31]=1199570944,a[32]=2147483648;for(let l=33;l<63;++l)a[l]=2147483648+(l-32<<23);a[63]=3347054592;for(let l=1;l<64;++l)l!==32&&(o[l]=1024);return{floatView:t,uint32View:r,baseTable:i,shiftTable:n,mantissaTable:s,exponentTable:a,offsetTable:o}}function ts(e){Math.abs(e)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),e=Jr(e,-65504,65504),Oa.floatView[0]=e;let t=Oa.uint32View[0],r=t>>23&511;return Oa.baseTable[r]+((t&8388607)>>Oa.shiftTable[r])}function zh(e){let t=e>>10;return Oa.uint32View[0]=Oa.mantissaTable[Oa.offsetTable[t]+(e&1023)]+Oa.exponentTable[t],Oa.floatView[0]}var _T={toHalfFloat:ts,fromHalfFloat:zh},fn=new je,lp=new Ft,ui=class{constructor(e,t,r=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=r,this.usage=Nh,this.updateRanges=[],this.gpuType=es,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,r){e*=this.itemSize,r*=t.itemSize;for(let i=0,n=this.itemSize;i<n;i++)this.array[e+i]=t.array[r+i];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,r=this.count;t<r;t++)lp.fromBufferAttribute(this,t),lp.applyMatrix3(e),this.setXY(t,lp.x,lp.y);else if(this.itemSize===3)for(let t=0,r=this.count;t<r;t++)fn.fromBufferAttribute(this,t),fn.applyMatrix3(e),this.setXYZ(t,fn.x,fn.y,fn.z);return this}applyMatrix4(e){for(let t=0,r=this.count;t<r;t++)fn.fromBufferAttribute(this,t),fn.applyMatrix4(e),this.setXYZ(t,fn.x,fn.y,fn.z);return this}applyNormalMatrix(e){for(let t=0,r=this.count;t<r;t++)fn.fromBufferAttribute(this,t),fn.applyNormalMatrix(e),this.setXYZ(t,fn.x,fn.y,fn.z);return this}transformDirection(e){for(let t=0,r=this.count;t<r;t++)fn.fromBufferAttribute(this,t),fn.transformDirection(e),this.setXYZ(t,fn.x,fn.y,fn.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let r=this.array[e*this.itemSize+t];return this.normalized&&(r=Yn(r,this.array)),r}setComponent(e,t,r){return this.normalized&&(r=ti(r,this.array)),this.array[e*this.itemSize+t]=r,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Yn(t,this.array)),t}setX(e,t){return this.normalized&&(t=ti(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Yn(t,this.array)),t}setY(e,t){return this.normalized&&(t=ti(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=Yn(t,this.array)),t}setZ(e,t){return this.normalized&&(t=ti(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=Yn(t,this.array)),t}setW(e,t){return this.normalized&&(t=ti(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,r){return e*=this.itemSize,this.normalized&&(t=ti(t,this.array),r=ti(r,this.array)),this.array[e+0]=t,this.array[e+1]=r,this}setXYZ(e,t,r,i){return e*=this.itemSize,this.normalized&&(t=ti(t,this.array),r=ti(r,this.array),i=ti(i,this.array)),this.array[e+0]=t,this.array[e+1]=r,this.array[e+2]=i,this}setXYZW(e,t,r,i,n){return e*=this.itemSize,this.normalized&&(t=ti(t,this.array),r=ti(r,this.array),i=ti(i,this.array),n=ti(n,this.array)),this.array[e+0]=t,this.array[e+1]=r,this.array[e+2]=i,this.array[e+3]=n,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){let e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return this.name!==""&&(e.name=this.name),this.usage!==Nh&&(e.usage=this.usage),e}},ET=class extends ui{constructor(e,t,r){super(new Int8Array(e),t,r)}},ST=class extends ui{constructor(e,t,r){super(new Uint8Array(e),t,r)}},MT=class extends ui{constructor(e,t,r){super(new Uint8ClampedArray(e),t,r)}},AT=class extends ui{constructor(e,t,r){super(new Int16Array(e),t,r)}},Rg=class extends ui{constructor(e,t,r){super(new Uint16Array(e),t,r)}},TT=class extends ui{constructor(e,t,r){super(new Int32Array(e),t,r)}},Pg=class extends ui{constructor(e,t,r){super(new Uint32Array(e),t,r)}},CT=class extends ui{constructor(e,t,r){super(new Uint16Array(e),t,r),this.isFloat16BufferAttribute=!0}getX(e){let t=zh(this.array[e*this.itemSize]);return this.normalized&&(t=Yn(t,this.array)),t}setX(e,t){return this.normalized&&(t=ti(t,this.array)),this.array[e*this.itemSize]=ts(t),this}getY(e){let t=zh(this.array[e*this.itemSize+1]);return this.normalized&&(t=Yn(t,this.array)),t}setY(e,t){return this.normalized&&(t=ti(t,this.array)),this.array[e*this.itemSize+1]=ts(t),this}getZ(e){let t=zh(this.array[e*this.itemSize+2]);return this.normalized&&(t=Yn(t,this.array)),t}setZ(e,t){return this.normalized&&(t=ti(t,this.array)),this.array[e*this.itemSize+2]=ts(t),this}getW(e){let t=zh(this.array[e*this.itemSize+3]);return this.normalized&&(t=Yn(t,this.array)),t}setW(e,t){return this.normalized&&(t=ti(t,this.array)),this.array[e*this.itemSize+3]=ts(t),this}setXY(e,t,r){return e*=this.itemSize,this.normalized&&(t=ti(t,this.array),r=ti(r,this.array)),this.array[e+0]=ts(t),this.array[e+1]=ts(r),this}setXYZ(e,t,r,i){return e*=this.itemSize,this.normalized&&(t=ti(t,this.array),r=ti(r,this.array),i=ti(i,this.array)),this.array[e+0]=ts(t),this.array[e+1]=ts(r),this.array[e+2]=ts(i),this}setXYZW(e,t,r,i,n){return e*=this.itemSize,this.normalized&&(t=ti(t,this.array),r=ti(r,this.array),i=ti(i,this.array),n=ti(n,this.array)),this.array[e+0]=ts(t),this.array[e+1]=ts(r),this.array[e+2]=ts(i),this.array[e+3]=ts(n),this}},hr=class extends ui{constructor(e,t,r){super(new Float32Array(e),t,r)}},RT=0,Cs=new Ir,Ig=new mi,sc=new je,gs=new Xi,Bh=new Xi,Tn=new je,Hr=class KS extends ha{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:RT++}),this.uuid=fs(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(t){return Array.isArray(t)?this.index=new(Px(t)?Pg:Rg)(t,1):this.index=t,this}setIndirect(t){return this.indirect=t,this}getIndirect(){return this.indirect}getAttribute(t){return this.attributes[t]}setAttribute(t,r){return this.attributes[t]=r,this}deleteAttribute(t){return delete this.attributes[t],this}hasAttribute(t){return this.attributes[t]!==void 0}addGroup(t,r,i=0){this.groups.push({start:t,count:r,materialIndex:i})}clearGroups(){this.groups=[]}setDrawRange(t,r){this.drawRange.start=t,this.drawRange.count=r}applyMatrix4(t){let r=this.attributes.position;r!==void 0&&(r.applyMatrix4(t),r.needsUpdate=!0);let i=this.attributes.normal;if(i!==void 0){let s=new si().getNormalMatrix(t);i.applyNormalMatrix(s),i.needsUpdate=!0}let n=this.attributes.tangent;return n!==void 0&&(n.transformDirection(t),n.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(t){return Cs.makeRotationFromQuaternion(t),this.applyMatrix4(Cs),this}rotateX(t){return Cs.makeRotationX(t),this.applyMatrix4(Cs),this}rotateY(t){return Cs.makeRotationY(t),this.applyMatrix4(Cs),this}rotateZ(t){return Cs.makeRotationZ(t),this.applyMatrix4(Cs),this}translate(t,r,i){return Cs.makeTranslation(t,r,i),this.applyMatrix4(Cs),this}scale(t,r,i){return Cs.makeScale(t,r,i),this.applyMatrix4(Cs),this}lookAt(t){return Ig.lookAt(t),Ig.updateMatrix(),this.applyMatrix4(Ig.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(sc).negate(),this.translate(sc.x,sc.y,sc.z),this}setFromPoints(t){let r=this.getAttribute("position");if(r===void 0){let i=[];for(let n=0,s=t.length;n<s;n++){let a=t[n];i.push(a.x,a.y,a.z||0)}this.setAttribute("position",new hr(i,3))}else{let i=Math.min(t.length,r.count);for(let n=0;n<i;n++){let s=t[n];r.setXYZ(n,s.x,s.y,s.z||0)}t.length>r.count&&console.warn("THREE.BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),r.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Xi);let t=this.attributes.position,r=this.morphAttributes.position;if(t&&t.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new je(-1/0,-1/0,-1/0),new je(1/0,1/0,1/0));return}if(t!==void 0){if(this.boundingBox.setFromBufferAttribute(t),r)for(let i=0,n=r.length;i<n;i++){let s=r[i];gs.setFromBufferAttribute(s),this.morphTargetsRelative?(Tn.addVectors(this.boundingBox.min,gs.min),this.boundingBox.expandByPoint(Tn),Tn.addVectors(this.boundingBox.max,gs.max),this.boundingBox.expandByPoint(Tn)):(this.boundingBox.expandByPoint(gs.min),this.boundingBox.expandByPoint(gs.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&console.error('THREE.BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new on);let t=this.attributes.position,r=this.morphAttributes.position;if(t&&t.isGLBufferAttribute){console.error("THREE.BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new je,1/0);return}if(t){let i=this.boundingSphere.center;if(gs.setFromBufferAttribute(t),r)for(let s=0,a=r.length;s<a;s++){let o=r[s];Bh.setFromBufferAttribute(o),this.morphTargetsRelative?(Tn.addVectors(gs.min,Bh.min),gs.expandByPoint(Tn),Tn.addVectors(gs.max,Bh.max),gs.expandByPoint(Tn)):(gs.expandByPoint(Bh.min),gs.expandByPoint(Bh.max))}gs.getCenter(i);let n=0;for(let s=0,a=t.count;s<a;s++)Tn.fromBufferAttribute(t,s),n=Math.max(n,i.distanceToSquared(Tn));if(r)for(let s=0,a=r.length;s<a;s++){let o=r[s],l=this.morphTargetsRelative;for(let c=0,u=o.count;c<u;c++)Tn.fromBufferAttribute(o,c),l&&(sc.fromBufferAttribute(t,c),Tn.add(sc)),n=Math.max(n,i.distanceToSquared(Tn))}this.boundingSphere.radius=Math.sqrt(n),isNaN(this.boundingSphere.radius)&&console.error('THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){let t=this.index,r=this.attributes;if(t===null||r.position===void 0||r.normal===void 0||r.uv===void 0){console.error("THREE.BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}let i=r.position,n=r.normal,s=r.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new ui(new Float32Array(4*i.count),4));let a=this.getAttribute("tangent"),o=[],l=[];for(let D=0;D<i.count;D++)o[D]=new je,l[D]=new je;let c=new je,u=new je,d=new je,f=new Ft,y=new Ft,b=new Ft,x=new je,g=new je;function v(D,I,L){c.fromBufferAttribute(i,D),u.fromBufferAttribute(i,I),d.fromBufferAttribute(i,L),f.fromBufferAttribute(s,D),y.fromBufferAttribute(s,I),b.fromBufferAttribute(s,L),u.sub(c),d.sub(c),y.sub(f),b.sub(f);let Z=1/(y.x*b.y-b.x*y.y);isFinite(Z)&&(x.copy(u).multiplyScalar(b.y).addScaledVector(d,-y.y).multiplyScalar(Z),g.copy(d).multiplyScalar(y.x).addScaledVector(u,-b.x).multiplyScalar(Z),o[D].add(x),o[I].add(x),o[L].add(x),l[D].add(g),l[I].add(g),l[L].add(g))}let _=this.groups;_.length===0&&(_=[{start:0,count:t.count}]);for(let D=0,I=_.length;D<I;++D){let L=_[D],Z=L.start,se=L.count;for(let ce=Z,fe=Z+se;ce<fe;ce+=3)v(t.getX(ce+0),t.getX(ce+1),t.getX(ce+2))}let E=new je,M=new je,P=new je,k=new je;function z(D){P.fromBufferAttribute(n,D),k.copy(P);let I=o[D];E.copy(I),E.sub(P.multiplyScalar(P.dot(I))).normalize(),M.crossVectors(k,I);let L=M.dot(l[D])<0?-1:1;a.setXYZW(D,E.x,E.y,E.z,L)}for(let D=0,I=_.length;D<I;++D){let L=_[D],Z=L.start,se=L.count;for(let ce=Z,fe=Z+se;ce<fe;ce+=3)z(t.getX(ce+0)),z(t.getX(ce+1)),z(t.getX(ce+2))}}computeVertexNormals(){let t=this.index,r=this.getAttribute("position");if(r!==void 0){let i=this.getAttribute("normal");if(i===void 0)i=new ui(new Float32Array(r.count*3),3),this.setAttribute("normal",i);else for(let f=0,y=i.count;f<y;f++)i.setXYZ(f,0,0,0);let n=new je,s=new je,a=new je,o=new je,l=new je,c=new je,u=new je,d=new je;if(t)for(let f=0,y=t.count;f<y;f+=3){let b=t.getX(f+0),x=t.getX(f+1),g=t.getX(f+2);n.fromBufferAttribute(r,b),s.fromBufferAttribute(r,x),a.fromBufferAttribute(r,g),u.subVectors(a,s),d.subVectors(n,s),u.cross(d),o.fromBufferAttribute(i,b),l.fromBufferAttribute(i,x),c.fromBufferAttribute(i,g),o.add(u),l.add(u),c.add(u),i.setXYZ(b,o.x,o.y,o.z),i.setXYZ(x,l.x,l.y,l.z),i.setXYZ(g,c.x,c.y,c.z)}else for(let f=0,y=r.count;f<y;f+=3)n.fromBufferAttribute(r,f+0),s.fromBufferAttribute(r,f+1),a.fromBufferAttribute(r,f+2),u.subVectors(a,s),d.subVectors(n,s),u.cross(d),i.setXYZ(f+0,u.x,u.y,u.z),i.setXYZ(f+1,u.x,u.y,u.z),i.setXYZ(f+2,u.x,u.y,u.z);this.normalizeNormals(),i.needsUpdate=!0}}normalizeNormals(){let t=this.attributes.normal;for(let r=0,i=t.count;r<i;r++)Tn.fromBufferAttribute(t,r),Tn.normalize(),t.setXYZ(r,Tn.x,Tn.y,Tn.z)}toNonIndexed(){function t(o,l){let c=o.array,u=o.itemSize,d=o.normalized,f=new c.constructor(l.length*u),y=0,b=0;for(let x=0,g=l.length;x<g;x++){o.isInterleavedBufferAttribute?y=l[x]*o.data.stride+o.offset:y=l[x]*u;for(let v=0;v<u;v++)f[b++]=c[y++]}return new ui(f,u,d)}if(this.index===null)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;let r=new KS,i=this.index.array,n=this.attributes;for(let o in n){let l=n[o],c=t(l,i);r.setAttribute(o,c)}let s=this.morphAttributes;for(let o in s){let l=[],c=s[o];for(let u=0,d=c.length;u<d;u++){let f=c[u],y=t(f,i);l.push(y)}r.morphAttributes[o]=l}r.morphTargetsRelative=this.morphTargetsRelative;let a=this.groups;for(let o=0,l=a.length;o<l;o++){let c=a[o];r.addGroup(c.start,c.count,c.materialIndex)}return r}toJSON(){let t={metadata:{version:4.6,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(t.uuid=this.uuid,t.type=this.type,this.name!==""&&(t.name=this.name),Object.keys(this.userData).length>0&&(t.userData=this.userData),this.parameters!==void 0){let l=this.parameters;for(let c in l)l[c]!==void 0&&(t[c]=l[c]);return t}t.data={attributes:{}};let r=this.index;r!==null&&(t.data.index={type:r.array.constructor.name,array:Array.prototype.slice.call(r.array)});let i=this.attributes;for(let l in i){let c=i[l];t.data.attributes[l]=c.toJSON(t.data)}let n={},s=!1;for(let l in this.morphAttributes){let c=this.morphAttributes[l],u=[];for(let d=0,f=c.length;d<f;d++){let y=c[d];u.push(y.toJSON(t.data))}u.length>0&&(n[l]=u,s=!0)}s&&(t.data.morphAttributes=n,t.data.morphTargetsRelative=this.morphTargetsRelative);let a=this.groups;a.length>0&&(t.data.groups=JSON.parse(JSON.stringify(a)));let o=this.boundingSphere;return o!==null&&(t.data.boundingSphere={center:o.center.toArray(),radius:o.radius}),t}clone(){return new this.constructor().copy(this)}copy(t){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let r={};this.name=t.name;let i=t.index;i!==null&&this.setIndex(i.clone(r));let n=t.attributes;for(let c in n){let u=n[c];this.setAttribute(c,u.clone(r))}let s=t.morphAttributes;for(let c in s){let u=[],d=s[c];for(let f=0,y=d.length;f<y;f++)u.push(d[f].clone(r));this.morphAttributes[c]=u}this.morphTargetsRelative=t.morphTargetsRelative;let a=t.groups;for(let c=0,u=a.length;c<u;c++){let d=a[c];this.addGroup(d.start,d.count,d.materialIndex)}let o=t.boundingBox;o!==null&&(this.boundingBox=o.clone());let l=t.boundingSphere;return l!==null&&(this.boundingSphere=l.clone()),this.drawRange.start=t.drawRange.start,this.drawRange.count=t.drawRange.count,this.userData=t.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}},Yx=new Ir,Xo=new Wo,cp=new on,qx=new je,hp=new je,up=new je,dp=new je,Ng=new je,pp=new je,Kx=new je,fp=new je,qr=class extends mi{constructor(e=new Hr,t=new en){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let r=e[t[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let i=0,n=r.length;i<n;i++){let s=r[i].name||String(i);this.morphTargetInfluences.push(0),this.morphTargetDictionary[s]=i}}}}getVertexPosition(e,t){let r=this.geometry,i=r.attributes.position,n=r.morphAttributes.position,s=r.morphTargetsRelative;t.fromBufferAttribute(i,e);let a=this.morphTargetInfluences;if(n&&a){pp.set(0,0,0);for(let o=0,l=n.length;o<l;o++){let c=a[o],u=n[o];c!==0&&(Ng.fromBufferAttribute(u,e),s?pp.addScaledVector(Ng,c):pp.addScaledVector(Ng.sub(t),c))}t.add(pp)}return t}raycast(e,t){let r=this.geometry,i=this.material,n=this.matrixWorld;i!==void 0&&(r.boundingSphere===null&&r.computeBoundingSphere(),cp.copy(r.boundingSphere),cp.applyMatrix4(n),Xo.copy(e.ray).recast(e.near),!(cp.containsPoint(Xo.origin)===!1&&(Xo.intersectSphere(cp,qx)===null||Xo.origin.distanceToSquared(qx)>(e.far-e.near)**2))&&(Yx.copy(n).invert(),Xo.copy(e.ray).applyMatrix4(Yx),!(r.boundingBox!==null&&Xo.intersectsBox(r.boundingBox)===!1)&&this._computeIntersections(e,t,Xo)))}_computeIntersections(e,t,r){let i,n=this.geometry,s=this.material,a=n.index,o=n.attributes.position,l=n.attributes.uv,c=n.attributes.uv1,u=n.attributes.normal,d=n.groups,f=n.drawRange;if(a!==null)if(Array.isArray(s))for(let y=0,b=d.length;y<b;y++){let x=d[y],g=s[x.materialIndex],v=Math.max(x.start,f.start),_=Math.min(a.count,Math.min(x.start+x.count,f.start+f.count));for(let E=v,M=_;E<M;E+=3){let P=a.getX(E),k=a.getX(E+1),z=a.getX(E+2);i=mp(this,g,e,r,l,c,u,P,k,z),i&&(i.faceIndex=Math.floor(E/3),i.face.materialIndex=x.materialIndex,t.push(i))}}else{let y=Math.max(0,f.start),b=Math.min(a.count,f.start+f.count);for(let x=y,g=b;x<g;x+=3){let v=a.getX(x),_=a.getX(x+1),E=a.getX(x+2);i=mp(this,s,e,r,l,c,u,v,_,E),i&&(i.faceIndex=Math.floor(x/3),t.push(i))}}else if(o!==void 0)if(Array.isArray(s))for(let y=0,b=d.length;y<b;y++){let x=d[y],g=s[x.materialIndex],v=Math.max(x.start,f.start),_=Math.min(o.count,Math.min(x.start+x.count,f.start+f.count));for(let E=v,M=_;E<M;E+=3){let P=E,k=E+1,z=E+2;i=mp(this,g,e,r,l,c,u,P,k,z),i&&(i.faceIndex=Math.floor(E/3),i.face.materialIndex=x.materialIndex,t.push(i))}}else{let y=Math.max(0,f.start),b=Math.min(o.count,f.start+f.count);for(let x=y,g=b;x<g;x+=3){let v=x,_=x+1,E=x+2;i=mp(this,s,e,r,l,c,u,v,_,E),i&&(i.faceIndex=Math.floor(x/3),t.push(i))}}}};function PT(e,t,r,i,n,s,a,o){let l;if(t.side===tt?l=i.intersectTriangle(a,s,n,!0,o):l=i.intersectTriangle(n,s,a,t.side===Ce,o),l===null)return null;fp.copy(o),fp.applyMatrix4(e.matrixWorld);let c=r.ray.origin.distanceTo(fp);return c<r.near||c>r.far?null:{distance:c,point:fp.clone(),object:e}}function mp(e,t,r,i,n,s,a,o,l,c){e.getVertexPosition(o,hp),e.getVertexPosition(l,up),e.getVertexPosition(c,dp);let u=PT(e,t,r,i,hp,up,dp,Kx);if(u){let d=new je;ka.getBarycoord(Kx,hp,up,dp,d),n&&(u.uv=ka.getInterpolatedAttribute(n,o,l,c,d,new Ft)),s&&(u.uv1=ka.getInterpolatedAttribute(s,o,l,c,d,new Ft)),a&&(u.normal=ka.getInterpolatedAttribute(a,o,l,c,d,new je),u.normal.dot(i.direction)>0&&u.normal.multiplyScalar(-1));let f={a:o,b:l,c,normal:new je,materialIndex:0};ka.getNormal(hp,up,dp,f.normal),u.face=f,u.barycoord=d}return u}var Da=class ZS extends Hr{constructor(t=1,r=1,i=1,n=1,s=1,a=1){super(),this.type="BoxGeometry",this.parameters={width:t,height:r,depth:i,widthSegments:n,heightSegments:s,depthSegments:a};let o=this;n=Math.floor(n),s=Math.floor(s),a=Math.floor(a);let l=[],c=[],u=[],d=[],f=0,y=0;b("z","y","x",-1,-1,i,r,t,a,s,0),b("z","y","x",1,-1,i,r,-t,a,s,1),b("x","z","y",1,1,t,i,r,n,a,2),b("x","z","y",1,-1,t,i,-r,n,a,3),b("x","y","z",1,-1,t,r,i,n,s,4),b("x","y","z",-1,-1,t,r,-i,n,s,5),this.setIndex(l),this.setAttribute("position",new hr(c,3)),this.setAttribute("normal",new hr(u,3)),this.setAttribute("uv",new hr(d,2));function b(x,g,v,_,E,M,P,k,z,D,I){let L=M/z,Z=P/D,se=M/2,ce=P/2,fe=k/2,ze=z+1,Fe=D+1,Pe=0,ue=0,Te=new je;for(let de=0;de<Fe;de++){let Ie=de*Z-ce;for(let Re=0;Re<ze;Re++){let Be=Re*L-se;Te[x]=Be*_,Te[g]=Ie*E,Te[v]=fe,c.push(Te.x,Te.y,Te.z),Te[x]=0,Te[g]=0,Te[v]=k>0?1:-1,u.push(Te.x,Te.y,Te.z),d.push(Re/z),d.push(1-de/D),Pe+=1}}for(let de=0;de<D;de++)for(let Ie=0;Ie<z;Ie++){let Re=f+Ie+ze*de,Be=f+Ie+ze*(de+1),Se=f+(Ie+1)+ze*(de+1),U=f+(Ie+1)+ze*de;l.push(Re,Be,U),l.push(Be,Se,U),ue+=6}o.addGroup(y,ue,I),y+=ue,f+=Pe}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new ZS(t.width,t.height,t.depth,t.widthSegments,t.heightSegments,t.depthSegments)}};function ac(e){let t={};for(let r in e){t[r]={};for(let i in e[r]){let n=e[r][i];n&&(n.isColor||n.isMatrix3||n.isMatrix4||n.isVector2||n.isVector3||n.isVector4||n.isTexture||n.isQuaternion)?n.isRenderTargetTexture?(console.warn("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),t[r][i]=null):t[r][i]=n.clone():Array.isArray(n)?t[r][i]=n.slice():t[r][i]=n}}return t}function qn(e){let t={};for(let r=0;r<e.length;r++){let i=ac(e[r]);for(let n in i)t[n]=i[n]}return t}function IT(e){let t=[];for(let r=0;r<e.length;r++)t.push(e[r].clone());return t}function Zx(e){let t=e.getRenderTarget();return t===null?e.outputColorSpace:t.isXRRenderTarget===!0?t.texture.colorSpace:li.workingColorSpace}var Rs={clone:ac,merge:qn},NT=`void main() {
	gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,LT=`void main() {
	gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
}`,ln=class extends bn{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=NT,this.fragmentShader=LT,this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,e!==void 0&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=ac(e.uniforms),this.uniformsGroups=IT(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this}toJSON(e){let t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(let i in this.uniforms){let n=this.uniforms[i].value;n&&n.isTexture?t.uniforms[i]={type:"t",value:n.toJSON(e).uuid}:n&&n.isColor?t.uniforms[i]={type:"c",value:n.getHex()}:n&&n.isVector2?t.uniforms[i]={type:"v2",value:n.toArray()}:n&&n.isVector3?t.uniforms[i]={type:"v3",value:n.toArray()}:n&&n.isVector4?t.uniforms[i]={type:"v4",value:n.toArray()}:n&&n.isMatrix3?t.uniforms[i]={type:"m3",value:n.toArray()}:n&&n.isMatrix4?t.uniforms[i]={type:"m4",value:n.toArray()}:t.uniforms[i]={value:n}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let r={};for(let i in this.extensions)this.extensions[i]===!0&&(r[i]=!0);return Object.keys(r).length>0&&(t.extensions=r),t}},gp=class extends mi{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Ir,this.projectionMatrix=new Ir,this.projectionMatrixInverse=new Ir,this.coordinateSystem=ca}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return new this.constructor().copy(this)}},uo=new je,$x=new Ft,Jx=new Ft,cn=class extends gp{constructor(e=50,t=1,r=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=r,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=e.view===null?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){let t=.5*this.getFilmHeight()/e;this.fov=Xl*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(jo*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Xl*2*Math.atan(Math.tan(jo*.5*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,r){uo.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(uo.x,uo.y).multiplyScalar(-e/uo.z),uo.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),r.set(uo.x,uo.y).multiplyScalar(-e/uo.z)}getViewSize(e,t){return this.getViewBounds(e,$x,Jx),t.subVectors(Jx,$x)}setViewOffset(e,t,r,i,n,s){this.aspect=e/t,this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=r,this.view.offsetY=i,this.view.width=n,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=this.near,t=e*Math.tan(jo*.5*this.fov)/this.zoom,r=2*t,i=this.aspect*r,n=-.5*i,s=this.view;if(this.view!==null&&this.view.enabled){let o=s.fullWidth,l=s.fullHeight;n+=s.offsetX*i/o,t-=s.offsetY*r/l,i*=s.width/o,r*=s.height/l}let a=this.filmOffset;a!==0&&(n+=e*a/this.getFilmWidth()),this.projectionMatrix.makePerspective(n,n+i,t,t-r,e,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,this.view!==null&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}},oc=-90,lc=1,Qx=class extends mi{constructor(e,t,r){super(),this.type="CubeCamera",this.renderTarget=r,this.coordinateSystem=null,this.activeMipmapLevel=0;let i=new cn(oc,lc,e,t);i.layers=this.layers,this.add(i);let n=new cn(oc,lc,e,t);n.layers=this.layers,this.add(n);let s=new cn(oc,lc,e,t);s.layers=this.layers,this.add(s);let a=new cn(oc,lc,e,t);a.layers=this.layers,this.add(a);let o=new cn(oc,lc,e,t);o.layers=this.layers,this.add(o);let l=new cn(oc,lc,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[r,i,n,s,a,o]=t;for(let l of t)this.remove(l);if(e===ca)r.up.set(0,1,0),r.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),n.up.set(0,0,-1),n.lookAt(0,1,0),s.up.set(0,0,1),s.lookAt(0,-1,0),a.up.set(0,1,0),a.lookAt(0,0,1),o.up.set(0,1,0),o.lookAt(0,0,-1);else if(e===Lh)r.up.set(0,-1,0),r.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),n.up.set(0,0,1),n.lookAt(0,1,0),s.up.set(0,0,-1),s.lookAt(0,-1,0),a.up.set(0,-1,0),a.lookAt(0,0,1),o.up.set(0,-1,0),o.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(let l of t)this.add(l),l.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let{renderTarget:r,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[n,s,a,o,l,c]=this.children,u=e.getRenderTarget(),d=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),y=e.xr.enabled;e.xr.enabled=!1;let b=r.texture.generateMipmaps;r.texture.generateMipmaps=!1,e.setRenderTarget(r,0,i),e.render(t,n),e.setRenderTarget(r,1,i),e.render(t,s),e.setRenderTarget(r,2,i),e.render(t,a),e.setRenderTarget(r,3,i),e.render(t,o),e.setRenderTarget(r,4,i),e.render(t,l),r.texture.generateMipmaps=b,e.setRenderTarget(r,5,i),e.render(t,c),e.setRenderTarget(u,d,f),e.xr.enabled=y,r.texture.needsPMREMUpdate=!0}},jh=class extends Qi{constructor(e,t,r,i,n,s,a,o,l,c){e=e!==void 0?e:[],t=t!==void 0?t:br,super(e,t,r,i,n,s,a,o,l,c),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},eb=class extends In{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;let r={width:e,height:e,depth:1},i=[r,r,r,r,r,r];this.texture=new jh(i,t.mapping,t.wrapS,t.wrapT,t.magFilter,t.minFilter,t.format,t.type,t.anisotropy,t.colorSpace),this.texture.isRenderTargetTexture=!0,this.texture.generateMipmaps=t.generateMipmaps!==void 0?t.generateMipmaps:!1,this.texture.minFilter=t.minFilter!==void 0?t.minFilter:Pi}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;let r={uniforms:{tEquirect:{value:null}},vertexShader:`

				varying vec3 vWorldDirection;

				vec3 transformDirection( in vec3 dir, in mat4 matrix ) {

					return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );

				}

				void main() {

					vWorldDirection = transformDirection( position, modelMatrix );

					#include <begin_vertex>
					#include <project_vertex>

				}
			`,fragmentShader:`

				uniform sampler2D tEquirect;

				varying vec3 vWorldDirection;

				#include <common>

				void main() {

					vec3 direction = normalize( vWorldDirection );

					vec2 sampleUV = equirectUv( direction );

					gl_FragColor = texture2D( tEquirect, sampleUV );

				}
			`},i=new Da(5,5,5),n=new ln({name:"CubemapFromEquirect",uniforms:ac(r.uniforms),vertexShader:r.vertexShader,fragmentShader:r.fragmentShader,side:tt,blending:Ye});n.uniforms.tEquirect.value=t;let s=new qr(i,n),a=t.minFilter;return t.minFilter===Fi&&(t.minFilter=Pi),new Qx(1,10,this).update(e,s),t.minFilter=a,s.geometry.dispose(),s.material.dispose(),this}clear(e,t,r,i){let n=e.getRenderTarget();for(let s=0;s<6;s++)e.setRenderTarget(this,s),e.clear(t,r,i);e.setRenderTarget(n)}},tb=class $S{constructor(t,r=25e-5){this.isFogExp2=!0,this.name="",this.color=new or(t),this.density=r}clone(){return new $S(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}},rb=class JS{constructor(t,r=1,i=1e3){this.isFog=!0,this.name="",this.color=new or(t),this.near=r,this.far=i}clone(){return new JS(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}},Yo=class extends mi{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new Ys,this.environmentIntensity=1,this.environmentRotation=new Ys,this.overrideMaterial=null,typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),e.background!==null&&(this.background=e.background.clone()),e.environment!==null&&(this.environment=e.environment.clone()),e.fog!==null&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),e.overrideMaterial!==null&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){let t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}},Vh=class{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=Nh,this.updateRanges=[],this.version=0,this.uuid=fs()}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,r){e*=this.stride,r*=t.stride;for(let i=0,n=this.stride;i<n;i++)this.array[e+i]=t.array[r+i];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=fs()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);let t=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),r=new this.constructor(t,this.stride);return r.setUsage(this.usage),r}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){return e.arrayBuffers===void 0&&(e.arrayBuffers={}),this.array.buffer._uuid===void 0&&(this.array.buffer._uuid=fs()),e.arrayBuffers[this.array.buffer._uuid]===void 0&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}},Kn=new je,cc=class QS{constructor(t,r,i,n=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=t,this.itemSize=r,this.offset=i,this.normalized=n}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(t){this.data.needsUpdate=t}applyMatrix4(t){for(let r=0,i=this.data.count;r<i;r++)Kn.fromBufferAttribute(this,r),Kn.applyMatrix4(t),this.setXYZ(r,Kn.x,Kn.y,Kn.z);return this}applyNormalMatrix(t){for(let r=0,i=this.count;r<i;r++)Kn.fromBufferAttribute(this,r),Kn.applyNormalMatrix(t),this.setXYZ(r,Kn.x,Kn.y,Kn.z);return this}transformDirection(t){for(let r=0,i=this.count;r<i;r++)Kn.fromBufferAttribute(this,r),Kn.transformDirection(t),this.setXYZ(r,Kn.x,Kn.y,Kn.z);return this}getComponent(t,r){let i=this.array[t*this.data.stride+this.offset+r];return this.normalized&&(i=Yn(i,this.array)),i}setComponent(t,r,i){return this.normalized&&(i=ti(i,this.array)),this.data.array[t*this.data.stride+this.offset+r]=i,this}setX(t,r){return this.normalized&&(r=ti(r,this.array)),this.data.array[t*this.data.stride+this.offset]=r,this}setY(t,r){return this.normalized&&(r=ti(r,this.array)),this.data.array[t*this.data.stride+this.offset+1]=r,this}setZ(t,r){return this.normalized&&(r=ti(r,this.array)),this.data.array[t*this.data.stride+this.offset+2]=r,this}setW(t,r){return this.normalized&&(r=ti(r,this.array)),this.data.array[t*this.data.stride+this.offset+3]=r,this}getX(t){let r=this.data.array[t*this.data.stride+this.offset];return this.normalized&&(r=Yn(r,this.array)),r}getY(t){let r=this.data.array[t*this.data.stride+this.offset+1];return this.normalized&&(r=Yn(r,this.array)),r}getZ(t){let r=this.data.array[t*this.data.stride+this.offset+2];return this.normalized&&(r=Yn(r,this.array)),r}getW(t){let r=this.data.array[t*this.data.stride+this.offset+3];return this.normalized&&(r=Yn(r,this.array)),r}setXY(t,r,i){return t=t*this.data.stride+this.offset,this.normalized&&(r=ti(r,this.array),i=ti(i,this.array)),this.data.array[t+0]=r,this.data.array[t+1]=i,this}setXYZ(t,r,i,n){return t=t*this.data.stride+this.offset,this.normalized&&(r=ti(r,this.array),i=ti(i,this.array),n=ti(n,this.array)),this.data.array[t+0]=r,this.data.array[t+1]=i,this.data.array[t+2]=n,this}setXYZW(t,r,i,n,s){return t=t*this.data.stride+this.offset,this.normalized&&(r=ti(r,this.array),i=ti(i,this.array),n=ti(n,this.array),s=ti(s,this.array)),this.data.array[t+0]=r,this.data.array[t+1]=i,this.data.array[t+2]=n,this.data.array[t+3]=s,this}clone(t){if(t===void 0){console.log("THREE.InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");let r=[];for(let i=0;i<this.count;i++){let n=i*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)r.push(this.data.array[n+s])}return new ui(new this.array.constructor(r),this.itemSize,this.normalized)}else return t.interleavedBuffers===void 0&&(t.interleavedBuffers={}),t.interleavedBuffers[this.data.uuid]===void 0&&(t.interleavedBuffers[this.data.uuid]=this.data.clone(t)),new QS(t.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(t){if(t===void 0){console.log("THREE.InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");let r=[];for(let i=0;i<this.count;i++){let n=i*this.data.stride+this.offset;for(let s=0;s<this.itemSize;s++)r.push(this.data.array[n+s])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:r,normalized:this.normalized}}else return t.interleavedBuffers===void 0&&(t.interleavedBuffers={}),t.interleavedBuffers[this.data.uuid]===void 0&&(t.interleavedBuffers[this.data.uuid]=this.data.toJSON(t)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}},yp=class extends bn{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new or(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}},hc,Hh=new je,uc=new je,dc=new je,pc=new Ft,Gh=new Ft,ib=new Ir,vp=new je,Wh=new je,xp=new je,nb=new Ft,Lg=new Ft,sb=new Ft,kg=class extends mi{constructor(e=new yp){if(super(),this.isSprite=!0,this.type="Sprite",hc===void 0){hc=new Hr;let t=new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),r=new Vh(t,5);hc.setIndex([0,1,2,0,2,3]),hc.setAttribute("position",new cc(r,3,0,!1)),hc.setAttribute("uv",new cc(r,2,3,!1))}this.geometry=hc,this.material=e,this.center=new Ft(.5,.5)}raycast(e,t){e.camera===null&&console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'),uc.setFromMatrixScale(this.matrixWorld),ib.copy(e.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(e.camera.matrixWorldInverse,this.matrixWorld),dc.setFromMatrixPosition(this.modelViewMatrix),e.camera.isPerspectiveCamera&&this.material.sizeAttenuation===!1&&uc.multiplyScalar(-dc.z);let r=this.material.rotation,i,n;r!==0&&(n=Math.cos(r),i=Math.sin(r));let s=this.center;bp(vp.set(-.5,-.5,0),dc,s,uc,i,n),bp(Wh.set(.5,-.5,0),dc,s,uc,i,n),bp(xp.set(.5,.5,0),dc,s,uc,i,n),nb.set(0,0),Lg.set(1,0),sb.set(1,1);let a=e.ray.intersectTriangle(vp,Wh,xp,!1,Hh);if(a===null&&(bp(Wh.set(-.5,.5,0),dc,s,uc,i,n),Lg.set(0,1),a=e.ray.intersectTriangle(vp,xp,Wh,!1,Hh),a===null))return;let o=e.ray.origin.distanceTo(Hh);o<e.near||o>e.far||t.push({distance:o,point:Hh.clone(),uv:ka.getInterpolation(Hh,vp,Wh,xp,nb,Lg,sb,new Ft),face:null,object:this})}copy(e,t){return super.copy(e,t),e.center!==void 0&&this.center.copy(e.center),this.material=e.material,this}};function bp(e,t,r,i,n,s){pc.subVectors(e,r).addScalar(.5).multiply(i),n!==void 0?(Gh.x=s*pc.x-n*pc.y,Gh.y=n*pc.x+s*pc.y):Gh.copy(pc),e.copy(t),e.x+=Gh.x,e.y+=Gh.y,e.applyMatrix4(ib)}var wp=new je,ab=new je,ob=class extends mi{constructor(){super(),this._currentLevel=0,this.type="LOD",Object.defineProperties(this,{levels:{enumerable:!0,value:[]},isLOD:{value:!0}}),this.autoUpdate=!0}copy(e){super.copy(e,!1);let t=e.levels;for(let r=0,i=t.length;r<i;r++){let n=t[r];this.addLevel(n.object.clone(),n.distance,n.hysteresis)}return this.autoUpdate=e.autoUpdate,this}addLevel(e,t=0,r=0){t=Math.abs(t);let i=this.levels,n;for(n=0;n<i.length&&!(t<i[n].distance);n++);return i.splice(n,0,{distance:t,hysteresis:r,object:e}),this.add(e),this}removeLevel(e){let t=this.levels;for(let r=0;r<t.length;r++)if(t[r].distance===e){let i=t.splice(r,1);return this.remove(i[0].object),!0}return!1}getCurrentLevel(){return this._currentLevel}getObjectForDistance(e){let t=this.levels;if(t.length>0){let r,i;for(r=1,i=t.length;r<i;r++){let n=t[r].distance;if(t[r].object.visible&&(n-=n*t[r].hysteresis),e<n)break}return t[r-1].object}return null}raycast(e,t){if(this.levels.length>0){wp.setFromMatrixPosition(this.matrixWorld);let r=e.ray.origin.distanceTo(wp);this.getObjectForDistance(r).raycast(e,t)}}update(e){let t=this.levels;if(t.length>1){wp.setFromMatrixPosition(e.matrixWorld),ab.setFromMatrixPosition(this.matrixWorld);let r=wp.distanceTo(ab)/e.zoom;t[0].object.visible=!0;let i,n;for(i=1,n=t.length;i<n;i++){let s=t[i].distance;if(t[i].object.visible&&(s-=s*t[i].hysteresis),r>=s)t[i-1].object.visible=!1,t[i].object.visible=!0;else break}for(this._currentLevel=i-1;i<n;i++)t[i].object.visible=!1}}toJSON(e){let t=super.toJSON(e);this.autoUpdate===!1&&(t.object.autoUpdate=!1),t.object.levels=[];let r=this.levels;for(let i=0,n=r.length;i<n;i++){let s=r[i];t.object.levels.push({object:s.object.uuid,distance:s.distance,hysteresis:s.hysteresis})}return t}},lb=new je,cb=new _i,hb=new _i,kT=new je,ub=new Ir,_p=new je,Og=new on,db=new Ir,Dg=new Wo,Ug=class extends qr{constructor(e,t){super(e,t),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=fi,this.bindMatrix=new Ir,this.bindMatrixInverse=new Ir,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){let e=this.geometry;this.boundingBox===null&&(this.boundingBox=new Xi),this.boundingBox.makeEmpty();let t=e.getAttribute("position");for(let r=0;r<t.count;r++)this.getVertexPosition(r,_p),this.boundingBox.expandByPoint(_p)}computeBoundingSphere(){let e=this.geometry;this.boundingSphere===null&&(this.boundingSphere=new on),this.boundingSphere.makeEmpty();let t=e.getAttribute("position");for(let r=0;r<t.count;r++)this.getVertexPosition(r,_p),this.boundingSphere.expandByPoint(_p)}copy(e,t){return super.copy(e,t),this.bindMode=e.bindMode,this.bindMatrix.copy(e.bindMatrix),this.bindMatrixInverse.copy(e.bindMatrixInverse),this.skeleton=e.skeleton,e.boundingBox!==null&&(this.boundingBox=e.boundingBox.clone()),e.boundingSphere!==null&&(this.boundingSphere=e.boundingSphere.clone()),this}raycast(e,t){let r=this.material,i=this.matrixWorld;r!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),Og.copy(this.boundingSphere),Og.applyMatrix4(i),e.ray.intersectsSphere(Og)!==!1&&(db.copy(i).invert(),Dg.copy(e.ray).applyMatrix4(db),!(this.boundingBox!==null&&Dg.intersectsBox(this.boundingBox)===!1)&&this._computeIntersections(e,t,Dg)))}getVertexPosition(e,t){return super.getVertexPosition(e,t),this.applyBoneTransform(e,t),t}bind(e,t){this.skeleton=e,t===void 0&&(this.updateMatrixWorld(!0),this.skeleton.calculateInverses(),t=this.matrixWorld),this.bindMatrix.copy(t),this.bindMatrixInverse.copy(t).invert()}pose(){this.skeleton.pose()}normalizeSkinWeights(){let e=new _i,t=this.geometry.attributes.skinWeight;for(let r=0,i=t.count;r<i;r++){e.fromBufferAttribute(t,r);let n=1/e.manhattanLength();n!==1/0?e.multiplyScalar(n):e.set(1,0,0,0),t.setXYZW(r,e.x,e.y,e.z,e.w)}}updateMatrixWorld(e){super.updateMatrixWorld(e),this.bindMode===fi?this.bindMatrixInverse.copy(this.matrixWorld).invert():this.bindMode===Mi?this.bindMatrixInverse.copy(this.bindMatrix).invert():console.warn("THREE.SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}applyBoneTransform(e,t){let r=this.skeleton,i=this.geometry;cb.fromBufferAttribute(i.attributes.skinIndex,e),hb.fromBufferAttribute(i.attributes.skinWeight,e),lb.copy(t).applyMatrix4(this.bindMatrix),t.set(0,0,0);for(let n=0;n<4;n++){let s=hb.getComponent(n);if(s!==0){let a=cb.getComponent(n);ub.multiplyMatrices(r.bones[a].matrixWorld,r.boneInverses[a]),t.addScaledVector(kT.copy(lb).applyMatrix4(ub),s)}}return t.applyMatrix4(this.bindMatrixInverse)}},Ep=class extends mi{constructor(){super(),this.isBone=!0,this.type="Bone"}},ys=class extends Qi{constructor(e=null,t=1,r=1,i,n,s,a,o,l=oi,c=oi,u,d){super(null,s,a,o,l,c,i,n,u,d),this.isDataTexture=!0,this.image={data:e,width:t,height:r},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},pb=new Ir,OT=new Ir,Fg=class eM{constructor(t=[],r=[]){this.uuid=fs(),this.bones=t.slice(0),this.boneInverses=r,this.boneMatrices=null,this.boneTexture=null,this.init()}init(){let t=this.bones,r=this.boneInverses;if(this.boneMatrices=new Float32Array(t.length*16),r.length===0)this.calculateInverses();else if(t.length!==r.length){console.warn("THREE.Skeleton: Number of inverse bone matrices does not match amount of bones."),this.boneInverses=[];for(let i=0,n=this.bones.length;i<n;i++)this.boneInverses.push(new Ir)}}calculateInverses(){this.boneInverses.length=0;for(let t=0,r=this.bones.length;t<r;t++){let i=new Ir;this.bones[t]&&i.copy(this.bones[t].matrixWorld).invert(),this.boneInverses.push(i)}}pose(){for(let t=0,r=this.bones.length;t<r;t++){let i=this.bones[t];i&&i.matrixWorld.copy(this.boneInverses[t]).invert()}for(let t=0,r=this.bones.length;t<r;t++){let i=this.bones[t];i&&(i.parent&&i.parent.isBone?(i.matrix.copy(i.parent.matrixWorld).invert(),i.matrix.multiply(i.matrixWorld)):i.matrix.copy(i.matrixWorld),i.matrix.decompose(i.position,i.quaternion,i.scale))}}update(){let t=this.bones,r=this.boneInverses,i=this.boneMatrices,n=this.boneTexture;for(let s=0,a=t.length;s<a;s++){let o=t[s]?t[s].matrixWorld:OT;pb.multiplyMatrices(o,r[s]),pb.toArray(i,s*16)}n!==null&&(n.needsUpdate=!0)}clone(){return new eM(this.bones,this.boneInverses)}computeBoneTexture(){let t=Math.sqrt(this.bones.length*4);t=Math.ceil(t/4)*4,t=Math.max(t,4);let r=new Float32Array(t*t*4);r.set(this.boneMatrices);let i=new ys(r,t,t,Ln,es);return i.needsUpdate=!0,this.boneMatrices=r,this.boneTexture=i,this}getBoneByName(t){for(let r=0,i=this.bones.length;r<i;r++){let n=this.bones[r];if(n.name===t)return n}}dispose(){this.boneTexture!==null&&(this.boneTexture.dispose(),this.boneTexture=null)}fromJSON(t,r){this.uuid=t.uuid;for(let i=0,n=t.bones.length;i<n;i++){let s=t.bones[i],a=r[s];a===void 0&&(console.warn("THREE.Skeleton: No bone found with UUID:",s),a=new Ep),this.bones.push(a),this.boneInverses.push(new Ir().fromArray(t.boneInverses[i]))}return this.init(),this}toJSON(){let t={metadata:{version:4.6,type:"Skeleton",generator:"Skeleton.toJSON"},bones:[],boneInverses:[]};t.uuid=this.uuid;let r=this.bones,i=this.boneInverses;for(let n=0,s=r.length;n<s;n++){let a=r[n];t.bones.push(a.uuid);let o=i[n];t.boneInverses.push(o.toArray())}return t}},qo=class extends ui{constructor(e,t,r,i=1){super(e,t,r),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=i}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){let e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}},fc=new Ir,fb=new Ir,Sp=[],mb=new Xi,DT=new Ir,Xh=new qr,Yh=new on,Mp=class extends qr{constructor(e,t,r){super(e,t),this.isInstancedMesh=!0,this.instanceMatrix=new qo(new Float32Array(r*16),16),this.instanceColor=null,this.morphTexture=null,this.count=r,this.boundingBox=null,this.boundingSphere=null;for(let i=0;i<r;i++)this.setMatrixAt(i,DT)}computeBoundingBox(){let e=this.geometry,t=this.count;this.boundingBox===null&&(this.boundingBox=new Xi),e.boundingBox===null&&e.computeBoundingBox(),this.boundingBox.makeEmpty();for(let r=0;r<t;r++)this.getMatrixAt(r,fc),mb.copy(e.boundingBox).applyMatrix4(fc),this.boundingBox.union(mb)}computeBoundingSphere(){let e=this.geometry,t=this.count;this.boundingSphere===null&&(this.boundingSphere=new on),e.boundingSphere===null&&e.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let r=0;r<t;r++)this.getMatrixAt(r,fc),Yh.copy(e.boundingSphere).applyMatrix4(fc),this.boundingSphere.union(Yh)}copy(e,t){return super.copy(e,t),this.instanceMatrix.copy(e.instanceMatrix),e.morphTexture!==null&&(this.morphTexture=e.morphTexture.clone()),e.instanceColor!==null&&(this.instanceColor=e.instanceColor.clone()),this.count=e.count,e.boundingBox!==null&&(this.boundingBox=e.boundingBox.clone()),e.boundingSphere!==null&&(this.boundingSphere=e.boundingSphere.clone()),this}getColorAt(e,t){t.fromArray(this.instanceColor.array,e*3)}getMatrixAt(e,t){t.fromArray(this.instanceMatrix.array,e*16)}getMorphAt(e,t){let r=t.morphTargetInfluences,i=this.morphTexture.source.data.data,n=r.length+1,s=e*n+1;for(let a=0;a<r.length;a++)r[a]=i[s+a]}raycast(e,t){let r=this.matrixWorld,i=this.count;if(Xh.geometry=this.geometry,Xh.material=this.material,Xh.material!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),Yh.copy(this.boundingSphere),Yh.applyMatrix4(r),e.ray.intersectsSphere(Yh)!==!1))for(let n=0;n<i;n++){this.getMatrixAt(n,fc),fb.multiplyMatrices(r,fc),Xh.matrixWorld=fb,Xh.raycast(e,Sp);for(let s=0,a=Sp.length;s<a;s++){let o=Sp[s];o.instanceId=n,o.object=this,t.push(o)}Sp.length=0}}setColorAt(e,t){this.instanceColor===null&&(this.instanceColor=new qo(new Float32Array(this.instanceMatrix.count*3).fill(1),3)),t.toArray(this.instanceColor.array,e*3)}setMatrixAt(e,t){t.toArray(this.instanceMatrix.array,e*16)}setMorphAt(e,t){let r=t.morphTargetInfluences,i=r.length+1;this.morphTexture===null&&(this.morphTexture=new ys(new Float32Array(i*this.count),i,this.count,xd,es));let n=this.morphTexture.source.data.data,s=0;for(let l=0;l<r.length;l++)s+=r[l];let a=this.geometry.morphTargetsRelative?1:1-s,o=i*e;n[o]=a,n.set(r,o+1)}updateMorphTargets(){}dispose(){return this.dispatchEvent({type:"dispose"}),this.morphTexture!==null&&(this.morphTexture.dispose(),this.morphTexture=null),this}},zg=new je,UT=new je,FT=new si,Ua=class{constructor(e=new je(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,r,i){return this.normal.set(e,t,r),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,r){let i=zg.subVectors(r,t).cross(UT.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){let e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){let r=e.delta(zg),i=this.normal.dot(r);if(i===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;let n=-(e.start.dot(this.normal)+this.constant)/i;return n<0||n>1?null:t.copy(e.start).addScaledVector(r,n)}intersectsLine(e){let t=this.distanceToPoint(e.start),r=this.distanceToPoint(e.end);return t<0&&r>0||r<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){let r=t||FT.getNormalMatrix(e),i=this.coplanarPoint(zg).applyMatrix4(e),n=this.normal.applyMatrix3(r).normalize();return this.constant=-i.dot(n),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}},Ko=new on,Ap=new je,qh=class{constructor(e=new Ua,t=new Ua,r=new Ua,i=new Ua,n=new Ua,s=new Ua){this.planes=[e,t,r,i,n,s]}set(e,t,r,i,n,s){let a=this.planes;return a[0].copy(e),a[1].copy(t),a[2].copy(r),a[3].copy(i),a[4].copy(n),a[5].copy(s),this}copy(e){let t=this.planes;for(let r=0;r<6;r++)t[r].copy(e.planes[r]);return this}setFromProjectionMatrix(e,t=ca){let r=this.planes,i=e.elements,n=i[0],s=i[1],a=i[2],o=i[3],l=i[4],c=i[5],u=i[6],d=i[7],f=i[8],y=i[9],b=i[10],x=i[11],g=i[12],v=i[13],_=i[14],E=i[15];if(r[0].setComponents(o-n,d-l,x-f,E-g).normalize(),r[1].setComponents(o+n,d+l,x+f,E+g).normalize(),r[2].setComponents(o+s,d+c,x+y,E+v).normalize(),r[3].setComponents(o-s,d-c,x-y,E-v).normalize(),r[4].setComponents(o-a,d-u,x-b,E-_).normalize(),t===ca)r[5].setComponents(o+a,d+u,x+b,E+_).normalize();else if(t===Lh)r[5].setComponents(a,u,b,_).normalize();else throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Ko.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Ko.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Ko)}intersectsSprite(e){return Ko.center.set(0,0,0),Ko.radius=.7071067811865476,Ko.applyMatrix4(e.matrixWorld),this.intersectsSphere(Ko)}intersectsSphere(e){let t=this.planes,r=e.center,i=-e.radius;for(let n=0;n<6;n++)if(t[n].distanceToPoint(r)<i)return!1;return!0}intersectsBox(e){let t=this.planes;for(let r=0;r<6;r++){let i=t[r];if(Ap.x=i.normal.x>0?e.max.x:e.min.x,Ap.y=i.normal.y>0?e.max.y:e.min.y,Ap.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(Ap)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let r=0;r<6;r++)if(t[r].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}};function Bg(e,t){return e-t}function zT(e,t){return e.z-t.z}function BT(e,t){return t.z-e.z}var jT=class{constructor(){this.index=0,this.pool=[],this.list=[]}push(e,t,r,i){let n=this.pool,s=this.list;this.index>=n.length&&n.push({start:-1,count:-1,z:-1,index:-1});let a=n[this.index];s.push(a),this.index++,a.start=e,a.count=t,a.z=r,a.index=i}reset(){this.list.length=0,this.index=0}},rs=new Ir,VT=new or(1,1,1),jg=new qh,Tp=new Xi,Zo=new on,Kh=new je,gb=new je,HT=new je,Vg=new jT,Un=new qr,Cp=[];function GT(e,t,r=0){let i=t.itemSize;if(e.isInterleavedBufferAttribute||e.array.constructor!==t.array.constructor){let n=e.count;for(let s=0;s<n;s++)for(let a=0;a<i;a++)t.setComponent(s+r,a,e.getComponent(s,a))}else t.array.set(e.array,r*i);t.needsUpdate=!0}function $o(e,t){if(e.constructor!==t.constructor){let r=Math.min(e.length,t.length);for(let i=0;i<r;i++)t[i]=e[i]}else{let r=Math.min(e.length,t.length);t.set(new e.constructor(e.buffer,0,r))}}var yb=class extends qr{get maxInstanceCount(){return this._maxInstanceCount}get instanceCount(){return this._instanceInfo.length-this._availableInstanceIds.length}get unusedVertexCount(){return this._maxVertexCount-this._nextVertexStart}get unusedIndexCount(){return this._maxIndexCount-this._nextIndexStart}constructor(e,t,r=t*2,i){super(new Hr,i),this.isBatchedMesh=!0,this.perObjectFrustumCulled=!0,this.sortObjects=!0,this.boundingBox=null,this.boundingSphere=null,this.customSort=null,this._instanceInfo=[],this._geometryInfo=[],this._availableInstanceIds=[],this._availableGeometryIds=[],this._nextIndexStart=0,this._nextVertexStart=0,this._geometryCount=0,this._visibilityChanged=!0,this._geometryInitialized=!1,this._maxInstanceCount=e,this._maxVertexCount=t,this._maxIndexCount=r,this._multiDrawCounts=new Int32Array(e),this._multiDrawStarts=new Int32Array(e),this._multiDrawCount=0,this._multiDrawInstances=null,this._matricesTexture=null,this._indirectTexture=null,this._colorsTexture=null,this._initMatricesTexture(),this._initIndirectTexture()}_initMatricesTexture(){let e=Math.sqrt(this._maxInstanceCount*4);e=Math.ceil(e/4)*4,e=Math.max(e,4);let t=new Float32Array(e*e*4),r=new ys(t,e,e,Ln,es);this._matricesTexture=r}_initIndirectTexture(){let e=Math.sqrt(this._maxInstanceCount);e=Math.ceil(e);let t=new Uint32Array(e*e),r=new ys(t,e,e,Sh,Aa);this._indirectTexture=r}_initColorsTexture(){let e=Math.sqrt(this._maxInstanceCount);e=Math.ceil(e);let t=new Float32Array(e*e*4).fill(1),r=new ys(t,e,e,Ln,es);r.colorSpace=li.workingColorSpace,this._colorsTexture=r}_initializeGeometry(e){let t=this.geometry,r=this._maxVertexCount,i=this._maxIndexCount;if(this._geometryInitialized===!1){for(let n in e.attributes){let s=e.getAttribute(n),{array:a,itemSize:o,normalized:l}=s,c=new a.constructor(r*o),u=new ui(c,o,l);t.setAttribute(n,u)}if(e.getIndex()!==null){let n=r>65535?new Uint32Array(i):new Uint16Array(i);t.setIndex(new ui(n,1))}this._geometryInitialized=!0}}_validateGeometry(e){let t=this.geometry;if(!!e.getIndex()!=!!t.getIndex())throw new Error('THREE.BatchedMesh: All geometries must consistently have "index".');for(let r in t.attributes){if(!e.hasAttribute(r))throw new Error(`THREE.BatchedMesh: Added geometry missing "${r}". All geometries must have consistent attributes.`);let i=e.getAttribute(r),n=t.getAttribute(r);if(i.itemSize!==n.itemSize||i.normalized!==n.normalized)throw new Error("THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.")}}validateInstanceId(e){let t=this._instanceInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`THREE.BatchedMesh: Invalid instanceId ${e}. Instance is either out of range or has been deleted.`)}validateGeometryId(e){let t=this._geometryInfo;if(e<0||e>=t.length||t[e].active===!1)throw new Error(`THREE.BatchedMesh: Invalid geometryId ${e}. Geometry is either out of range or has been deleted.`)}setCustomSort(e){return this.customSort=e,this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Xi);let e=this.boundingBox,t=this._instanceInfo;e.makeEmpty();for(let r=0,i=t.length;r<i;r++){if(t[r].active===!1)continue;let n=t[r].geometryIndex;this.getMatrixAt(r,rs),this.getBoundingBoxAt(n,Tp).applyMatrix4(rs),e.union(Tp)}}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new on);let e=this.boundingSphere,t=this._instanceInfo;e.makeEmpty();for(let r=0,i=t.length;r<i;r++){if(t[r].active===!1)continue;let n=t[r].geometryIndex;this.getMatrixAt(r,rs),this.getBoundingSphereAt(n,Zo).applyMatrix4(rs),e.union(Zo)}}addInstance(e){if(this._instanceInfo.length>=this.maxInstanceCount&&this._availableInstanceIds.length===0)throw new Error("THREE.BatchedMesh: Maximum item count reached.");let t={visible:!0,active:!0,geometryIndex:e},r=null;this._availableInstanceIds.length>0?(this._availableInstanceIds.sort(Bg),r=this._availableInstanceIds.shift(),this._instanceInfo[r]=t):(r=this._instanceInfo.length,this._instanceInfo.push(t));let i=this._matricesTexture;rs.identity().toArray(i.image.data,r*16),i.needsUpdate=!0;let n=this._colorsTexture;return n&&(VT.toArray(n.image.data,r*4),n.needsUpdate=!0),this._visibilityChanged=!0,r}addGeometry(e,t=-1,r=-1){this._initializeGeometry(e),this._validateGeometry(e);let i={vertexStart:-1,vertexCount:-1,reservedVertexCount:-1,indexStart:-1,indexCount:-1,reservedIndexCount:-1,start:-1,count:-1,boundingBox:null,boundingSphere:null,active:!0},n=this._geometryInfo;i.vertexStart=this._nextVertexStart,i.reservedVertexCount=t===-1?e.getAttribute("position").count:t;let s=e.getIndex();if(s!==null&&(i.indexStart=this._nextIndexStart,i.reservedIndexCount=r===-1?s.count:r),i.indexStart!==-1&&i.indexStart+i.reservedIndexCount>this._maxIndexCount||i.vertexStart+i.reservedVertexCount>this._maxVertexCount)throw new Error("THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.");let a;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(Bg),a=this._availableGeometryIds.shift(),n[a]=i):(a=this._geometryCount,this._geometryCount++,n.push(i)),this.setGeometryAt(a,e),this._nextIndexStart=i.indexStart+i.reservedIndexCount,this._nextVertexStart=i.vertexStart+i.reservedVertexCount,a}setGeometryAt(e,t){if(e>=this._geometryCount)throw new Error("THREE.BatchedMesh: Maximum geometry count reached.");this._validateGeometry(t);let r=this.geometry,i=r.getIndex()!==null,n=r.getIndex(),s=t.getIndex(),a=this._geometryInfo[e];if(i&&s.count>a.reservedIndexCount||t.attributes.position.count>a.reservedVertexCount)throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry.");let o=a.vertexStart,l=a.reservedVertexCount;a.vertexCount=t.getAttribute("position").count;for(let c in r.attributes){let u=t.getAttribute(c),d=r.getAttribute(c);GT(u,d,o);let f=u.itemSize;for(let y=u.count,b=l;y<b;y++){let x=o+y;for(let g=0;g<f;g++)d.setComponent(x,g,0)}d.needsUpdate=!0,d.addUpdateRange(o*f,l*f)}if(i){let c=a.indexStart,u=a.reservedIndexCount;a.indexCount=t.getIndex().count;for(let d=0;d<s.count;d++)n.setX(c+d,o+s.getX(d));for(let d=s.count,f=u;d<f;d++)n.setX(c+d,o);n.needsUpdate=!0,n.addUpdateRange(c,a.reservedIndexCount)}return a.start=i?a.indexStart:a.vertexStart,a.count=i?a.indexCount:a.vertexCount,a.boundingBox=null,t.boundingBox!==null&&(a.boundingBox=t.boundingBox.clone()),a.boundingSphere=null,t.boundingSphere!==null&&(a.boundingSphere=t.boundingSphere.clone()),this._visibilityChanged=!0,e}deleteGeometry(e){let t=this._geometryInfo;if(e>=t.length||t[e].active===!1)return this;let r=this._instanceInfo;for(let i=0,n=r.length;i<n;i++)r[i].geometryIndex===e&&this.deleteInstance(i);return t[e].active=!1,this._availableGeometryIds.push(e),this._visibilityChanged=!0,this}deleteInstance(e){return this.validateInstanceId(e),this._instanceInfo[e].active=!1,this._availableInstanceIds.push(e),this._visibilityChanged=!0,this}optimize(){let e=0,t=0,r=this._geometryInfo,i=r.map((s,a)=>a).sort((s,a)=>r[s].vertexStart-r[a].vertexStart),n=this.geometry;for(let s=0,a=r.length;s<a;s++){let o=i[s],l=r[o];if(l.active!==!1){if(n.index!==null){if(l.indexStart!==t){let{indexStart:c,vertexStart:u,reservedIndexCount:d}=l,f=n.index,y=f.array,b=e-u;for(let x=c;x<c+d;x++)y[x]=y[x]+b;f.array.copyWithin(t,c,c+d),f.addUpdateRange(t,d),l.indexStart=t}t+=l.reservedIndexCount}if(l.vertexStart!==e){let{vertexStart:c,reservedVertexCount:u}=l,d=n.attributes;for(let f in d){let y=d[f],{array:b,itemSize:x}=y;b.copyWithin(e*x,c*x,(c+u)*x),y.addUpdateRange(e*x,u*x)}l.vertexStart=e}e+=l.reservedVertexCount,l.start=n.index?l.indexStart:l.vertexStart,this._nextIndexStart=n.index?l.indexStart+l.reservedIndexCount:0,this._nextVertexStart=l.vertexStart+l.reservedVertexCount}}return this}getBoundingBoxAt(e,t){if(e>=this._geometryCount)return null;let r=this.geometry,i=this._geometryInfo[e];if(i.boundingBox===null){let n=new Xi,s=r.index,a=r.attributes.position;for(let o=i.start,l=i.start+i.count;o<l;o++){let c=o;s&&(c=s.getX(c)),n.expandByPoint(Kh.fromBufferAttribute(a,c))}i.boundingBox=n}return t.copy(i.boundingBox),t}getBoundingSphereAt(e,t){if(e>=this._geometryCount)return null;let r=this.geometry,i=this._geometryInfo[e];if(i.boundingSphere===null){let n=new on;this.getBoundingBoxAt(e,Tp),Tp.getCenter(n.center);let s=r.index,a=r.attributes.position,o=0;for(let l=i.start,c=i.start+i.count;l<c;l++){let u=l;s&&(u=s.getX(u)),Kh.fromBufferAttribute(a,u),o=Math.max(o,n.center.distanceToSquared(Kh))}n.radius=Math.sqrt(o),i.boundingSphere=n}return t.copy(i.boundingSphere),t}setMatrixAt(e,t){this.validateInstanceId(e);let r=this._matricesTexture,i=this._matricesTexture.image.data;return t.toArray(i,e*16),r.needsUpdate=!0,this}getMatrixAt(e,t){return this.validateInstanceId(e),t.fromArray(this._matricesTexture.image.data,e*16)}setColorAt(e,t){return this.validateInstanceId(e),this._colorsTexture===null&&this._initColorsTexture(),t.toArray(this._colorsTexture.image.data,e*4),this._colorsTexture.needsUpdate=!0,this}getColorAt(e,t){return this.validateInstanceId(e),t.fromArray(this._colorsTexture.image.data,e*4)}setVisibleAt(e,t){return this.validateInstanceId(e),this._instanceInfo[e].visible===t?this:(this._instanceInfo[e].visible=t,this._visibilityChanged=!0,this)}getVisibleAt(e){return this.validateInstanceId(e),this._instanceInfo[e].visible}setGeometryIdAt(e,t){return this.validateInstanceId(e),this.validateGeometryId(t),this._instanceInfo[e].geometryIndex=t,this}getGeometryIdAt(e){return this.validateInstanceId(e),this._instanceInfo[e].geometryIndex}getGeometryRangeAt(e,t={}){this.validateGeometryId(e);let r=this._geometryInfo[e];return t.vertexStart=r.vertexStart,t.vertexCount=r.vertexCount,t.reservedVertexCount=r.reservedVertexCount,t.indexStart=r.indexStart,t.indexCount=r.indexCount,t.reservedIndexCount=r.reservedIndexCount,t.start=r.start,t.count=r.count,t}setInstanceCount(e){let t=this._availableInstanceIds,r=this._instanceInfo;for(t.sort(Bg);t[t.length-1]===r.length;)r.pop(),t.pop();if(e<r.length)throw new Error(`BatchedMesh: Instance ids outside the range ${e} are being used. Cannot shrink instance count.`);let i=new Int32Array(e),n=new Int32Array(e);$o(this._multiDrawCounts,i),$o(this._multiDrawStarts,n),this._multiDrawCounts=i,this._multiDrawStarts=n,this._maxInstanceCount=e;let s=this._indirectTexture,a=this._matricesTexture,o=this._colorsTexture;s.dispose(),this._initIndirectTexture(),$o(s.image.data,this._indirectTexture.image.data),a.dispose(),this._initMatricesTexture(),$o(a.image.data,this._matricesTexture.image.data),o&&(o.dispose(),this._initColorsTexture(),$o(o.image.data,this._colorsTexture.image.data))}setGeometrySize(e,t){let r=[...this._geometryInfo].filter(s=>s.active);if(Math.max(...r.map(s=>s.vertexStart+s.reservedVertexCount))>e)throw new Error(`BatchedMesh: Geometry vertex values are being used outside the range ${t}. Cannot shrink further.`);if(this.geometry.index&&Math.max(...r.map(s=>s.indexStart+s.reservedIndexCount))>t)throw new Error(`BatchedMesh: Geometry index values are being used outside the range ${t}. Cannot shrink further.`);let i=this.geometry;i.dispose(),this._maxVertexCount=e,this._maxIndexCount=t,this._geometryInitialized&&(this._geometryInitialized=!1,this.geometry=new Hr,this._initializeGeometry(i));let n=this.geometry;i.index&&$o(i.index.array,n.index.array);for(let s in i.attributes)$o(i.attributes[s].array,n.attributes[s].array)}raycast(e,t){let r=this._instanceInfo,i=this._geometryInfo,n=this.matrixWorld,s=this.geometry;Un.material=this.material,Un.geometry.index=s.index,Un.geometry.attributes=s.attributes,Un.geometry.boundingBox===null&&(Un.geometry.boundingBox=new Xi),Un.geometry.boundingSphere===null&&(Un.geometry.boundingSphere=new on);for(let a=0,o=r.length;a<o;a++){if(!r[a].visible||!r[a].active)continue;let l=r[a].geometryIndex,c=i[l];Un.geometry.setDrawRange(c.start,c.count),this.getMatrixAt(a,Un.matrixWorld).premultiply(n),this.getBoundingBoxAt(l,Un.geometry.boundingBox),this.getBoundingSphereAt(l,Un.geometry.boundingSphere),Un.raycast(e,Cp);for(let u=0,d=Cp.length;u<d;u++){let f=Cp[u];f.object=this,f.batchId=a,t.push(f)}Cp.length=0}Un.material=null,Un.geometry.index=null,Un.geometry.attributes={},Un.geometry.setDrawRange(0,1/0)}copy(e){return super.copy(e),this.geometry=e.geometry.clone(),this.perObjectFrustumCulled=e.perObjectFrustumCulled,this.sortObjects=e.sortObjects,this.boundingBox=e.boundingBox!==null?e.boundingBox.clone():null,this.boundingSphere=e.boundingSphere!==null?e.boundingSphere.clone():null,this._geometryInfo=e._geometryInfo.map(t=>({...t,boundingBox:t.boundingBox!==null?t.boundingBox.clone():null,boundingSphere:t.boundingSphere!==null?t.boundingSphere.clone():null})),this._instanceInfo=e._instanceInfo.map(t=>({...t})),this._maxInstanceCount=e._maxInstanceCount,this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._geometryCount=e._geometryCount,this._multiDrawCounts=e._multiDrawCounts.slice(),this._multiDrawStarts=e._multiDrawStarts.slice(),this._matricesTexture=e._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),this._colorsTexture!==null&&(this._colorsTexture=e._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice()),this}dispose(){return this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,this._colorsTexture!==null&&(this._colorsTexture.dispose(),this._colorsTexture=null),this}onBeforeRender(e,t,r,i,n){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;let s=i.getIndex(),a=s===null?1:s.array.BYTES_PER_ELEMENT,o=this._instanceInfo,l=this._multiDrawStarts,c=this._multiDrawCounts,u=this._geometryInfo,d=this.perObjectFrustumCulled,f=this._indirectTexture,y=f.image.data;d&&(rs.multiplyMatrices(r.projectionMatrix,r.matrixWorldInverse).multiply(this.matrixWorld),jg.setFromProjectionMatrix(rs,e.coordinateSystem));let b=0;if(this.sortObjects){rs.copy(this.matrixWorld).invert(),Kh.setFromMatrixPosition(r.matrixWorld).applyMatrix4(rs),gb.set(0,0,-1).transformDirection(r.matrixWorld).transformDirection(rs);for(let v=0,_=o.length;v<_;v++)if(o[v].visible&&o[v].active){let E=o[v].geometryIndex;this.getMatrixAt(v,rs),this.getBoundingSphereAt(E,Zo).applyMatrix4(rs);let M=!1;if(d&&(M=!jg.intersectsSphere(Zo)),!M){let P=u[E],k=HT.subVectors(Zo.center,Kh).dot(gb);Vg.push(P.start,P.count,k,v)}}let x=Vg.list,g=this.customSort;g===null?x.sort(n.transparent?BT:zT):g.call(this,x,r);for(let v=0,_=x.length;v<_;v++){let E=x[v];l[b]=E.start*a,c[b]=E.count,y[b]=E.index,b++}Vg.reset()}else for(let x=0,g=o.length;x<g;x++)if(o[x].visible&&o[x].active){let v=o[x].geometryIndex,_=!1;if(d&&(this.getMatrixAt(x,rs),this.getBoundingSphereAt(v,Zo).applyMatrix4(rs),_=!jg.intersectsSphere(Zo)),!_){let E=u[v];l[b]=E.start*a,c[b]=E.count,y[b]=x,b++}}f.needsUpdate=!0,this._multiDrawCount=b,this._visibilityChanged=!1}onBeforeShadow(e,t,r,i,n,s){this.onBeforeRender(e,null,i,n,s)}},tn=class extends bn{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new or(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}},Rp=new je,Pp=new je,vb=new Ir,Zh=new Wo,Ip=new on,Hg=new je,xb=new je,ua=class extends mi{constructor(e=new Hr,t=new tn){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=t,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,r=[0];for(let i=1,n=t.count;i<n;i++)Rp.fromBufferAttribute(t,i-1),Pp.fromBufferAttribute(t,i),r[i]=r[i-1],r[i]+=Rp.distanceTo(Pp);e.setAttribute("lineDistance",new hr(r,1))}else console.warn("THREE.Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}raycast(e,t){let r=this.geometry,i=this.matrixWorld,n=e.params.Line.threshold,s=r.drawRange;if(r.boundingSphere===null&&r.computeBoundingSphere(),Ip.copy(r.boundingSphere),Ip.applyMatrix4(i),Ip.radius+=n,e.ray.intersectsSphere(Ip)===!1)return;vb.copy(i).invert(),Zh.copy(e.ray).applyMatrix4(vb);let a=n/((this.scale.x+this.scale.y+this.scale.z)/3),o=a*a,l=this.isLineSegments?2:1,c=r.index,u=r.attributes.position;if(c!==null){let d=Math.max(0,s.start),f=Math.min(c.count,s.start+s.count);for(let y=d,b=f-1;y<b;y+=l){let x=c.getX(y),g=c.getX(y+1),v=Np(this,e,Zh,o,x,g);v&&t.push(v)}if(this.isLineLoop){let y=c.getX(f-1),b=c.getX(d),x=Np(this,e,Zh,o,y,b);x&&t.push(x)}}else{let d=Math.max(0,s.start),f=Math.min(u.count,s.start+s.count);for(let y=d,b=f-1;y<b;y+=l){let x=Np(this,e,Zh,o,y,y+1);x&&t.push(x)}if(this.isLineLoop){let y=Np(this,e,Zh,o,f-1,d);y&&t.push(y)}}}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let r=e[t[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let i=0,n=r.length;i<n;i++){let s=r[i].name||String(i);this.morphTargetInfluences.push(0),this.morphTargetDictionary[s]=i}}}}};function Np(e,t,r,i,n,s){let a=e.geometry.attributes.position;if(Rp.fromBufferAttribute(a,n),Pp.fromBufferAttribute(a,s),r.distanceSqToSegment(Rp,Pp,Hg,xb)>i)return;Hg.applyMatrix4(e.matrixWorld);let o=t.ray.origin.distanceTo(Hg);if(!(o<t.near||o>t.far))return{distance:o,point:xb.clone().applyMatrix4(e.matrixWorld),index:n,face:null,faceIndex:null,barycoord:null,object:e}}var bb=new je,wb=new je,Fn=class extends ua{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,r=[];for(let i=0,n=t.count;i<n;i+=2)bb.fromBufferAttribute(t,i),wb.fromBufferAttribute(t,i+1),r[i]=i===0?0:r[i-1],r[i+1]=r[i]+bb.distanceTo(wb);e.setAttribute("lineDistance",new hr(r,1))}else console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}},Lp=class extends ua{constructor(e,t){super(e,t),this.isLineLoop=!0,this.type="LineLoop"}},$h=class extends bn{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new or(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}},_b=new Ir,Gg=new Wo,kp=new on,Op=new je,Dp=class extends mi{constructor(e=new Hr,t=new $h){super(),this.isPoints=!0,this.type="Points",this.geometry=e,this.material=t,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}raycast(e,t){let r=this.geometry,i=this.matrixWorld,n=e.params.Points.threshold,s=r.drawRange;if(r.boundingSphere===null&&r.computeBoundingSphere(),kp.copy(r.boundingSphere),kp.applyMatrix4(i),kp.radius+=n,e.ray.intersectsSphere(kp)===!1)return;_b.copy(i).invert(),Gg.copy(e.ray).applyMatrix4(_b);let a=n/((this.scale.x+this.scale.y+this.scale.z)/3),o=a*a,l=r.index,c=r.attributes.position;if(l!==null){let u=Math.max(0,s.start),d=Math.min(l.count,s.start+s.count);for(let f=u,y=d;f<y;f++){let b=l.getX(f);Op.fromBufferAttribute(c,b),Eb(Op,b,o,i,e,t,this)}}else{let u=Math.max(0,s.start),d=Math.min(c.count,s.start+s.count);for(let f=u,y=d;f<y;f++)Op.fromBufferAttribute(c,f),Eb(Op,f,o,i,e,t,this)}}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let r=e[t[0]];if(r!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let i=0,n=r.length;i<n;i++){let s=r[i].name||String(i);this.morphTargetInfluences.push(0),this.morphTargetDictionary[s]=i}}}}};function Eb(e,t,r,i,n,s,a){let o=Gg.distanceSqToPoint(e);if(o<r){let l=new je;Gg.closestPointToPoint(e,l),l.applyMatrix4(i);let c=n.ray.origin.distanceTo(l);if(c<n.near||c>n.far)return;s.push({distance:c,distanceToRay:Math.sqrt(o),point:l,index:t,face:null,faceIndex:null,barycoord:null,object:a})}}var Wi=class extends mi{constructor(){super(),this.isGroup=!0,this.type="Group"}},WT=class extends Qi{constructor(e,t,r,i,n,s,a,o,l){super(e,t,r,i,n,s,a,o,l),this.isVideoTexture=!0,this.minFilter=s!==void 0?s:Pi,this.magFilter=n!==void 0?n:Pi,this.generateMipmaps=!1;let c=this;function u(){c.needsUpdate=!0,e.requestVideoFrameCallback(u)}"requestVideoFrameCallback"in e&&e.requestVideoFrameCallback(u)}clone(){return new this.constructor(this.image).copy(this)}update(){let e=this.image;!("requestVideoFrameCallback"in e)&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}},XT=class extends Qi{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=oi,this.minFilter=oi,this.generateMipmaps=!1,this.needsUpdate=!0}},Up=class extends Qi{constructor(e,t,r,i,n,s,a,o,l,c,u,d){super(null,s,a,o,l,c,i,n,u,d),this.isCompressedTexture=!0,this.image={width:t,height:r},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}},YT=class extends Up{constructor(e,t,r,i,n,s){super(e,t,r,n,s),this.isCompressedArrayTexture=!0,this.image.depth=i,this.wrapR=ei,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},qT=class extends Up{constructor(e,t,r){super(void 0,e[0].width,e[0].height,t,r,br),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}},Fp=class extends Qi{constructor(e,t,r,i,n,s,a,o,l){super(e,t,r,i,n,s,a,o,l),this.isCanvasTexture=!0,this.needsUpdate=!0}},zp=class extends Qi{constructor(e,t,r,i,n,s,a,o,l,c=Uo){if(c!==Uo&&c!==no)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");r===void 0&&c===Uo&&(r=Aa),r===void 0&&c===no&&(r=io),super(null,i,n,s,a,o,c,r,l),this.isDepthTexture=!0,this.image={width:e,height:t},this.magFilter=a!==void 0?a:oi,this.minFilter=o!==void 0?o:oi,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}},Ks=class{constructor(){this.type="Curve",this.arcLengthDivisions=200}getPoint(){return console.warn("THREE.Curve: .getPoint() not implemented."),null}getPointAt(e,t){let r=this.getUtoTmapping(e);return this.getPoint(r,t)}getPoints(e=5){let t=[];for(let r=0;r<=e;r++)t.push(this.getPoint(r/e));return t}getSpacedPoints(e=5){let t=[];for(let r=0;r<=e;r++)t.push(this.getPointAt(r/e));return t}getLength(){let e=this.getLengths();return e[e.length-1]}getLengths(e=this.arcLengthDivisions){if(this.cacheArcLengths&&this.cacheArcLengths.length===e+1&&!this.needsUpdate)return this.cacheArcLengths;this.needsUpdate=!1;let t=[],r,i=this.getPoint(0),n=0;t.push(0);for(let s=1;s<=e;s++)r=this.getPoint(s/e),n+=r.distanceTo(i),t.push(n),i=r;return this.cacheArcLengths=t,t}updateArcLengths(){this.needsUpdate=!0,this.getLengths()}getUtoTmapping(e,t){let r=this.getLengths(),i=0,n=r.length,s;t?s=t:s=e*r[n-1];let a=0,o=n-1,l;for(;a<=o;)if(i=Math.floor(a+(o-a)/2),l=r[i]-s,l<0)a=i+1;else if(l>0)o=i-1;else{o=i;break}if(i=o,r[i]===s)return i/(n-1);let c=r[i],u=r[i+1]-c,d=(s-c)/u;return(i+d)/(n-1)}getTangent(e,t){let r=e-1e-4,i=e+1e-4;r<0&&(r=0),i>1&&(i=1);let n=this.getPoint(r),s=this.getPoint(i),a=t||(n.isVector2?new Ft:new je);return a.copy(s).sub(n).normalize(),a}getTangentAt(e,t){let r=this.getUtoTmapping(e);return this.getTangent(r,t)}computeFrenetFrames(e,t){let r=new je,i=[],n=[],s=[],a=new je,o=new Ir;for(let f=0;f<=e;f++){let y=f/e;i[f]=this.getTangentAt(y,new je)}n[0]=new je,s[0]=new je;let l=Number.MAX_VALUE,c=Math.abs(i[0].x),u=Math.abs(i[0].y),d=Math.abs(i[0].z);c<=l&&(l=c,r.set(1,0,0)),u<=l&&(l=u,r.set(0,1,0)),d<=l&&r.set(0,0,1),a.crossVectors(i[0],r).normalize(),n[0].crossVectors(i[0],a),s[0].crossVectors(i[0],n[0]);for(let f=1;f<=e;f++){if(n[f]=n[f-1].clone(),s[f]=s[f-1].clone(),a.crossVectors(i[f-1],i[f]),a.length()>Number.EPSILON){a.normalize();let y=Math.acos(Jr(i[f-1].dot(i[f]),-1,1));n[f].applyMatrix4(o.makeRotationAxis(a,y))}s[f].crossVectors(i[f],n[f])}if(t===!0){let f=Math.acos(Jr(n[0].dot(n[e]),-1,1));f/=e,i[0].dot(a.crossVectors(n[0],n[e]))>0&&(f=-f);for(let y=1;y<=e;y++)n[y].applyMatrix4(o.makeRotationAxis(i[y],f*y)),s[y].crossVectors(i[y],n[y])}return{tangents:i,normals:n,binormals:s}}clone(){return new this.constructor().copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){let e={metadata:{version:4.6,type:"Curve",generator:"Curve.toJSON"}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}},Bp=class extends Ks{constructor(e=0,t=0,r=1,i=1,n=0,s=Math.PI*2,a=!1,o=0){super(),this.isEllipseCurve=!0,this.type="EllipseCurve",this.aX=e,this.aY=t,this.xRadius=r,this.yRadius=i,this.aStartAngle=n,this.aEndAngle=s,this.aClockwise=a,this.aRotation=o}getPoint(e,t=new Ft){let r=t,i=Math.PI*2,n=this.aEndAngle-this.aStartAngle,s=Math.abs(n)<Number.EPSILON;for(;n<0;)n+=i;for(;n>i;)n-=i;n<Number.EPSILON&&(s?n=0:n=i),this.aClockwise===!0&&!s&&(n===i?n=-i:n=n-i);let a=this.aStartAngle+e*n,o=this.aX+this.xRadius*Math.cos(a),l=this.aY+this.yRadius*Math.sin(a);if(this.aRotation!==0){let c=Math.cos(this.aRotation),u=Math.sin(this.aRotation),d=o-this.aX,f=l-this.aY;o=d*c-f*u+this.aX,l=d*u+f*c+this.aY}return r.set(o,l)}copy(e){return super.copy(e),this.aX=e.aX,this.aY=e.aY,this.xRadius=e.xRadius,this.yRadius=e.yRadius,this.aStartAngle=e.aStartAngle,this.aEndAngle=e.aEndAngle,this.aClockwise=e.aClockwise,this.aRotation=e.aRotation,this}toJSON(){let e=super.toJSON();return e.aX=this.aX,e.aY=this.aY,e.xRadius=this.xRadius,e.yRadius=this.yRadius,e.aStartAngle=this.aStartAngle,e.aEndAngle=this.aEndAngle,e.aClockwise=this.aClockwise,e.aRotation=this.aRotation,e}fromJSON(e){return super.fromJSON(e),this.aX=e.aX,this.aY=e.aY,this.xRadius=e.xRadius,this.yRadius=e.yRadius,this.aStartAngle=e.aStartAngle,this.aEndAngle=e.aEndAngle,this.aClockwise=e.aClockwise,this.aRotation=e.aRotation,this}},Sb=class extends Bp{constructor(e,t,r,i,n,s){super(e,t,r,r,i,n,s),this.isArcCurve=!0,this.type="ArcCurve"}};function Wg(){let e=0,t=0,r=0,i=0;function n(s,a,o,l){e=s,t=o,r=-3*s+3*a-2*o-l,i=2*s-2*a+o+l}return{initCatmullRom:function(s,a,o,l,c){n(a,o,c*(o-s),c*(l-a))},initNonuniformCatmullRom:function(s,a,o,l,c,u,d){let f=(a-s)/c-(o-s)/(c+u)+(o-a)/u,y=(o-a)/u-(l-a)/(u+d)+(l-o)/d;f*=u,y*=u,n(a,o,f,y)},calc:function(s){let a=s*s,o=a*s;return e+t*s+r*a+i*o}}}var jp=new je,Xg=new Wg,Yg=new Wg,qg=new Wg,Mb=class extends Ks{constructor(e=[],t=!1,r="centripetal",i=.5){super(),this.isCatmullRomCurve3=!0,this.type="CatmullRomCurve3",this.points=e,this.closed=t,this.curveType=r,this.tension=i}getPoint(e,t=new je){let r=t,i=this.points,n=i.length,s=(n-(this.closed?0:1))*e,a=Math.floor(s),o=s-a;this.closed?a+=a>0?0:(Math.floor(Math.abs(a)/n)+1)*n:o===0&&a===n-1&&(a=n-2,o=1);let l,c;this.closed||a>0?l=i[(a-1)%n]:(jp.subVectors(i[0],i[1]).add(i[0]),l=jp);let u=i[a%n],d=i[(a+1)%n];if(this.closed||a+2<n?c=i[(a+2)%n]:(jp.subVectors(i[n-1],i[n-2]).add(i[n-1]),c=jp),this.curveType==="centripetal"||this.curveType==="chordal"){let f=this.curveType==="chordal"?.5:.25,y=Math.pow(l.distanceToSquared(u),f),b=Math.pow(u.distanceToSquared(d),f),x=Math.pow(d.distanceToSquared(c),f);b<1e-4&&(b=1),y<1e-4&&(y=b),x<1e-4&&(x=b),Xg.initNonuniformCatmullRom(l.x,u.x,d.x,c.x,y,b,x),Yg.initNonuniformCatmullRom(l.y,u.y,d.y,c.y,y,b,x),qg.initNonuniformCatmullRom(l.z,u.z,d.z,c.z,y,b,x)}else this.curveType==="catmullrom"&&(Xg.initCatmullRom(l.x,u.x,d.x,c.x,this.tension),Yg.initCatmullRom(l.y,u.y,d.y,c.y,this.tension),qg.initCatmullRom(l.z,u.z,d.z,c.z,this.tension));return r.set(Xg.calc(o),Yg.calc(o),qg.calc(o)),r}copy(e){super.copy(e),this.points=[];for(let t=0,r=e.points.length;t<r;t++){let i=e.points[t];this.points.push(i.clone())}return this.closed=e.closed,this.curveType=e.curveType,this.tension=e.tension,this}toJSON(){let e=super.toJSON();e.points=[];for(let t=0,r=this.points.length;t<r;t++){let i=this.points[t];e.points.push(i.toArray())}return e.closed=this.closed,e.curveType=this.curveType,e.tension=this.tension,e}fromJSON(e){super.fromJSON(e),this.points=[];for(let t=0,r=e.points.length;t<r;t++){let i=e.points[t];this.points.push(new je().fromArray(i))}return this.closed=e.closed,this.curveType=e.curveType,this.tension=e.tension,this}};function Ab(e,t,r,i,n){let s=(i-t)*.5,a=(n-r)*.5,o=e*e,l=e*o;return(2*r-2*i+s+a)*l+(-3*r+3*i-2*s-a)*o+s*e+r}function KT(e,t){let r=1-e;return r*r*t}function ZT(e,t){return 2*(1-e)*e*t}function $T(e,t){return e*e*t}function Jh(e,t,r,i){return KT(e,t)+ZT(e,r)+$T(e,i)}function JT(e,t){let r=1-e;return r*r*r*t}function QT(e,t){let r=1-e;return 3*r*r*e*t}function e2(e,t){return 3*(1-e)*e*e*t}function t2(e,t){return e*e*e*t}function Qh(e,t,r,i,n){return JT(e,t)+QT(e,r)+e2(e,i)+t2(e,n)}var Kg=class extends Ks{constructor(e=new Ft,t=new Ft,r=new Ft,i=new Ft){super(),this.isCubicBezierCurve=!0,this.type="CubicBezierCurve",this.v0=e,this.v1=t,this.v2=r,this.v3=i}getPoint(e,t=new Ft){let r=t,i=this.v0,n=this.v1,s=this.v2,a=this.v3;return r.set(Qh(e,i.x,n.x,s.x,a.x),Qh(e,i.y,n.y,s.y,a.y)),r}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this.v3.copy(e.v3),this}toJSON(){let e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e.v3=this.v3.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this.v3.fromArray(e.v3),this}},Tb=class extends Ks{constructor(e=new je,t=new je,r=new je,i=new je){super(),this.isCubicBezierCurve3=!0,this.type="CubicBezierCurve3",this.v0=e,this.v1=t,this.v2=r,this.v3=i}getPoint(e,t=new je){let r=t,i=this.v0,n=this.v1,s=this.v2,a=this.v3;return r.set(Qh(e,i.x,n.x,s.x,a.x),Qh(e,i.y,n.y,s.y,a.y),Qh(e,i.z,n.z,s.z,a.z)),r}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this.v3.copy(e.v3),this}toJSON(){let e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e.v3=this.v3.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this.v3.fromArray(e.v3),this}},Zg=class extends Ks{constructor(e=new Ft,t=new Ft){super(),this.isLineCurve=!0,this.type="LineCurve",this.v1=e,this.v2=t}getPoint(e,t=new Ft){let r=t;return e===1?r.copy(this.v2):(r.copy(this.v2).sub(this.v1),r.multiplyScalar(e).add(this.v1)),r}getPointAt(e,t){return this.getPoint(e,t)}getTangent(e,t=new Ft){return t.subVectors(this.v2,this.v1).normalize()}getTangentAt(e,t){return this.getTangent(e,t)}copy(e){return super.copy(e),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){let e=super.toJSON();return e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}},Cb=class extends Ks{constructor(e=new je,t=new je){super(),this.isLineCurve3=!0,this.type="LineCurve3",this.v1=e,this.v2=t}getPoint(e,t=new je){let r=t;return e===1?r.copy(this.v2):(r.copy(this.v2).sub(this.v1),r.multiplyScalar(e).add(this.v1)),r}getPointAt(e,t){return this.getPoint(e,t)}getTangent(e,t=new je){return t.subVectors(this.v2,this.v1).normalize()}getTangentAt(e,t){return this.getTangent(e,t)}copy(e){return super.copy(e),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){let e=super.toJSON();return e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}},$g=class extends Ks{constructor(e=new Ft,t=new Ft,r=new Ft){super(),this.isQuadraticBezierCurve=!0,this.type="QuadraticBezierCurve",this.v0=e,this.v1=t,this.v2=r}getPoint(e,t=new Ft){let r=t,i=this.v0,n=this.v1,s=this.v2;return r.set(Jh(e,i.x,n.x,s.x),Jh(e,i.y,n.y,s.y)),r}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){let e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}},Jg=class extends Ks{constructor(e=new je,t=new je,r=new je){super(),this.isQuadraticBezierCurve3=!0,this.type="QuadraticBezierCurve3",this.v0=e,this.v1=t,this.v2=r}getPoint(e,t=new je){let r=t,i=this.v0,n=this.v1,s=this.v2;return r.set(Jh(e,i.x,n.x,s.x),Jh(e,i.y,n.y,s.y),Jh(e,i.z,n.z,s.z)),r}copy(e){return super.copy(e),this.v0.copy(e.v0),this.v1.copy(e.v1),this.v2.copy(e.v2),this}toJSON(){let e=super.toJSON();return e.v0=this.v0.toArray(),e.v1=this.v1.toArray(),e.v2=this.v2.toArray(),e}fromJSON(e){return super.fromJSON(e),this.v0.fromArray(e.v0),this.v1.fromArray(e.v1),this.v2.fromArray(e.v2),this}},Qg=class extends Ks{constructor(e=[]){super(),this.isSplineCurve=!0,this.type="SplineCurve",this.points=e}getPoint(e,t=new Ft){let r=t,i=this.points,n=(i.length-1)*e,s=Math.floor(n),a=n-s,o=i[s===0?s:s-1],l=i[s],c=i[s>i.length-2?i.length-1:s+1],u=i[s>i.length-3?i.length-1:s+2];return r.set(Ab(a,o.x,l.x,c.x,u.x),Ab(a,o.y,l.y,c.y,u.y)),r}copy(e){super.copy(e),this.points=[];for(let t=0,r=e.points.length;t<r;t++){let i=e.points[t];this.points.push(i.clone())}return this}toJSON(){let e=super.toJSON();e.points=[];for(let t=0,r=this.points.length;t<r;t++){let i=this.points[t];e.points.push(i.toArray())}return e}fromJSON(e){super.fromJSON(e),this.points=[];for(let t=0,r=e.points.length;t<r;t++){let i=e.points[t];this.points.push(new Ft().fromArray(i))}return this}},Vp=Object.freeze({__proto__:null,ArcCurve:Sb,CatmullRomCurve3:Mb,CubicBezierCurve:Kg,CubicBezierCurve3:Tb,EllipseCurve:Bp,LineCurve:Zg,LineCurve3:Cb,QuadraticBezierCurve:$g,QuadraticBezierCurve3:Jg,SplineCurve:Qg}),Rb=class extends Ks{constructor(){super(),this.type="CurvePath",this.curves=[],this.autoClose=!1}add(e){this.curves.push(e)}closePath(){let e=this.curves[0].getPoint(0),t=this.curves[this.curves.length-1].getPoint(1);if(!e.equals(t)){let r=e.isVector2===!0?"LineCurve":"LineCurve3";this.curves.push(new Vp[r](t,e))}return this}getPoint(e,t){let r=e*this.getLength(),i=this.getCurveLengths(),n=0;for(;n<i.length;){if(i[n]>=r){let s=i[n]-r,a=this.curves[n],o=a.getLength(),l=o===0?0:1-s/o;return a.getPointAt(l,t)}n++}return null}getLength(){let e=this.getCurveLengths();return e[e.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;let e=[],t=0;for(let r=0,i=this.curves.length;r<i;r++)t+=this.curves[r].getLength(),e.push(t);return this.cacheLengths=e,e}getSpacedPoints(e=40){let t=[];for(let r=0;r<=e;r++)t.push(this.getPoint(r/e));return this.autoClose&&t.push(t[0]),t}getPoints(e=12){let t=[],r;for(let i=0,n=this.curves;i<n.length;i++){let s=n[i],a=s.isEllipseCurve?e*2:s.isLineCurve||s.isLineCurve3?1:s.isSplineCurve?e*s.points.length:e,o=s.getPoints(a);for(let l=0;l<o.length;l++){let c=o[l];r&&r.equals(c)||(t.push(c),r=c)}}return this.autoClose&&t.length>1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,r=e.curves.length;t<r;t++){let i=e.curves[t];this.curves.push(i.clone())}return this.autoClose=e.autoClose,this}toJSON(){let e=super.toJSON();e.autoClose=this.autoClose,e.curves=[];for(let t=0,r=this.curves.length;t<r;t++){let i=this.curves[t];e.curves.push(i.toJSON())}return e}fromJSON(e){super.fromJSON(e),this.autoClose=e.autoClose,this.curves=[];for(let t=0,r=e.curves.length;t<r;t++){let i=e.curves[t];this.curves.push(new Vp[i.type]().fromJSON(i))}return this}},mc=class extends Rb{constructor(e){super(),this.type="Path",this.currentPoint=new Ft,e&&this.setFromPoints(e)}setFromPoints(e){this.moveTo(e[0].x,e[0].y);for(let t=1,r=e.length;t<r;t++)this.lineTo(e[t].x,e[t].y);return this}moveTo(e,t){return this.currentPoint.set(e,t),this}lineTo(e,t){let r=new Zg(this.currentPoint.clone(),new Ft(e,t));return this.curves.push(r),this.currentPoint.set(e,t),this}quadraticCurveTo(e,t,r,i){let n=new $g(this.currentPoint.clone(),new Ft(e,t),new Ft(r,i));return this.curves.push(n),this.currentPoint.set(r,i),this}bezierCurveTo(e,t,r,i,n,s){let a=new Kg(this.currentPoint.clone(),new Ft(e,t),new Ft(r,i),new Ft(n,s));return this.curves.push(a),this.currentPoint.set(n,s),this}splineThru(e){let t=[this.currentPoint.clone()].concat(e),r=new Qg(t);return this.curves.push(r),this.currentPoint.copy(e[e.length-1]),this}arc(e,t,r,i,n,s){let a=this.currentPoint.x,o=this.currentPoint.y;return this.absarc(e+a,t+o,r,i,n,s),this}absarc(e,t,r,i,n,s){return this.absellipse(e,t,r,r,i,n,s),this}ellipse(e,t,r,i,n,s,a,o){let l=this.currentPoint.x,c=this.currentPoint.y;return this.absellipse(e+l,t+c,r,i,n,s,a,o),this}absellipse(e,t,r,i,n,s,a,o){let l=new Bp(e,t,r,i,n,s,a,o);if(this.curves.length>0){let u=l.getPoint(0);u.equals(this.currentPoint)||this.lineTo(u.x,u.y)}this.curves.push(l);let c=l.getPoint(1);return this.currentPoint.copy(c),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){let e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}},ey=class tM extends Hr{constructor(t=[new Ft(0,-.5),new Ft(.5,0),new Ft(0,.5)],r=12,i=0,n=Math.PI*2){super(),this.type="LatheGeometry",this.parameters={points:t,segments:r,phiStart:i,phiLength:n},r=Math.floor(r),n=Jr(n,0,Math.PI*2);let s=[],a=[],o=[],l=[],c=[],u=1/r,d=new je,f=new Ft,y=new je,b=new je,x=new je,g=0,v=0;for(let _=0;_<=t.length-1;_++)switch(_){case 0:g=t[_+1].x-t[_].x,v=t[_+1].y-t[_].y,y.x=v*1,y.y=-g,y.z=v*0,x.copy(y),y.normalize(),l.push(y.x,y.y,y.z);break;case t.length-1:l.push(x.x,x.y,x.z);break;default:g=t[_+1].x-t[_].x,v=t[_+1].y-t[_].y,y.x=v*1,y.y=-g,y.z=v*0,b.copy(y),y.x+=x.x,y.y+=x.y,y.z+=x.z,y.normalize(),l.push(y.x,y.y,y.z),x.copy(b)}for(let _=0;_<=r;_++){let E=i+_*u*n,M=Math.sin(E),P=Math.cos(E);for(let k=0;k<=t.length-1;k++){d.x=t[k].x*M,d.y=t[k].y,d.z=t[k].x*P,a.push(d.x,d.y,d.z),f.x=_/r,f.y=k/(t.length-1),o.push(f.x,f.y);let z=l[3*k+0]*M,D=l[3*k+1],I=l[3*k+0]*P;c.push(z,D,I)}}for(let _=0;_<r;_++)for(let E=0;E<t.length-1;E++){let M=E+_*t.length,P=M,k=M+t.length,z=M+t.length+1,D=M+1;s.push(P,k,D),s.push(z,D,k)}this.setIndex(s),this.setAttribute("position",new hr(a,3)),this.setAttribute("uv",new hr(o,2)),this.setAttribute("normal",new hr(c,3))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new tM(t.points,t.segments,t.phiStart,t.phiLength)}},Pb=class rM extends ey{constructor(t=1,r=1,i=4,n=8){let s=new mc;s.absarc(0,-r/2,t,Math.PI*1.5,0),s.absarc(0,r/2,t,0,Math.PI*.5),super(s.getPoints(i),n),this.type="CapsuleGeometry",this.parameters={radius:t,length:r,capSegments:i,radialSegments:n}}static fromJSON(t){return new rM(t.radius,t.length,t.capSegments,t.radialSegments)}},Ib=class iM extends Hr{constructor(t=1,r=32,i=0,n=Math.PI*2){super(),this.type="CircleGeometry",this.parameters={radius:t,segments:r,thetaStart:i,thetaLength:n},r=Math.max(3,r);let s=[],a=[],o=[],l=[],c=new je,u=new Ft;a.push(0,0,0),o.push(0,0,1),l.push(.5,.5);for(let d=0,f=3;d<=r;d++,f+=3){let y=i+d/r*n;c.x=t*Math.cos(y),c.y=t*Math.sin(y),a.push(c.x,c.y,c.z),o.push(0,0,1),u.x=(a[f]/t+1)/2,u.y=(a[f+1]/t+1)/2,l.push(u.x,u.y)}for(let d=1;d<=r;d++)s.push(d,d+1,0);this.setIndex(s),this.setAttribute("position",new hr(a,3)),this.setAttribute("normal",new hr(o,3)),this.setAttribute("uv",new hr(l,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new iM(t.radius,t.segments,t.thetaStart,t.thetaLength)}},eu=class nM extends Hr{constructor(t=1,r=1,i=1,n=32,s=1,a=!1,o=0,l=Math.PI*2){super(),this.type="CylinderGeometry",this.parameters={radiusTop:t,radiusBottom:r,height:i,radialSegments:n,heightSegments:s,openEnded:a,thetaStart:o,thetaLength:l};let c=this;n=Math.floor(n),s=Math.floor(s);let u=[],d=[],f=[],y=[],b=0,x=[],g=i/2,v=0;_(),a===!1&&(t>0&&E(!0),r>0&&E(!1)),this.setIndex(u),this.setAttribute("position",new hr(d,3)),this.setAttribute("normal",new hr(f,3)),this.setAttribute("uv",new hr(y,2));function _(){let M=new je,P=new je,k=0,z=(r-t)/i;for(let D=0;D<=s;D++){let I=[],L=D/s,Z=L*(r-t)+t;for(let se=0;se<=n;se++){let ce=se/n,fe=ce*l+o,ze=Math.sin(fe),Fe=Math.cos(fe);P.x=Z*ze,P.y=-L*i+g,P.z=Z*Fe,d.push(P.x,P.y,P.z),M.set(ze,z,Fe).normalize(),f.push(M.x,M.y,M.z),y.push(ce,1-L),I.push(b++)}x.push(I)}for(let D=0;D<n;D++)for(let I=0;I<s;I++){let L=x[I][D],Z=x[I+1][D],se=x[I+1][D+1],ce=x[I][D+1];(t>0||I!==0)&&(u.push(L,Z,ce),k+=3),(r>0||I!==s-1)&&(u.push(Z,se,ce),k+=3)}c.addGroup(v,k,0),v+=k}function E(M){let P=b,k=new Ft,z=new je,D=0,I=M===!0?t:r,L=M===!0?1:-1;for(let se=1;se<=n;se++)d.push(0,g*L,0),f.push(0,L,0),y.push(.5,.5),b++;let Z=b;for(let se=0;se<=n;se++){let ce=se/n*l+o,fe=Math.cos(ce),ze=Math.sin(ce);z.x=I*ze,z.y=g*L,z.z=I*fe,d.push(z.x,z.y,z.z),f.push(0,L,0),k.x=fe*.5+.5,k.y=ze*.5*L+.5,y.push(k.x,k.y),b++}for(let se=0;se<n;se++){let ce=P+se,fe=Z+se;M===!0?u.push(fe,fe+1,ce):u.push(fe+1,fe,ce),D+=3}c.addGroup(v,D,M===!0?1:2),v+=D}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new nM(t.radiusTop,t.radiusBottom,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}},ty=class sM extends eu{constructor(t=1,r=1,i=32,n=1,s=!1,a=0,o=Math.PI*2){super(0,t,r,i,n,s,a,o),this.type="ConeGeometry",this.parameters={radius:t,height:r,radialSegments:i,heightSegments:n,openEnded:s,thetaStart:a,thetaLength:o}}static fromJSON(t){return new sM(t.radius,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}},gc=class aM extends Hr{constructor(t=[],r=[],i=1,n=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:t,indices:r,radius:i,detail:n};let s=[],a=[];o(n),c(i),u(),this.setAttribute("position",new hr(s,3)),this.setAttribute("normal",new hr(s.slice(),3)),this.setAttribute("uv",new hr(a,2)),n===0?this.computeVertexNormals():this.normalizeNormals();function o(_){let E=new je,M=new je,P=new je;for(let k=0;k<r.length;k+=3)y(r[k+0],E),y(r[k+1],M),y(r[k+2],P),l(E,M,P,_)}function l(_,E,M,P){let k=P+1,z=[];for(let D=0;D<=k;D++){z[D]=[];let I=_.clone().lerp(M,D/k),L=E.clone().lerp(M,D/k),Z=k-D;for(let se=0;se<=Z;se++)se===0&&D===k?z[D][se]=I:z[D][se]=I.clone().lerp(L,se/Z)}for(let D=0;D<k;D++)for(let I=0;I<2*(k-D)-1;I++){let L=Math.floor(I/2);I%2===0?(f(z[D][L+1]),f(z[D+1][L]),f(z[D][L])):(f(z[D][L+1]),f(z[D+1][L+1]),f(z[D+1][L]))}}function c(_){let E=new je;for(let M=0;M<s.length;M+=3)E.x=s[M+0],E.y=s[M+1],E.z=s[M+2],E.normalize().multiplyScalar(_),s[M+0]=E.x,s[M+1]=E.y,s[M+2]=E.z}function u(){let _=new je;for(let E=0;E<s.length;E+=3){_.x=s[E+0],_.y=s[E+1],_.z=s[E+2];let M=g(_)/2/Math.PI+.5,P=v(_)/Math.PI+.5;a.push(M,1-P)}b(),d()}function d(){for(let _=0;_<a.length;_+=6){let E=a[_+0],M=a[_+2],P=a[_+4],k=Math.max(E,M,P),z=Math.min(E,M,P);k>.9&&z<.1&&(E<.2&&(a[_+0]+=1),M<.2&&(a[_+2]+=1),P<.2&&(a[_+4]+=1))}}function f(_){s.push(_.x,_.y,_.z)}function y(_,E){let M=_*3;E.x=t[M+0],E.y=t[M+1],E.z=t[M+2]}function b(){let _=new je,E=new je,M=new je,P=new je,k=new Ft,z=new Ft,D=new Ft;for(let I=0,L=0;I<s.length;I+=9,L+=6){_.set(s[I+0],s[I+1],s[I+2]),E.set(s[I+3],s[I+4],s[I+5]),M.set(s[I+6],s[I+7],s[I+8]),k.set(a[L+0],a[L+1]),z.set(a[L+2],a[L+3]),D.set(a[L+4],a[L+5]),P.copy(_).add(E).add(M).divideScalar(3);let Z=g(P);x(k,L+0,_,Z),x(z,L+2,E,Z),x(D,L+4,M,Z)}}function x(_,E,M,P){P<0&&_.x===1&&(a[E]=_.x-1),M.x===0&&M.z===0&&(a[E]=P/2/Math.PI+.5)}function g(_){return Math.atan2(_.z,-_.x)}function v(_){return Math.atan2(-_.y,Math.sqrt(_.x*_.x+_.z*_.z))}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new aM(t.vertices,t.indices,t.radius,t.details)}},Nb=class oM extends gc{constructor(t=1,r=0){let i=(1+Math.sqrt(5))/2,n=1/i,s=[-1,-1,-1,-1,-1,1,-1,1,-1,-1,1,1,1,-1,-1,1,-1,1,1,1,-1,1,1,1,0,-n,-i,0,-n,i,0,n,-i,0,n,i,-n,-i,0,-n,i,0,n,-i,0,n,i,0,-i,0,-n,i,0,-n,-i,0,n,i,0,n],a=[3,11,7,3,7,15,3,15,13,7,19,17,7,17,6,7,6,15,17,4,8,17,8,10,17,10,6,8,0,16,8,16,2,8,2,10,0,12,1,0,1,18,0,18,16,6,10,2,6,2,13,6,13,15,2,16,18,2,18,3,2,3,13,18,1,9,18,9,11,18,11,3,4,14,12,4,12,0,4,0,8,11,9,5,11,5,19,11,19,7,19,5,14,19,14,4,19,4,17,1,12,14,1,14,5,1,5,9];super(s,a,t,r),this.type="DodecahedronGeometry",this.parameters={radius:t,detail:r}}static fromJSON(t){return new oM(t.radius,t.detail)}},Hp=new je,Gp=new je,ry=new je,Wp=new ka,tu=class extends Hr{constructor(e=null,t=1){if(super(),this.type="EdgesGeometry",this.parameters={geometry:e,thresholdAngle:t},e!==null){let r=Math.pow(10,4),i=Math.cos(jo*t),n=e.getIndex(),s=e.getAttribute("position"),a=n?n.count:s.count,o=[0,0,0],l=["a","b","c"],c=new Array(3),u={},d=[];for(let f=0;f<a;f+=3){n?(o[0]=n.getX(f),o[1]=n.getX(f+1),o[2]=n.getX(f+2)):(o[0]=f,o[1]=f+1,o[2]=f+2);let{a:y,b,c:x}=Wp;if(y.fromBufferAttribute(s,o[0]),b.fromBufferAttribute(s,o[1]),x.fromBufferAttribute(s,o[2]),Wp.getNormal(ry),c[0]=`${Math.round(y.x*r)},${Math.round(y.y*r)},${Math.round(y.z*r)}`,c[1]=`${Math.round(b.x*r)},${Math.round(b.y*r)},${Math.round(b.z*r)}`,c[2]=`${Math.round(x.x*r)},${Math.round(x.y*r)},${Math.round(x.z*r)}`,!(c[0]===c[1]||c[1]===c[2]||c[2]===c[0]))for(let g=0;g<3;g++){let v=(g+1)%3,_=c[g],E=c[v],M=Wp[l[g]],P=Wp[l[v]],k=`${_}_${E}`,z=`${E}_${_}`;z in u&&u[z]?(ry.dot(u[z].normal)<=i&&(d.push(M.x,M.y,M.z),d.push(P.x,P.y,P.z)),u[z]=null):k in u||(u[k]={index0:o[g],index1:o[v],normal:ry.clone()})}}for(let f in u)if(u[f]){let{index0:y,index1:b}=u[f];Hp.fromBufferAttribute(s,y),Gp.fromBufferAttribute(s,b),d.push(Hp.x,Hp.y,Hp.z),d.push(Gp.x,Gp.y,Gp.z)}this.setAttribute("position",new hr(d,3))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}},Fa=class extends mc{constructor(e){super(e),this.uuid=fs(),this.type="Shape",this.holes=[]}getPointsHoles(e){let t=[];for(let r=0,i=this.holes.length;r<i;r++)t[r]=this.holes[r].getPoints(e);return t}extractPoints(e){return{shape:this.getPoints(e),holes:this.getPointsHoles(e)}}copy(e){super.copy(e),this.holes=[];for(let t=0,r=e.holes.length;t<r;t++){let i=e.holes[t];this.holes.push(i.clone())}return this}toJSON(){let e=super.toJSON();e.uuid=this.uuid,e.holes=[];for(let t=0,r=this.holes.length;t<r;t++){let i=this.holes[t];e.holes.push(i.toJSON())}return e}fromJSON(e){super.fromJSON(e),this.uuid=e.uuid,this.holes=[];for(let t=0,r=e.holes.length;t<r;t++){let i=e.holes[t];this.holes.push(new mc().fromJSON(i))}return this}},r2={triangulate:function(e,t,r=2){let i=t&&t.length,n=i?t[0]*r:e.length,s=Lb(e,0,n,r,!0),a=[];if(!s||s.next===s.prev)return a;let o,l,c,u,d,f,y;if(i&&(s=o2(e,t,s,r)),e.length>80*r){o=c=e[0],l=u=e[1];for(let b=r;b<n;b+=r)d=e[b],f=e[b+1],d<o&&(o=d),f<l&&(l=f),d>c&&(c=d),f>u&&(u=f);y=Math.max(c-o,u-l),y=y!==0?32767/y:0}return ru(s,a,r,o,l,y,0),a}};function Lb(e,t,r,i,n){let s,a;if(n===v2(e,t,r,i)>0)for(s=t;s<r;s+=i)a=Db(s,e[s],e[s+1],a);else for(s=r-i;s>=t;s-=i)a=Db(s,e[s],e[s+1],a);return a&&Xp(a,a.next)&&(nu(a),a=a.next),a}function Jo(e,t){if(!e)return e;t||(t=e);let r=e,i;do if(i=!1,!r.steiner&&(Xp(r,r.next)||Ki(r.prev,r,r.next)===0)){if(nu(r),r=t=r.prev,r===r.next)break;i=!0}else r=r.next;while(i||r!==t);return t}function ru(e,t,r,i,n,s,a){if(!e)return;!a&&s&&d2(e,i,n,s);let o=e,l,c;for(;e.prev!==e.next;){if(l=e.prev,c=e.next,s?n2(e,i,n,s):i2(e)){t.push(l.i/r|0),t.push(e.i/r|0),t.push(c.i/r|0),nu(e),e=c.next,o=c.next;continue}if(e=c,e===o){a?a===1?(e=s2(Jo(e),t,r),ru(e,t,r,i,n,s,2)):a===2&&a2(e,t,r,i,n,s):ru(Jo(e),t,r,i,n,s,1);break}}}function i2(e){let t=e.prev,r=e,i=e.next;if(Ki(t,r,i)>=0)return!1;let n=t.x,s=r.x,a=i.x,o=t.y,l=r.y,c=i.y,u=n<s?n<a?n:a:s<a?s:a,d=o<l?o<c?o:c:l<c?l:c,f=n>s?n>a?n:a:s>a?s:a,y=o>l?o>c?o:c:l>c?l:c,b=i.next;for(;b!==t;){if(b.x>=u&&b.x<=f&&b.y>=d&&b.y<=y&&yc(n,o,s,l,a,c,b.x,b.y)&&Ki(b.prev,b,b.next)>=0)return!1;b=b.next}return!0}function n2(e,t,r,i){let n=e.prev,s=e,a=e.next;if(Ki(n,s,a)>=0)return!1;let o=n.x,l=s.x,c=a.x,u=n.y,d=s.y,f=a.y,y=o<l?o<c?o:c:l<c?l:c,b=u<d?u<f?u:f:d<f?d:f,x=o>l?o>c?o:c:l>c?l:c,g=u>d?u>f?u:f:d>f?d:f,v=iy(y,b,t,r,i),_=iy(x,g,t,r,i),E=e.prevZ,M=e.nextZ;for(;E&&E.z>=v&&M&&M.z<=_;){if(E.x>=y&&E.x<=x&&E.y>=b&&E.y<=g&&E!==n&&E!==a&&yc(o,u,l,d,c,f,E.x,E.y)&&Ki(E.prev,E,E.next)>=0||(E=E.prevZ,M.x>=y&&M.x<=x&&M.y>=b&&M.y<=g&&M!==n&&M!==a&&yc(o,u,l,d,c,f,M.x,M.y)&&Ki(M.prev,M,M.next)>=0))return!1;M=M.nextZ}for(;E&&E.z>=v;){if(E.x>=y&&E.x<=x&&E.y>=b&&E.y<=g&&E!==n&&E!==a&&yc(o,u,l,d,c,f,E.x,E.y)&&Ki(E.prev,E,E.next)>=0)return!1;E=E.prevZ}for(;M&&M.z<=_;){if(M.x>=y&&M.x<=x&&M.y>=b&&M.y<=g&&M!==n&&M!==a&&yc(o,u,l,d,c,f,M.x,M.y)&&Ki(M.prev,M,M.next)>=0)return!1;M=M.nextZ}return!0}function s2(e,t,r){let i=e;do{let n=i.prev,s=i.next.next;!Xp(n,s)&&kb(n,i,i.next,s)&&iu(n,s)&&iu(s,n)&&(t.push(n.i/r|0),t.push(i.i/r|0),t.push(s.i/r|0),nu(i),nu(i.next),i=e=s),i=i.next}while(i!==e);return Jo(i)}function a2(e,t,r,i,n,s){let a=e;do{let o=a.next.next;for(;o!==a.prev;){if(a.i!==o.i&&m2(a,o)){let l=Ob(a,o);a=Jo(a,a.next),l=Jo(l,l.next),ru(a,t,r,i,n,s,0),ru(l,t,r,i,n,s,0);return}o=o.next}a=a.next}while(a!==e)}function o2(e,t,r,i){let n=[],s,a,o,l,c;for(s=0,a=t.length;s<a;s++)o=t[s]*i,l=s<a-1?t[s+1]*i:e.length,c=Lb(e,o,l,i,!1),c===c.next&&(c.steiner=!0),n.push(f2(c));for(n.sort(l2),s=0;s<n.length;s++)r=c2(n[s],r);return r}function l2(e,t){return e.x-t.x}function c2(e,t){let r=h2(e,t);if(!r)return t;let i=Ob(r,e);return Jo(i,i.next),Jo(r,r.next)}function h2(e,t){let r=t,i=-1/0,n,s=e.x,a=e.y;do{if(a<=r.y&&a>=r.next.y&&r.next.y!==r.y){let f=r.x+(a-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(f<=s&&f>i&&(i=f,n=r.x<r.next.x?r:r.next,f===s))return n}r=r.next}while(r!==t);if(!n)return null;let o=n,l=n.x,c=n.y,u=1/0,d;r=n;do s>=r.x&&r.x>=l&&s!==r.x&&yc(a<c?s:i,a,l,c,a<c?i:s,a,r.x,r.y)&&(d=Math.abs(a-r.y)/(s-r.x),iu(r,e)&&(d<u||d===u&&(r.x>n.x||r.x===n.x&&u2(n,r)))&&(n=r,u=d)),r=r.next;while(r!==o);return n}function u2(e,t){return Ki(e.prev,e,t.prev)<0&&Ki(t.next,e,e.next)<0}function d2(e,t,r,i){let n=e;do n.z===0&&(n.z=iy(n.x,n.y,t,r,i)),n.prevZ=n.prev,n.nextZ=n.next,n=n.next;while(n!==e);n.prevZ.nextZ=null,n.prevZ=null,p2(n)}function p2(e){let t,r,i,n,s,a,o,l,c=1;do{for(r=e,e=null,s=null,a=0;r;){for(a++,i=r,o=0,t=0;t<c&&(o++,i=i.nextZ,!!i);t++);for(l=c;o>0||l>0&&i;)o!==0&&(l===0||!i||r.z<=i.z)?(n=r,r=r.nextZ,o--):(n=i,i=i.nextZ,l--),s?s.nextZ=n:e=n,n.prevZ=s,s=n;r=i}s.nextZ=null,c*=2}while(a>1);return e}function iy(e,t,r,i,n){return e=(e-r)*n|0,t=(t-i)*n|0,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,t=(t|t<<8)&16711935,t=(t|t<<4)&252645135,t=(t|t<<2)&858993459,t=(t|t<<1)&1431655765,e|t<<1}function f2(e){let t=e,r=e;do(t.x<r.x||t.x===r.x&&t.y<r.y)&&(r=t),t=t.next;while(t!==e);return r}function yc(e,t,r,i,n,s,a,o){return(n-a)*(t-o)>=(e-a)*(s-o)&&(e-a)*(i-o)>=(r-a)*(t-o)&&(r-a)*(s-o)>=(n-a)*(i-o)}function m2(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!g2(e,t)&&(iu(e,t)&&iu(t,e)&&y2(e,t)&&(Ki(e.prev,e,t.prev)||Ki(e,t.prev,t))||Xp(e,t)&&Ki(e.prev,e,e.next)>0&&Ki(t.prev,t,t.next)>0)}function Ki(e,t,r){return(t.y-e.y)*(r.x-t.x)-(t.x-e.x)*(r.y-t.y)}function Xp(e,t){return e.x===t.x&&e.y===t.y}function kb(e,t,r,i){let n=qp(Ki(e,t,r)),s=qp(Ki(e,t,i)),a=qp(Ki(r,i,e)),o=qp(Ki(r,i,t));return!!(n!==s&&a!==o||n===0&&Yp(e,r,t)||s===0&&Yp(e,i,t)||a===0&&Yp(r,e,i)||o===0&&Yp(r,t,i))}function Yp(e,t,r){return t.x<=Math.max(e.x,r.x)&&t.x>=Math.min(e.x,r.x)&&t.y<=Math.max(e.y,r.y)&&t.y>=Math.min(e.y,r.y)}function qp(e){return e>0?1:e<0?-1:0}function g2(e,t){let r=e;do{if(r.i!==e.i&&r.next.i!==e.i&&r.i!==t.i&&r.next.i!==t.i&&kb(r,r.next,e,t))return!0;r=r.next}while(r!==e);return!1}function iu(e,t){return Ki(e.prev,e,e.next)<0?Ki(e,t,e.next)>=0&&Ki(e,e.prev,t)>=0:Ki(e,t,e.prev)<0||Ki(e,e.next,t)<0}function y2(e,t){let r=e,i=!1,n=(e.x+t.x)/2,s=(e.y+t.y)/2;do r.y>s!=r.next.y>s&&r.next.y!==r.y&&n<(r.next.x-r.x)*(s-r.y)/(r.next.y-r.y)+r.x&&(i=!i),r=r.next;while(r!==e);return i}function Ob(e,t){let r=new ny(e.i,e.x,e.y),i=new ny(t.i,t.x,t.y),n=e.next,s=t.prev;return e.next=t,t.prev=e,r.next=n,n.prev=r,i.next=r,r.prev=i,s.next=i,i.prev=s,i}function Db(e,t,r,i){let n=new ny(e,t,r);return i?(n.next=i.next,n.prev=i,i.next.prev=n,i.next=n):(n.prev=n,n.next=n),n}function nu(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function ny(e,t,r){this.i=e,this.x=t,this.y=r,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function v2(e,t,r,i){let n=0;for(let s=t,a=r-i;s<r;s+=i)n+=(e[a]-e[s])*(e[s+1]+e[a+1]),a=s;return n}var za=class lM{static area(t){let r=t.length,i=0;for(let n=r-1,s=0;s<r;n=s++)i+=t[n].x*t[s].y-t[s].x*t[n].y;return i*.5}static isClockWise(t){return lM.area(t)<0}static triangulateShape(t,r){let i=[],n=[],s=[];Ub(t),Fb(i,t);let a=t.length;r.forEach(Ub);for(let l=0;l<r.length;l++)n.push(a),a+=r[l].length,Fb(i,r[l]);let o=r2.triangulate(i,n);for(let l=0;l<o.length;l+=3)s.push(o.slice(l,l+3));return s}};function Ub(e){let t=e.length;t>2&&e[t-1].equals(e[0])&&e.pop()}function Fb(e,t){for(let r=0;r<t.length;r++)e.push(t[r].x),e.push(t[r].y)}var Kp=class cM extends Hr{constructor(t=new Fa([new Ft(.5,.5),new Ft(-.5,.5),new Ft(-.5,-.5),new Ft(.5,-.5)]),r={}){super(),this.type="ExtrudeGeometry",this.parameters={shapes:t,options:r},t=Array.isArray(t)?t:[t];let i=this,n=[],s=[];for(let o=0,l=t.length;o<l;o++){let c=t[o];a(c)}this.setAttribute("position",new hr(n,3)),this.setAttribute("uv",new hr(s,2)),this.computeVertexNormals();function a(o){let l=[],c=r.curveSegments!==void 0?r.curveSegments:12,u=r.steps!==void 0?r.steps:1,d=r.depth!==void 0?r.depth:1,f=r.bevelEnabled!==void 0?r.bevelEnabled:!0,y=r.bevelThickness!==void 0?r.bevelThickness:.2,b=r.bevelSize!==void 0?r.bevelSize:y-.1,x=r.bevelOffset!==void 0?r.bevelOffset:0,g=r.bevelSegments!==void 0?r.bevelSegments:3,v=r.extrudePath,_=r.UVGenerator!==void 0?r.UVGenerator:x2,E,M=!1,P,k,z,D;v&&(E=v.getSpacedPoints(u),M=!0,f=!1,P=v.computeFrenetFrames(u,!1),k=new je,z=new je,D=new je),f||(g=0,y=0,b=0,x=0);let I=o.extractPoints(c),L=I.shape,Z=I.holes;if(!za.isClockWise(L)){L=L.reverse();for(let Qe=0,ct=Z.length;Qe<ct;Qe++){let ye=Z[Qe];za.isClockWise(ye)&&(Z[Qe]=ye.reverse())}}let se=za.triangulateShape(L,Z),ce=L;for(let Qe=0,ct=Z.length;Qe<ct;Qe++){let ye=Z[Qe];L=L.concat(ye)}function fe(Qe,ct,ye){return ct||console.error("THREE.ExtrudeGeometry: vec does not exist"),Qe.clone().addScaledVector(ct,ye)}let ze=L.length,Fe=se.length;function Pe(Qe,ct,ye){let dt,xt,Dt,We=Qe.x-ct.x,mt=Qe.y-ct.y,it=ye.x-Qe.x,st=ye.y-Qe.y,oe=We*We+mt*mt,F=We*st-mt*it;if(Math.abs(F)>Number.EPSILON){let le=Math.sqrt(oe),pe=Math.sqrt(it*it+st*st),Le=ct.x-mt/le,He=ct.y+We/le,at=ye.x-st/pe,rt=ye.y+it/pe,ht=((at-Le)*st-(rt-He)*it)/(We*st-mt*it);dt=Le+We*ht-Qe.x,xt=He+mt*ht-Qe.y;let Tt=dt*dt+xt*xt;if(Tt<=2)return new Ft(dt,xt);Dt=Math.sqrt(Tt/2)}else{let le=!1;We>Number.EPSILON?it>Number.EPSILON&&(le=!0):We<-Number.EPSILON?it<-Number.EPSILON&&(le=!0):Math.sign(mt)===Math.sign(st)&&(le=!0),le?(dt=-mt,xt=We,Dt=Math.sqrt(oe)):(dt=We,xt=mt,Dt=Math.sqrt(oe/2))}return new Ft(dt/Dt,xt/Dt)}let ue=[];for(let Qe=0,ct=ce.length,ye=ct-1,dt=Qe+1;Qe<ct;Qe++,ye++,dt++)ye===ct&&(ye=0),dt===ct&&(dt=0),ue[Qe]=Pe(ce[Qe],ce[ye],ce[dt]);let Te=[],de,Ie=ue.concat();for(let Qe=0,ct=Z.length;Qe<ct;Qe++){let ye=Z[Qe];de=[];for(let dt=0,xt=ye.length,Dt=xt-1,We=dt+1;dt<xt;dt++,Dt++,We++)Dt===xt&&(Dt=0),We===xt&&(We=0),de[dt]=Pe(ye[dt],ye[Dt],ye[We]);Te.push(de),Ie=Ie.concat(de)}for(let Qe=0;Qe<g;Qe++){let ct=Qe/g,ye=y*Math.cos(ct*Math.PI/2),dt=b*Math.sin(ct*Math.PI/2)+x;for(let xt=0,Dt=ce.length;xt<Dt;xt++){let We=fe(ce[xt],ue[xt],dt);ie(We.x,We.y,-ye)}for(let xt=0,Dt=Z.length;xt<Dt;xt++){let We=Z[xt];de=Te[xt];for(let mt=0,it=We.length;mt<it;mt++){let st=fe(We[mt],de[mt],dt);ie(st.x,st.y,-ye)}}}let Re=b+x;for(let Qe=0;Qe<ze;Qe++){let ct=f?fe(L[Qe],Ie[Qe],Re):L[Qe];M?(z.copy(P.normals[0]).multiplyScalar(ct.x),k.copy(P.binormals[0]).multiplyScalar(ct.y),D.copy(E[0]).add(z).add(k),ie(D.x,D.y,D.z)):ie(ct.x,ct.y,0)}for(let Qe=1;Qe<=u;Qe++)for(let ct=0;ct<ze;ct++){let ye=f?fe(L[ct],Ie[ct],Re):L[ct];M?(z.copy(P.normals[Qe]).multiplyScalar(ye.x),k.copy(P.binormals[Qe]).multiplyScalar(ye.y),D.copy(E[Qe]).add(z).add(k),ie(D.x,D.y,D.z)):ie(ye.x,ye.y,d/u*Qe)}for(let Qe=g-1;Qe>=0;Qe--){let ct=Qe/g,ye=y*Math.cos(ct*Math.PI/2),dt=b*Math.sin(ct*Math.PI/2)+x;for(let xt=0,Dt=ce.length;xt<Dt;xt++){let We=fe(ce[xt],ue[xt],dt);ie(We.x,We.y,d+ye)}for(let xt=0,Dt=Z.length;xt<Dt;xt++){let We=Z[xt];de=Te[xt];for(let mt=0,it=We.length;mt<it;mt++){let st=fe(We[mt],de[mt],dt);M?ie(st.x,st.y+E[u-1].y,E[u-1].x+ye):ie(st.x,st.y,d+ye)}}}Be(),Se();function Be(){let Qe=n.length/3;if(f){let ct=0,ye=ze*ct;for(let dt=0;dt<Fe;dt++){let xt=se[dt];Ae(xt[2]+ye,xt[1]+ye,xt[0]+ye)}ct=u+g*2,ye=ze*ct;for(let dt=0;dt<Fe;dt++){let xt=se[dt];Ae(xt[0]+ye,xt[1]+ye,xt[2]+ye)}}else{for(let ct=0;ct<Fe;ct++){let ye=se[ct];Ae(ye[2],ye[1],ye[0])}for(let ct=0;ct<Fe;ct++){let ye=se[ct];Ae(ye[0]+ze*u,ye[1]+ze*u,ye[2]+ze*u)}}i.addGroup(Qe,n.length/3-Qe,0)}function Se(){let Qe=n.length/3,ct=0;U(ce,ct),ct+=ce.length;for(let ye=0,dt=Z.length;ye<dt;ye++){let xt=Z[ye];U(xt,ct),ct+=xt.length}i.addGroup(Qe,n.length/3-Qe,1)}function U(Qe,ct){let ye=Qe.length;for(;--ye>=0;){let dt=ye,xt=ye-1;xt<0&&(xt=Qe.length-1);for(let Dt=0,We=u+g*2;Dt<We;Dt++){let mt=ze*Dt,it=ze*(Dt+1),st=ct+dt+mt,oe=ct+xt+mt,F=ct+xt+it,le=ct+dt+it;Ue(st,oe,F,le)}}}function ie(Qe,ct,ye){l.push(Qe),l.push(ct),l.push(ye)}function Ae(Qe,ct,ye){Ge(Qe),Ge(ct),Ge(ye);let dt=n.length/3,xt=_.generateTopUV(i,n,dt-3,dt-2,dt-1);nt(xt[0]),nt(xt[1]),nt(xt[2])}function Ue(Qe,ct,ye,dt){Ge(Qe),Ge(ct),Ge(dt),Ge(ct),Ge(ye),Ge(dt);let xt=n.length/3,Dt=_.generateSideWallUV(i,n,xt-6,xt-3,xt-2,xt-1);nt(Dt[0]),nt(Dt[1]),nt(Dt[3]),nt(Dt[1]),nt(Dt[2]),nt(Dt[3])}function Ge(Qe){n.push(l[Qe*3+0]),n.push(l[Qe*3+1]),n.push(l[Qe*3+2])}function nt(Qe){s.push(Qe.x),s.push(Qe.y)}}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}toJSON(){let t=super.toJSON(),r=this.parameters.shapes,i=this.parameters.options;return b2(r,i,t)}static fromJSON(t,r){let i=[];for(let s=0,a=t.shapes.length;s<a;s++){let o=r[t.shapes[s]];i.push(o)}let n=t.options.extrudePath;return n!==void 0&&(t.options.extrudePath=new Vp[n.type]().fromJSON(n)),new cM(i,t.options)}},x2={generateTopUV:function(e,t,r,i,n){let s=t[r*3],a=t[r*3+1],o=t[i*3],l=t[i*3+1],c=t[n*3],u=t[n*3+1];return[new Ft(s,a),new Ft(o,l),new Ft(c,u)]},generateSideWallUV:function(e,t,r,i,n,s){let a=t[r*3],o=t[r*3+1],l=t[r*3+2],c=t[i*3],u=t[i*3+1],d=t[i*3+2],f=t[n*3],y=t[n*3+1],b=t[n*3+2],x=t[s*3],g=t[s*3+1],v=t[s*3+2];return Math.abs(o-u)<Math.abs(a-c)?[new Ft(a,1-l),new Ft(c,1-d),new Ft(f,1-b),new Ft(x,1-v)]:[new Ft(o,1-l),new Ft(u,1-d),new Ft(y,1-b),new Ft(g,1-v)]}};function b2(e,t,r){if(r.shapes=[],Array.isArray(e))for(let i=0,n=e.length;i<n;i++){let s=e[i];r.shapes.push(s.uuid)}else r.shapes.push(e.uuid);return r.options=Object.assign({},t),t.extrudePath!==void 0&&(r.options.extrudePath=t.extrudePath.toJSON()),r}var zb=class hM extends gc{constructor(t=1,r=0){let i=(1+Math.sqrt(5))/2,n=[-1,i,0,1,i,0,-1,-i,0,1,-i,0,0,-1,i,0,1,i,0,-1,-i,0,1,-i,i,0,-1,i,0,1,-i,0,-1,-i,0,1],s=[0,11,5,0,5,1,0,1,7,0,7,10,0,10,11,1,5,9,5,11,4,11,10,2,10,7,6,7,1,8,3,9,4,3,4,2,3,2,6,3,6,8,3,8,9,4,9,5,2,4,11,6,2,10,8,6,7,9,8,1];super(n,s,t,r),this.type="IcosahedronGeometry",this.parameters={radius:t,detail:r}}static fromJSON(t){return new hM(t.radius,t.detail)}},sy=class uM extends gc{constructor(t=1,r=0){let i=[1,0,0,-1,0,0,0,1,0,0,-1,0,0,0,1,0,0,-1],n=[0,2,4,0,4,3,0,3,5,0,5,2,1,2,5,1,5,3,1,3,4,1,4,2];super(i,n,t,r),this.type="OctahedronGeometry",this.parameters={radius:t,detail:r}}static fromJSON(t){return new uM(t.radius,t.detail)}},vc=class dM extends Hr{constructor(t=1,r=1,i=1,n=1){super(),this.type="PlaneGeometry",this.parameters={width:t,height:r,widthSegments:i,heightSegments:n};let s=t/2,a=r/2,o=Math.floor(i),l=Math.floor(n),c=o+1,u=l+1,d=t/o,f=r/l,y=[],b=[],x=[],g=[];for(let v=0;v<u;v++){let _=v*f-a;for(let E=0;E<c;E++){let M=E*d-s;b.push(M,-_,0),x.push(0,0,1),g.push(E/o),g.push(1-v/l)}}for(let v=0;v<l;v++)for(let _=0;_<o;_++){let E=_+c*v,M=_+c*(v+1),P=_+1+c*(v+1),k=_+1+c*v;y.push(E,M,k),y.push(M,P,k)}this.setIndex(y),this.setAttribute("position",new hr(b,3)),this.setAttribute("normal",new hr(x,3)),this.setAttribute("uv",new hr(g,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new dM(t.width,t.height,t.widthSegments,t.heightSegments)}},Bb=class pM extends Hr{constructor(t=.5,r=1,i=32,n=1,s=0,a=Math.PI*2){super(),this.type="RingGeometry",this.parameters={innerRadius:t,outerRadius:r,thetaSegments:i,phiSegments:n,thetaStart:s,thetaLength:a},i=Math.max(3,i),n=Math.max(1,n);let o=[],l=[],c=[],u=[],d=t,f=(r-t)/n,y=new je,b=new Ft;for(let x=0;x<=n;x++){for(let g=0;g<=i;g++){let v=s+g/i*a;y.x=d*Math.cos(v),y.y=d*Math.sin(v),l.push(y.x,y.y,y.z),c.push(0,0,1),b.x=(y.x/r+1)/2,b.y=(y.y/r+1)/2,u.push(b.x,b.y)}d+=f}for(let x=0;x<n;x++){let g=x*(i+1);for(let v=0;v<i;v++){let _=v+g,E=_,M=_+i+1,P=_+i+2,k=_+1;o.push(E,M,k),o.push(M,P,k)}}this.setIndex(o),this.setAttribute("position",new hr(l,3)),this.setAttribute("normal",new hr(c,3)),this.setAttribute("uv",new hr(u,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new pM(t.innerRadius,t.outerRadius,t.thetaSegments,t.phiSegments,t.thetaStart,t.thetaLength)}},jb=class fM extends Hr{constructor(t=new Fa([new Ft(0,.5),new Ft(-.5,-.5),new Ft(.5,-.5)]),r=12){super(),this.type="ShapeGeometry",this.parameters={shapes:t,curveSegments:r};let i=[],n=[],s=[],a=[],o=0,l=0;if(Array.isArray(t)===!1)c(t);else for(let u=0;u<t.length;u++)c(t[u]),this.addGroup(o,l,u),o+=l,l=0;this.setIndex(i),this.setAttribute("position",new hr(n,3)),this.setAttribute("normal",new hr(s,3)),this.setAttribute("uv",new hr(a,2));function c(u){let d=n.length/3,f=u.extractPoints(r),y=f.shape,b=f.holes;za.isClockWise(y)===!1&&(y=y.reverse());for(let g=0,v=b.length;g<v;g++){let _=b[g];za.isClockWise(_)===!0&&(b[g]=_.reverse())}let x=za.triangulateShape(y,b);for(let g=0,v=b.length;g<v;g++){let _=b[g];y=y.concat(_)}for(let g=0,v=y.length;g<v;g++){let _=y[g];n.push(_.x,_.y,0),s.push(0,0,1),a.push(_.x,_.y)}for(let g=0,v=x.length;g<v;g++){let _=x[g],E=_[0]+d,M=_[1]+d,P=_[2]+d;i.push(E,M,P),l+=3}}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}toJSON(){let t=super.toJSON(),r=this.parameters.shapes;return w2(r,t)}static fromJSON(t,r){let i=[];for(let n=0,s=t.shapes.length;n<s;n++){let a=r[t.shapes[n]];i.push(a)}return new fM(i,t.curveSegments)}};function w2(e,t){if(t.shapes=[],Array.isArray(e))for(let r=0,i=e.length;r<i;r++){let n=e[r];t.shapes.push(n.uuid)}else t.shapes.push(e.uuid);return t}var po=class mM extends Hr{constructor(t=1,r=32,i=16,n=0,s=Math.PI*2,a=0,o=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:t,widthSegments:r,heightSegments:i,phiStart:n,phiLength:s,thetaStart:a,thetaLength:o},r=Math.max(3,Math.floor(r)),i=Math.max(2,Math.floor(i));let l=Math.min(a+o,Math.PI),c=0,u=[],d=new je,f=new je,y=[],b=[],x=[],g=[];for(let v=0;v<=i;v++){let _=[],E=v/i,M=0;v===0&&a===0?M=.5/r:v===i&&l===Math.PI&&(M=-.5/r);for(let P=0;P<=r;P++){let k=P/r;d.x=-t*Math.cos(n+k*s)*Math.sin(a+E*o),d.y=t*Math.cos(a+E*o),d.z=t*Math.sin(n+k*s)*Math.sin(a+E*o),b.push(d.x,d.y,d.z),f.copy(d).normalize(),x.push(f.x,f.y,f.z),g.push(k+M,1-E),_.push(c++)}u.push(_)}for(let v=0;v<i;v++)for(let _=0;_<r;_++){let E=u[v][_+1],M=u[v][_],P=u[v+1][_],k=u[v+1][_+1];(v!==0||a>0)&&y.push(E,M,k),(v!==i-1||l<Math.PI)&&y.push(M,P,k)}this.setIndex(y),this.setAttribute("position",new hr(b,3)),this.setAttribute("normal",new hr(x,3)),this.setAttribute("uv",new hr(g,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new mM(t.radius,t.widthSegments,t.heightSegments,t.phiStart,t.phiLength,t.thetaStart,t.thetaLength)}},Vb=class gM extends gc{constructor(t=1,r=0){let i=[1,1,1,-1,-1,1,-1,1,-1,1,-1,-1],n=[2,1,0,0,3,2,1,3,0,2,3,1];super(i,n,t,r),this.type="TetrahedronGeometry",this.parameters={radius:t,detail:r}}static fromJSON(t){return new gM(t.radius,t.detail)}},Hb=class yM extends Hr{constructor(t=1,r=.4,i=12,n=48,s=Math.PI*2){super(),this.type="TorusGeometry",this.parameters={radius:t,tube:r,radialSegments:i,tubularSegments:n,arc:s},i=Math.floor(i),n=Math.floor(n);let a=[],o=[],l=[],c=[],u=new je,d=new je,f=new je;for(let y=0;y<=i;y++)for(let b=0;b<=n;b++){let x=b/n*s,g=y/i*Math.PI*2;d.x=(t+r*Math.cos(g))*Math.cos(x),d.y=(t+r*Math.cos(g))*Math.sin(x),d.z=r*Math.sin(g),o.push(d.x,d.y,d.z),u.x=t*Math.cos(x),u.y=t*Math.sin(x),f.subVectors(d,u).normalize(),l.push(f.x,f.y,f.z),c.push(b/n),c.push(y/i)}for(let y=1;y<=i;y++)for(let b=1;b<=n;b++){let x=(n+1)*y+b-1,g=(n+1)*(y-1)+b-1,v=(n+1)*(y-1)+b,_=(n+1)*y+b;a.push(x,g,_),a.push(g,v,_)}this.setIndex(a),this.setAttribute("position",new hr(o,3)),this.setAttribute("normal",new hr(l,3)),this.setAttribute("uv",new hr(c,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new yM(t.radius,t.tube,t.radialSegments,t.tubularSegments,t.arc)}},Gb=class vM extends Hr{constructor(t=1,r=.4,i=64,n=8,s=2,a=3){super(),this.type="TorusKnotGeometry",this.parameters={radius:t,tube:r,tubularSegments:i,radialSegments:n,p:s,q:a},i=Math.floor(i),n=Math.floor(n);let o=[],l=[],c=[],u=[],d=new je,f=new je,y=new je,b=new je,x=new je,g=new je,v=new je;for(let E=0;E<=i;++E){let M=E/i*s*Math.PI*2;_(M,s,a,t,y),_(M+.01,s,a,t,b),g.subVectors(b,y),v.addVectors(b,y),x.crossVectors(g,v),v.crossVectors(x,g),x.normalize(),v.normalize();for(let P=0;P<=n;++P){let k=P/n*Math.PI*2,z=-r*Math.cos(k),D=r*Math.sin(k);d.x=y.x+(z*v.x+D*x.x),d.y=y.y+(z*v.y+D*x.y),d.z=y.z+(z*v.z+D*x.z),l.push(d.x,d.y,d.z),f.subVectors(d,y).normalize(),c.push(f.x,f.y,f.z),u.push(E/i),u.push(P/n)}}for(let E=1;E<=i;E++)for(let M=1;M<=n;M++){let P=(n+1)*(E-1)+(M-1),k=(n+1)*E+(M-1),z=(n+1)*E+M,D=(n+1)*(E-1)+M;o.push(P,k,D),o.push(k,z,D)}this.setIndex(o),this.setAttribute("position",new hr(l,3)),this.setAttribute("normal",new hr(c,3)),this.setAttribute("uv",new hr(u,2));function _(E,M,P,k,z){let D=Math.cos(E),I=Math.sin(E),L=P/M*E,Z=Math.cos(L);z.x=k*(2+Z)*.5*D,z.y=k*(2+Z)*I*.5,z.z=k*Math.sin(L)*.5}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new vM(t.radius,t.tube,t.tubularSegments,t.radialSegments,t.p,t.q)}},Wb=class xM extends Hr{constructor(t=new Jg(new je(-1,-1,0),new je(-1,1,0),new je(1,1,0)),r=64,i=1,n=8,s=!1){super(),this.type="TubeGeometry",this.parameters={path:t,tubularSegments:r,radius:i,radialSegments:n,closed:s};let a=t.computeFrenetFrames(r,s);this.tangents=a.tangents,this.normals=a.normals,this.binormals=a.binormals;let o=new je,l=new je,c=new Ft,u=new je,d=[],f=[],y=[],b=[];x(),this.setIndex(b),this.setAttribute("position",new hr(d,3)),this.setAttribute("normal",new hr(f,3)),this.setAttribute("uv",new hr(y,2));function x(){for(let E=0;E<r;E++)g(E);g(s===!1?r:0),_(),v()}function g(E){u=t.getPointAt(E/r,u);let M=a.normals[E],P=a.binormals[E];for(let k=0;k<=n;k++){let z=k/n*Math.PI*2,D=Math.sin(z),I=-Math.cos(z);l.x=I*M.x+D*P.x,l.y=I*M.y+D*P.y,l.z=I*M.z+D*P.z,l.normalize(),f.push(l.x,l.y,l.z),o.x=u.x+i*l.x,o.y=u.y+i*l.y,o.z=u.z+i*l.z,d.push(o.x,o.y,o.z)}}function v(){for(let E=1;E<=r;E++)for(let M=1;M<=n;M++){let P=(n+1)*(E-1)+(M-1),k=(n+1)*E+(M-1),z=(n+1)*E+M,D=(n+1)*(E-1)+M;b.push(P,k,D),b.push(k,z,D)}}function _(){for(let E=0;E<=r;E++)for(let M=0;M<=n;M++)c.x=E/r,c.y=M/n,y.push(c.x,c.y)}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}toJSON(){let t=super.toJSON();return t.path=this.parameters.path.toJSON(),t}static fromJSON(t){return new xM(new Vp[t.path.type]().fromJSON(t.path),t.tubularSegments,t.radius,t.radialSegments,t.closed)}},Xb=class extends Hr{constructor(e=null){if(super(),this.type="WireframeGeometry",this.parameters={geometry:e},e!==null){let t=[],r=new Set,i=new je,n=new je;if(e.index!==null){let s=e.attributes.position,a=e.index,o=e.groups;o.length===0&&(o=[{start:0,count:a.count,materialIndex:0}]);for(let l=0,c=o.length;l<c;++l){let u=o[l],d=u.start,f=u.count;for(let y=d,b=d+f;y<b;y+=3)for(let x=0;x<3;x++){let g=a.getX(y+x),v=a.getX(y+(x+1)%3);i.fromBufferAttribute(s,g),n.fromBufferAttribute(s,v),Yb(i,n,r)===!0&&(t.push(i.x,i.y,i.z),t.push(n.x,n.y,n.z))}}}else{let s=e.attributes.position;for(let a=0,o=s.count/3;a<o;a++)for(let l=0;l<3;l++){let c=3*a+l,u=3*a+(l+1)%3;i.fromBufferAttribute(s,c),n.fromBufferAttribute(s,u),Yb(i,n,r)===!0&&(t.push(i.x,i.y,i.z),t.push(n.x,n.y,n.z))}}this.setAttribute("position",new hr(t,3))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}};function Yb(e,t,r){let i=`${e.x},${e.y},${e.z}-${t.x},${t.y},${t.z}`,n=`${t.x},${t.y},${t.z}-${e.x},${e.y},${e.z}`;return r.has(i)===!0||r.has(n)===!0?!1:(r.add(i),r.add(n),!0)}var qb=Object.freeze({__proto__:null,BoxGeometry:Da,CapsuleGeometry:Pb,CircleGeometry:Ib,ConeGeometry:ty,CylinderGeometry:eu,DodecahedronGeometry:Nb,EdgesGeometry:tu,ExtrudeGeometry:Kp,IcosahedronGeometry:zb,LatheGeometry:ey,OctahedronGeometry:sy,PlaneGeometry:vc,PolyhedronGeometry:gc,RingGeometry:Bb,ShapeGeometry:jb,SphereGeometry:po,TetrahedronGeometry:Vb,TorusGeometry:Hb,TorusKnotGeometry:Gb,TubeGeometry:Wb,WireframeGeometry:Xb}),Kb=class extends bn{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new or(0),this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.fog=e.fog,this}},ay=class extends ln{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}},is=class extends bn{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new or(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new or(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=so,this.normalScale=new Ft(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Ys,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:""},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},vs=class extends is{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new Ft(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return Jr(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(t){this.ior=(1+.4*t)/(1-.4*t)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new or(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new or(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new or(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}},oy=class extends bn{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new or(16777215),this.specular=new or(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new or(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=so,this.normalScale=new Ft(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Ys,this.combine=mr,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},Zb=class extends bn{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new or(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new or(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=so,this.normalScale=new Ft(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},ly=class extends bn{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=so,this.normalScale=new Ft(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}},$b=class extends bn{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new or(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new or(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=so,this.normalScale=new Ft(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Ys,this.combine=mr,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},cy=class extends bn{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=vx,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}},hy=class extends bn{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type="MeshDistanceMaterial",this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}},Jb=class extends bn{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new or(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=so,this.normalScale=new Ft(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.flatShading=e.flatShading,this.fog=e.fog,this}},Qb=class extends tn{constructor(e){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}};function Qo(e,t,r){return!e||!r&&e.constructor===t?e:typeof t.BYTES_PER_ELEMENT=="number"?new t(e):Array.prototype.slice.call(e)}function e1(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function t1(e){function t(n,s){return e[n]-e[s]}let r=e.length,i=new Array(r);for(let n=0;n!==r;++n)i[n]=n;return i.sort(t),i}function uy(e,t,r){let i=e.length,n=new e.constructor(i);for(let s=0,a=0;a!==i;++s){let o=r[s]*t;for(let l=0;l!==t;++l)n[a++]=e[o+l]}return n}function dy(e,t,r,i){let n=1,s=e[0];for(;s!==void 0&&s[i]===void 0;)s=e[n++];if(s===void 0)return;let a=s[i];if(a!==void 0)if(Array.isArray(a))do a=s[i],a!==void 0&&(t.push(s.time),r.push.apply(r,a)),s=e[n++];while(s!==void 0);else if(a.toArray!==void 0)do a=s[i],a!==void 0&&(t.push(s.time),a.toArray(r,r.length)),s=e[n++];while(s!==void 0);else do a=s[i],a!==void 0&&(t.push(s.time),r.push(a)),s=e[n++];while(s!==void 0)}function _2(e,t,r,i,n=30){let s=e.clone();s.name=t;let a=[];for(let l=0;l<s.tracks.length;++l){let c=s.tracks[l],u=c.getValueSize(),d=[],f=[];for(let y=0;y<c.times.length;++y){let b=c.times[y]*n;if(!(b<r||b>=i)){d.push(c.times[y]);for(let x=0;x<u;++x)f.push(c.values[y*u+x])}}d.length!==0&&(c.times=Qo(d,c.times.constructor),c.values=Qo(f,c.values.constructor),a.push(c))}s.tracks=a;let o=1/0;for(let l=0;l<s.tracks.length;++l)o>s.tracks[l].times[0]&&(o=s.tracks[l].times[0]);for(let l=0;l<s.tracks.length;++l)s.tracks[l].shift(-1*o);return s.resetDuration(),s}function E2(e,t=0,r=e,i=30){i<=0&&(i=30);let n=r.tracks.length,s=t/i;for(let a=0;a<n;++a){let o=r.tracks[a],l=o.ValueTypeName;if(l==="bool"||l==="string")continue;let c=e.tracks.find(function(v){return v.name===o.name&&v.ValueTypeName===l});if(c===void 0)continue;let u=0,d=o.getValueSize();o.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(u=d/3);let f=0,y=c.getValueSize();c.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(f=y/3);let b=o.times.length-1,x;if(s<=o.times[0]){let v=u,_=d-u;x=o.values.slice(v,_)}else if(s>=o.times[b]){let v=b*d+u,_=v+d-u;x=o.values.slice(v,_)}else{let v=o.createInterpolant(),_=u,E=d-u;v.evaluate(s),x=v.resultBuffer.slice(_,E)}l==="quaternion"&&new pn().fromArray(x).normalize().conjugate().toArray(x);let g=c.times.length;for(let v=0;v<g;++v){let _=v*y+f;if(l==="quaternion")pn.multiplyQuaternionsFlat(c.values,_,x,0,c.values,_);else{let E=y-f*2;for(let M=0;M<E;++M)c.values[_+M]-=x[M]}}}return e.blendMode=sg,e}var S2={convertArray:Qo,isTypedArray:e1,getKeyframeOrder:t1,sortedArray:uy,flattenJSON:dy,subclip:_2,makeClipAdditive:E2},xc=class{constructor(e,t,r,i){this.parameterPositions=e,this._cachedIndex=0,this.resultBuffer=i!==void 0?i:new t.constructor(r),this.sampleValues=t,this.valueSize=r,this.settings=null,this.DefaultSettings_={}}evaluate(e){let t=this.parameterPositions,r=this._cachedIndex,i=t[r],n=t[r-1];e:{t:{let s;r:{i:if(!(e<i)){for(let a=r+2;;){if(i===void 0){if(e<n)break i;return r=t.length,this._cachedIndex=r,this.copySampleValue_(r-1)}if(r===a)break;if(n=i,i=t[++r],e<i)break t}s=t.length;break r}if(!(e>=n)){let a=t[1];e<a&&(r=2,n=a);for(let o=r-2;;){if(n===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(r===o)break;if(i=n,n=t[--r-1],e>=n)break t}s=r,r=0;break r}break e}for(;r<s;){let a=r+s>>>1;e<t[a]?s=a:r=a+1}if(i=t[r],n=t[r-1],n===void 0)return this._cachedIndex=0,this.copySampleValue_(0);if(i===void 0)return r=t.length,this._cachedIndex=r,this.copySampleValue_(r-1)}this._cachedIndex=r,this.intervalChanged_(r,n,i)}return this.interpolate_(r,n,e,i)}getSettings_(){return this.settings||this.DefaultSettings_}copySampleValue_(e){let t=this.resultBuffer,r=this.sampleValues,i=this.valueSize,n=e*i;for(let s=0;s!==i;++s)t[s]=r[n+s];return t}interpolate_(){throw new Error("call to abstract method")}intervalChanged_(){}},r1=class extends xc{constructor(e,t,r,i){super(e,t,r,i),this._weightPrev=-0,this._offsetPrev=-0,this._weightNext=-0,this._offsetNext=-0,this.DefaultSettings_={endingStart:Fo,endingEnd:Fo}}intervalChanged_(e,t,r){let i=this.parameterPositions,n=e-2,s=e+1,a=i[n],o=i[s];if(a===void 0)switch(this.getSettings_().endingStart){case zo:n=e,a=2*t-r;break;case Ph:n=i.length-2,a=t+i[n]-i[n+1];break;default:n=e,a=r}if(o===void 0)switch(this.getSettings_().endingEnd){case zo:s=e,o=2*r-t;break;case Ph:s=1,o=r+i[1]-i[0];break;default:s=e-1,o=t}let l=(r-t)*.5,c=this.valueSize;this._weightPrev=l/(t-a),this._weightNext=l/(o-r),this._offsetPrev=n*c,this._offsetNext=s*c}interpolate_(e,t,r,i){let n=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=e*a,l=o-a,c=this._offsetPrev,u=this._offsetNext,d=this._weightPrev,f=this._weightNext,y=(r-t)/(i-t),b=y*y,x=b*y,g=-d*x+2*d*b-d*y,v=(1+d)*x+(-1.5-2*d)*b+(-.5+d)*y+1,_=(-1-f)*x+(1.5+f)*b+.5*y,E=f*x-f*b;for(let M=0;M!==a;++M)n[M]=g*s[c+M]+v*s[l+M]+_*s[o+M]+E*s[u+M];return n}},py=class extends xc{constructor(e,t,r,i){super(e,t,r,i)}interpolate_(e,t,r,i){let n=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=e*a,l=o-a,c=(r-t)/(i-t),u=1-c;for(let d=0;d!==a;++d)n[d]=s[l+d]*u+s[o+d]*c;return n}},i1=class extends xc{constructor(e,t,r,i){super(e,t,r,i)}interpolate_(e){return this.copySampleValue_(e-1)}},Zs=class{constructor(e,t,r,i){if(e===void 0)throw new Error("THREE.KeyframeTrack: track name is undefined");if(t===void 0||t.length===0)throw new Error("THREE.KeyframeTrack: no keyframes in track named "+e);this.name=e,this.times=Qo(t,this.TimeBufferType),this.values=Qo(r,this.ValueBufferType),this.setInterpolation(i||this.DefaultInterpolation)}static toJSON(e){let t=e.constructor,r;if(t.toJSON!==this.toJSON)r=t.toJSON(e);else{r={name:e.name,times:Qo(e.times,Array),values:Qo(e.values,Array)};let i=e.getInterpolation();i!==e.DefaultInterpolation&&(r.interpolation=i)}return r.type=e.ValueTypeName,r}InterpolantFactoryMethodDiscrete(e){return new i1(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new py(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new r1(this.times,this.values,this.getValueSize(),e)}setInterpolation(e){let t;switch(e){case Gl:t=this.InterpolantFactoryMethodDiscrete;break;case Wl:t=this.InterpolantFactoryMethodLinear;break;case qd:t=this.InterpolantFactoryMethodSmooth;break}if(t===void 0){let r="unsupported interpolation for "+this.ValueTypeName+" keyframe track named "+this.name;if(this.createInterpolant===void 0)if(e!==this.DefaultInterpolation)this.setInterpolation(this.DefaultInterpolation);else throw new Error(r);return console.warn("THREE.KeyframeTrack:",r),this}return this.createInterpolant=t,this}getInterpolation(){switch(this.createInterpolant){case this.InterpolantFactoryMethodDiscrete:return Gl;case this.InterpolantFactoryMethodLinear:return Wl;case this.InterpolantFactoryMethodSmooth:return qd}}getValueSize(){return this.values.length/this.times.length}shift(e){if(e!==0){let t=this.times;for(let r=0,i=t.length;r!==i;++r)t[r]+=e}return this}scale(e){if(e!==1){let t=this.times;for(let r=0,i=t.length;r!==i;++r)t[r]*=e}return this}trim(e,t){let r=this.times,i=r.length,n=0,s=i-1;for(;n!==i&&r[n]<e;)++n;for(;s!==-1&&r[s]>t;)--s;if(++s,n!==0||s!==i){n>=s&&(s=Math.max(s,1),n=s-1);let a=this.getValueSize();this.times=r.slice(n,s),this.values=this.values.slice(n*a,s*a)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(console.error("THREE.KeyframeTrack: Invalid value size in track.",this),e=!1);let r=this.times,i=this.values,n=r.length;n===0&&(console.error("THREE.KeyframeTrack: Track is empty.",this),e=!1);let s=null;for(let a=0;a!==n;a++){let o=r[a];if(typeof o=="number"&&isNaN(o)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,a,o),e=!1;break}if(s!==null&&s>o){console.error("THREE.KeyframeTrack: Out of order keys.",this,a,o,s),e=!1;break}s=o}if(i!==void 0&&e1(i))for(let a=0,o=i.length;a!==o;++a){let l=i[a];if(isNaN(l)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,a,l),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),r=this.getValueSize(),i=this.getInterpolation()===qd,n=e.length-1,s=1;for(let a=1;a<n;++a){let o=!1,l=e[a],c=e[a+1];if(l!==c&&(a!==1||l!==e[0]))if(i)o=!0;else{let u=a*r,d=u-r,f=u+r;for(let y=0;y!==r;++y){let b=t[u+y];if(b!==t[d+y]||b!==t[f+y]){o=!0;break}}}if(o){if(a!==s){e[s]=e[a];let u=a*r,d=s*r;for(let f=0;f!==r;++f)t[d+f]=t[u+f]}++s}}if(n>0){e[s]=e[n];for(let a=n*r,o=s*r,l=0;l!==r;++l)t[o+l]=t[a+l];++s}return s!==e.length?(this.times=e.slice(0,s),this.values=t.slice(0,s*r)):(this.times=e,this.values=t),this}clone(){let e=this.times.slice(),t=this.values.slice(),r=this.constructor,i=new r(this.name,e,t);return i.createInterpolant=this.createInterpolant,i}};Zs.prototype.TimeBufferType=Float32Array,Zs.prototype.ValueBufferType=Float32Array,Zs.prototype.DefaultInterpolation=Wl;var el=class extends Zs{constructor(e,t,r){super(e,t,r)}};el.prototype.ValueTypeName="bool",el.prototype.ValueBufferType=Array,el.prototype.DefaultInterpolation=Gl,el.prototype.InterpolantFactoryMethodLinear=void 0,el.prototype.InterpolantFactoryMethodSmooth=void 0;var fy=class extends Zs{};fy.prototype.ValueTypeName="color";var tl=class extends Zs{};tl.prototype.ValueTypeName="number";var n1=class extends xc{constructor(e,t,r,i){super(e,t,r,i)}interpolate_(e,t,r,i){let n=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=(r-t)/(i-t),l=e*a;for(let c=l+a;l!==c;l+=4)pn.slerpFlat(n,0,s,l-a,s,l,o);return n}},rl=class extends Zs{InterpolantFactoryMethodLinear(e){return new n1(this.times,this.values,this.getValueSize(),e)}};rl.prototype.ValueTypeName="quaternion",rl.prototype.InterpolantFactoryMethodSmooth=void 0;var il=class extends Zs{constructor(e,t,r){super(e,t,r)}};il.prototype.ValueTypeName="string",il.prototype.ValueBufferType=Array,il.prototype.DefaultInterpolation=Gl,il.prototype.InterpolantFactoryMethodLinear=void 0,il.prototype.InterpolantFactoryMethodSmooth=void 0;var nl=class extends Zs{};nl.prototype.ValueTypeName="vector";var bc=class{constructor(e="",t=-1,r=[],i=Kd){this.name=e,this.tracks=r,this.duration=t,this.blendMode=i,this.uuid=fs(),this.duration<0&&this.resetDuration()}static parse(e){let t=[],r=e.tracks,i=1/(e.fps||1);for(let s=0,a=r.length;s!==a;++s)t.push(A2(r[s]).scale(i));let n=new this(e.name,e.duration,t,e.blendMode);return n.uuid=e.uuid,n}static toJSON(e){let t=[],r=e.tracks,i={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode};for(let n=0,s=r.length;n!==s;++n)t.push(Zs.toJSON(r[n]));return i}static CreateFromMorphTargetSequence(e,t,r,i){let n=t.length,s=[];for(let a=0;a<n;a++){let o=[],l=[];o.push((a+n-1)%n,a,(a+1)%n),l.push(0,1,0);let c=t1(o);o=uy(o,1,c),l=uy(l,1,c),!i&&o[0]===0&&(o.push(n),l.push(l[0])),s.push(new tl(".morphTargetInfluences["+t[a].name+"]",o,l).scale(1/r))}return new this(e,-1,s)}static findByName(e,t){let r=e;if(!Array.isArray(e)){let i=e;r=i.geometry&&i.geometry.animations||i.animations}for(let i=0;i<r.length;i++)if(r[i].name===t)return r[i];return null}static CreateClipsFromMorphTargetSequences(e,t,r){let i={},n=/^([\w-]*?)([\d]+)$/;for(let a=0,o=e.length;a<o;a++){let l=e[a],c=l.name.match(n);if(c&&c.length>1){let u=c[1],d=i[u];d||(i[u]=d=[]),d.push(l)}}let s=[];for(let a in i)s.push(this.CreateFromMorphTargetSequence(a,i[a],t,r));return s}static parseAnimation(e,t){if(!e)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;let r=function(c,u,d,f,y){if(d.length!==0){let b=[],x=[];dy(d,b,x,f),b.length!==0&&y.push(new c(u,b,x))}},i=[],n=e.name||"default",s=e.fps||30,a=e.blendMode,o=e.length||-1,l=e.hierarchy||[];for(let c=0;c<l.length;c++){let u=l[c].keys;if(!(!u||u.length===0))if(u[0].morphTargets){let d={},f;for(f=0;f<u.length;f++)if(u[f].morphTargets)for(let y=0;y<u[f].morphTargets.length;y++)d[u[f].morphTargets[y]]=-1;for(let y in d){let b=[],x=[];for(let g=0;g!==u[f].morphTargets.length;++g){let v=u[f];b.push(v.time),x.push(v.morphTarget===y?1:0)}i.push(new tl(".morphTargetInfluence["+y+"]",b,x))}o=d.length*s}else{let d=".bones["+t[c].name+"]";r(nl,d+".position",u,"pos",i),r(rl,d+".quaternion",u,"rot",i),r(nl,d+".scale",u,"scl",i)}}return i.length===0?null:new this(n,o,i,a)}resetDuration(){let e=this.tracks,t=0;for(let r=0,i=e.length;r!==i;++r){let n=this.tracks[r];t=Math.max(t,n.times[n.times.length-1])}return this.duration=t,this}trim(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].trim(0,this.duration);return this}validate(){let e=!0;for(let t=0;t<this.tracks.length;t++)e=e&&this.tracks[t].validate();return e}optimize(){for(let e=0;e<this.tracks.length;e++)this.tracks[e].optimize();return this}clone(){let e=[];for(let t=0;t<this.tracks.length;t++)e.push(this.tracks[t].clone());return new this.constructor(this.name,this.duration,e,this.blendMode)}toJSON(){return this.constructor.toJSON(this)}};function M2(e){switch(e.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return tl;case"vector":case"vector2":case"vector3":case"vector4":return nl;case"color":return fy;case"quaternion":return rl;case"bool":case"boolean":return el;case"string":return il}throw new Error("THREE.KeyframeTrack: Unsupported typeName: "+e)}function A2(e){if(e.type===void 0)throw new Error("THREE.KeyframeTrack: track type undefined, can not parse");let t=M2(e.type);if(e.times===void 0){let r=[],i=[];dy(e.keys,r,i,"value"),e.times=r,e.values=i}return t.parse!==void 0?t.parse(e):new t(e.name,e.times,e.values,e.interpolation)}var Ba={enabled:!1,files:{},add:function(e,t){this.enabled!==!1&&(this.files[e]=t)},get:function(e){if(this.enabled!==!1)return this.files[e]},remove:function(e){delete this.files[e]},clear:function(){this.files={}}},my=class{constructor(e,t,r){let i=this,n=!1,s=0,a=0,o,l=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=r,this.itemStart=function(c){a++,n===!1&&i.onStart!==void 0&&i.onStart(c,s,a),n=!0},this.itemEnd=function(c){s++,i.onProgress!==void 0&&i.onProgress(c,s,a),s===a&&(n=!1,i.onLoad!==void 0&&i.onLoad())},this.itemError=function(c){i.onError!==void 0&&i.onError(c)},this.resolveURL=function(c){return o?o(c):c},this.setURLModifier=function(c){return o=c,this},this.addHandler=function(c,u){return l.push(c,u),this},this.removeHandler=function(c){let u=l.indexOf(c);return u!==-1&&l.splice(u,2),this},this.getHandler=function(c){for(let u=0,d=l.length;u<d;u+=2){let f=l[u],y=l[u+1];if(f.global&&(f.lastIndex=0),f.test(c))return y}return null}}},s1=new my,mn=class{constructor(e){this.manager=e!==void 0?e:s1,this.crossOrigin="anonymous",this.withCredentials=!1,this.path="",this.resourcePath="",this.requestHeader={}}load(){}loadAsync(e,t){let r=this;return new Promise(function(i,n){r.load(e,i,t,n)})}parse(){}setCrossOrigin(e){return this.crossOrigin=e,this}setWithCredentials(e){return this.withCredentials=e,this}setPath(e){return this.path=e,this}setResourcePath(e){return this.resourcePath=e,this}setRequestHeader(e){return this.requestHeader=e,this}};mn.DEFAULT_MATERIAL_NAME="__DEFAULT";var ja={},T2=class extends Error{constructor(e,t){super(e),this.response=t}},Ps=class extends mn{constructor(e){super(e)}load(e,t,r,i){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let n=Ba.get(e);if(n!==void 0)return this.manager.itemStart(e),setTimeout(()=>{t&&t(n),this.manager.itemEnd(e)},0),n;if(ja[e]!==void 0){ja[e].push({onLoad:t,onProgress:r,onError:i});return}ja[e]=[],ja[e].push({onLoad:t,onProgress:r,onError:i});let s=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),a=this.mimeType,o=this.responseType;fetch(s).then(l=>{if(l.status===200||l.status===0){if(l.status===0&&console.warn("THREE.FileLoader: HTTP Status 0 received."),typeof ReadableStream>"u"||l.body===void 0||l.body.getReader===void 0)return l;let c=ja[e],u=l.body.getReader(),d=l.headers.get("X-File-Size")||l.headers.get("Content-Length"),f=d?parseInt(d):0,y=f!==0,b=0,x=new ReadableStream({start(g){v();function v(){u.read().then(({done:_,value:E})=>{if(_)g.close();else{b+=E.byteLength;let M=new ProgressEvent("progress",{lengthComputable:y,loaded:b,total:f});for(let P=0,k=c.length;P<k;P++){let z=c[P];z.onProgress&&z.onProgress(M)}g.enqueue(E),v()}},_=>{g.error(_)})}}});return new Response(x)}else throw new T2(`fetch for "${l.url}" responded with ${l.status}: ${l.statusText}`,l)}).then(l=>{switch(o){case"arraybuffer":return l.arrayBuffer();case"blob":return l.blob();case"document":return l.text().then(c=>new DOMParser().parseFromString(c,a));case"json":return l.json();default:if(a===void 0)return l.text();{let c=/charset="?([^;"\s]*)"?/i.exec(a),u=c&&c[1]?c[1].toLowerCase():void 0,d=new TextDecoder(u);return l.arrayBuffer().then(f=>d.decode(f))}}}).then(l=>{Ba.add(e,l);let c=ja[e];delete ja[e];for(let u=0,d=c.length;u<d;u++){let f=c[u];f.onLoad&&f.onLoad(l)}}).catch(l=>{let c=ja[e];if(c===void 0)throw this.manager.itemError(e),l;delete ja[e];for(let u=0,d=c.length;u<d;u++){let f=c[u];f.onError&&f.onError(l)}this.manager.itemError(e)}).finally(()=>{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}},C2=class extends mn{constructor(e){super(e)}load(e,t,r,i){let n=this,s=new Ps(this.manager);s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,function(a){try{t(n.parse(JSON.parse(a)))}catch(o){i?i(o):console.error(o),n.manager.itemError(e)}},r,i)}parse(e){let t=[];for(let r=0;r<e.length;r++){let i=bc.parse(e[r]);t.push(i)}return t}},R2=class extends mn{constructor(e){super(e)}load(e,t,r,i){let n=this,s=[],a=new Up,o=new Ps(this.manager);o.setPath(this.path),o.setResponseType("arraybuffer"),o.setRequestHeader(this.requestHeader),o.setWithCredentials(n.withCredentials);let l=0;function c(u){o.load(e[u],function(d){let f=n.parse(d,!0);s[u]={width:f.width,height:f.height,format:f.format,mipmaps:f.mipmaps},l+=1,l===6&&(f.mipmapCount===1&&(a.minFilter=Pi),a.image=s,a.format=f.format,a.needsUpdate=!0,t&&t(a))},r,i)}if(Array.isArray(e))for(let u=0,d=e.length;u<d;++u)c(u);else o.load(e,function(u){let d=n.parse(u,!0);if(d.isCubemap){let f=d.mipmaps.length/d.mipmapCount;for(let y=0;y<f;y++){s[y]={mipmaps:[]};for(let b=0;b<d.mipmapCount;b++)s[y].mipmaps.push(d.mipmaps[y*d.mipmapCount+b]),s[y].format=d.format,s[y].width=d.width,s[y].height=d.height}a.image=s}else a.image.width=d.width,a.image.height=d.height,a.mipmaps=d.mipmaps;d.mipmapCount===1&&(a.minFilter=Pi),a.format=d.format,a.needsUpdate=!0,t&&t(a)},r,i);return a}},su=class extends mn{constructor(e){super(e)}load(e,t,r,i){this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let n=this,s=Ba.get(e);if(s!==void 0)return n.manager.itemStart(e),setTimeout(function(){t&&t(s),n.manager.itemEnd(e)},0),s;let a=Oh("img");function o(){c(),Ba.add(e,this),t&&t(this),n.manager.itemEnd(e)}function l(u){c(),i&&i(u),n.manager.itemError(e),n.manager.itemEnd(e)}function c(){a.removeEventListener("load",o,!1),a.removeEventListener("error",l,!1)}return a.addEventListener("load",o,!1),a.addEventListener("error",l,!1),e.slice(0,5)!=="data:"&&this.crossOrigin!==void 0&&(a.crossOrigin=this.crossOrigin),n.manager.itemStart(e),a.src=e,a}},P2=class extends mn{constructor(e){super(e)}load(e,t,r,i){let n=new jh;n.colorSpace=xi;let s=new su(this.manager);s.setCrossOrigin(this.crossOrigin),s.setPath(this.path);let a=0;function o(l){s.load(e[l],function(c){n.images[l]=c,a++,a===6&&(n.needsUpdate=!0,t&&t(n))},void 0,i)}for(let l=0;l<e.length;++l)o(l);return n}},I2=class extends mn{constructor(e){super(e)}load(e,t,r,i){let n=this,s=new ys,a=new Ps(this.manager);return a.setResponseType("arraybuffer"),a.setRequestHeader(this.requestHeader),a.setPath(this.path),a.setWithCredentials(n.withCredentials),a.load(e,function(o){let l;try{l=n.parse(o)}catch(c){if(i!==void 0)i(c);else{console.error(c);return}}l.image!==void 0?s.image=l.image:l.data!==void 0&&(s.image.width=l.width,s.image.height=l.height,s.image.data=l.data),s.wrapS=l.wrapS!==void 0?l.wrapS:ei,s.wrapT=l.wrapT!==void 0?l.wrapT:ei,s.magFilter=l.magFilter!==void 0?l.magFilter:Pi,s.minFilter=l.minFilter!==void 0?l.minFilter:Pi,s.anisotropy=l.anisotropy!==void 0?l.anisotropy:1,l.colorSpace!==void 0&&(s.colorSpace=l.colorSpace),l.flipY!==void 0&&(s.flipY=l.flipY),l.format!==void 0&&(s.format=l.format),l.type!==void 0&&(s.type=l.type),l.mipmaps!==void 0&&(s.mipmaps=l.mipmaps,s.minFilter=Fi),l.mipmapCount===1&&(s.minFilter=Pi),l.generateMipmaps!==void 0&&(s.generateMipmaps=l.generateMipmaps),s.needsUpdate=!0,t&&t(s,l)},r,i),s}},gy=class extends mn{constructor(e){super(e)}load(e,t,r,i){let n=new Qi,s=new su(this.manager);return s.setCrossOrigin(this.crossOrigin),s.setPath(this.path),s.load(e,function(a){n.image=a,n.needsUpdate=!0,t!==void 0&&t(n)},r,i),n}},fo=class extends mi{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new or(e),this.intensity=t}dispose(){}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){let t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,this.groundColor!==void 0&&(t.object.groundColor=this.groundColor.getHex()),this.distance!==void 0&&(t.object.distance=this.distance),this.angle!==void 0&&(t.object.angle=this.angle),this.decay!==void 0&&(t.object.decay=this.decay),this.penumbra!==void 0&&(t.object.penumbra=this.penumbra),this.shadow!==void 0&&(t.object.shadow=this.shadow.toJSON()),this.target!==void 0&&(t.object.target=this.target.uuid),t}},a1=class extends fo{constructor(e,t,r){super(e,r),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(mi.DEFAULT_UP),this.updateMatrix(),this.groundColor=new or(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}},yy=new Ir,o1=new je,l1=new je,vy=class{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new Ft(512,512),this.map=null,this.mapPass=null,this.matrix=new Ir,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new qh,this._frameExtents=new Ft(1,1),this._viewportCount=1,this._viewports=[new _i(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){let t=this.camera,r=this.matrix;o1.setFromMatrixPosition(e.matrixWorld),t.position.copy(o1),l1.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(l1),t.updateMatrixWorld(),yy.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(yy),r.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),r.multiply(yy)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.mapSize.copy(e.mapSize),this}clone(){return new this.constructor().copy(this)}toJSON(){let e={};return this.intensity!==1&&(e.intensity=this.intensity),this.bias!==0&&(e.bias=this.bias),this.normalBias!==0&&(e.normalBias=this.normalBias),this.radius!==1&&(e.radius=this.radius),(this.mapSize.x!==512||this.mapSize.y!==512)&&(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}},N2=class extends vy{constructor(){super(new cn(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1}updateMatrices(e){let t=this.camera,r=Xl*2*e.angle*this.focus,i=this.mapSize.width/this.mapSize.height,n=e.distance||t.far;(r!==t.fov||i!==t.aspect||n!==t.far)&&(t.fov=r,t.aspect=i,t.far=n,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}},xy=class extends fo{constructor(e,t,r=0,i=Math.PI/3,n=0,s=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(mi.DEFAULT_UP),this.updateMatrix(),this.target=new mi,this.distance=r,this.angle=i,this.penumbra=n,this.decay=s,this.map=null,this.shadow=new N2}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}},c1=new Ir,au=new je,by=new je,L2=class extends vy{constructor(){super(new cn(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new Ft(4,2),this._viewportCount=6,this._viewports=[new _i(2,1,1,1),new _i(0,1,1,1),new _i(3,1,1,1),new _i(1,1,1,1),new _i(3,0,1,1),new _i(1,0,1,1)],this._cubeDirections=[new je(1,0,0),new je(-1,0,0),new je(0,0,1),new je(0,0,-1),new je(0,1,0),new je(0,-1,0)],this._cubeUps=[new je(0,1,0),new je(0,1,0),new je(0,1,0),new je(0,1,0),new je(0,0,1),new je(0,0,-1)]}updateMatrices(e,t=0){let r=this.camera,i=this.matrix,n=e.distance||r.far;n!==r.far&&(r.far=n,r.updateProjectionMatrix()),au.setFromMatrixPosition(e.matrixWorld),r.position.copy(au),by.copy(r.position),by.add(this._cubeDirections[t]),r.up.copy(this._cubeUps[t]),r.lookAt(by),r.updateMatrixWorld(),i.makeTranslation(-au.x,-au.y,-au.z),c1.multiplyMatrices(r.projectionMatrix,r.matrixWorldInverse),this._frustum.setFromProjectionMatrix(c1)}},Zp=class extends fo{constructor(e,t,r=0,i=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=r,this.decay=i,this.shadow=new L2}get power(){return this.intensity*4*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}},wc=class extends gp{constructor(e=-1,t=1,r=1,i=-1,n=.1,s=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=r,this.bottom=i,this.near=n,this.far=s,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=e.view===null?null:Object.assign({},e.view),this}setViewOffset(e,t,r,i,n,s){this.view===null&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=r,this.view.offsetY=i,this.view.width=n,this.view.height=s,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),r=(this.right+this.left)/2,i=(this.top+this.bottom)/2,n=r-e,s=r+e,a=i+t,o=i-t;if(this.view!==null&&this.view.enabled){let l=(this.right-this.left)/this.view.fullWidth/this.zoom,c=(this.top-this.bottom)/this.view.fullHeight/this.zoom;n+=l*this.view.offsetX,s=n+l*this.view.width,a-=c*this.view.offsetY,o=a-c*this.view.height}this.projectionMatrix.makeOrthographic(n,s,a,o,this.near,this.far,this.coordinateSystem),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){let t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,this.view!==null&&(t.object.view=Object.assign({},this.view)),t}},k2=class extends vy{constructor(){super(new wc(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}},$p=class extends fo{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(mi.DEFAULT_UP),this.updateMatrix(),this.target=new mi,this.shadow=new k2}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}},wy=class extends fo{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}},h1=class extends fo{constructor(e,t,r=10,i=10){super(e,t),this.isRectAreaLight=!0,this.type="RectAreaLight",this.width=r,this.height=i}get power(){return this.intensity*this.width*this.height*Math.PI}set power(e){this.intensity=e/(this.width*this.height*Math.PI)}copy(e){return super.copy(e),this.width=e.width,this.height=e.height,this}toJSON(e){let t=super.toJSON(e);return t.object.width=this.width,t.object.height=this.height,t}},u1=class{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new je)}set(e){for(let t=0;t<9;t++)this.coefficients[t].copy(e[t]);return this}zero(){for(let e=0;e<9;e++)this.coefficients[e].set(0,0,0);return this}getAt(e,t){let r=e.x,i=e.y,n=e.z,s=this.coefficients;return t.copy(s[0]).multiplyScalar(.282095),t.addScaledVector(s[1],.488603*i),t.addScaledVector(s[2],.488603*n),t.addScaledVector(s[3],.488603*r),t.addScaledVector(s[4],1.092548*(r*i)),t.addScaledVector(s[5],1.092548*(i*n)),t.addScaledVector(s[6],.315392*(3*n*n-1)),t.addScaledVector(s[7],1.092548*(r*n)),t.addScaledVector(s[8],.546274*(r*r-i*i)),t}getIrradianceAt(e,t){let r=e.x,i=e.y,n=e.z,s=this.coefficients;return t.copy(s[0]).multiplyScalar(.886227),t.addScaledVector(s[1],2*.511664*i),t.addScaledVector(s[2],2*.511664*n),t.addScaledVector(s[3],2*.511664*r),t.addScaledVector(s[4],2*.429043*r*i),t.addScaledVector(s[5],2*.429043*i*n),t.addScaledVector(s[6],.743125*n*n-.247708),t.addScaledVector(s[7],2*.429043*r*n),t.addScaledVector(s[8],.429043*(r*r-i*i)),t}add(e){for(let t=0;t<9;t++)this.coefficients[t].add(e.coefficients[t]);return this}addScaledSH(e,t){for(let r=0;r<9;r++)this.coefficients[r].addScaledVector(e.coefficients[r],t);return this}scale(e){for(let t=0;t<9;t++)this.coefficients[t].multiplyScalar(e);return this}lerp(e,t){for(let r=0;r<9;r++)this.coefficients[r].lerp(e.coefficients[r],t);return this}equals(e){for(let t=0;t<9;t++)if(!this.coefficients[t].equals(e.coefficients[t]))return!1;return!0}copy(e){return this.set(e.coefficients)}clone(){return new this.constructor().copy(this)}fromArray(e,t=0){let r=this.coefficients;for(let i=0;i<9;i++)r[i].fromArray(e,t+i*3);return this}toArray(e=[],t=0){let r=this.coefficients;for(let i=0;i<9;i++)r[i].toArray(e,t+i*3);return e}static getBasisAt(e,t){let r=e.x,i=e.y,n=e.z;t[0]=.282095,t[1]=.488603*i,t[2]=.488603*n,t[3]=.488603*r,t[4]=1.092548*r*i,t[5]=1.092548*i*n,t[6]=.315392*(3*n*n-1),t[7]=1.092548*r*n,t[8]=.546274*(r*r-i*i)}},d1=class extends fo{constructor(e=new u1,t=1){super(void 0,t),this.isLightProbe=!0,this.sh=e}copy(e){return super.copy(e),this.sh.copy(e.sh),this}fromJSON(e){return this.intensity=e.intensity,this.sh.fromArray(e.sh),this}toJSON(e){let t=super.toJSON(e);return t.object.sh=this.sh.toArray(),t}},p1=class bM extends mn{constructor(t){super(t),this.textures={}}load(t,r,i,n){let s=this,a=new Ps(s.manager);a.setPath(s.path),a.setRequestHeader(s.requestHeader),a.setWithCredentials(s.withCredentials),a.load(t,function(o){try{r(s.parse(JSON.parse(o)))}catch(l){n?n(l):console.error(l),s.manager.itemError(t)}},i,n)}parse(t){let r=this.textures;function i(s){return r[s]===void 0&&console.warn("THREE.MaterialLoader: Undefined texture",s),r[s]}let n=this.createMaterialFromType(t.type);if(t.uuid!==void 0&&(n.uuid=t.uuid),t.name!==void 0&&(n.name=t.name),t.color!==void 0&&n.color!==void 0&&n.color.setHex(t.color),t.roughness!==void 0&&(n.roughness=t.roughness),t.metalness!==void 0&&(n.metalness=t.metalness),t.sheen!==void 0&&(n.sheen=t.sheen),t.sheenColor!==void 0&&(n.sheenColor=new or().setHex(t.sheenColor)),t.sheenRoughness!==void 0&&(n.sheenRoughness=t.sheenRoughness),t.emissive!==void 0&&n.emissive!==void 0&&n.emissive.setHex(t.emissive),t.specular!==void 0&&n.specular!==void 0&&n.specular.setHex(t.specular),t.specularIntensity!==void 0&&(n.specularIntensity=t.specularIntensity),t.specularColor!==void 0&&n.specularColor!==void 0&&n.specularColor.setHex(t.specularColor),t.shininess!==void 0&&(n.shininess=t.shininess),t.clearcoat!==void 0&&(n.clearcoat=t.clearcoat),t.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=t.clearcoatRoughness),t.dispersion!==void 0&&(n.dispersion=t.dispersion),t.iridescence!==void 0&&(n.iridescence=t.iridescence),t.iridescenceIOR!==void 0&&(n.iridescenceIOR=t.iridescenceIOR),t.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=t.iridescenceThicknessRange),t.transmission!==void 0&&(n.transmission=t.transmission),t.thickness!==void 0&&(n.thickness=t.thickness),t.attenuationDistance!==void 0&&(n.attenuationDistance=t.attenuationDistance),t.attenuationColor!==void 0&&n.attenuationColor!==void 0&&n.attenuationColor.setHex(t.attenuationColor),t.anisotropy!==void 0&&(n.anisotropy=t.anisotropy),t.anisotropyRotation!==void 0&&(n.anisotropyRotation=t.anisotropyRotation),t.fog!==void 0&&(n.fog=t.fog),t.flatShading!==void 0&&(n.flatShading=t.flatShading),t.blending!==void 0&&(n.blending=t.blending),t.combine!==void 0&&(n.combine=t.combine),t.side!==void 0&&(n.side=t.side),t.shadowSide!==void 0&&(n.shadowSide=t.shadowSide),t.opacity!==void 0&&(n.opacity=t.opacity),t.transparent!==void 0&&(n.transparent=t.transparent),t.alphaTest!==void 0&&(n.alphaTest=t.alphaTest),t.alphaHash!==void 0&&(n.alphaHash=t.alphaHash),t.depthFunc!==void 0&&(n.depthFunc=t.depthFunc),t.depthTest!==void 0&&(n.depthTest=t.depthTest),t.depthWrite!==void 0&&(n.depthWrite=t.depthWrite),t.colorWrite!==void 0&&(n.colorWrite=t.colorWrite),t.blendSrc!==void 0&&(n.blendSrc=t.blendSrc),t.blendDst!==void 0&&(n.blendDst=t.blendDst),t.blendEquation!==void 0&&(n.blendEquation=t.blendEquation),t.blendSrcAlpha!==void 0&&(n.blendSrcAlpha=t.blendSrcAlpha),t.blendDstAlpha!==void 0&&(n.blendDstAlpha=t.blendDstAlpha),t.blendEquationAlpha!==void 0&&(n.blendEquationAlpha=t.blendEquationAlpha),t.blendColor!==void 0&&n.blendColor!==void 0&&n.blendColor.setHex(t.blendColor),t.blendAlpha!==void 0&&(n.blendAlpha=t.blendAlpha),t.stencilWriteMask!==void 0&&(n.stencilWriteMask=t.stencilWriteMask),t.stencilFunc!==void 0&&(n.stencilFunc=t.stencilFunc),t.stencilRef!==void 0&&(n.stencilRef=t.stencilRef),t.stencilFuncMask!==void 0&&(n.stencilFuncMask=t.stencilFuncMask),t.stencilFail!==void 0&&(n.stencilFail=t.stencilFail),t.stencilZFail!==void 0&&(n.stencilZFail=t.stencilZFail),t.stencilZPass!==void 0&&(n.stencilZPass=t.stencilZPass),t.stencilWrite!==void 0&&(n.stencilWrite=t.stencilWrite),t.wireframe!==void 0&&(n.wireframe=t.wireframe),t.wireframeLinewidth!==void 0&&(n.wireframeLinewidth=t.wireframeLinewidth),t.wireframeLinecap!==void 0&&(n.wireframeLinecap=t.wireframeLinecap),t.wireframeLinejoin!==void 0&&(n.wireframeLinejoin=t.wireframeLinejoin),t.rotation!==void 0&&(n.rotation=t.rotation),t.linewidth!==void 0&&(n.linewidth=t.linewidth),t.dashSize!==void 0&&(n.dashSize=t.dashSize),t.gapSize!==void 0&&(n.gapSize=t.gapSize),t.scale!==void 0&&(n.scale=t.scale),t.polygonOffset!==void 0&&(n.polygonOffset=t.polygonOffset),t.polygonOffsetFactor!==void 0&&(n.polygonOffsetFactor=t.polygonOffsetFactor),t.polygonOffsetUnits!==void 0&&(n.polygonOffsetUnits=t.polygonOffsetUnits),t.dithering!==void 0&&(n.dithering=t.dithering),t.alphaToCoverage!==void 0&&(n.alphaToCoverage=t.alphaToCoverage),t.premultipliedAlpha!==void 0&&(n.premultipliedAlpha=t.premultipliedAlpha),t.forceSinglePass!==void 0&&(n.forceSinglePass=t.forceSinglePass),t.visible!==void 0&&(n.visible=t.visible),t.toneMapped!==void 0&&(n.toneMapped=t.toneMapped),t.userData!==void 0&&(n.userData=t.userData),t.vertexColors!==void 0&&(typeof t.vertexColors=="number"?n.vertexColors=t.vertexColors>0:n.vertexColors=t.vertexColors),t.uniforms!==void 0)for(let s in t.uniforms){let a=t.uniforms[s];switch(n.uniforms[s]={},a.type){case"t":n.uniforms[s].value=i(a.value);break;case"c":n.uniforms[s].value=new or().setHex(a.value);break;case"v2":n.uniforms[s].value=new Ft().fromArray(a.value);break;case"v3":n.uniforms[s].value=new je().fromArray(a.value);break;case"v4":n.uniforms[s].value=new _i().fromArray(a.value);break;case"m3":n.uniforms[s].value=new si().fromArray(a.value);break;case"m4":n.uniforms[s].value=new Ir().fromArray(a.value);break;default:n.uniforms[s].value=a.value}}if(t.defines!==void 0&&(n.defines=t.defines),t.vertexShader!==void 0&&(n.vertexShader=t.vertexShader),t.fragmentShader!==void 0&&(n.fragmentShader=t.fragmentShader),t.glslVersion!==void 0&&(n.glslVersion=t.glslVersion),t.extensions!==void 0)for(let s in t.extensions)n.extensions[s]=t.extensions[s];if(t.lights!==void 0&&(n.lights=t.lights),t.clipping!==void 0&&(n.clipping=t.clipping),t.size!==void 0&&(n.size=t.size),t.sizeAttenuation!==void 0&&(n.sizeAttenuation=t.sizeAttenuation),t.map!==void 0&&(n.map=i(t.map)),t.matcap!==void 0&&(n.matcap=i(t.matcap)),t.alphaMap!==void 0&&(n.alphaMap=i(t.alphaMap)),t.bumpMap!==void 0&&(n.bumpMap=i(t.bumpMap)),t.bumpScale!==void 0&&(n.bumpScale=t.bumpScale),t.normalMap!==void 0&&(n.normalMap=i(t.normalMap)),t.normalMapType!==void 0&&(n.normalMapType=t.normalMapType),t.normalScale!==void 0){let s=t.normalScale;Array.isArray(s)===!1&&(s=[s,s]),n.normalScale=new Ft().fromArray(s)}return t.displacementMap!==void 0&&(n.displacementMap=i(t.displacementMap)),t.displacementScale!==void 0&&(n.displacementScale=t.displacementScale),t.displacementBias!==void 0&&(n.displacementBias=t.displacementBias),t.roughnessMap!==void 0&&(n.roughnessMap=i(t.roughnessMap)),t.metalnessMap!==void 0&&(n.metalnessMap=i(t.metalnessMap)),t.emissiveMap!==void 0&&(n.emissiveMap=i(t.emissiveMap)),t.emissiveIntensity!==void 0&&(n.emissiveIntensity=t.emissiveIntensity),t.specularMap!==void 0&&(n.specularMap=i(t.specularMap)),t.specularIntensityMap!==void 0&&(n.specularIntensityMap=i(t.specularIntensityMap)),t.specularColorMap!==void 0&&(n.specularColorMap=i(t.specularColorMap)),t.envMap!==void 0&&(n.envMap=i(t.envMap)),t.envMapRotation!==void 0&&n.envMapRotation.fromArray(t.envMapRotation),t.envMapIntensity!==void 0&&(n.envMapIntensity=t.envMapIntensity),t.reflectivity!==void 0&&(n.reflectivity=t.reflectivity),t.refractionRatio!==void 0&&(n.refractionRatio=t.refractionRatio),t.lightMap!==void 0&&(n.lightMap=i(t.lightMap)),t.lightMapIntensity!==void 0&&(n.lightMapIntensity=t.lightMapIntensity),t.aoMap!==void 0&&(n.aoMap=i(t.aoMap)),t.aoMapIntensity!==void 0&&(n.aoMapIntensity=t.aoMapIntensity),t.gradientMap!==void 0&&(n.gradientMap=i(t.gradientMap)),t.clearcoatMap!==void 0&&(n.clearcoatMap=i(t.clearcoatMap)),t.clearcoatRoughnessMap!==void 0&&(n.clearcoatRoughnessMap=i(t.clearcoatRoughnessMap)),t.clearcoatNormalMap!==void 0&&(n.clearcoatNormalMap=i(t.clearcoatNormalMap)),t.clearcoatNormalScale!==void 0&&(n.clearcoatNormalScale=new Ft().fromArray(t.clearcoatNormalScale)),t.iridescenceMap!==void 0&&(n.iridescenceMap=i(t.iridescenceMap)),t.iridescenceThicknessMap!==void 0&&(n.iridescenceThicknessMap=i(t.iridescenceThicknessMap)),t.transmissionMap!==void 0&&(n.transmissionMap=i(t.transmissionMap)),t.thicknessMap!==void 0&&(n.thicknessMap=i(t.thicknessMap)),t.anisotropyMap!==void 0&&(n.anisotropyMap=i(t.anisotropyMap)),t.sheenColorMap!==void 0&&(n.sheenColorMap=i(t.sheenColorMap)),t.sheenRoughnessMap!==void 0&&(n.sheenRoughnessMap=i(t.sheenRoughnessMap)),n}setTextures(t){return this.textures=t,this}createMaterialFromType(t){return bM.createMaterialFromType(t)}static createMaterialFromType(t){let r={ShadowMaterial:Kb,SpriteMaterial:yp,RawShaderMaterial:ay,ShaderMaterial:ln,PointsMaterial:$h,MeshPhysicalMaterial:vs,MeshStandardMaterial:is,MeshPhongMaterial:oy,MeshToonMaterial:Zb,MeshNormalMaterial:ly,MeshLambertMaterial:$b,MeshDepthMaterial:cy,MeshDistanceMaterial:hy,MeshBasicMaterial:en,MeshMatcapMaterial:Jb,LineDashedMaterial:Qb,LineBasicMaterial:tn,Material:bn};return new r[t]}},Va=class{static decodeText(e){if(console.warn("THREE.LoaderUtils: decodeText() has been deprecated with r165 and will be removed with r175. Use TextDecoder instead."),typeof TextDecoder<"u")return new TextDecoder().decode(e);let t="";for(let r=0,i=e.length;r<i;r++)t+=String.fromCharCode(e[r]);try{return decodeURIComponent(escape(t))}catch{return t}}static extractUrlBase(e){let t=e.lastIndexOf("/");return t===-1?"./":e.slice(0,t+1)}static resolveURL(e,t){return typeof e!="string"||e===""?"":(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^\/]+).*/i,"$1")),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}},f1=class extends Hr{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type="InstancedBufferGeometry",this.instanceCount=1/0}copy(e){return super.copy(e),this.instanceCount=e.instanceCount,this}toJSON(){let e=super.toJSON();return e.instanceCount=this.instanceCount,e.isInstancedBufferGeometry=!0,e}},m1=class extends mn{constructor(e){super(e)}load(e,t,r,i){let n=this,s=new Ps(n.manager);s.setPath(n.path),s.setRequestHeader(n.requestHeader),s.setWithCredentials(n.withCredentials),s.load(e,function(a){try{t(n.parse(JSON.parse(a)))}catch(o){i?i(o):console.error(o),n.manager.itemError(e)}},r,i)}parse(e){let t={},r={};function i(d,f){if(t[f]!==void 0)return t[f];let y=d.interleavedBuffers[f],b=n(d,y.buffer),x=Yl(y.type,b),g=new Vh(x,y.stride);return g.uuid=y.uuid,t[f]=g,g}function n(d,f){if(r[f]!==void 0)return r[f];let y=d.arrayBuffers[f],b=new Uint32Array(y).buffer;return r[f]=b,b}let s=e.isInstancedBufferGeometry?new f1:new Hr,a=e.data.index;if(a!==void 0){let d=Yl(a.type,a.array);s.setIndex(new ui(d,1))}let o=e.data.attributes;for(let d in o){let f=o[d],y;if(f.isInterleavedBufferAttribute){let b=i(e.data,f.data);y=new cc(b,f.itemSize,f.offset,f.normalized)}else{let b=Yl(f.type,f.array),x=f.isInstancedBufferAttribute?qo:ui;y=new x(b,f.itemSize,f.normalized)}f.name!==void 0&&(y.name=f.name),f.usage!==void 0&&y.setUsage(f.usage),s.setAttribute(d,y)}let l=e.data.morphAttributes;if(l)for(let d in l){let f=l[d],y=[];for(let b=0,x=f.length;b<x;b++){let g=f[b],v;if(g.isInterleavedBufferAttribute){let _=i(e.data,g.data);v=new cc(_,g.itemSize,g.offset,g.normalized)}else{let _=Yl(g.type,g.array);v=new ui(_,g.itemSize,g.normalized)}g.name!==void 0&&(v.name=g.name),y.push(v)}s.morphAttributes[d]=y}e.data.morphTargetsRelative&&(s.morphTargetsRelative=!0);let c=e.data.groups||e.data.drawcalls||e.data.offsets;if(c!==void 0)for(let d=0,f=c.length;d!==f;++d){let y=c[d];s.addGroup(y.start,y.count,y.materialIndex)}let u=e.data.boundingSphere;if(u!==void 0){let d=new je;u.center!==void 0&&d.fromArray(u.center),s.boundingSphere=new on(d,u.radius)}return e.name&&(s.name=e.name),e.userData&&(s.userData=e.userData),s}},O2=class extends mn{constructor(e){super(e)}load(e,t,r,i){let n=this,s=this.path===""?Va.extractUrlBase(e):this.path;this.resourcePath=this.resourcePath||s;let a=new Ps(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(o){let l=null;try{l=JSON.parse(o)}catch(u){i!==void 0&&i(u),console.error("THREE:ObjectLoader: Can't parse "+e+".",u.message);return}let c=l.metadata;if(c===void 0||c.type===void 0||c.type.toLowerCase()==="geometry"){i!==void 0&&i(new Error("THREE.ObjectLoader: Can't load "+e)),console.error("THREE.ObjectLoader: Can't load "+e);return}n.parse(l,t)},r,i)}async loadAsync(e,t){let r=this,i=this.path===""?Va.extractUrlBase(e):this.path;this.resourcePath=this.resourcePath||i;let n=new Ps(this.manager);n.setPath(this.path),n.setRequestHeader(this.requestHeader),n.setWithCredentials(this.withCredentials);let s=await n.loadAsync(e,t),a=JSON.parse(s),o=a.metadata;if(o===void 0||o.type===void 0||o.type.toLowerCase()==="geometry")throw new Error("THREE.ObjectLoader: Can't load "+e);return await r.parseAsync(a)}parse(e,t){let r=this.parseAnimations(e.animations),i=this.parseShapes(e.shapes),n=this.parseGeometries(e.geometries,i),s=this.parseImages(e.images,function(){t!==void 0&&t(l)}),a=this.parseTextures(e.textures,s),o=this.parseMaterials(e.materials,a),l=this.parseObject(e.object,n,o,a,r),c=this.parseSkeletons(e.skeletons,l);if(this.bindSkeletons(l,c),this.bindLightTargets(l),t!==void 0){let u=!1;for(let d in s)if(s[d].data instanceof HTMLImageElement){u=!0;break}u===!1&&t(l)}return l}async parseAsync(e){let t=this.parseAnimations(e.animations),r=this.parseShapes(e.shapes),i=this.parseGeometries(e.geometries,r),n=await this.parseImagesAsync(e.images),s=this.parseTextures(e.textures,n),a=this.parseMaterials(e.materials,s),o=this.parseObject(e.object,i,a,s,t),l=this.parseSkeletons(e.skeletons,o);return this.bindSkeletons(o,l),this.bindLightTargets(o),o}parseShapes(e){let t={};if(e!==void 0)for(let r=0,i=e.length;r<i;r++){let n=new Fa().fromJSON(e[r]);t[n.uuid]=n}return t}parseSkeletons(e,t){let r={},i={};if(t.traverse(function(n){n.isBone&&(i[n.uuid]=n)}),e!==void 0)for(let n=0,s=e.length;n<s;n++){let a=new Fg().fromJSON(e[n],i);r[a.uuid]=a}return r}parseGeometries(e,t){let r={};if(e!==void 0){let i=new m1;for(let n=0,s=e.length;n<s;n++){let a,o=e[n];switch(o.type){case"BufferGeometry":case"InstancedBufferGeometry":a=i.parse(o);break;default:o.type in qb?a=qb[o.type].fromJSON(o,t):console.warn(`THREE.ObjectLoader: Unsupported geometry type "${o.type}"`)}a.uuid=o.uuid,o.name!==void 0&&(a.name=o.name),o.userData!==void 0&&(a.userData=o.userData),r[o.uuid]=a}}return r}parseMaterials(e,t){let r={},i={};if(e!==void 0){let n=new p1;n.setTextures(t);for(let s=0,a=e.length;s<a;s++){let o=e[s];r[o.uuid]===void 0&&(r[o.uuid]=n.parse(o)),i[o.uuid]=r[o.uuid]}}return i}parseAnimations(e){let t={};if(e!==void 0)for(let r=0;r<e.length;r++){let i=e[r],n=bc.parse(i);t[n.uuid]=n}return t}parseImages(e,t){let r=this,i={},n;function s(o){return r.manager.itemStart(o),n.load(o,function(){r.manager.itemEnd(o)},void 0,function(){r.manager.itemError(o),r.manager.itemEnd(o)})}function a(o){if(typeof o=="string"){let l=o,c=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(l)?l:r.resourcePath+l;return s(c)}else return o.data?{data:Yl(o.type,o.data),width:o.width,height:o.height}:null}if(e!==void 0&&e.length>0){let o=new my(t);n=new su(o),n.setCrossOrigin(this.crossOrigin);for(let l=0,c=e.length;l<c;l++){let u=e[l],d=u.url;if(Array.isArray(d)){let f=[];for(let y=0,b=d.length;y<b;y++){let x=d[y],g=a(x);g!==null&&(g instanceof HTMLImageElement?f.push(g):f.push(new ys(g.data,g.width,g.height)))}i[u.uuid]=new Vo(f)}else{let f=a(u.url);i[u.uuid]=new Vo(f)}}}return i}async parseImagesAsync(e){let t=this,r={},i;async function n(s){if(typeof s=="string"){let a=s,o=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(a)?a:t.resourcePath+a;return await i.loadAsync(o)}else return s.data?{data:Yl(s.type,s.data),width:s.width,height:s.height}:null}if(e!==void 0&&e.length>0){i=new su(this.manager),i.setCrossOrigin(this.crossOrigin);for(let s=0,a=e.length;s<a;s++){let o=e[s],l=o.url;if(Array.isArray(l)){let c=[];for(let u=0,d=l.length;u<d;u++){let f=l[u],y=await n(f);y!==null&&(y instanceof HTMLImageElement?c.push(y):c.push(new ys(y.data,y.width,y.height)))}r[o.uuid]=new Vo(c)}else{let c=await n(o.url);r[o.uuid]=new Vo(c)}}}return r}parseTextures(e,t){function r(n,s){return typeof n=="number"?n:(console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.",n),s[n])}let i={};if(e!==void 0)for(let n=0,s=e.length;n<s;n++){let a=e[n];a.image===void 0&&console.warn('THREE.ObjectLoader: No "image" specified for',a.uuid),t[a.image]===void 0&&console.warn("THREE.ObjectLoader: Undefined image",a.image);let o=t[a.image],l=o.data,c;Array.isArray(l)?(c=new jh,l.length===6&&(c.needsUpdate=!0)):(l&&l.data?c=new ys:c=new Qi,l&&(c.needsUpdate=!0)),c.source=o,c.uuid=a.uuid,a.name!==void 0&&(c.name=a.name),a.mapping!==void 0&&(c.mapping=r(a.mapping,D2)),a.channel!==void 0&&(c.channel=a.channel),a.offset!==void 0&&c.offset.fromArray(a.offset),a.repeat!==void 0&&c.repeat.fromArray(a.repeat),a.center!==void 0&&c.center.fromArray(a.center),a.rotation!==void 0&&(c.rotation=a.rotation),a.wrap!==void 0&&(c.wrapS=r(a.wrap[0],g1),c.wrapT=r(a.wrap[1],g1)),a.format!==void 0&&(c.format=a.format),a.internalFormat!==void 0&&(c.internalFormat=a.internalFormat),a.type!==void 0&&(c.type=a.type),a.colorSpace!==void 0&&(c.colorSpace=a.colorSpace),a.minFilter!==void 0&&(c.minFilter=r(a.minFilter,y1)),a.magFilter!==void 0&&(c.magFilter=r(a.magFilter,y1)),a.anisotropy!==void 0&&(c.anisotropy=a.anisotropy),a.flipY!==void 0&&(c.flipY=a.flipY),a.generateMipmaps!==void 0&&(c.generateMipmaps=a.generateMipmaps),a.premultiplyAlpha!==void 0&&(c.premultiplyAlpha=a.premultiplyAlpha),a.unpackAlignment!==void 0&&(c.unpackAlignment=a.unpackAlignment),a.compareFunction!==void 0&&(c.compareFunction=a.compareFunction),a.userData!==void 0&&(c.userData=a.userData),i[a.uuid]=c}return i}parseObject(e,t,r,i,n){let s;function a(d){return t[d]===void 0&&console.warn("THREE.ObjectLoader: Undefined geometry",d),t[d]}function o(d){if(d!==void 0){if(Array.isArray(d)){let f=[];for(let y=0,b=d.length;y<b;y++){let x=d[y];r[x]===void 0&&console.warn("THREE.ObjectLoader: Undefined material",x),f.push(r[x])}return f}return r[d]===void 0&&console.warn("THREE.ObjectLoader: Undefined material",d),r[d]}}function l(d){return i[d]===void 0&&console.warn("THREE.ObjectLoader: Undefined texture",d),i[d]}let c,u;switch(e.type){case"Scene":s=new Yo,e.background!==void 0&&(Number.isInteger(e.background)?s.background=new or(e.background):s.background=l(e.background)),e.environment!==void 0&&(s.environment=l(e.environment)),e.fog!==void 0&&(e.fog.type==="Fog"?s.fog=new rb(e.fog.color,e.fog.near,e.fog.far):e.fog.type==="FogExp2"&&(s.fog=new tb(e.fog.color,e.fog.density)),e.fog.name!==""&&(s.fog.name=e.fog.name)),e.backgroundBlurriness!==void 0&&(s.backgroundBlurriness=e.backgroundBlurriness),e.backgroundIntensity!==void 0&&(s.backgroundIntensity=e.backgroundIntensity),e.backgroundRotation!==void 0&&s.backgroundRotation.fromArray(e.backgroundRotation),e.environmentIntensity!==void 0&&(s.environmentIntensity=e.environmentIntensity),e.environmentRotation!==void 0&&s.environmentRotation.fromArray(e.environmentRotation);break;case"PerspectiveCamera":s=new cn(e.fov,e.aspect,e.near,e.far),e.focus!==void 0&&(s.focus=e.focus),e.zoom!==void 0&&(s.zoom=e.zoom),e.filmGauge!==void 0&&(s.filmGauge=e.filmGauge),e.filmOffset!==void 0&&(s.filmOffset=e.filmOffset),e.view!==void 0&&(s.view=Object.assign({},e.view));break;case"OrthographicCamera":s=new wc(e.left,e.right,e.top,e.bottom,e.near,e.far),e.zoom!==void 0&&(s.zoom=e.zoom),e.view!==void 0&&(s.view=Object.assign({},e.view));break;case"AmbientLight":s=new wy(e.color,e.intensity);break;case"DirectionalLight":s=new $p(e.color,e.intensity),s.target=e.target||"";break;case"PointLight":s=new Zp(e.color,e.intensity,e.distance,e.decay);break;case"RectAreaLight":s=new h1(e.color,e.intensity,e.width,e.height);break;case"SpotLight":s=new xy(e.color,e.intensity,e.distance,e.angle,e.penumbra,e.decay),s.target=e.target||"";break;case"HemisphereLight":s=new a1(e.color,e.groundColor,e.intensity);break;case"LightProbe":s=new d1().fromJSON(e);break;case"SkinnedMesh":c=a(e.geometry),u=o(e.material),s=new Ug(c,u),e.bindMode!==void 0&&(s.bindMode=e.bindMode),e.bindMatrix!==void 0&&s.bindMatrix.fromArray(e.bindMatrix),e.skeleton!==void 0&&(s.skeleton=e.skeleton);break;case"Mesh":c=a(e.geometry),u=o(e.material),s=new qr(c,u);break;case"InstancedMesh":c=a(e.geometry),u=o(e.material);let d=e.count,f=e.instanceMatrix,y=e.instanceColor;s=new Mp(c,u,d),s.instanceMatrix=new qo(new Float32Array(f.array),16),y!==void 0&&(s.instanceColor=new qo(new Float32Array(y.array),y.itemSize));break;case"BatchedMesh":c=a(e.geometry),u=o(e.material),s=new yb(e.maxInstanceCount,e.maxVertexCount,e.maxIndexCount,u),s.geometry=c,s.perObjectFrustumCulled=e.perObjectFrustumCulled,s.sortObjects=e.sortObjects,s._drawRanges=e.drawRanges,s._reservedRanges=e.reservedRanges,s._visibility=e.visibility,s._active=e.active,s._bounds=e.bounds.map(b=>{let x=new Xi;x.min.fromArray(b.boxMin),x.max.fromArray(b.boxMax);let g=new on;return g.radius=b.sphereRadius,g.center.fromArray(b.sphereCenter),{boxInitialized:b.boxInitialized,box:x,sphereInitialized:b.sphereInitialized,sphere:g}}),s._maxInstanceCount=e.maxInstanceCount,s._maxVertexCount=e.maxVertexCount,s._maxIndexCount=e.maxIndexCount,s._geometryInitialized=e.geometryInitialized,s._geometryCount=e.geometryCount,s._matricesTexture=l(e.matricesTexture.uuid),e.colorsTexture!==void 0&&(s._colorsTexture=l(e.colorsTexture.uuid));break;case"LOD":s=new ob;break;case"Line":s=new ua(a(e.geometry),o(e.material));break;case"LineLoop":s=new Lp(a(e.geometry),o(e.material));break;case"LineSegments":s=new Fn(a(e.geometry),o(e.material));break;case"PointCloud":case"Points":s=new Dp(a(e.geometry),o(e.material));break;case"Sprite":s=new kg(o(e.material));break;case"Group":s=new Wi;break;case"Bone":s=new Ep;break;default:s=new mi}if(s.uuid=e.uuid,e.name!==void 0&&(s.name=e.name),e.matrix!==void 0?(s.matrix.fromArray(e.matrix),e.matrixAutoUpdate!==void 0&&(s.matrixAutoUpdate=e.matrixAutoUpdate),s.matrixAutoUpdate&&s.matrix.decompose(s.position,s.quaternion,s.scale)):(e.position!==void 0&&s.position.fromArray(e.position),e.rotation!==void 0&&s.rotation.fromArray(e.rotation),e.quaternion!==void 0&&s.quaternion.fromArray(e.quaternion),e.scale!==void 0&&s.scale.fromArray(e.scale)),e.up!==void 0&&s.up.fromArray(e.up),e.castShadow!==void 0&&(s.castShadow=e.castShadow),e.receiveShadow!==void 0&&(s.receiveShadow=e.receiveShadow),e.shadow&&(e.shadow.intensity!==void 0&&(s.shadow.intensity=e.shadow.intensity),e.shadow.bias!==void 0&&(s.shadow.bias=e.shadow.bias),e.shadow.normalBias!==void 0&&(s.shadow.normalBias=e.shadow.normalBias),e.shadow.radius!==void 0&&(s.shadow.radius=e.shadow.radius),e.shadow.mapSize!==void 0&&s.shadow.mapSize.fromArray(e.shadow.mapSize),e.shadow.camera!==void 0&&(s.shadow.camera=this.parseObject(e.shadow.camera))),e.visible!==void 0&&(s.visible=e.visible),e.frustumCulled!==void 0&&(s.frustumCulled=e.frustumCulled),e.renderOrder!==void 0&&(s.renderOrder=e.renderOrder),e.userData!==void 0&&(s.userData=e.userData),e.layers!==void 0&&(s.layers.mask=e.layers),e.children!==void 0){let d=e.children;for(let f=0;f<d.length;f++)s.add(this.parseObject(d[f],t,r,i,n))}if(e.animations!==void 0){let d=e.animations;for(let f=0;f<d.length;f++){let y=d[f];s.animations.push(n[y])}}if(e.type==="LOD"){e.autoUpdate!==void 0&&(s.autoUpdate=e.autoUpdate);let d=e.levels;for(let f=0;f<d.length;f++){let y=d[f],b=s.getObjectByProperty("uuid",y.object);b!==void 0&&s.addLevel(b,y.distance,y.hysteresis)}}return s}bindSkeletons(e,t){Object.keys(t).length!==0&&e.traverse(function(r){if(r.isSkinnedMesh===!0&&r.skeleton!==void 0){let i=t[r.skeleton];i===void 0?console.warn("THREE.ObjectLoader: No skeleton found with UUID:",r.skeleton):r.bind(i,r.bindMatrix)}})}bindLightTargets(e){e.traverse(function(t){if(t.isDirectionalLight||t.isSpotLight){let r=t.target,i=e.getObjectByProperty("uuid",r);i!==void 0?t.target=i:t.target=new mi}})}},D2={UVMapping:Rr,CubeReflectionMapping:br,CubeRefractionMapping:wi,EquirectangularReflectionMapping:an,EquirectangularRefractionMapping:Rn,CubeUVReflectionMapping:vi},g1={RepeatWrapping:Wr,ClampToEdgeWrapping:ei,MirroredRepeatWrapping:Ri},y1={NearestFilter:oi,NearestMipmapNearestFilter:Pn,NearestMipmapLinearFilter:Qn,LinearFilter:Pi,LinearMipmapNearestFilter:Wn,LinearMipmapLinearFilter:Fi},v1=class extends mn{constructor(e){super(e),this.isImageBitmapLoader=!0,typeof createImageBitmap>"u"&&console.warn("THREE.ImageBitmapLoader: createImageBitmap() not supported."),typeof fetch>"u"&&console.warn("THREE.ImageBitmapLoader: fetch() not supported."),this.options={premultiplyAlpha:"none"}}setOptions(e){return this.options=e,this}load(e,t,r,i){e===void 0&&(e=""),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let n=this,s=Ba.get(e);if(s!==void 0){if(n.manager.itemStart(e),s.then){s.then(l=>{t&&t(l),n.manager.itemEnd(e)}).catch(l=>{i&&i(l)});return}return setTimeout(function(){t&&t(s),n.manager.itemEnd(e)},0),s}let a={};a.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",a.headers=this.requestHeader;let o=fetch(e,a).then(function(l){return l.blob()}).then(function(l){return createImageBitmap(l,Object.assign(n.options,{colorSpaceConversion:"none"}))}).then(function(l){return Ba.add(e,l),t&&t(l),n.manager.itemEnd(e),l}).catch(function(l){i&&i(l),Ba.remove(e),n.manager.itemError(e),n.manager.itemEnd(e)});Ba.add(e,o),n.manager.itemStart(e)}},Jp,_y=class{static getContext(){return Jp===void 0&&(Jp=new(window.AudioContext||window.webkitAudioContext)),Jp}static setContext(e){Jp=e}},U2=class extends mn{constructor(e){super(e)}load(e,t,r,i){let n=this,s=new Ps(this.manager);s.setResponseType("arraybuffer"),s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.load(e,function(o){try{let l=o.slice(0);_y.getContext().decodeAudioData(l,function(c){t(c)}).catch(a)}catch(l){a(l)}},r,i);function a(o){i?i(o):console.error(o),n.manager.itemError(e)}}},x1=new Ir,b1=new Ir,sl=new Ir,F2=class{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new cn,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new cn,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(e){let t=this._cache;if(t.focus!==e.focus||t.fov!==e.fov||t.aspect!==e.aspect*this.aspect||t.near!==e.near||t.far!==e.far||t.zoom!==e.zoom||t.eyeSep!==this.eyeSep){t.focus=e.focus,t.fov=e.fov,t.aspect=e.aspect*this.aspect,t.near=e.near,t.far=e.far,t.zoom=e.zoom,t.eyeSep=this.eyeSep,sl.copy(e.projectionMatrix);let r=t.eyeSep/2,i=r*t.near/t.focus,n=t.near*Math.tan(jo*t.fov*.5)/t.zoom,s,a;b1.elements[12]=-r,x1.elements[12]=r,s=-n*t.aspect+i,a=n*t.aspect+i,sl.elements[0]=2*t.near/(a-s),sl.elements[8]=(a+s)/(a-s),this.cameraL.projectionMatrix.copy(sl),s=-n*t.aspect-i,a=n*t.aspect-i,sl.elements[0]=2*t.near/(a-s),sl.elements[8]=(a+s)/(a-s),this.cameraR.projectionMatrix.copy(sl)}this.cameraL.matrixWorld.copy(e.matrixWorld).multiply(b1),this.cameraR.matrixWorld.copy(e.matrixWorld).multiply(x1)}},w1=class extends cn{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e}},Ey=class{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=_1(),this.oldTime=this.startTime,this.elapsedTime=0,this.running=!0}stop(){this.getElapsedTime(),this.running=!1,this.autoStart=!1}getElapsedTime(){return this.getDelta(),this.elapsedTime}getDelta(){let e=0;if(this.autoStart&&!this.running)return this.start(),0;if(this.running){let t=_1();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}};function _1(){return performance.now()}var al=new je,E1=new pn,z2=new je,ol=new je,B2=class extends mi{constructor(){super(),this.type="AudioListener",this.context=_y.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new Ey}getInput(){return this.gain}removeFilter(){return this.filter!==null&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(e){return this.filter!==null?(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)):this.gain.disconnect(this.context.destination),this.filter=e,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}updateMatrixWorld(e){super.updateMatrixWorld(e);let t=this.context.listener,r=this.up;if(this.timeDelta=this._clock.getDelta(),this.matrixWorld.decompose(al,E1,z2),ol.set(0,0,-1).applyQuaternion(E1),t.positionX){let i=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(al.x,i),t.positionY.linearRampToValueAtTime(al.y,i),t.positionZ.linearRampToValueAtTime(al.z,i),t.forwardX.linearRampToValueAtTime(ol.x,i),t.forwardY.linearRampToValueAtTime(ol.y,i),t.forwardZ.linearRampToValueAtTime(ol.z,i),t.upX.linearRampToValueAtTime(r.x,i),t.upY.linearRampToValueAtTime(r.y,i),t.upZ.linearRampToValueAtTime(r.z,i)}else t.setPosition(al.x,al.y,al.z),t.setOrientation(ol.x,ol.y,ol.z,r.x,r.y,r.z)}},S1=class extends mi{constructor(e){super(),this.type="Audio",this.listener=e,this.context=e.context,this.gain=this.context.createGain(),this.gain.connect(e.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType="empty",this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(e){return this.hasPlaybackControl=!1,this.sourceType="audioNode",this.source=e,this.connect(),this}setMediaElementSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaNode",this.source=this.context.createMediaElementSource(e),this.connect(),this}setMediaStreamSource(e){return this.hasPlaybackControl=!1,this.sourceType="mediaStreamNode",this.source=this.context.createMediaStreamSource(e),this.connect(),this}setBuffer(e){return this.buffer=e,this.sourceType="buffer",this.autoplay&&this.play(),this}play(e=0){if(this.isPlaying===!0){console.warn("THREE.Audio: Audio is already playing.");return}if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}this._startedAt=this.context.currentTime+e;let t=this.context.createBufferSource();return t.buffer=this.buffer,t.loop=this.loop,t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.onended=this.onEnded.bind(this),t.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=t,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this.isPlaying===!0&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,this.loop===!0&&(this._progress=this._progress%(this.duration||this.buffer.duration)),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this}stop(e=0){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this._progress=0,this.source!==null&&(this.source.stop(this.context.currentTime+e),this.source.onended=null),this.isPlaying=!1,this}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let e=1,t=this.filters.length;e<t;e++)this.filters[e-1].connect(this.filters[e]);this.filters[this.filters.length-1].connect(this.getOutput())}else this.source.connect(this.getOutput());return this._connected=!0,this}disconnect(){if(this._connected!==!1){if(this.filters.length>0){this.source.disconnect(this.filters[0]);for(let e=1,t=this.filters.length;e<t;e++)this.filters[e-1].disconnect(this.filters[e]);this.filters[this.filters.length-1].disconnect(this.getOutput())}else this.source.disconnect(this.getOutput());return this._connected=!1,this}}getFilters(){return this.filters}setFilters(e){return e||(e=[]),this._connected===!0?(this.disconnect(),this.filters=e.slice(),this.connect()):this.filters=e.slice(),this}setDetune(e){return this.detune=e,this.isPlaying===!0&&this.source.detune!==void 0&&this.source.detune.setTargetAtTime(this.detune,this.context.currentTime,.01),this}getDetune(){return this.detune}getFilter(){return this.getFilters()[0]}setFilter(e){return this.setFilters(e?[e]:[])}setPlaybackRate(e){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this.playbackRate=e,this.isPlaying===!0&&this.source.playbackRate.setTargetAtTime(this.playbackRate,this.context.currentTime,.01),this}getPlaybackRate(){return this.playbackRate}onEnded(){this.isPlaying=!1,this._progress=0}getLoop(){return this.hasPlaybackControl===!1?(console.warn("THREE.Audio: this Audio has no playback control."),!1):this.loop}setLoop(e){if(this.hasPlaybackControl===!1){console.warn("THREE.Audio: this Audio has no playback control.");return}return this.loop=e,this.isPlaying===!0&&(this.source.loop=this.loop),this}setLoopStart(e){return this.loopStart=e,this}setLoopEnd(e){return this.loopEnd=e,this}getVolume(){return this.gain.gain.value}setVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}copy(e,t){return super.copy(e,t),e.sourceType!=="buffer"?(console.warn("THREE.Audio: Audio source type cannot be copied."),this):(this.autoplay=e.autoplay,this.buffer=e.buffer,this.detune=e.detune,this.loop=e.loop,this.loopStart=e.loopStart,this.loopEnd=e.loopEnd,this.offset=e.offset,this.duration=e.duration,this.playbackRate=e.playbackRate,this.hasPlaybackControl=e.hasPlaybackControl,this.sourceType=e.sourceType,this.filters=e.filters.slice(),this)}clone(e){return new this.constructor(this.listener).copy(this,e)}},ll=new je,M1=new pn,j2=new je,cl=new je,V2=class extends S1{constructor(e){super(e),this.panner=this.context.createPanner(),this.panner.panningModel="HRTF",this.panner.connect(this.gain)}connect(){super.connect(),this.panner.connect(this.gain)}disconnect(){super.disconnect(),this.panner.disconnect(this.gain)}getOutput(){return this.panner}getRefDistance(){return this.panner.refDistance}setRefDistance(e){return this.panner.refDistance=e,this}getRolloffFactor(){return this.panner.rolloffFactor}setRolloffFactor(e){return this.panner.rolloffFactor=e,this}getDistanceModel(){return this.panner.distanceModel}setDistanceModel(e){return this.panner.distanceModel=e,this}getMaxDistance(){return this.panner.maxDistance}setMaxDistance(e){return this.panner.maxDistance=e,this}setDirectionalCone(e,t,r){return this.panner.coneInnerAngle=e,this.panner.coneOuterAngle=t,this.panner.coneOuterGain=r,this}updateMatrixWorld(e){if(super.updateMatrixWorld(e),this.hasPlaybackControl===!0&&this.isPlaying===!1)return;this.matrixWorld.decompose(ll,M1,j2),cl.set(0,0,1).applyQuaternion(M1);let t=this.panner;if(t.positionX){let r=this.context.currentTime+this.listener.timeDelta;t.positionX.linearRampToValueAtTime(ll.x,r),t.positionY.linearRampToValueAtTime(ll.y,r),t.positionZ.linearRampToValueAtTime(ll.z,r),t.orientationX.linearRampToValueAtTime(cl.x,r),t.orientationY.linearRampToValueAtTime(cl.y,r),t.orientationZ.linearRampToValueAtTime(cl.z,r)}else t.setPosition(ll.x,ll.y,ll.z),t.setOrientation(cl.x,cl.y,cl.z)}},H2=class{constructor(e,t=2048){this.analyser=e.context.createAnalyser(),this.analyser.fftSize=t,this.data=new Uint8Array(this.analyser.frequencyBinCount),e.getOutput().connect(this.analyser)}getFrequencyData(){return this.analyser.getByteFrequencyData(this.data),this.data}getAverageFrequency(){let e=0,t=this.getFrequencyData();for(let r=0;r<t.length;r++)e+=t[r];return e/t.length}},A1=class{constructor(e,t,r){this.binding=e,this.valueSize=r;let i,n,s;switch(t){case"quaternion":i=this._slerp,n=this._slerpAdditive,s=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(r*6),this._workIndex=5;break;case"string":case"bool":i=this._select,n=this._select,s=this._setAdditiveIdentityOther,this.buffer=new Array(r*5);break;default:i=this._lerp,n=this._lerpAdditive,s=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(r*5)}this._mixBufferRegion=i,this._mixBufferRegionAdditive=n,this._setIdentity=s,this._origIndex=3,this._addIndex=4,this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,this.useCount=0,this.referenceCount=0}accumulate(e,t){let r=this.buffer,i=this.valueSize,n=e*i+i,s=this.cumulativeWeight;if(s===0){for(let a=0;a!==i;++a)r[n+a]=r[a];s=t}else{s+=t;let a=t/s;this._mixBufferRegion(r,n,0,a,i)}this.cumulativeWeight=s}accumulateAdditive(e){let t=this.buffer,r=this.valueSize,i=r*this._addIndex;this.cumulativeWeightAdditive===0&&this._setIdentity(),this._mixBufferRegionAdditive(t,i,0,e,r),this.cumulativeWeightAdditive+=e}apply(e){let t=this.valueSize,r=this.buffer,i=e*t+t,n=this.cumulativeWeight,s=this.cumulativeWeightAdditive,a=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,n<1){let o=t*this._origIndex;this._mixBufferRegion(r,i,o,1-n,t)}s>0&&this._mixBufferRegionAdditive(r,i,this._addIndex*t,1,t);for(let o=t,l=t+t;o!==l;++o)if(r[o]!==r[o+t]){a.setValue(r,i);break}}saveOriginalState(){let e=this.binding,t=this.buffer,r=this.valueSize,i=r*this._origIndex;e.getValue(t,i);for(let n=r,s=i;n!==s;++n)t[n]=t[i+n%r];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){let e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){let e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let r=e;r<t;r++)this.buffer[r]=0}_setAdditiveIdentityQuaternion(){this._setAdditiveIdentityNumeric(),this.buffer[this._addIndex*this.valueSize+3]=1}_setAdditiveIdentityOther(){let e=this._origIndex*this.valueSize,t=this._addIndex*this.valueSize;for(let r=0;r<this.valueSize;r++)this.buffer[t+r]=this.buffer[e+r]}_select(e,t,r,i,n){if(i>=.5)for(let s=0;s!==n;++s)e[t+s]=e[r+s]}_slerp(e,t,r,i){pn.slerpFlat(e,t,e,t,e,r,i)}_slerpAdditive(e,t,r,i,n){let s=this._workIndex*n;pn.multiplyQuaternionsFlat(e,s,e,t,e,r),pn.slerpFlat(e,t,e,t,e,s,i)}_lerp(e,t,r,i,n){let s=1-i;for(let a=0;a!==n;++a){let o=t+a;e[o]=e[o]*s+e[r+a]*i}}_lerpAdditive(e,t,r,i,n){for(let s=0;s!==n;++s){let a=t+s;e[a]=e[a]+e[r+s]*i}}},Sy="\\[\\]\\.:\\/",G2=new RegExp("["+Sy+"]","g"),My="[^"+Sy+"]",W2="[^"+Sy.replace("\\.","")+"]",X2=/((?:WC+[\/:])*)/.source.replace("WC",My),Y2=/(WCOD+)?/.source.replace("WCOD",W2),q2=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",My),K2=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",My),Z2=new RegExp("^"+X2+Y2+q2+K2+"$"),$2=["material","materials","bones","map"],J2=class{constructor(e,t,r){let i=r||zi.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,i)}getValue(e,t){this.bind();let r=this._targetGroup.nCachedObjects_,i=this._bindings[r];i!==void 0&&i.getValue(e,t)}setValue(e,t){let r=this._bindings;for(let i=this._targetGroup.nCachedObjects_,n=r.length;i!==n;++i)r[i].setValue(e,t)}bind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,r=e.length;t!==r;++t)e[t].bind()}unbind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,r=e.length;t!==r;++t)e[t].unbind()}},zi=class ph{constructor(t,r,i){this.path=r,this.parsedPath=i||ph.parseTrackName(r),this.node=ph.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,r,i){return t&&t.isAnimationObjectGroup?new ph.Composite(t,r,i):new ph(t,r,i)}static sanitizeNodeName(t){return t.replace(/\s/g,"_").replace(G2,"")}static parseTrackName(t){let r=Z2.exec(t);if(r===null)throw new Error("PropertyBinding: Cannot parse trackName: "+t);let i={nodeName:r[2],objectName:r[3],objectIndex:r[4],propertyName:r[5],propertyIndex:r[6]},n=i.nodeName&&i.nodeName.lastIndexOf(".");if(n!==void 0&&n!==-1){let s=i.nodeName.substring(n+1);$2.indexOf(s)!==-1&&(i.nodeName=i.nodeName.substring(0,n),i.objectName=s)}if(i.propertyName===null||i.propertyName.length===0)throw new Error("PropertyBinding: can not parse propertyName from trackName: "+t);return i}static findNode(t,r){if(r===void 0||r===""||r==="."||r===-1||r===t.name||r===t.uuid)return t;if(t.skeleton){let i=t.skeleton.getBoneByName(r);if(i!==void 0)return i}if(t.children){let i=function(s){for(let a=0;a<s.length;a++){let o=s[a];if(o.name===r||o.uuid===r)return o;let l=i(o.children);if(l)return l}return null},n=i(t.children);if(n)return n}return null}_getValue_unavailable(){}_setValue_unavailable(){}_getValue_direct(t,r){t[r]=this.targetObject[this.propertyName]}_getValue_array(t,r){let i=this.resolvedProperty;for(let n=0,s=i.length;n!==s;++n)t[r++]=i[n]}_getValue_arrayElement(t,r){t[r]=this.resolvedProperty[this.propertyIndex]}_getValue_toArray(t,r){this.resolvedProperty.toArray(t,r)}_setValue_direct(t,r){this.targetObject[this.propertyName]=t[r]}_setValue_direct_setNeedsUpdate(t,r){this.targetObject[this.propertyName]=t[r],this.targetObject.needsUpdate=!0}_setValue_direct_setMatrixWorldNeedsUpdate(t,r){this.targetObject[this.propertyName]=t[r],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_array(t,r){let i=this.resolvedProperty;for(let n=0,s=i.length;n!==s;++n)i[n]=t[r++]}_setValue_array_setNeedsUpdate(t,r){let i=this.resolvedProperty;for(let n=0,s=i.length;n!==s;++n)i[n]=t[r++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(t,r){let i=this.resolvedProperty;for(let n=0,s=i.length;n!==s;++n)i[n]=t[r++];this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_arrayElement(t,r){this.resolvedProperty[this.propertyIndex]=t[r]}_setValue_arrayElement_setNeedsUpdate(t,r){this.resolvedProperty[this.propertyIndex]=t[r],this.targetObject.needsUpdate=!0}_setValue_arrayElement_setMatrixWorldNeedsUpdate(t,r){this.resolvedProperty[this.propertyIndex]=t[r],this.targetObject.matrixWorldNeedsUpdate=!0}_setValue_fromArray(t,r){this.resolvedProperty.fromArray(t,r)}_setValue_fromArray_setNeedsUpdate(t,r){this.resolvedProperty.fromArray(t,r),this.targetObject.needsUpdate=!0}_setValue_fromArray_setMatrixWorldNeedsUpdate(t,r){this.resolvedProperty.fromArray(t,r),this.targetObject.matrixWorldNeedsUpdate=!0}_getValue_unbound(t,r){this.bind(),this.getValue(t,r)}_setValue_unbound(t,r){this.bind(),this.setValue(t,r)}bind(){let t=this.node,r=this.parsedPath,i=r.objectName,n=r.propertyName,s=r.propertyIndex;if(t||(t=ph.findNode(this.rootNode,r.nodeName),this.node=t),this.getValue=this._getValue_unavailable,this.setValue=this._setValue_unavailable,!t){console.warn("THREE.PropertyBinding: No target node found for track: "+this.path+".");return}if(i){let c=r.objectIndex;switch(i){case"materials":if(!t.material){console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!t.material.materials){console.error("THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.",this);return}t=t.material.materials;break;case"bones":if(!t.skeleton){console.error("THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.",this);return}t=t.skeleton.bones;for(let u=0;u<t.length;u++)if(t[u].name===c){c=u;break}break;case"map":if("map"in t){t=t.map;break}if(!t.material){console.error("THREE.PropertyBinding: Can not bind to material as node does not have a material.",this);return}if(!t.material.map){console.error("THREE.PropertyBinding: Can not bind to material.map as node.material does not have a map.",this);return}t=t.material.map;break;default:if(t[i]===void 0){console.error("THREE.PropertyBinding: Can not bind to objectName of node undefined.",this);return}t=t[i]}if(c!==void 0){if(t[c]===void 0){console.error("THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.",this,t);return}t=t[c]}}let a=t[n];if(a===void 0){let c=r.nodeName;console.error("THREE.PropertyBinding: Trying to update property for track: "+c+"."+n+" but it wasn't found.",t);return}let o=this.Versioning.None;this.targetObject=t,t.needsUpdate!==void 0?o=this.Versioning.NeedsUpdate:t.matrixWorldNeedsUpdate!==void 0&&(o=this.Versioning.MatrixWorldNeedsUpdate);let l=this.BindingType.Direct;if(s!==void 0){if(n==="morphTargetInfluences"){if(!t.geometry){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.",this);return}if(!t.geometry.morphAttributes){console.error("THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.",this);return}t.morphTargetDictionary[s]!==void 0&&(s=t.morphTargetDictionary[s])}l=this.BindingType.ArrayElement,this.resolvedProperty=a,this.propertyIndex=s}else a.fromArray!==void 0&&a.toArray!==void 0?(l=this.BindingType.HasFromToArray,this.resolvedProperty=a):Array.isArray(a)?(l=this.BindingType.EntireArray,this.resolvedProperty=a):this.propertyName=n;this.getValue=this.GetterByBindingType[l],this.setValue=this.SetterByBindingTypeAndVersioning[l][o]}unbind(){this.node=null,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}};zi.Composite=J2,zi.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},zi.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},zi.prototype.GetterByBindingType=[zi.prototype._getValue_direct,zi.prototype._getValue_array,zi.prototype._getValue_arrayElement,zi.prototype._getValue_toArray],zi.prototype.SetterByBindingTypeAndVersioning=[[zi.prototype._setValue_direct,zi.prototype._setValue_direct_setNeedsUpdate,zi.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[zi.prototype._setValue_array,zi.prototype._setValue_array_setNeedsUpdate,zi.prototype._setValue_array_setMatrixWorldNeedsUpdate],[zi.prototype._setValue_arrayElement,zi.prototype._setValue_arrayElement_setNeedsUpdate,zi.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[zi.prototype._setValue_fromArray,zi.prototype._setValue_fromArray_setNeedsUpdate,zi.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];var Q2=class{constructor(){this.isAnimationObjectGroup=!0,this.uuid=fs(),this._objects=Array.prototype.slice.call(arguments),this.nCachedObjects_=0;let e={};this._indicesByUUID=e;for(let r=0,i=arguments.length;r!==i;++r)e[arguments[r].uuid]=r;this._paths=[],this._parsedPaths=[],this._bindings=[],this._bindingsIndicesByPath={};let t=this;this.stats={objects:{get total(){return t._objects.length},get inUse(){return this.total-t.nCachedObjects_}},get bindingsPerObject(){return t._bindings.length}}}add(){let e=this._objects,t=this._indicesByUUID,r=this._paths,i=this._parsedPaths,n=this._bindings,s=n.length,a,o=e.length,l=this.nCachedObjects_;for(let c=0,u=arguments.length;c!==u;++c){let d=arguments[c],f=d.uuid,y=t[f];if(y===void 0){y=o++,t[f]=y,e.push(d);for(let b=0,x=s;b!==x;++b)n[b].push(new zi(d,r[b],i[b]))}else if(y<l){a=e[y];let b=--l,x=e[b];t[x.uuid]=y,e[y]=x,t[f]=b,e[b]=d;for(let g=0,v=s;g!==v;++g){let _=n[g],E=_[b],M=_[y];_[y]=E,M===void 0&&(M=new zi(d,r[g],i[g])),_[b]=M}}else e[y]!==a&&console.error("THREE.AnimationObjectGroup: Different objects with the same UUID detected. Clean the caches or recreate your infrastructure when reloading scenes.")}this.nCachedObjects_=l}remove(){let e=this._objects,t=this._indicesByUUID,r=this._bindings,i=r.length,n=this.nCachedObjects_;for(let s=0,a=arguments.length;s!==a;++s){let o=arguments[s],l=o.uuid,c=t[l];if(c!==void 0&&c>=n){let u=n++,d=e[u];t[d.uuid]=c,e[c]=d,t[l]=u,e[u]=o;for(let f=0,y=i;f!==y;++f){let b=r[f],x=b[u],g=b[c];b[c]=x,b[u]=g}}}this.nCachedObjects_=n}uncache(){let e=this._objects,t=this._indicesByUUID,r=this._bindings,i=r.length,n=this.nCachedObjects_,s=e.length;for(let a=0,o=arguments.length;a!==o;++a){let l=arguments[a],c=l.uuid,u=t[c];if(u!==void 0)if(delete t[c],u<n){let d=--n,f=e[d],y=--s,b=e[y];t[f.uuid]=u,e[u]=f,t[b.uuid]=d,e[d]=b,e.pop();for(let x=0,g=i;x!==g;++x){let v=r[x],_=v[d],E=v[y];v[u]=_,v[d]=E,v.pop()}}else{let d=--s,f=e[d];d>0&&(t[f.uuid]=u),e[u]=f,e.pop();for(let y=0,b=i;y!==b;++y){let x=r[y];x[u]=x[d],x.pop()}}}this.nCachedObjects_=n}subscribe_(e,t){let r=this._bindingsIndicesByPath,i=r[e],n=this._bindings;if(i!==void 0)return n[i];let s=this._paths,a=this._parsedPaths,o=this._objects,l=o.length,c=this.nCachedObjects_,u=new Array(l);i=n.length,r[e]=i,s.push(e),a.push(t),n.push(u);for(let d=c,f=o.length;d!==f;++d){let y=o[d];u[d]=new zi(y,e,t)}return u}unsubscribe_(e){let t=this._bindingsIndicesByPath,r=t[e];if(r!==void 0){let i=this._paths,n=this._parsedPaths,s=this._bindings,a=s.length-1,o=s[a],l=e[a];t[l]=r,s[r]=o,s.pop(),n[r]=n[a],n.pop(),i[r]=i[a],i.pop()}}},T1=class{constructor(e,t,r=null,i=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=r,this.blendMode=i;let n=t.tracks,s=n.length,a=new Array(s),o={endingStart:Fo,endingEnd:Fo};for(let l=0;l!==s;++l){let c=n[l].createInterpolant(null);a[l]=c,c.settings=o}this._interpolantSettings=o,this._interpolants=a,this._propertyBindings=new Array(s),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=mx,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,r){if(e.fadeOut(t),this.fadeIn(t),r){let i=this._clip.duration,n=e._clip.duration,s=n/i,a=i/n;e.warp(1,s,t),this.warp(a,1,t)}return this}crossFadeTo(e,t,r){return e.crossFadeFrom(this,t,r)}stopFading(){let e=this._weightInterpolant;return e!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,r){let i=this._mixer,n=i.time,s=this.timeScale,a=this._timeScaleInterpolant;a===null&&(a=i._lendControlInterpolant(),this._timeScaleInterpolant=a);let o=a.parameterPositions,l=a.sampleValues;return o[0]=n,o[1]=n+r,l[0]=e/s,l[1]=t/s,this}stopWarping(){let e=this._timeScaleInterpolant;return e!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,r,i){if(!this.enabled){this._updateWeight(e);return}let n=this._startTime;if(n!==null){let o=(e-n)*r;o<0||r===0?t=0:(this._startTime=null,t=r*o)}t*=this._updateTimeScale(e);let s=this._updateTime(t),a=this._updateWeight(e);if(a>0){let o=this._interpolants,l=this._propertyBindings;switch(this.blendMode){case sg:for(let c=0,u=o.length;c!==u;++c)o[c].evaluate(s),l[c].accumulateAdditive(a);break;case Kd:default:for(let c=0,u=o.length;c!==u;++c)o[c].evaluate(s),l[c].accumulate(i,a)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;let r=this._weightInterpolant;if(r!==null){let i=r.evaluate(e)[0];t*=i,e>r.parameterPositions[1]&&(this.stopFading(),i===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;let r=this._timeScaleInterpolant;if(r!==null){let i=r.evaluate(e)[0];t*=i,e>r.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){let t=this._clip.duration,r=this.loop,i=this.time+e,n=this._loopCount,s=r===gx;if(e===0)return n===-1?i:s&&(n&1)===1?t-i:i;if(r===fx){n===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));e:{if(i>=t)i=t;else if(i<0)i=0;else{this.time=i;break e}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e<0?-1:1})}}else{if(n===-1&&(e>=0?(n=0,this._setEndings(!0,this.repetitions===0,s)):this._setEndings(this.repetitions===0,!0,s)),i>=t||i<0){let a=Math.floor(i/t);i-=t*a,n+=Math.abs(a);let o=this.repetitions-n;if(o<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,i=e>0?t:0,this.time=i,this._mixer.dispatchEvent({type:"finished",action:this,direction:e>0?1:-1});else{if(o===1){let l=e<0;this._setEndings(l,!l,s)}else this._setEndings(!1,!1,s);this._loopCount=n,this.time=i,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:a})}}else this.time=i;if(s&&(n&1)===1)return t-i}return i}_setEndings(e,t,r){let i=this._interpolantSettings;r?(i.endingStart=zo,i.endingEnd=zo):(e?i.endingStart=this.zeroSlopeAtStart?zo:Fo:i.endingStart=Ph,t?i.endingEnd=this.zeroSlopeAtEnd?zo:Fo:i.endingEnd=Ph)}_scheduleFading(e,t,r){let i=this._mixer,n=i.time,s=this._weightInterpolant;s===null&&(s=i._lendControlInterpolant(),this._weightInterpolant=s);let a=s.parameterPositions,o=s.sampleValues;return a[0]=n,o[0]=t,a[1]=n+e,o[1]=r,this}},eC=new Float32Array(1),tC=class extends ha{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1}_bindAction(e,t){let r=e._localRoot||this._root,i=e._clip.tracks,n=i.length,s=e._propertyBindings,a=e._interpolants,o=r.uuid,l=this._bindingsByRootAndName,c=l[o];c===void 0&&(c={},l[o]=c);for(let u=0;u!==n;++u){let d=i[u],f=d.name,y=c[f];if(y!==void 0)++y.referenceCount,s[u]=y;else{if(y=s[u],y!==void 0){y._cacheIndex===null&&(++y.referenceCount,this._addInactiveBinding(y,o,f));continue}let b=t&&t._propertyBindings[u].binding.parsedPath;y=new A1(zi.create(r,f,b),d.ValueTypeName,d.getValueSize()),++y.referenceCount,this._addInactiveBinding(y,o,f),s[u]=y}a[u].resultBuffer=y.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){let r=(e._localRoot||this._root).uuid,i=e._clip.uuid,n=this._actionsByClip[i];this._bindAction(e,n&&n.knownActions[0]),this._addInactiveAction(e,i,r)}let t=e._propertyBindings;for(let r=0,i=t.length;r!==i;++r){let n=t[r];n.useCount++===0&&(this._lendBinding(n),n.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){let t=e._propertyBindings;for(let r=0,i=t.length;r!==i;++r){let n=t[r];--n.useCount===0&&(n.restoreOriginalState(),this._takeBackBinding(n))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;let e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){let t=e._cacheIndex;return t!==null&&t<this._nActiveActions}_addInactiveAction(e,t,r){let i=this._actions,n=this._actionsByClip,s=n[t];if(s===void 0)s={knownActions:[e],actionByRoot:{}},e._byClipCacheIndex=0,n[t]=s;else{let a=s.knownActions;e._byClipCacheIndex=a.length,a.push(e)}e._cacheIndex=i.length,i.push(e),s.actionByRoot[r]=e}_removeInactiveAction(e){let t=this._actions,r=t[t.length-1],i=e._cacheIndex;r._cacheIndex=i,t[i]=r,t.pop(),e._cacheIndex=null;let n=e._clip.uuid,s=this._actionsByClip,a=s[n],o=a.knownActions,l=o[o.length-1],c=e._byClipCacheIndex;l._byClipCacheIndex=c,o[c]=l,o.pop(),e._byClipCacheIndex=null;let u=a.actionByRoot,d=(e._localRoot||this._root).uuid;delete u[d],o.length===0&&delete s[n],this._removeInactiveBindingsForAction(e)}_removeInactiveBindingsForAction(e){let t=e._propertyBindings;for(let r=0,i=t.length;r!==i;++r){let n=t[r];--n.referenceCount===0&&this._removeInactiveBinding(n)}}_lendAction(e){let t=this._actions,r=e._cacheIndex,i=this._nActiveActions++,n=t[i];e._cacheIndex=i,t[i]=e,n._cacheIndex=r,t[r]=n}_takeBackAction(e){let t=this._actions,r=e._cacheIndex,i=--this._nActiveActions,n=t[i];e._cacheIndex=i,t[i]=e,n._cacheIndex=r,t[r]=n}_addInactiveBinding(e,t,r){let i=this._bindingsByRootAndName,n=this._bindings,s=i[t];s===void 0&&(s={},i[t]=s),s[r]=e,e._cacheIndex=n.length,n.push(e)}_removeInactiveBinding(e){let t=this._bindings,r=e.binding,i=r.rootNode.uuid,n=r.path,s=this._bindingsByRootAndName,a=s[i],o=t[t.length-1],l=e._cacheIndex;o._cacheIndex=l,t[l]=o,t.pop(),delete a[n],Object.keys(a).length===0&&delete s[i]}_lendBinding(e){let t=this._bindings,r=e._cacheIndex,i=this._nActiveBindings++,n=t[i];e._cacheIndex=i,t[i]=e,n._cacheIndex=r,t[r]=n}_takeBackBinding(e){let t=this._bindings,r=e._cacheIndex,i=--this._nActiveBindings,n=t[i];e._cacheIndex=i,t[i]=e,n._cacheIndex=r,t[r]=n}_lendControlInterpolant(){let e=this._controlInterpolants,t=this._nActiveControlInterpolants++,r=e[t];return r===void 0&&(r=new py(new Float32Array(2),new Float32Array(2),1,eC),r.__cacheIndex=t,e[t]=r),r}_takeBackControlInterpolant(e){let t=this._controlInterpolants,r=e.__cacheIndex,i=--this._nActiveControlInterpolants,n=t[i];e.__cacheIndex=i,t[i]=e,n.__cacheIndex=r,t[r]=n}clipAction(e,t,r){let i=t||this._root,n=i.uuid,s=typeof e=="string"?bc.findByName(i,e):e,a=s!==null?s.uuid:e,o=this._actionsByClip[a],l=null;if(r===void 0&&(s!==null?r=s.blendMode:r=Kd),o!==void 0){let u=o.actionByRoot[n];if(u!==void 0&&u.blendMode===r)return u;l=o.knownActions[0],s===null&&(s=l._clip)}if(s===null)return null;let c=new T1(this,s,t,r);return this._bindAction(c,l),this._addInactiveAction(c,a,n),c}existingAction(e,t){let r=t||this._root,i=r.uuid,n=typeof e=="string"?bc.findByName(r,e):e,s=n?n.uuid:e,a=this._actionsByClip[s];return a!==void 0&&a.actionByRoot[i]||null}stopAllAction(){let e=this._actions,t=this._nActiveActions;for(let r=t-1;r>=0;--r)e[r].stop();return this}update(e){e*=this.timeScale;let t=this._actions,r=this._nActiveActions,i=this.time+=e,n=Math.sign(e),s=this._accuIndex^=1;for(let l=0;l!==r;++l)t[l]._update(i,e,n,s);let a=this._bindings,o=this._nActiveBindings;for(let l=0;l!==o;++l)a[l].apply(s);return this}setTime(e){this.time=0;for(let t=0;t<this._actions.length;t++)this._actions[t].time=0;return this.update(e)}getRoot(){return this._root}uncacheClip(e){let t=this._actions,r=e.uuid,i=this._actionsByClip,n=i[r];if(n!==void 0){let s=n.knownActions;for(let a=0,o=s.length;a!==o;++a){let l=s[a];this._deactivateAction(l);let c=l._cacheIndex,u=t[t.length-1];l._cacheIndex=null,l._byClipCacheIndex=null,u._cacheIndex=c,t[c]=u,t.pop(),this._removeInactiveBindingsForAction(l)}delete i[r]}}uncacheRoot(e){let t=e.uuid,r=this._actionsByClip;for(let s in r){let a=r[s].actionByRoot,o=a[t];o!==void 0&&(this._deactivateAction(o),this._removeInactiveAction(o))}let i=this._bindingsByRootAndName,n=i[t];if(n!==void 0)for(let s in n){let a=n[s];a.restoreOriginalState(),this._removeInactiveBinding(a)}}uncacheAction(e,t){let r=this.existingAction(e,t);r!==null&&(this._deactivateAction(r),this._removeInactiveAction(r))}},rC=class wM{constructor(t){this.value=t}clone(){return new wM(this.value.clone===void 0?this.value:this.value.clone())}},iC=0,nC=class extends ha{constructor(){super(),this.isUniformsGroup=!0,Object.defineProperty(this,"id",{value:iC++}),this.name="",this.usage=Nh,this.uniforms=[]}add(e){return this.uniforms.push(e),this}remove(e){let t=this.uniforms.indexOf(e);return t!==-1&&this.uniforms.splice(t,1),this}setName(e){return this.name=e,this}setUsage(e){return this.usage=e,this}dispose(){return this.dispatchEvent({type:"dispose"}),this}copy(e){this.name=e.name,this.usage=e.usage;let t=e.uniforms;this.uniforms.length=0;for(let r=0,i=t.length;r<i;r++){let n=Array.isArray(t[r])?t[r]:[t[r]];for(let s=0;s<n.length;s++)this.uniforms.push(n[s].clone())}return this}clone(){return new this.constructor().copy(this)}},sC=class extends Vh{constructor(e,t,r=1){super(e,t),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=r}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}clone(e){let t=super.clone(e);return t.meshPerAttribute=this.meshPerAttribute,t}toJSON(e){let t=super.toJSON(e);return t.isInstancedInterleavedBuffer=!0,t.meshPerAttribute=this.meshPerAttribute,t}},aC=class{constructor(e,t,r,i,n){this.isGLBufferAttribute=!0,this.name="",this.buffer=e,this.type=t,this.itemSize=r,this.elementSize=i,this.count=n,this.version=0}set needsUpdate(e){e===!0&&this.version++}setBuffer(e){return this.buffer=e,this}setType(e,t){return this.type=e,this.elementSize=t,this}setItemSize(e){return this.itemSize=e,this}setCount(e){return this.count=e,this}},C1=new Ir,ou=class{constructor(e,t,r=0,i=1/0){this.ray=new Wo(e,t),this.near=r,this.far=i,this.camera=null,this.layers=new sp,this.params={Mesh:{},Line:{threshold:1},LOD:{},Points:{threshold:1},Sprite:{}}}set(e,t){this.ray.set(e,t)}setFromCamera(e,t){t.isPerspectiveCamera?(this.ray.origin.setFromMatrixPosition(t.matrixWorld),this.ray.direction.set(e.x,e.y,.5).unproject(t).sub(this.ray.origin).normalize(),this.camera=t):t.isOrthographicCamera?(this.ray.origin.set(e.x,e.y,(t.near+t.far)/(t.near-t.far)).unproject(t),this.ray.direction.set(0,0,-1).transformDirection(t.matrixWorld),this.camera=t):console.error("THREE.Raycaster: Unsupported camera type: "+t.type)}setFromXRController(e){return C1.identity().extractRotation(e.matrixWorld),this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(C1),this}intersectObject(e,t=!0,r=[]){return Ay(e,this,r,t),r.sort(R1),r}intersectObjects(e,t=!0,r=[]){for(let i=0,n=e.length;i<n;i++)Ay(e[i],this,r,t);return r.sort(R1),r}};function R1(e,t){return e.distance-t.distance}function Ay(e,t,r,i){let n=!0;if(e.layers.test(t.layers)&&e.raycast(t,r)===!1&&(n=!1),n===!0&&i===!0){let s=e.children;for(let a=0,o=s.length;a<o;a++)Ay(s[a],t,r,!0)}}var Ty=class{constructor(e=1,t=0,r=0){return this.radius=e,this.phi=t,this.theta=r,this}set(e,t,r){return this.radius=e,this.phi=t,this.theta=r,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){return this.phi=Jr(this.phi,1e-6,Math.PI-1e-6),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,r){return this.radius=Math.sqrt(e*e+t*t+r*r),this.radius===0?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,r),this.phi=Math.acos(Jr(t/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}},oC=class{constructor(e=1,t=0,r=0){return this.radius=e,this.theta=t,this.y=r,this}set(e,t,r){return this.radius=e,this.theta=t,this.y=r,this}copy(e){return this.radius=e.radius,this.theta=e.theta,this.y=e.y,this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,r){return this.radius=Math.sqrt(e*e+r*r),this.theta=Math.atan2(e,r),this.y=t,this}clone(){return new this.constructor().copy(this)}},lC=class _M{constructor(t,r,i,n){_M.prototype.isMatrix2=!0,this.elements=[1,0,0,1],t!==void 0&&this.set(t,r,i,n)}identity(){return this.set(1,0,0,1),this}fromArray(t,r=0){for(let i=0;i<4;i++)this.elements[i]=t[i+r];return this}set(t,r,i,n){let s=this.elements;return s[0]=t,s[2]=r,s[1]=i,s[3]=n,this}},P1=new Ft,cC=class{constructor(e=new Ft(1/0,1/0),t=new Ft(-1/0,-1/0)){this.isBox2=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromPoints(e){this.makeEmpty();for(let t=0,r=e.length;t<r;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){let r=P1.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(r),this.max.copy(e).add(r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=1/0,this.max.x=this.max.y=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y}getCenter(e){return this.isEmpty()?e.set(0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,P1).distanceTo(e)}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}},I1=new je,Qp=new je,hC=class{constructor(e=new je,t=new je){this.start=e,this.end=t}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){I1.subVectors(e,this.start),Qp.subVectors(this.end,this.start);let r=Qp.dot(Qp),i=Qp.dot(I1)/r;return t&&(i=Jr(i,0,1)),i}closestPointToPoint(e,t,r){let i=this.closestPointToPointParameter(e,t);return this.delta(r).multiplyScalar(i).add(this.start)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return new this.constructor().copy(this)}},N1=new je,uC=class extends mi{constructor(e,t){super(),this.light=e,this.matrixAutoUpdate=!1,this.color=t,this.type="SpotLightHelper";let r=new Hr,i=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let s=0,a=1,o=32;s<o;s++,a++){let l=s/o*Math.PI*2,c=a/o*Math.PI*2;i.push(Math.cos(l),Math.sin(l),1,Math.cos(c),Math.sin(c),1)}r.setAttribute("position",new hr(i,3));let n=new tn({fog:!1,toneMapped:!1});this.cone=new Fn(r,n),this.add(this.cone),this.update()}dispose(){this.cone.geometry.dispose(),this.cone.material.dispose()}update(){this.light.updateWorldMatrix(!0,!1),this.light.target.updateWorldMatrix(!0,!1),this.parent?(this.parent.updateWorldMatrix(!0),this.matrix.copy(this.parent.matrixWorld).invert().multiply(this.light.matrixWorld)):this.matrix.copy(this.light.matrixWorld),this.matrixWorld.copy(this.light.matrixWorld);let e=this.light.distance?this.light.distance:1e3,t=e*Math.tan(this.light.angle);this.cone.scale.set(t,t,e),N1.setFromMatrixPosition(this.light.target.matrixWorld),this.cone.lookAt(N1),this.color!==void 0?this.cone.material.color.set(this.color):this.cone.material.color.copy(this.light.color)}},mo=new je,ef=new Ir,Cy=new Ir,dC=class extends Fn{constructor(e){let t=L1(e),r=new Hr,i=[],n=[],s=new or(0,0,1),a=new or(0,1,0);for(let l=0;l<t.length;l++){let c=t[l];c.parent&&c.parent.isBone&&(i.push(0,0,0),i.push(0,0,0),n.push(s.r,s.g,s.b),n.push(a.r,a.g,a.b))}r.setAttribute("position",new hr(i,3)),r.setAttribute("color",new hr(n,3));let o=new tn({vertexColors:!0,depthTest:!1,depthWrite:!1,toneMapped:!1,transparent:!0});super(r,o),this.isSkeletonHelper=!0,this.type="SkeletonHelper",this.root=e,this.bones=t,this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1}updateMatrixWorld(e){let t=this.bones,r=this.geometry,i=r.getAttribute("position");Cy.copy(this.root.matrixWorld).invert();for(let n=0,s=0;n<t.length;n++){let a=t[n];a.parent&&a.parent.isBone&&(ef.multiplyMatrices(Cy,a.matrixWorld),mo.setFromMatrixPosition(ef),i.setXYZ(s,mo.x,mo.y,mo.z),ef.multiplyMatrices(Cy,a.parent.matrixWorld),mo.setFromMatrixPosition(ef),i.setXYZ(s+1,mo.x,mo.y,mo.z),s+=2)}r.getAttribute("position").needsUpdate=!0,super.updateMatrixWorld(e)}dispose(){this.geometry.dispose(),this.material.dispose()}};function L1(e){let t=[];e.isBone===!0&&t.push(e);for(let r=0;r<e.children.length;r++)t.push.apply(t,L1(e.children[r]));return t}var pC=class extends qr{constructor(e,t,r){let i=new po(t,4,2),n=new en({wireframe:!0,fog:!1,toneMapped:!1});super(i,n),this.light=e,this.color=r,this.type="PointLightHelper",this.matrix=this.light.matrixWorld,this.matrixAutoUpdate=!1,this.update()}dispose(){this.geometry.dispose(),this.material.dispose()}update(){this.light.updateWorldMatrix(!0,!1),this.color!==void 0?this.material.color.set(this.color):this.material.color.copy(this.light.color)}},fC=new je,k1=new or,O1=new or,mC=class extends mi{constructor(e,t,r){super(),this.light=e,this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.color=r,this.type="HemisphereLightHelper";let i=new sy(t);i.rotateY(Math.PI*.5),this.material=new en({wireframe:!0,fog:!1,toneMapped:!1}),this.color===void 0&&(this.material.vertexColors=!0);let n=i.getAttribute("position"),s=new Float32Array(n.count*3);i.setAttribute("color",new ui(s,3)),this.add(new qr(i,this.material)),this.update()}dispose(){this.children[0].geometry.dispose(),this.children[0].material.dispose()}update(){let e=this.children[0];if(this.color!==void 0)this.material.color.set(this.color);else{let t=e.geometry.getAttribute("color");k1.copy(this.light.color),O1.copy(this.light.groundColor);for(let r=0,i=t.count;r<i;r++){let n=r<i/2?k1:O1;t.setXYZ(r,n.r,n.g,n.b)}t.needsUpdate=!0}this.light.updateWorldMatrix(!0,!1),e.lookAt(fC.setFromMatrixPosition(this.light.matrixWorld).negate())}},gC=class extends Fn{constructor(e=10,t=10,r=4473924,i=8947848){r=new or(r),i=new or(i);let n=t/2,s=e/t,a=e/2,o=[],l=[];for(let d=0,f=0,y=-a;d<=t;d++,y+=s){o.push(-a,0,y,a,0,y),o.push(y,0,-a,y,0,a);let b=d===n?r:i;b.toArray(l,f),f+=3,b.toArray(l,f),f+=3,b.toArray(l,f),f+=3,b.toArray(l,f),f+=3}let c=new Hr;c.setAttribute("position",new hr(o,3)),c.setAttribute("color",new hr(l,3));let u=new tn({vertexColors:!0,toneMapped:!1});super(c,u),this.type="GridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}},yC=class extends Fn{constructor(e=10,t=16,r=8,i=64,n=4473924,s=8947848){n=new or(n),s=new or(s);let a=[],o=[];if(t>1)for(let u=0;u<t;u++){let d=u/t*(Math.PI*2),f=Math.sin(d)*e,y=Math.cos(d)*e;a.push(0,0,0),a.push(f,0,y);let b=u&1?n:s;o.push(b.r,b.g,b.b),o.push(b.r,b.g,b.b)}for(let u=0;u<r;u++){let d=u&1?n:s,f=e-e/r*u;for(let y=0;y<i;y++){let b=y/i*(Math.PI*2),x=Math.sin(b)*f,g=Math.cos(b)*f;a.push(x,0,g),o.push(d.r,d.g,d.b),b=(y+1)/i*(Math.PI*2),x=Math.sin(b)*f,g=Math.cos(b)*f,a.push(x,0,g),o.push(d.r,d.g,d.b)}}let l=new Hr;l.setAttribute("position",new hr(a,3)),l.setAttribute("color",new hr(o,3));let c=new tn({vertexColors:!0,toneMapped:!1});super(l,c),this.type="PolarGridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}},D1=new je,tf=new je,U1=new je,vC=class extends mi{constructor(e,t,r){super(),this.light=e,this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.color=r,this.type="DirectionalLightHelper",t===void 0&&(t=1);let i=new Hr;i.setAttribute("position",new hr([-t,t,0,t,t,0,t,-t,0,-t,-t,0,-t,t,0],3));let n=new tn({fog:!1,toneMapped:!1});this.lightPlane=new ua(i,n),this.add(this.lightPlane),i=new Hr,i.setAttribute("position",new hr([0,0,0,0,0,1],3)),this.targetLine=new ua(i,n),this.add(this.targetLine),this.update()}dispose(){this.lightPlane.geometry.dispose(),this.lightPlane.material.dispose(),this.targetLine.geometry.dispose(),this.targetLine.material.dispose()}update(){this.light.updateWorldMatrix(!0,!1),this.light.target.updateWorldMatrix(!0,!1),D1.setFromMatrixPosition(this.light.matrixWorld),tf.setFromMatrixPosition(this.light.target.matrixWorld),U1.subVectors(tf,D1),this.lightPlane.lookAt(tf),this.color!==void 0?(this.lightPlane.material.color.set(this.color),this.targetLine.material.color.set(this.color)):(this.lightPlane.material.color.copy(this.light.color),this.targetLine.material.color.copy(this.light.color)),this.targetLine.lookAt(tf),this.targetLine.scale.z=U1.length()}},rf=new je,rn=new gp,xC=class extends Fn{constructor(e){let t=new Hr,r=new tn({color:16777215,vertexColors:!0,toneMapped:!1}),i=[],n=[],s={};a("n1","n2"),a("n2","n4"),a("n4","n3"),a("n3","n1"),a("f1","f2"),a("f2","f4"),a("f4","f3"),a("f3","f1"),a("n1","f1"),a("n2","f2"),a("n3","f3"),a("n4","f4"),a("p","n1"),a("p","n2"),a("p","n3"),a("p","n4"),a("u1","u2"),a("u2","u3"),a("u3","u1"),a("c","t"),a("p","c"),a("cn1","cn2"),a("cn3","cn4"),a("cf1","cf2"),a("cf3","cf4");function a(y,b){o(y),o(b)}function o(y){i.push(0,0,0),n.push(0,0,0),s[y]===void 0&&(s[y]=[]),s[y].push(i.length/3-1)}t.setAttribute("position",new hr(i,3)),t.setAttribute("color",new hr(n,3)),super(t,r),this.type="CameraHelper",this.camera=e,this.camera.updateProjectionMatrix&&this.camera.updateProjectionMatrix(),this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.pointMap=s,this.update();let l=new or(16755200),c=new or(16711680),u=new or(43775),d=new or(16777215),f=new or(3355443);this.setColors(l,c,u,d,f)}setColors(e,t,r,i,n){let s=this.geometry.getAttribute("color");s.setXYZ(0,e.r,e.g,e.b),s.setXYZ(1,e.r,e.g,e.b),s.setXYZ(2,e.r,e.g,e.b),s.setXYZ(3,e.r,e.g,e.b),s.setXYZ(4,e.r,e.g,e.b),s.setXYZ(5,e.r,e.g,e.b),s.setXYZ(6,e.r,e.g,e.b),s.setXYZ(7,e.r,e.g,e.b),s.setXYZ(8,e.r,e.g,e.b),s.setXYZ(9,e.r,e.g,e.b),s.setXYZ(10,e.r,e.g,e.b),s.setXYZ(11,e.r,e.g,e.b),s.setXYZ(12,e.r,e.g,e.b),s.setXYZ(13,e.r,e.g,e.b),s.setXYZ(14,e.r,e.g,e.b),s.setXYZ(15,e.r,e.g,e.b),s.setXYZ(16,e.r,e.g,e.b),s.setXYZ(17,e.r,e.g,e.b),s.setXYZ(18,e.r,e.g,e.b),s.setXYZ(19,e.r,e.g,e.b),s.setXYZ(20,e.r,e.g,e.b),s.setXYZ(21,e.r,e.g,e.b),s.setXYZ(22,e.r,e.g,e.b),s.setXYZ(23,e.r,e.g,e.b),s.setXYZ(24,t.r,t.g,t.b),s.setXYZ(25,t.r,t.g,t.b),s.setXYZ(26,t.r,t.g,t.b),s.setXYZ(27,t.r,t.g,t.b),s.setXYZ(28,t.r,t.g,t.b),s.setXYZ(29,t.r,t.g,t.b),s.setXYZ(30,t.r,t.g,t.b),s.setXYZ(31,t.r,t.g,t.b),s.setXYZ(32,r.r,r.g,r.b),s.setXYZ(33,r.r,r.g,r.b),s.setXYZ(34,r.r,r.g,r.b),s.setXYZ(35,r.r,r.g,r.b),s.setXYZ(36,r.r,r.g,r.b),s.setXYZ(37,r.r,r.g,r.b),s.setXYZ(38,i.r,i.g,i.b),s.setXYZ(39,i.r,i.g,i.b),s.setXYZ(40,n.r,n.g,n.b),s.setXYZ(41,n.r,n.g,n.b),s.setXYZ(42,n.r,n.g,n.b),s.setXYZ(43,n.r,n.g,n.b),s.setXYZ(44,n.r,n.g,n.b),s.setXYZ(45,n.r,n.g,n.b),s.setXYZ(46,n.r,n.g,n.b),s.setXYZ(47,n.r,n.g,n.b),s.setXYZ(48,n.r,n.g,n.b),s.setXYZ(49,n.r,n.g,n.b),s.needsUpdate=!0}update(){let e=this.geometry,t=this.pointMap,r=1,i=1;rn.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse),hn("c",t,e,rn,0,0,-1),hn("t",t,e,rn,0,0,1),hn("n1",t,e,rn,-r,-i,-1),hn("n2",t,e,rn,r,-i,-1),hn("n3",t,e,rn,-r,i,-1),hn("n4",t,e,rn,r,i,-1),hn("f1",t,e,rn,-r,-i,1),hn("f2",t,e,rn,r,-i,1),hn("f3",t,e,rn,-r,i,1),hn("f4",t,e,rn,r,i,1),hn("u1",t,e,rn,r*.7,i*1.1,-1),hn("u2",t,e,rn,-r*.7,i*1.1,-1),hn("u3",t,e,rn,0,i*2,-1),hn("cf1",t,e,rn,-r,0,1),hn("cf2",t,e,rn,r,0,1),hn("cf3",t,e,rn,0,-i,1),hn("cf4",t,e,rn,0,i,1),hn("cn1",t,e,rn,-r,0,-1),hn("cn2",t,e,rn,r,0,-1),hn("cn3",t,e,rn,0,-i,-1),hn("cn4",t,e,rn,0,i,-1),e.getAttribute("position").needsUpdate=!0}dispose(){this.geometry.dispose(),this.material.dispose()}};function hn(e,t,r,i,n,s,a){rf.set(n,s,a).unproject(i);let o=t[e];if(o!==void 0){let l=r.getAttribute("position");for(let c=0,u=o.length;c<u;c++)l.setXYZ(o[c],rf.x,rf.y,rf.z)}}var nf=new Xi,bC=class extends Fn{constructor(e,t=16776960){let r=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),i=new Float32Array(24),n=new Hr;n.setIndex(new ui(r,1)),n.setAttribute("position",new ui(i,3)),super(n,new tn({color:t,toneMapped:!1})),this.object=e,this.type="BoxHelper",this.matrixAutoUpdate=!1,this.update()}update(e){if(e!==void 0&&console.warn("THREE.BoxHelper: .update() has no longer arguments."),this.object!==void 0&&nf.setFromObject(this.object),nf.isEmpty())return;let t=nf.min,r=nf.max,i=this.geometry.attributes.position,n=i.array;n[0]=r.x,n[1]=r.y,n[2]=r.z,n[3]=t.x,n[4]=r.y,n[5]=r.z,n[6]=t.x,n[7]=t.y,n[8]=r.z,n[9]=r.x,n[10]=t.y,n[11]=r.z,n[12]=r.x,n[13]=r.y,n[14]=t.z,n[15]=t.x,n[16]=r.y,n[17]=t.z,n[18]=t.x,n[19]=t.y,n[20]=t.z,n[21]=r.x,n[22]=t.y,n[23]=t.z,i.needsUpdate=!0,this.geometry.computeBoundingSphere()}setFromObject(e){return this.object=e,this.update(),this}copy(e,t){return super.copy(e,t),this.object=e.object,this}dispose(){this.geometry.dispose(),this.material.dispose()}},wC=class extends Fn{constructor(e,t=16776960){let r=new Uint16Array([0,1,1,2,2,3,3,0,4,5,5,6,6,7,7,4,0,4,1,5,2,6,3,7]),i=[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,-1,-1,1,-1,-1,-1,-1,1,-1,-1],n=new Hr;n.setIndex(new ui(r,1)),n.setAttribute("position",new hr(i,3)),super(n,new tn({color:t,toneMapped:!1})),this.box=e,this.type="Box3Helper",this.geometry.computeBoundingSphere()}updateMatrixWorld(e){let t=this.box;t.isEmpty()||(t.getCenter(this.position),t.getSize(this.scale),this.scale.multiplyScalar(.5),super.updateMatrixWorld(e))}dispose(){this.geometry.dispose(),this.material.dispose()}},_C=class extends ua{constructor(e,t=1,r=16776960){let i=r,n=[1,-1,0,-1,1,0,-1,-1,0,1,1,0,-1,1,0,-1,-1,0,1,-1,0,1,1,0],s=new Hr;s.setAttribute("position",new hr(n,3)),s.computeBoundingSphere(),super(s,new tn({color:i,toneMapped:!1})),this.type="PlaneHelper",this.plane=e,this.size=t;let a=[1,1,0,-1,1,0,-1,-1,0,1,1,0,-1,-1,0,1,-1,0],o=new Hr;o.setAttribute("position",new hr(a,3)),o.computeBoundingSphere(),this.add(new qr(o,new en({color:i,opacity:.2,transparent:!0,depthWrite:!1,toneMapped:!1})))}updateMatrixWorld(e){this.position.set(0,0,0),this.scale.set(.5*this.size,.5*this.size,1),this.lookAt(this.plane.normal),this.translateZ(-this.plane.constant),super.updateMatrixWorld(e)}dispose(){this.geometry.dispose(),this.material.dispose(),this.children[0].geometry.dispose(),this.children[0].material.dispose()}},F1=new je,sf,Ry,EC=class extends mi{constructor(e=new je(0,0,1),t=new je(0,0,0),r=1,i=16776960,n=r*.2,s=n*.2){super(),this.type="ArrowHelper",sf===void 0&&(sf=new Hr,sf.setAttribute("position",new hr([0,0,0,0,1,0],3)),Ry=new eu(0,.5,1,5,1),Ry.translate(0,-.5,0)),this.position.copy(t),this.line=new ua(sf,new tn({color:i,toneMapped:!1})),this.line.matrixAutoUpdate=!1,this.add(this.line),this.cone=new qr(Ry,new en({color:i,toneMapped:!1})),this.cone.matrixAutoUpdate=!1,this.add(this.cone),this.setDirection(e),this.setLength(r,n,s)}setDirection(e){if(e.y>.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{F1.set(e.z,0,-e.x).normalize();let t=Math.acos(e.y);this.quaternion.setFromAxisAngle(F1,t)}}setLength(e,t=e*.2,r=t*.2){this.line.scale.set(1,Math.max(1e-4,e-t),1),this.line.updateMatrix(),this.cone.scale.set(r,t,r),this.cone.position.y=e,this.cone.updateMatrix()}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}},SC=class extends Fn{constructor(e=1){let t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],r=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],i=new Hr;i.setAttribute("position",new hr(t,3)),i.setAttribute("color",new hr(r,3));let n=new tn({vertexColors:!0,toneMapped:!1});super(i,n),this.type="AxesHelper"}setColors(e,t,r){let i=new or,n=this.geometry.attributes.color.array;return i.set(e),i.toArray(n,0),i.toArray(n,3),i.set(t),i.toArray(n,6),i.toArray(n,9),i.set(r),i.toArray(n,12),i.toArray(n,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}},MC=class{constructor(){this.type="ShapePath",this.color=new or,this.subPaths=[],this.currentPath=null}moveTo(e,t){return this.currentPath=new mc,this.subPaths.push(this.currentPath),this.currentPath.moveTo(e,t),this}lineTo(e,t){return this.currentPath.lineTo(e,t),this}quadraticCurveTo(e,t,r,i){return this.currentPath.quadraticCurveTo(e,t,r,i),this}bezierCurveTo(e,t,r,i,n,s){return this.currentPath.bezierCurveTo(e,t,r,i,n,s),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(e){function t(g){let v=[];for(let _=0,E=g.length;_<E;_++){let M=g[_],P=new Fa;P.curves=M.curves,v.push(P)}return v}function r(g,v){let _=v.length,E=!1;for(let M=_-1,P=0;P<_;M=P++){let k=v[M],z=v[P],D=z.x-k.x,I=z.y-k.y;if(Math.abs(I)>Number.EPSILON){if(I<0&&(k=v[P],D=-D,z=v[M],I=-I),g.y<k.y||g.y>z.y)continue;if(g.y===k.y){if(g.x===k.x)return!0}else{let L=I*(g.x-k.x)-D*(g.y-k.y);if(L===0)return!0;if(L<0)continue;E=!E}}else{if(g.y!==k.y)continue;if(z.x<=g.x&&g.x<=k.x||k.x<=g.x&&g.x<=z.x)return!0}}return E}let i=za.isClockWise,n=this.subPaths;if(n.length===0)return[];let s,a,o,l=[];if(n.length===1)return a=n[0],o=new Fa,o.curves=a.curves,l.push(o),l;let c=!i(n[0].getPoints());c=e?!c:c;let u=[],d=[],f=[],y=0,b;d[y]=void 0,f[y]=[];for(let g=0,v=n.length;g<v;g++)a=n[g],b=a.getPoints(),s=i(b),s=e?!s:s,s?(!c&&d[y]&&y++,d[y]={s:new Fa,p:b},d[y].s.curves=a.curves,c&&y++,f[y]=[]):f[y].push({h:a,p:b[0]});if(!d[0])return t(n);if(d.length>1){let g=!1,v=0;for(let _=0,E=d.length;_<E;_++)u[_]=[];for(let _=0,E=d.length;_<E;_++){let M=f[_];for(let P=0;P<M.length;P++){let k=M[P],z=!0;for(let D=0;D<d.length;D++)r(k.p,d[D].p)&&(_!==D&&v++,z?(z=!1,u[D].push(k)):g=!0);z&&u[_].push(k)}}v>0&&g===!1&&(f=u)}let x;for(let g=0,v=d.length;g<v;g++){o=d[g].s,l.push(o),x=f[g];for(let _=0,E=x.length;_<E;_++)o.holes.push(x[_].h)}return l}},z1=class extends ha{constructor(e,t=null){super(),this.object=e,this.domElement=t,this.enabled=!0,this.state=-1,this.keys={},this.mouseButtons={LEFT:null,MIDDLE:null,RIGHT:null},this.touches={ONE:null,TWO:null}}connect(){}disconnect(){}dispose(){}update(){}};function AC(e,t){let r=e.image&&e.image.width?e.image.width/e.image.height:1;return r>t?(e.repeat.x=1,e.repeat.y=r/t,e.offset.x=0,e.offset.y=(1-e.repeat.y)/2):(e.repeat.x=t/r,e.repeat.y=1,e.offset.x=(1-e.repeat.x)/2,e.offset.y=0),e}function TC(e,t){let r=e.image&&e.image.width?e.image.width/e.image.height:1;return r>t?(e.repeat.x=t/r,e.repeat.y=1,e.offset.x=(1-e.repeat.x)/2,e.offset.y=0):(e.repeat.x=1,e.repeat.y=r/t,e.offset.x=0,e.offset.y=(1-e.repeat.y)/2),e}function CC(e){return e.repeat.x=1,e.repeat.y=1,e.offset.x=0,e.offset.y=0,e}function Py(e,t,r,i){let n=RC(i);switch(r){case Qm:return e*t;case tg:return e*t;case rg:return e*t*2;case xd:return e*t/n.components*n.byteLength;case Sh:return e*t/n.components*n.byteLength;case ig:return e*t*2/n.components*n.byteLength;case bd:return e*t*2/n.components*n.byteLength;case eg:return e*t*3/n.components*n.byteLength;case Ln:return e*t*4/n.components*n.byteLength;case wd:return e*t*4/n.components*n.byteLength;case Mh:case Ah:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Th:case Ch:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Ed:case Md:return Math.max(e,16)*Math.max(t,8)/4;case _d:case Sd:return Math.max(e,8)*Math.max(t,8)/2;case Ad:case Td:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Cd:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Rd:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Pd:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case Id:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case Nd:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case Ld:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case kd:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case Od:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case Dd:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case Ud:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case Fd:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case zd:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case Bd:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case jd:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case Vd:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case Rh:case Hd:case Gd:return Math.ceil(e/4)*Math.ceil(t/4)*16;case ng:case Wd:return Math.ceil(e/4)*Math.ceil(t/4)*8;case Xd:case Yd:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw new Error(`Unable to determine texture byte length for ${r} format.`)}function RC(e){switch(e){case Ji:case Sa:return{byteLength:1,components:1};case Ma:case Eh:case Ts:return{byteLength:2,components:1};case yd:case vd:return{byteLength:2,components:4};case Aa:case Do:case es:return{byteLength:4,components:1};case Jm:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${e}.`)}var PC={contain:AC,cover:TC,fill:CC,getByteLength:Py},IC=class extends In{constructor(e=1,t=1,r=1,i={}){console.warn('THREE.WebGLMultipleRenderTargets has been deprecated and will be removed in r172. Use THREE.WebGLRenderTarget and set the "count" parameter to enable MRT.'),super(e,t,{...i,count:r}),this.isWebGLMultipleRenderTargets=!0}get texture(){return this.textures}};typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:"171"}})),typeof window<"u"&&(window.__THREE__?console.warn("WARNING: Multiple instances of Three.js being imported."):window.__THREE__="171");function B1(){let e=null,t=!1,r=null,i=null;function n(s,a){r(s,a),i=e.requestAnimationFrame(n)}return{start:function(){t!==!0&&r!==null&&(i=e.requestAnimationFrame(n),t=!0)},stop:function(){e.cancelAnimationFrame(i),t=!1},setAnimationLoop:function(s){r=s},setContext:function(s){e=s}}}function NC(e){let t=new WeakMap;function r(o,l){let c=o.array,u=o.usage,d=c.byteLength,f=e.createBuffer();e.bindBuffer(l,f),e.bufferData(l,c,u),o.onUploadCallback();let y;if(c instanceof Float32Array)y=e.FLOAT;else if(c instanceof Uint16Array)o.isFloat16BufferAttribute?y=e.HALF_FLOAT:y=e.UNSIGNED_SHORT;else if(c instanceof Int16Array)y=e.SHORT;else if(c instanceof Uint32Array)y=e.UNSIGNED_INT;else if(c instanceof Int32Array)y=e.INT;else if(c instanceof Int8Array)y=e.BYTE;else if(c instanceof Uint8Array)y=e.UNSIGNED_BYTE;else if(c instanceof Uint8ClampedArray)y=e.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+c);return{buffer:f,type:y,bytesPerElement:c.BYTES_PER_ELEMENT,version:o.version,size:d}}function i(o,l,c){let u=l.array,d=l.updateRanges;if(e.bindBuffer(c,o),d.length===0)e.bufferSubData(c,0,u);else{d.sort((y,b)=>y.start-b.start);let f=0;for(let y=1;y<d.length;y++){let b=d[f],x=d[y];x.start<=b.start+b.count+1?b.count=Math.max(b.count,x.start+x.count-b.start):(++f,d[f]=x)}d.length=f+1;for(let y=0,b=d.length;y<b;y++){let x=d[y];e.bufferSubData(c,x.start*u.BYTES_PER_ELEMENT,u,x.start,x.count)}l.clearUpdateRanges()}l.onUploadCallback()}function n(o){return o.isInterleavedBufferAttribute&&(o=o.data),t.get(o)}function s(o){o.isInterleavedBufferAttribute&&(o=o.data);let l=t.get(o);l&&(e.deleteBuffer(l.buffer),t.delete(o))}function a(o,l){if(o.isInterleavedBufferAttribute&&(o=o.data),o.isGLBufferAttribute){let u=t.get(o);(!u||u.version<o.version)&&t.set(o,{buffer:o.buffer,type:o.type,bytesPerElement:o.elementSize,version:o.version});return}let c=t.get(o);if(c===void 0)t.set(o,r(o,l));else if(c.version<o.version){if(c.size!==o.array.byteLength)throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported.");i(c.buffer,o,l),c.version=o.version}}return{get:n,remove:s,update:a}}var LC=`#ifdef USE_ALPHAHASH
	if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
#endif`,kC=`#ifdef USE_ALPHAHASH
	const float ALPHA_HASH_SCALE = 0.05;
	float hash2D( vec2 value ) {
		return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );
	}
	float hash3D( vec3 value ) {
		return hash2D( vec2( hash2D( value.xy ), value.z ) );
	}
	float getAlphaHashThreshold( vec3 position ) {
		float maxDeriv = max(
			length( dFdx( position.xyz ) ),
			length( dFdy( position.xyz ) )
		);
		float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );
		vec2 pixScales = vec2(
			exp2( floor( log2( pixScale ) ) ),
			exp2( ceil( log2( pixScale ) ) )
		);
		vec2 alpha = vec2(
			hash3D( floor( pixScales.x * position.xyz ) ),
			hash3D( floor( pixScales.y * position.xyz ) )
		);
		float lerpFactor = fract( log2( pixScale ) );
		float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;
		float a = min( lerpFactor, 1.0 - lerpFactor );
		vec3 cases = vec3(
			x * x / ( 2.0 * a * ( 1.0 - a ) ),
			( x - 0.5 * a ) / ( 1.0 - a ),
			1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )
		);
		float threshold = ( x < ( 1.0 - a ) )
			? ( ( x < a ) ? cases.x : cases.y )
			: cases.z;
		return clamp( threshold , 1.0e-6, 1.0 );
	}
#endif`,OC=`#ifdef USE_ALPHAMAP
	diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
#endif`,DC=`#ifdef USE_ALPHAMAP
	uniform sampler2D alphaMap;
#endif`,UC=`#ifdef USE_ALPHATEST
	#ifdef ALPHA_TO_COVERAGE
	diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );
	if ( diffuseColor.a == 0.0 ) discard;
	#else
	if ( diffuseColor.a < alphaTest ) discard;
	#endif
#endif`,FC=`#ifdef USE_ALPHATEST
	uniform float alphaTest;
#endif`,zC=`#ifdef USE_AOMAP
	float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;
	reflectedLight.indirectDiffuse *= ambientOcclusion;
	#if defined( USE_CLEARCOAT ) 
		clearcoatSpecularIndirect *= ambientOcclusion;
	#endif
	#if defined( USE_SHEEN ) 
		sheenSpecularIndirect *= ambientOcclusion;
	#endif
	#if defined( USE_ENVMAP ) && defined( STANDARD )
		float dotNV = saturate( dot( geometryNormal, geometryViewDir ) );
		reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );
	#endif
#endif`,BC=`#ifdef USE_AOMAP
	uniform sampler2D aoMap;
	uniform float aoMapIntensity;
#endif`,jC=`#ifdef USE_BATCHING
	#if ! defined( GL_ANGLE_multi_draw )
	#define gl_DrawID _gl_DrawID
	uniform int _gl_DrawID;
	#endif
	uniform highp sampler2D batchingTexture;
	uniform highp usampler2D batchingIdTexture;
	mat4 getBatchingMatrix( const in float i ) {
		int size = textureSize( batchingTexture, 0 ).x;
		int j = int( i ) * 4;
		int x = j % size;
		int y = j / size;
		vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );
		vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );
		vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );
		vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );
		return mat4( v1, v2, v3, v4 );
	}
	float getIndirectIndex( const in int i ) {
		int size = textureSize( batchingIdTexture, 0 ).x;
		int x = i % size;
		int y = i / size;
		return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );
	}
#endif
#ifdef USE_BATCHING_COLOR
	uniform sampler2D batchingColorTexture;
	vec3 getBatchingColor( const in float i ) {
		int size = textureSize( batchingColorTexture, 0 ).x;
		int j = int( i );
		int x = j % size;
		int y = j / size;
		return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;
	}
#endif`,VC=`#ifdef USE_BATCHING
	mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );
#endif`,HC=`vec3 transformed = vec3( position );
#ifdef USE_ALPHAHASH
	vPosition = vec3( position );
#endif`,GC=`vec3 objectNormal = vec3( normal );
#ifdef USE_TANGENT
	vec3 objectTangent = vec3( tangent.xyz );
#endif`,WC=`float G_BlinnPhong_Implicit( ) {
	return 0.25;
}
float D_BlinnPhong( const in float shininess, const in float dotNH ) {
	return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );
}
vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {
	vec3 halfDir = normalize( lightDir + viewDir );
	float dotNH = saturate( dot( normal, halfDir ) );
	float dotVH = saturate( dot( viewDir, halfDir ) );
	vec3 F = F_Schlick( specularColor, 1.0, dotVH );
	float G = G_BlinnPhong_Implicit( );
	float D = D_BlinnPhong( shininess, dotNH );
	return F * ( G * D );
} // validated`,XC=`#ifdef USE_IRIDESCENCE
	const mat3 XYZ_TO_REC709 = mat3(
		 3.2404542, -0.9692660,  0.0556434,
		-1.5371385,  1.8760108, -0.2040259,
		-0.4985314,  0.0415560,  1.0572252
	);
	vec3 Fresnel0ToIor( vec3 fresnel0 ) {
		vec3 sqrtF0 = sqrt( fresnel0 );
		return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );
	}
	vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {
		return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );
	}
	float IorToFresnel0( float transmittedIor, float incidentIor ) {
		return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));
	}
	vec3 evalSensitivity( float OPD, vec3 shift ) {
		float phase = 2.0 * PI * OPD * 1.0e-9;
		vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
		vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
		vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
		vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );
		xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );
		xyz /= 1.0685e-7;
		vec3 rgb = XYZ_TO_REC709 * xyz;
		return rgb;
	}
	vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {
		vec3 I;
		float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
		float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );
		float cosTheta2Sq = 1.0 - sinTheta2Sq;
		if ( cosTheta2Sq < 0.0 ) {
			return vec3( 1.0 );
		}
		float cosTheta2 = sqrt( cosTheta2Sq );
		float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
		float R12 = F_Schlick( R0, 1.0, cosTheta1 );
		float T121 = 1.0 - R12;
		float phi12 = 0.0;
		if ( iridescenceIOR < outsideIOR ) phi12 = PI;
		float phi21 = PI - phi12;
		vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );		vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );
		vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );
		vec3 phi23 = vec3( 0.0 );
		if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;
		if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;
		if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;
		float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;
		vec3 phi = vec3( phi21 ) + phi23;
		vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );
		vec3 r123 = sqrt( R123 );
		vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );
		vec3 C0 = R12 + Rs;
		I = C0;
		vec3 Cm = Rs - T121;
		for ( int m = 1; m <= 2; ++ m ) {
			Cm *= r123;
			vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );
			I += Cm * Sm;
		}
		return max( I, vec3( 0.0 ) );
	}
#endif`,YC=`#ifdef USE_BUMPMAP
	uniform sampler2D bumpMap;
	uniform float bumpScale;
	vec2 dHdxy_fwd() {
		vec2 dSTdx = dFdx( vBumpMapUv );
		vec2 dSTdy = dFdy( vBumpMapUv );
		float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;
		float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;
		float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;
		return vec2( dBx, dBy );
	}
	vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {
		vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );
		vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );
		vec3 vN = surf_norm;
		vec3 R1 = cross( vSigmaY, vN );
		vec3 R2 = cross( vN, vSigmaX );
		float fDet = dot( vSigmaX, R1 ) * faceDirection;
		vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );
		return normalize( abs( fDet ) * surf_norm - vGrad );
	}
#endif`,qC=`#if NUM_CLIPPING_PLANES > 0
	vec4 plane;
	#ifdef ALPHA_TO_COVERAGE
		float distanceToPlane, distanceGradient;
		float clipOpacity = 1.0;
		#pragma unroll_loop_start
		for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
			plane = clippingPlanes[ i ];
			distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
			distanceGradient = fwidth( distanceToPlane ) / 2.0;
			clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
			if ( clipOpacity == 0.0 ) discard;
		}
		#pragma unroll_loop_end
		#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
			float unionClipOpacity = 1.0;
			#pragma unroll_loop_start
			for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
				plane = clippingPlanes[ i ];
				distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;
				distanceGradient = fwidth( distanceToPlane ) / 2.0;
				unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );
			}
			#pragma unroll_loop_end
			clipOpacity *= 1.0 - unionClipOpacity;
		#endif
		diffuseColor.a *= clipOpacity;
		if ( diffuseColor.a == 0.0 ) discard;
	#else
		#pragma unroll_loop_start
		for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {
			plane = clippingPlanes[ i ];
			if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;
		}
		#pragma unroll_loop_end
		#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES
			bool clipped = true;
			#pragma unroll_loop_start
			for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {
				plane = clippingPlanes[ i ];
				clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;
			}
			#pragma unroll_loop_end
			if ( clipped ) discard;
		#endif
	#endif
#endif`,KC=`#if NUM_CLIPPING_PLANES > 0
	varying vec3 vClipPosition;
	uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
#endif`,ZC=`#if NUM_CLIPPING_PLANES > 0
	varying vec3 vClipPosition;
#endif`,$C=`#if NUM_CLIPPING_PLANES > 0
	vClipPosition = - mvPosition.xyz;
#endif`,JC=`#if defined( USE_COLOR_ALPHA )
	diffuseColor *= vColor;
#elif defined( USE_COLOR )
	diffuseColor.rgb *= vColor;
#endif`,QC=`#if defined( USE_COLOR_ALPHA )
	varying vec4 vColor;
#elif defined( USE_COLOR )
	varying vec3 vColor;
#endif`,eR=`#if defined( USE_COLOR_ALPHA )
	varying vec4 vColor;
#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
	varying vec3 vColor;
#endif`,tR=`#if defined( USE_COLOR_ALPHA )
	vColor = vec4( 1.0 );
#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
	vColor = vec3( 1.0 );
#endif
#ifdef USE_COLOR
	vColor *= color;
#endif
#ifdef USE_INSTANCING_COLOR
	vColor.xyz *= instanceColor.xyz;
#endif
#ifdef USE_BATCHING_COLOR
	vec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );
	vColor.xyz *= batchingColor.xyz;
#endif`,rR=`#define PI 3.141592653589793
#define PI2 6.283185307179586
#define PI_HALF 1.5707963267948966
#define RECIPROCAL_PI 0.3183098861837907
#define RECIPROCAL_PI2 0.15915494309189535
#define EPSILON 1e-6
#ifndef saturate
#define saturate( a ) clamp( a, 0.0, 1.0 )
#endif
#define whiteComplement( a ) ( 1.0 - saturate( a ) )
float pow2( const in float x ) { return x*x; }
vec3 pow2( const in vec3 x ) { return x*x; }
float pow3( const in float x ) { return x*x*x; }
float pow4( const in float x ) { float x2 = x*x; return x2*x2; }
float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }
float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }
highp float rand( const in vec2 uv ) {
	const highp float a = 12.9898, b = 78.233, c = 43758.5453;
	highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );
	return fract( sin( sn ) * c );
}
#ifdef HIGH_PRECISION
	float precisionSafeLength( vec3 v ) { return length( v ); }
#else
	float precisionSafeLength( vec3 v ) {
		float maxComponent = max3( abs( v ) );
		return length( v / maxComponent ) * maxComponent;
	}
#endif
struct IncidentLight {
	vec3 color;
	vec3 direction;
	bool visible;
};
struct ReflectedLight {
	vec3 directDiffuse;
	vec3 directSpecular;
	vec3 indirectDiffuse;
	vec3 indirectSpecular;
};
#ifdef USE_ALPHAHASH
	varying vec3 vPosition;
#endif
vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
	return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
}
vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {
	return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );
}
mat3 transposeMat3( const in mat3 m ) {
	mat3 tmp;
	tmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );
	tmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );
	tmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );
	return tmp;
}
bool isPerspectiveMatrix( mat4 m ) {
	return m[ 2 ][ 3 ] == - 1.0;
}
vec2 equirectUv( in vec3 dir ) {
	float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;
	float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;
	return vec2( u, v );
}
vec3 BRDF_Lambert( const in vec3 diffuseColor ) {
	return RECIPROCAL_PI * diffuseColor;
}
vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {
	float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
	return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
}
float F_Schlick( const in float f0, const in float f90, const in float dotVH ) {
	float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );
	return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );
} // validated`,iR=`#ifdef ENVMAP_TYPE_CUBE_UV
	#define cubeUV_minMipLevel 4.0
	#define cubeUV_minTileSize 16.0
	float getFace( vec3 direction ) {
		vec3 absDirection = abs( direction );
		float face = - 1.0;
		if ( absDirection.x > absDirection.z ) {
			if ( absDirection.x > absDirection.y )
				face = direction.x > 0.0 ? 0.0 : 3.0;
			else
				face = direction.y > 0.0 ? 1.0 : 4.0;
		} else {
			if ( absDirection.z > absDirection.y )
				face = direction.z > 0.0 ? 2.0 : 5.0;
			else
				face = direction.y > 0.0 ? 1.0 : 4.0;
		}
		return face;
	}
	vec2 getUV( vec3 direction, float face ) {
		vec2 uv;
		if ( face == 0.0 ) {
			uv = vec2( direction.z, direction.y ) / abs( direction.x );
		} else if ( face == 1.0 ) {
			uv = vec2( - direction.x, - direction.z ) / abs( direction.y );
		} else if ( face == 2.0 ) {
			uv = vec2( - direction.x, direction.y ) / abs( direction.z );
		} else if ( face == 3.0 ) {
			uv = vec2( - direction.z, direction.y ) / abs( direction.x );
		} else if ( face == 4.0 ) {
			uv = vec2( - direction.x, direction.z ) / abs( direction.y );
		} else {
			uv = vec2( direction.x, direction.y ) / abs( direction.z );
		}
		return 0.5 * ( uv + 1.0 );
	}
	vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {
		float face = getFace( direction );
		float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );
		mipInt = max( mipInt, cubeUV_minMipLevel );
		float faceSize = exp2( mipInt );
		highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;
		if ( face > 2.0 ) {
			uv.y += faceSize;
			face -= 3.0;
		}
		uv.x += face * faceSize;
		uv.x += filterInt * 3.0 * cubeUV_minTileSize;
		uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );
		uv.x *= CUBEUV_TEXEL_WIDTH;
		uv.y *= CUBEUV_TEXEL_HEIGHT;
		#ifdef texture2DGradEXT
			return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;
		#else
			return texture2D( envMap, uv ).rgb;
		#endif
	}
	#define cubeUV_r0 1.0
	#define cubeUV_m0 - 2.0
	#define cubeUV_r1 0.8
	#define cubeUV_m1 - 1.0
	#define cubeUV_r4 0.4
	#define cubeUV_m4 2.0
	#define cubeUV_r5 0.305
	#define cubeUV_m5 3.0
	#define cubeUV_r6 0.21
	#define cubeUV_m6 4.0
	float roughnessToMip( float roughness ) {
		float mip = 0.0;
		if ( roughness >= cubeUV_r1 ) {
			mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;
		} else if ( roughness >= cubeUV_r4 ) {
			mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;
		} else if ( roughness >= cubeUV_r5 ) {
			mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;
		} else if ( roughness >= cubeUV_r6 ) {
			mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;
		} else {
			mip = - 2.0 * log2( 1.16 * roughness );		}
		return mip;
	}
	vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {
		float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
		float mipF = fract( mip );
		float mipInt = floor( mip );
		vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );
		if ( mipF == 0.0 ) {
			return vec4( color0, 1.0 );
		} else {
			vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );
			return vec4( mix( color0, color1, mipF ), 1.0 );
		}
	}
#endif`,nR=`vec3 transformedNormal = objectNormal;
#ifdef USE_TANGENT
	vec3 transformedTangent = objectTangent;
#endif
#ifdef USE_BATCHING
	mat3 bm = mat3( batchingMatrix );
	transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );
	transformedNormal = bm * transformedNormal;
	#ifdef USE_TANGENT
		transformedTangent = bm * transformedTangent;
	#endif
#endif
#ifdef USE_INSTANCING
	mat3 im = mat3( instanceMatrix );
	transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );
	transformedNormal = im * transformedNormal;
	#ifdef USE_TANGENT
		transformedTangent = im * transformedTangent;
	#endif
#endif
transformedNormal = normalMatrix * transformedNormal;
#ifdef FLIP_SIDED
	transformedNormal = - transformedNormal;
#endif
#ifdef USE_TANGENT
	transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;
	#ifdef FLIP_SIDED
		transformedTangent = - transformedTangent;
	#endif
#endif`,sR=`#ifdef USE_DISPLACEMENTMAP
	uniform sampler2D displacementMap;
	uniform float displacementScale;
	uniform float displacementBias;
#endif`,aR=`#ifdef USE_DISPLACEMENTMAP
	transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
#endif`,oR=`#ifdef USE_EMISSIVEMAP
	vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
	#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE
		emissiveColor = sRGBTransferEOTF( emissiveColor );
	#endif
	totalEmissiveRadiance *= emissiveColor.rgb;
#endif`,lR=`#ifdef USE_EMISSIVEMAP
	uniform sampler2D emissiveMap;
#endif`,cR="gl_FragColor = linearToOutputTexel( gl_FragColor );",hR=`vec4 LinearTransferOETF( in vec4 value ) {
	return value;
}
vec4 sRGBTransferEOTF( in vec4 value ) {
	return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );
}
vec4 sRGBTransferOETF( in vec4 value ) {
	return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );
}`,uR=`#ifdef USE_ENVMAP
	#ifdef ENV_WORLDPOS
		vec3 cameraToFrag;
		if ( isOrthographic ) {
			cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
		} else {
			cameraToFrag = normalize( vWorldPosition - cameraPosition );
		}
		vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
		#ifdef ENVMAP_MODE_REFLECTION
			vec3 reflectVec = reflect( cameraToFrag, worldNormal );
		#else
			vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );
		#endif
	#else
		vec3 reflectVec = vReflect;
	#endif
	#ifdef ENVMAP_TYPE_CUBE
		vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );
	#else
		vec4 envColor = vec4( 0.0 );
	#endif
	#ifdef ENVMAP_BLENDING_MULTIPLY
		outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );
	#elif defined( ENVMAP_BLENDING_MIX )
		outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );
	#elif defined( ENVMAP_BLENDING_ADD )
		outgoingLight += envColor.xyz * specularStrength * reflectivity;
	#endif
#endif`,dR=`#ifdef USE_ENVMAP
	uniform float envMapIntensity;
	uniform float flipEnvMap;
	uniform mat3 envMapRotation;
	#ifdef ENVMAP_TYPE_CUBE
		uniform samplerCube envMap;
	#else
		uniform sampler2D envMap;
	#endif
	
#endif`,pR=`#ifdef USE_ENVMAP
	uniform float reflectivity;
	#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
		#define ENV_WORLDPOS
	#endif
	#ifdef ENV_WORLDPOS
		varying vec3 vWorldPosition;
		uniform float refractionRatio;
	#else
		varying vec3 vReflect;
	#endif
#endif`,fR=`#ifdef USE_ENVMAP
	#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT )
		#define ENV_WORLDPOS
	#endif
	#ifdef ENV_WORLDPOS
		
		varying vec3 vWorldPosition;
	#else
		varying vec3 vReflect;
		uniform float refractionRatio;
	#endif
#endif`,mR=`#ifdef USE_ENVMAP
	#ifdef ENV_WORLDPOS
		vWorldPosition = worldPosition.xyz;
	#else
		vec3 cameraToVertex;
		if ( isOrthographic ) {
			cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );
		} else {
			cameraToVertex = normalize( worldPosition.xyz - cameraPosition );
		}
		vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
		#ifdef ENVMAP_MODE_REFLECTION
			vReflect = reflect( cameraToVertex, worldNormal );
		#else
			vReflect = refract( cameraToVertex, worldNormal, refractionRatio );
		#endif
	#endif
#endif`,gR=`#ifdef USE_FOG
	vFogDepth = - mvPosition.z;
#endif`,yR=`#ifdef USE_FOG
	varying float vFogDepth;
#endif`,vR=`#ifdef USE_FOG
	#ifdef FOG_EXP2
		float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth );
	#else
		float fogFactor = smoothstep( fogNear, fogFar, vFogDepth );
	#endif
	gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );
#endif`,xR=`#ifdef USE_FOG
	uniform vec3 fogColor;
	varying float vFogDepth;
	#ifdef FOG_EXP2
		uniform float fogDensity;
	#else
		uniform float fogNear;
		uniform float fogFar;
	#endif
#endif`,bR=`#ifdef USE_GRADIENTMAP
	uniform sampler2D gradientMap;
#endif
vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {
	float dotNL = dot( normal, lightDirection );
	vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );
	#ifdef USE_GRADIENTMAP
		return vec3( texture2D( gradientMap, coord ).r );
	#else
		vec2 fw = fwidth( coord ) * 0.5;
		return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) );
	#endif
}`,wR=`#ifdef USE_LIGHTMAP
	uniform sampler2D lightMap;
	uniform float lightMapIntensity;
#endif`,_R=`LambertMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularStrength = specularStrength;`,ER=`varying vec3 vViewPosition;
struct LambertMaterial {
	vec3 diffuseColor;
	float specularStrength;
};
void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {
	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
	vec3 irradiance = dotNL * directLight.color;
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct				RE_Direct_Lambert
#define RE_IndirectDiffuse		RE_IndirectDiffuse_Lambert`,SR=`uniform bool receiveShadow;
uniform vec3 ambientLightColor;
#if defined( USE_LIGHT_PROBES )
	uniform vec3 lightProbe[ 9 ];
#endif
vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {
	float x = normal.x, y = normal.y, z = normal.z;
	vec3 result = shCoefficients[ 0 ] * 0.886227;
	result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;
	result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;
	result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;
	result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;
	result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;
	result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );
	result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;
	result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );
	return result;
}
vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {
	vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
	vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );
	return irradiance;
}
vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {
	vec3 irradiance = ambientLightColor;
	return irradiance;
}
float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {
	float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );
	if ( cutoffDistance > 0.0 ) {
		distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );
	}
	return distanceFalloff;
}
float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {
	return smoothstep( coneCosine, penumbraCosine, angleCosine );
}
#if NUM_DIR_LIGHTS > 0
	struct DirectionalLight {
		vec3 direction;
		vec3 color;
	};
	uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];
	void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {
		light.color = directionalLight.color;
		light.direction = directionalLight.direction;
		light.visible = true;
	}
#endif
#if NUM_POINT_LIGHTS > 0
	struct PointLight {
		vec3 position;
		vec3 color;
		float distance;
		float decay;
	};
	uniform PointLight pointLights[ NUM_POINT_LIGHTS ];
	void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {
		vec3 lVector = pointLight.position - geometryPosition;
		light.direction = normalize( lVector );
		float lightDistance = length( lVector );
		light.color = pointLight.color;
		light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );
		light.visible = ( light.color != vec3( 0.0 ) );
	}
#endif
#if NUM_SPOT_LIGHTS > 0
	struct SpotLight {
		vec3 position;
		vec3 direction;
		vec3 color;
		float distance;
		float decay;
		float coneCos;
		float penumbraCos;
	};
	uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];
	void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {
		vec3 lVector = spotLight.position - geometryPosition;
		light.direction = normalize( lVector );
		float angleCos = dot( light.direction, spotLight.direction );
		float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );
		if ( spotAttenuation > 0.0 ) {
			float lightDistance = length( lVector );
			light.color = spotLight.color * spotAttenuation;
			light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );
			light.visible = ( light.color != vec3( 0.0 ) );
		} else {
			light.color = vec3( 0.0 );
			light.visible = false;
		}
	}
#endif
#if NUM_RECT_AREA_LIGHTS > 0
	struct RectAreaLight {
		vec3 color;
		vec3 position;
		vec3 halfWidth;
		vec3 halfHeight;
	};
	uniform sampler2D ltc_1;	uniform sampler2D ltc_2;
	uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];
#endif
#if NUM_HEMI_LIGHTS > 0
	struct HemisphereLight {
		vec3 direction;
		vec3 skyColor;
		vec3 groundColor;
	};
	uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];
	vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {
		float dotNL = dot( normal, hemiLight.direction );
		float hemiDiffuseWeight = 0.5 * dotNL + 0.5;
		vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );
		return irradiance;
	}
#endif`,MR=`#ifdef USE_ENVMAP
	vec3 getIBLIrradiance( const in vec3 normal ) {
		#ifdef ENVMAP_TYPE_CUBE_UV
			vec3 worldNormal = inverseTransformDirection( normal, viewMatrix );
			vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );
			return PI * envMapColor.rgb * envMapIntensity;
		#else
			return vec3( 0.0 );
		#endif
	}
	vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {
		#ifdef ENVMAP_TYPE_CUBE_UV
			vec3 reflectVec = reflect( - viewDir, normal );
			reflectVec = normalize( mix( reflectVec, normal, roughness * roughness) );
			reflectVec = inverseTransformDirection( reflectVec, viewMatrix );
			vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );
			return envMapColor.rgb * envMapIntensity;
		#else
			return vec3( 0.0 );
		#endif
	}
	#ifdef USE_ANISOTROPY
		vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {
			#ifdef ENVMAP_TYPE_CUBE_UV
				vec3 bentNormal = cross( bitangent, viewDir );
				bentNormal = normalize( cross( bentNormal, bitangent ) );
				bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );
				return getIBLRadiance( viewDir, bentNormal, roughness );
			#else
				return vec3( 0.0 );
			#endif
		}
	#endif
#endif`,AR=`ToonMaterial material;
material.diffuseColor = diffuseColor.rgb;`,TR=`varying vec3 vViewPosition;
struct ToonMaterial {
	vec3 diffuseColor;
};
void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {
	vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct				RE_Direct_Toon
#define RE_IndirectDiffuse		RE_IndirectDiffuse_Toon`,CR=`BlinnPhongMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularColor = specular;
material.specularShininess = shininess;
material.specularStrength = specularStrength;`,RR=`varying vec3 vViewPosition;
struct BlinnPhongMaterial {
	vec3 diffuseColor;
	vec3 specularColor;
	float specularShininess;
	float specularStrength;
};
void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
	vec3 irradiance = dotNL * directLight.color;
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
	reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;
}
void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
#define RE_Direct				RE_Direct_BlinnPhong
#define RE_IndirectDiffuse		RE_IndirectDiffuse_BlinnPhong`,PR=`PhysicalMaterial material;
material.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );
vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );
float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );
material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;
material.roughness = min( material.roughness, 1.0 );
#ifdef IOR
	material.ior = ior;
	#ifdef USE_SPECULAR
		float specularIntensityFactor = specularIntensity;
		vec3 specularColorFactor = specularColor;
		#ifdef USE_SPECULAR_COLORMAP
			specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;
		#endif
		#ifdef USE_SPECULAR_INTENSITYMAP
			specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;
		#endif
		material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );
	#else
		float specularIntensityFactor = 1.0;
		vec3 specularColorFactor = vec3( 1.0 );
		material.specularF90 = 1.0;
	#endif
	material.specularColor = mix( min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor, diffuseColor.rgb, metalnessFactor );
#else
	material.specularColor = mix( vec3( 0.04 ), diffuseColor.rgb, metalnessFactor );
	material.specularF90 = 1.0;
#endif
#ifdef USE_CLEARCOAT
	material.clearcoat = clearcoat;
	material.clearcoatRoughness = clearcoatRoughness;
	material.clearcoatF0 = vec3( 0.04 );
	material.clearcoatF90 = 1.0;
	#ifdef USE_CLEARCOATMAP
		material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;
	#endif
	#ifdef USE_CLEARCOAT_ROUGHNESSMAP
		material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;
	#endif
	material.clearcoat = saturate( material.clearcoat );	material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );
	material.clearcoatRoughness += geometryRoughness;
	material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );
#endif
#ifdef USE_DISPERSION
	material.dispersion = dispersion;
#endif
#ifdef USE_IRIDESCENCE
	material.iridescence = iridescence;
	material.iridescenceIOR = iridescenceIOR;
	#ifdef USE_IRIDESCENCEMAP
		material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;
	#endif
	#ifdef USE_IRIDESCENCE_THICKNESSMAP
		material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;
	#else
		material.iridescenceThickness = iridescenceThicknessMaximum;
	#endif
#endif
#ifdef USE_SHEEN
	material.sheenColor = sheenColor;
	#ifdef USE_SHEEN_COLORMAP
		material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;
	#endif
	material.sheenRoughness = clamp( sheenRoughness, 0.07, 1.0 );
	#ifdef USE_SHEEN_ROUGHNESSMAP
		material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;
	#endif
#endif
#ifdef USE_ANISOTROPY
	#ifdef USE_ANISOTROPYMAP
		mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );
		vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;
		vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;
	#else
		vec2 anisotropyV = anisotropyVector;
	#endif
	material.anisotropy = length( anisotropyV );
	if( material.anisotropy == 0.0 ) {
		anisotropyV = vec2( 1.0, 0.0 );
	} else {
		anisotropyV /= material.anisotropy;
		material.anisotropy = saturate( material.anisotropy );
	}
	material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );
	material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;
	material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;
#endif`,IR=`struct PhysicalMaterial {
	vec3 diffuseColor;
	float roughness;
	vec3 specularColor;
	float specularF90;
	float dispersion;
	#ifdef USE_CLEARCOAT
		float clearcoat;
		float clearcoatRoughness;
		vec3 clearcoatF0;
		float clearcoatF90;
	#endif
	#ifdef USE_IRIDESCENCE
		float iridescence;
		float iridescenceIOR;
		float iridescenceThickness;
		vec3 iridescenceFresnel;
		vec3 iridescenceF0;
	#endif
	#ifdef USE_SHEEN
		vec3 sheenColor;
		float sheenRoughness;
	#endif
	#ifdef IOR
		float ior;
	#endif
	#ifdef USE_TRANSMISSION
		float transmission;
		float transmissionAlpha;
		float thickness;
		float attenuationDistance;
		vec3 attenuationColor;
	#endif
	#ifdef USE_ANISOTROPY
		float anisotropy;
		float alphaT;
		vec3 anisotropyT;
		vec3 anisotropyB;
	#endif
};
vec3 clearcoatSpecularDirect = vec3( 0.0 );
vec3 clearcoatSpecularIndirect = vec3( 0.0 );
vec3 sheenSpecularDirect = vec3( 0.0 );
vec3 sheenSpecularIndirect = vec3(0.0 );
vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {
    float x = clamp( 1.0 - dotVH, 0.0, 1.0 );
    float x2 = x * x;
    float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );
    return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );
}
float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {
	float a2 = pow2( alpha );
	float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );
	float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );
	return 0.5 / max( gv + gl, EPSILON );
}
float D_GGX( const in float alpha, const in float dotNH ) {
	float a2 = pow2( alpha );
	float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;
	return RECIPROCAL_PI * a2 / pow2( denom );
}
#ifdef USE_ANISOTROPY
	float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {
		float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );
		float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );
		float v = 0.5 / ( gv + gl );
		return saturate(v);
	}
	float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {
		float a2 = alphaT * alphaB;
		highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );
		highp float v2 = dot( v, v );
		float w2 = a2 / v2;
		return RECIPROCAL_PI * a2 * pow2 ( w2 );
	}
#endif
#ifdef USE_CLEARCOAT
	vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {
		vec3 f0 = material.clearcoatF0;
		float f90 = material.clearcoatF90;
		float roughness = material.clearcoatRoughness;
		float alpha = pow2( roughness );
		vec3 halfDir = normalize( lightDir + viewDir );
		float dotNL = saturate( dot( normal, lightDir ) );
		float dotNV = saturate( dot( normal, viewDir ) );
		float dotNH = saturate( dot( normal, halfDir ) );
		float dotVH = saturate( dot( viewDir, halfDir ) );
		vec3 F = F_Schlick( f0, f90, dotVH );
		float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
		float D = D_GGX( alpha, dotNH );
		return F * ( V * D );
	}
#endif
vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {
	vec3 f0 = material.specularColor;
	float f90 = material.specularF90;
	float roughness = material.roughness;
	float alpha = pow2( roughness );
	vec3 halfDir = normalize( lightDir + viewDir );
	float dotNL = saturate( dot( normal, lightDir ) );
	float dotNV = saturate( dot( normal, viewDir ) );
	float dotNH = saturate( dot( normal, halfDir ) );
	float dotVH = saturate( dot( viewDir, halfDir ) );
	vec3 F = F_Schlick( f0, f90, dotVH );
	#ifdef USE_IRIDESCENCE
		F = mix( F, material.iridescenceFresnel, material.iridescence );
	#endif
	#ifdef USE_ANISOTROPY
		float dotTL = dot( material.anisotropyT, lightDir );
		float dotTV = dot( material.anisotropyT, viewDir );
		float dotTH = dot( material.anisotropyT, halfDir );
		float dotBL = dot( material.anisotropyB, lightDir );
		float dotBV = dot( material.anisotropyB, viewDir );
		float dotBH = dot( material.anisotropyB, halfDir );
		float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );
		float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );
	#else
		float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );
		float D = D_GGX( alpha, dotNH );
	#endif
	return F * ( V * D );
}
vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {
	const float LUT_SIZE = 64.0;
	const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
	const float LUT_BIAS = 0.5 / LUT_SIZE;
	float dotNV = saturate( dot( N, V ) );
	vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );
	uv = uv * LUT_SCALE + LUT_BIAS;
	return uv;
}
float LTC_ClippedSphereFormFactor( const in vec3 f ) {
	float l = length( f );
	return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );
}
vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {
	float x = dot( v1, v2 );
	float y = abs( x );
	float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;
	float b = 3.4175940 + ( 4.1616724 + y ) * y;
	float v = a / b;
	float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;
	return cross( v1, v2 ) * theta_sintheta;
}
vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {
	vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];
	vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];
	vec3 lightNormal = cross( v1, v2 );
	if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );
	vec3 T1, T2;
	T1 = normalize( V - N * dot( V, N ) );
	T2 = - cross( N, T1 );
	mat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );
	vec3 coords[ 4 ];
	coords[ 0 ] = mat * ( rectCoords[ 0 ] - P );
	coords[ 1 ] = mat * ( rectCoords[ 1 ] - P );
	coords[ 2 ] = mat * ( rectCoords[ 2 ] - P );
	coords[ 3 ] = mat * ( rectCoords[ 3 ] - P );
	coords[ 0 ] = normalize( coords[ 0 ] );
	coords[ 1 ] = normalize( coords[ 1 ] );
	coords[ 2 ] = normalize( coords[ 2 ] );
	coords[ 3 ] = normalize( coords[ 3 ] );
	vec3 vectorFormFactor = vec3( 0.0 );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );
	vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );
	float result = LTC_ClippedSphereFormFactor( vectorFormFactor );
	return vec3( result );
}
#if defined( USE_SHEEN )
float D_Charlie( float roughness, float dotNH ) {
	float alpha = pow2( roughness );
	float invAlpha = 1.0 / alpha;
	float cos2h = dotNH * dotNH;
	float sin2h = max( 1.0 - cos2h, 0.0078125 );
	return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );
}
float V_Neubelt( float dotNV, float dotNL ) {
	return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );
}
vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {
	vec3 halfDir = normalize( lightDir + viewDir );
	float dotNL = saturate( dot( normal, lightDir ) );
	float dotNV = saturate( dot( normal, viewDir ) );
	float dotNH = saturate( dot( normal, halfDir ) );
	float D = D_Charlie( sheenRoughness, dotNH );
	float V = V_Neubelt( dotNV, dotNL );
	return sheenColor * ( D * V );
}
#endif
float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
	float dotNV = saturate( dot( normal, viewDir ) );
	float r2 = roughness * roughness;
	float a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;
	float b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;
	float DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );
	return saturate( DG * RECIPROCAL_PI );
}
vec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {
	float dotNV = saturate( dot( normal, viewDir ) );
	const vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );
	const vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );
	vec4 r = roughness * c0 + c1;
	float a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;
	vec2 fab = vec2( - 1.04, 1.04 ) * a004 + r.zw;
	return fab;
}
vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {
	vec2 fab = DFGApprox( normal, viewDir, roughness );
	return specularColor * fab.x + specularF90 * fab.y;
}
#ifdef USE_IRIDESCENCE
void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
#else
void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {
#endif
	vec2 fab = DFGApprox( normal, viewDir, roughness );
	#ifdef USE_IRIDESCENCE
		vec3 Fr = mix( specularColor, iridescenceF0, iridescence );
	#else
		vec3 Fr = specularColor;
	#endif
	vec3 FssEss = Fr * fab.x + specularF90 * fab.y;
	float Ess = fab.x + fab.y;
	float Ems = 1.0 - Ess;
	vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;	vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );
	singleScatter += FssEss;
	multiScatter += Fms * Ems;
}
#if NUM_RECT_AREA_LIGHTS > 0
	void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
		vec3 normal = geometryNormal;
		vec3 viewDir = geometryViewDir;
		vec3 position = geometryPosition;
		vec3 lightPos = rectAreaLight.position;
		vec3 halfWidth = rectAreaLight.halfWidth;
		vec3 halfHeight = rectAreaLight.halfHeight;
		vec3 lightColor = rectAreaLight.color;
		float roughness = material.roughness;
		vec3 rectCoords[ 4 ];
		rectCoords[ 0 ] = lightPos + halfWidth - halfHeight;		rectCoords[ 1 ] = lightPos - halfWidth - halfHeight;
		rectCoords[ 2 ] = lightPos - halfWidth + halfHeight;
		rectCoords[ 3 ] = lightPos + halfWidth + halfHeight;
		vec2 uv = LTC_Uv( normal, viewDir, roughness );
		vec4 t1 = texture2D( ltc_1, uv );
		vec4 t2 = texture2D( ltc_2, uv );
		mat3 mInv = mat3(
			vec3( t1.x, 0, t1.y ),
			vec3(    0, 1,    0 ),
			vec3( t1.z, 0, t1.w )
		);
		vec3 fresnel = ( material.specularColor * t2.x + ( vec3( 1.0 ) - material.specularColor ) * t2.y );
		reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );
		reflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );
	}
#endif
void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
	float dotNL = saturate( dot( geometryNormal, directLight.direction ) );
	vec3 irradiance = dotNL * directLight.color;
	#ifdef USE_CLEARCOAT
		float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );
		vec3 ccIrradiance = dotNLcc * directLight.color;
		clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );
	#endif
	#ifdef USE_SHEEN
		sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );
	#endif
	reflectedLight.directSpecular += irradiance * BRDF_GGX( directLight.direction, geometryViewDir, geometryNormal, material );
	reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {
	reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );
}
void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {
	#ifdef USE_CLEARCOAT
		clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );
	#endif
	#ifdef USE_SHEEN
		sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );
	#endif
	vec3 singleScattering = vec3( 0.0 );
	vec3 multiScattering = vec3( 0.0 );
	vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;
	#ifdef USE_IRIDESCENCE
		computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnel, material.roughness, singleScattering, multiScattering );
	#else
		computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScattering, multiScattering );
	#endif
	vec3 totalScattering = singleScattering + multiScattering;
	vec3 diffuse = material.diffuseColor * ( 1.0 - max( max( totalScattering.r, totalScattering.g ), totalScattering.b ) );
	reflectedLight.indirectSpecular += radiance * singleScattering;
	reflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;
	reflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;
}
#define RE_Direct				RE_Direct_Physical
#define RE_Direct_RectArea		RE_Direct_RectArea_Physical
#define RE_IndirectDiffuse		RE_IndirectDiffuse_Physical
#define RE_IndirectSpecular		RE_IndirectSpecular_Physical
float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {
	return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );
}`,NR=`
vec3 geometryPosition = - vViewPosition;
vec3 geometryNormal = normal;
vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );
vec3 geometryClearcoatNormal = vec3( 0.0 );
#ifdef USE_CLEARCOAT
	geometryClearcoatNormal = clearcoatNormal;
#endif
#ifdef USE_IRIDESCENCE
	float dotNVi = saturate( dot( normal, geometryViewDir ) );
	if ( material.iridescenceThickness == 0.0 ) {
		material.iridescence = 0.0;
	} else {
		material.iridescence = saturate( material.iridescence );
	}
	if ( material.iridescence > 0.0 ) {
		material.iridescenceFresnel = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );
		material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );
	}
#endif
IncidentLight directLight;
#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )
	PointLight pointLight;
	#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0
	PointLightShadow pointLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {
		pointLight = pointLights[ i ];
		getPointLightInfo( pointLight, geometryPosition, directLight );
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS )
		pointLightShadow = pointLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )
	SpotLight spotLight;
	vec4 spotColor;
	vec3 spotLightCoord;
	bool inSpotLightMap;
	#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0
	SpotLightShadow spotLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {
		spotLight = spotLights[ i ];
		getSpotLightInfo( spotLight, geometryPosition, directLight );
		#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
		#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX
		#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
		#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS
		#else
		#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )
		#endif
		#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )
			spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;
			inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );
			spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );
			directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;
		#endif
		#undef SPOT_LIGHT_MAP_INDEX
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
		spotLightShadow = spotLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )
	DirectionalLight directionalLight;
	#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
	DirectionalLightShadow directionalLightShadow;
	#endif
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {
		directionalLight = directionalLights[ i ];
		getDirectionalLightInfo( directionalLight, directLight );
		#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
		directionalLightShadow = directionalLightShadows[ i ];
		directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
		#endif
		RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )
	RectAreaLight rectAreaLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {
		rectAreaLight = rectAreaLights[ i ];
		RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
	}
	#pragma unroll_loop_end
#endif
#if defined( RE_IndirectDiffuse )
	vec3 iblIrradiance = vec3( 0.0 );
	vec3 irradiance = getAmbientLightIrradiance( ambientLightColor );
	#if defined( USE_LIGHT_PROBES )
		irradiance += getLightProbeIrradiance( lightProbe, geometryNormal );
	#endif
	#if ( NUM_HEMI_LIGHTS > 0 )
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {
			irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );
		}
		#pragma unroll_loop_end
	#endif
#endif
#if defined( RE_IndirectSpecular )
	vec3 radiance = vec3( 0.0 );
	vec3 clearcoatRadiance = vec3( 0.0 );
#endif`,LR=`#if defined( RE_IndirectDiffuse )
	#ifdef USE_LIGHTMAP
		vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
		vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;
		irradiance += lightMapIrradiance;
	#endif
	#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )
		iblIrradiance += getIBLIrradiance( geometryNormal );
	#endif
#endif
#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )
	#ifdef USE_ANISOTROPY
		radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );
	#else
		radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );
	#endif
	#ifdef USE_CLEARCOAT
		clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );
	#endif
#endif`,kR=`#if defined( RE_IndirectDiffuse )
	RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
#endif
#if defined( RE_IndirectSpecular )
	RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );
#endif`,OR=`#if defined( USE_LOGDEPTHBUF )
	gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
#endif`,DR=`#if defined( USE_LOGDEPTHBUF )
	uniform float logDepthBufFC;
	varying float vFragDepth;
	varying float vIsPerspective;
#endif`,UR=`#ifdef USE_LOGDEPTHBUF
	varying float vFragDepth;
	varying float vIsPerspective;
#endif`,FR=`#ifdef USE_LOGDEPTHBUF
	vFragDepth = 1.0 + gl_Position.w;
	vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
#endif`,zR=`#ifdef USE_MAP
	vec4 sampledDiffuseColor = texture2D( map, vMapUv );
	#ifdef DECODE_VIDEO_TEXTURE
		sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );
	#endif
	diffuseColor *= sampledDiffuseColor;
#endif`,BR=`#ifdef USE_MAP
	uniform sampler2D map;
#endif`,jR=`#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
	#if defined( USE_POINTS_UV )
		vec2 uv = vUv;
	#else
		vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;
	#endif
#endif
#ifdef USE_MAP
	diffuseColor *= texture2D( map, uv );
#endif
#ifdef USE_ALPHAMAP
	diffuseColor.a *= texture2D( alphaMap, uv ).g;
#endif`,VR=`#if defined( USE_POINTS_UV )
	varying vec2 vUv;
#else
	#if defined( USE_MAP ) || defined( USE_ALPHAMAP )
		uniform mat3 uvTransform;
	#endif
#endif
#ifdef USE_MAP
	uniform sampler2D map;
#endif
#ifdef USE_ALPHAMAP
	uniform sampler2D alphaMap;
#endif`,HR=`float metalnessFactor = metalness;
#ifdef USE_METALNESSMAP
	vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
	metalnessFactor *= texelMetalness.b;
#endif`,GR=`#ifdef USE_METALNESSMAP
	uniform sampler2D metalnessMap;
#endif`,WR=`#ifdef USE_INSTANCING_MORPH
	float morphTargetInfluences[ MORPHTARGETS_COUNT ];
	float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		morphTargetInfluences[i] =  texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;
	}
#endif`,XR=`#if defined( USE_MORPHCOLORS )
	vColor *= morphTargetBaseInfluence;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		#if defined( USE_COLOR_ALPHA )
			if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];
		#elif defined( USE_COLOR )
			if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];
		#endif
	}
#endif`,YR=`#ifdef USE_MORPHNORMALS
	objectNormal *= morphTargetBaseInfluence;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];
	}
#endif`,qR=`#ifdef USE_MORPHTARGETS
	#ifndef USE_INSTANCING_MORPH
		uniform float morphTargetBaseInfluence;
		uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];
	#endif
	uniform sampler2DArray morphTargetsTexture;
	uniform ivec2 morphTargetsTextureSize;
	vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {
		int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;
		int y = texelIndex / morphTargetsTextureSize.x;
		int x = texelIndex - y * morphTargetsTextureSize.x;
		ivec3 morphUV = ivec3( x, y, morphTargetIndex );
		return texelFetch( morphTargetsTexture, morphUV, 0 );
	}
#endif`,KR=`#ifdef USE_MORPHTARGETS
	transformed *= morphTargetBaseInfluence;
	for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {
		if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];
	}
#endif`,ZR=`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;
#ifdef FLAT_SHADED
	vec3 fdx = dFdx( vViewPosition );
	vec3 fdy = dFdy( vViewPosition );
	vec3 normal = normalize( cross( fdx, fdy ) );
#else
	vec3 normal = normalize( vNormal );
	#ifdef DOUBLE_SIDED
		normal *= faceDirection;
	#endif
#endif
#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )
	#ifdef USE_TANGENT
		mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
	#else
		mat3 tbn = getTangentFrame( - vViewPosition, normal,
		#if defined( USE_NORMALMAP )
			vNormalMapUv
		#elif defined( USE_CLEARCOAT_NORMALMAP )
			vClearcoatNormalMapUv
		#else
			vUv
		#endif
		);
	#endif
	#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
		tbn[0] *= faceDirection;
		tbn[1] *= faceDirection;
	#endif
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	#ifdef USE_TANGENT
		mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );
	#else
		mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );
	#endif
	#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )
		tbn2[0] *= faceDirection;
		tbn2[1] *= faceDirection;
	#endif
#endif
vec3 nonPerturbedNormal = normal;`,$R=`#ifdef USE_NORMALMAP_OBJECTSPACE
	normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
	#ifdef FLIP_SIDED
		normal = - normal;
	#endif
	#ifdef DOUBLE_SIDED
		normal = normal * faceDirection;
	#endif
	normal = normalize( normalMatrix * normal );
#elif defined( USE_NORMALMAP_TANGENTSPACE )
	vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;
	mapN.xy *= normalScale;
	normal = normalize( tbn * mapN );
#elif defined( USE_BUMPMAP )
	normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );
#endif`,JR=`#ifndef FLAT_SHADED
	varying vec3 vNormal;
	#ifdef USE_TANGENT
		varying vec3 vTangent;
		varying vec3 vBitangent;
	#endif
#endif`,QR=`#ifndef FLAT_SHADED
	varying vec3 vNormal;
	#ifdef USE_TANGENT
		varying vec3 vTangent;
		varying vec3 vBitangent;
	#endif
#endif`,eP=`#ifndef FLAT_SHADED
	vNormal = normalize( transformedNormal );
	#ifdef USE_TANGENT
		vTangent = normalize( transformedTangent );
		vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
	#endif
#endif`,tP=`#ifdef USE_NORMALMAP
	uniform sampler2D normalMap;
	uniform vec2 normalScale;
#endif
#ifdef USE_NORMALMAP_OBJECTSPACE
	uniform mat3 normalMatrix;
#endif
#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )
	mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {
		vec3 q0 = dFdx( eye_pos.xyz );
		vec3 q1 = dFdy( eye_pos.xyz );
		vec2 st0 = dFdx( uv.st );
		vec2 st1 = dFdy( uv.st );
		vec3 N = surf_norm;
		vec3 q1perp = cross( q1, N );
		vec3 q0perp = cross( N, q0 );
		vec3 T = q1perp * st0.x + q0perp * st1.x;
		vec3 B = q1perp * st0.y + q0perp * st1.y;
		float det = max( dot( T, T ), dot( B, B ) );
		float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );
		return mat3( T * scale, B * scale, N );
	}
#endif`,rP=`#ifdef USE_CLEARCOAT
	vec3 clearcoatNormal = nonPerturbedNormal;
#endif`,iP=`#ifdef USE_CLEARCOAT_NORMALMAP
	vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
	clearcoatMapN.xy *= clearcoatNormalScale;
	clearcoatNormal = normalize( tbn2 * clearcoatMapN );
#endif`,nP=`#ifdef USE_CLEARCOATMAP
	uniform sampler2D clearcoatMap;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	uniform sampler2D clearcoatNormalMap;
	uniform vec2 clearcoatNormalScale;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	uniform sampler2D clearcoatRoughnessMap;
#endif`,sP=`#ifdef USE_IRIDESCENCEMAP
	uniform sampler2D iridescenceMap;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	uniform sampler2D iridescenceThicknessMap;
#endif`,aP=`#ifdef OPAQUE
diffuseColor.a = 1.0;
#endif
#ifdef USE_TRANSMISSION
diffuseColor.a *= material.transmissionAlpha;
#endif
gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,oP=`vec3 packNormalToRGB( const in vec3 normal ) {
	return normalize( normal ) * 0.5 + 0.5;
}
vec3 unpackRGBToNormal( const in vec3 rgb ) {
	return 2.0 * rgb.xyz - 1.0;
}
const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;
const float Inv255 = 1. / 255.;
const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );
const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );
const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );
const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );
vec4 packDepthToRGBA( const in float v ) {
	if( v <= 0.0 )
		return vec4( 0., 0., 0., 0. );
	if( v >= 1.0 )
		return vec4( 1., 1., 1., 1. );
	float vuf;
	float af = modf( v * PackFactors.a, vuf );
	float bf = modf( vuf * ShiftRight8, vuf );
	float gf = modf( vuf * ShiftRight8, vuf );
	return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );
}
vec3 packDepthToRGB( const in float v ) {
	if( v <= 0.0 )
		return vec3( 0., 0., 0. );
	if( v >= 1.0 )
		return vec3( 1., 1., 1. );
	float vuf;
	float bf = modf( v * PackFactors.b, vuf );
	float gf = modf( vuf * ShiftRight8, vuf );
	return vec3( vuf * Inv255, gf * PackUpscale, bf );
}
vec2 packDepthToRG( const in float v ) {
	if( v <= 0.0 )
		return vec2( 0., 0. );
	if( v >= 1.0 )
		return vec2( 1., 1. );
	float vuf;
	float gf = modf( v * 256., vuf );
	return vec2( vuf * Inv255, gf );
}
float unpackRGBAToDepth( const in vec4 v ) {
	return dot( v, UnpackFactors4 );
}
float unpackRGBToDepth( const in vec3 v ) {
	return dot( v, UnpackFactors3 );
}
float unpackRGToDepth( const in vec2 v ) {
	return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;
}
vec4 pack2HalfToRGBA( const in vec2 v ) {
	vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );
	return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );
}
vec2 unpackRGBATo2Half( const in vec4 v ) {
	return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );
}
float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {
	return ( viewZ + near ) / ( near - far );
}
float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {
	return depth * ( near - far ) - near;
}
float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {
	return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );
}
float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {
	return ( near * far ) / ( ( far - near ) * depth - far );
}`,lP=`#ifdef PREMULTIPLIED_ALPHA
	gl_FragColor.rgb *= gl_FragColor.a;
#endif`,cP=`vec4 mvPosition = vec4( transformed, 1.0 );
#ifdef USE_BATCHING
	mvPosition = batchingMatrix * mvPosition;
#endif
#ifdef USE_INSTANCING
	mvPosition = instanceMatrix * mvPosition;
#endif
mvPosition = modelViewMatrix * mvPosition;
gl_Position = projectionMatrix * mvPosition;`,hP=`#ifdef DITHERING
	gl_FragColor.rgb = dithering( gl_FragColor.rgb );
#endif`,uP=`#ifdef DITHERING
	vec3 dithering( vec3 color ) {
		float grid_position = rand( gl_FragCoord.xy );
		vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );
		dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );
		return color + dither_shift_RGB;
	}
#endif`,dP=`float roughnessFactor = roughness;
#ifdef USE_ROUGHNESSMAP
	vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
	roughnessFactor *= texelRoughness.g;
#endif`,pP=`#ifdef USE_ROUGHNESSMAP
	uniform sampler2D roughnessMap;
#endif`,fP=`#if NUM_SPOT_LIGHT_COORDS > 0
	varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
#endif
#if NUM_SPOT_LIGHT_MAPS > 0
	uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];
#endif
#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
		uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
		varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
		struct DirectionalLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
	#endif
	#if NUM_SPOT_LIGHT_SHADOWS > 0
		uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];
		struct SpotLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
		uniform sampler2D pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];
		varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
		struct PointLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
			float shadowCameraNear;
			float shadowCameraFar;
		};
		uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
	#endif
	float texture2DCompare( sampler2D depths, vec2 uv, float compare ) {
		return step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );
	}
	vec2 texture2DDistribution( sampler2D shadow, vec2 uv ) {
		return unpackRGBATo2Half( texture2D( shadow, uv ) );
	}
	float VSMShadow (sampler2D shadow, vec2 uv, float compare ){
		float occlusion = 1.0;
		vec2 distribution = texture2DDistribution( shadow, uv );
		float hard_shadow = step( compare , distribution.x );
		if (hard_shadow != 1.0 ) {
			float distance = compare - distribution.x ;
			float variance = max( 0.00000, distribution.y * distribution.y );
			float softness_probability = variance / (variance + distance * distance );			softness_probability = clamp( ( softness_probability - 0.3 ) / ( 0.95 - 0.3 ), 0.0, 1.0 );			occlusion = clamp( max( hard_shadow, softness_probability ), 0.0, 1.0 );
		}
		return occlusion;
	}
	float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {
		float shadow = 1.0;
		shadowCoord.xyz /= shadowCoord.w;
		shadowCoord.z += shadowBias;
		bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;
		bool frustumTest = inFrustum && shadowCoord.z <= 1.0;
		if ( frustumTest ) {
		#if defined( SHADOWMAP_TYPE_PCF )
			vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
			float dx0 = - texelSize.x * shadowRadius;
			float dy0 = - texelSize.y * shadowRadius;
			float dx1 = + texelSize.x * shadowRadius;
			float dy1 = + texelSize.y * shadowRadius;
			float dx2 = dx0 / 2.0;
			float dy2 = dy0 / 2.0;
			float dx3 = dx1 / 2.0;
			float dy3 = dy1 / 2.0;
			shadow = (
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy2 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx2, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx3, dy3 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )
			) * ( 1.0 / 17.0 );
		#elif defined( SHADOWMAP_TYPE_PCF_SOFT )
			vec2 texelSize = vec2( 1.0 ) / shadowMapSize;
			float dx = texelSize.x;
			float dy = texelSize.y;
			vec2 uv = shadowCoord.xy;
			vec2 f = fract( uv * shadowMapSize + 0.5 );
			uv -= f * texelSize;
			shadow = (
				texture2DCompare( shadowMap, uv, shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + vec2( dx, 0.0 ), shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + vec2( 0.0, dy ), shadowCoord.z ) +
				texture2DCompare( shadowMap, uv + texelSize, shadowCoord.z ) +
				mix( texture2DCompare( shadowMap, uv + vec2( -dx, 0.0 ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 0.0 ), shadowCoord.z ),
					 f.x ) +
				mix( texture2DCompare( shadowMap, uv + vec2( -dx, dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, dy ), shadowCoord.z ),
					 f.x ) +
				mix( texture2DCompare( shadowMap, uv + vec2( 0.0, -dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( 0.0, 2.0 * dy ), shadowCoord.z ),
					 f.y ) +
				mix( texture2DCompare( shadowMap, uv + vec2( dx, -dy ), shadowCoord.z ),
					 texture2DCompare( shadowMap, uv + vec2( dx, 2.0 * dy ), shadowCoord.z ),
					 f.y ) +
				mix( mix( texture2DCompare( shadowMap, uv + vec2( -dx, -dy ), shadowCoord.z ),
						  texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, -dy ), shadowCoord.z ),
						  f.x ),
					 mix( texture2DCompare( shadowMap, uv + vec2( -dx, 2.0 * dy ), shadowCoord.z ),
						  texture2DCompare( shadowMap, uv + vec2( 2.0 * dx, 2.0 * dy ), shadowCoord.z ),
						  f.x ),
					 f.y )
			) * ( 1.0 / 9.0 );
		#elif defined( SHADOWMAP_TYPE_VSM )
			shadow = VSMShadow( shadowMap, shadowCoord.xy, shadowCoord.z );
		#else
			shadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );
		#endif
		}
		return mix( 1.0, shadow, shadowIntensity );
	}
	vec2 cubeToUV( vec3 v, float texelSizeY ) {
		vec3 absV = abs( v );
		float scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );
		absV *= scaleToCube;
		v *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );
		vec2 planar = v.xy;
		float almostATexel = 1.5 * texelSizeY;
		float almostOne = 1.0 - almostATexel;
		if ( absV.z >= almostOne ) {
			if ( v.z > 0.0 )
				planar.x = 4.0 - v.x;
		} else if ( absV.x >= almostOne ) {
			float signX = sign( v.x );
			planar.x = v.z * signX + 2.0 * signX;
		} else if ( absV.y >= almostOne ) {
			float signY = sign( v.y );
			planar.x = v.x + 2.0 * signY + 2.0;
			planar.y = v.z * signY - 2.0;
		}
		return vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );
	}
	float getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {
		float shadow = 1.0;
		vec3 lightToPosition = shadowCoord.xyz;
		
		float lightToPositionLength = length( lightToPosition );
		if ( lightToPositionLength - shadowCameraFar <= 0.0 && lightToPositionLength - shadowCameraNear >= 0.0 ) {
			float dp = ( lightToPositionLength - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear );			dp += shadowBias;
			vec3 bd3D = normalize( lightToPosition );
			vec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );
			#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT ) || defined( SHADOWMAP_TYPE_VSM )
				vec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;
				shadow = (
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +
					texture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )
				) * ( 1.0 / 9.0 );
			#else
				shadow = texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );
			#endif
		}
		return mix( 1.0, shadow, shadowIntensity );
	}
#endif`,mP=`#if NUM_SPOT_LIGHT_COORDS > 0
	uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];
	varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];
#endif
#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
		uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];
		varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
		struct DirectionalLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];
	#endif
	#if NUM_SPOT_LIGHT_SHADOWS > 0
		struct SpotLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
		};
		uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
		uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];
		varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];
		struct PointLightShadow {
			float shadowIntensity;
			float shadowBias;
			float shadowNormalBias;
			float shadowRadius;
			vec2 shadowMapSize;
			float shadowCameraNear;
			float shadowCameraFar;
		};
		uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];
	#endif
#endif`,gP=`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )
	vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );
	vec4 shadowWorldPosition;
#endif
#if defined( USE_SHADOWMAP )
	#if NUM_DIR_LIGHT_SHADOWS > 0
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
			shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );
			vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;
		}
		#pragma unroll_loop_end
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
		#pragma unroll_loop_start
		for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
			shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );
			vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;
		}
		#pragma unroll_loop_end
	#endif
#endif
#if NUM_SPOT_LIGHT_COORDS > 0
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {
		shadowWorldPosition = worldPosition;
		#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )
			shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;
		#endif
		vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;
	}
	#pragma unroll_loop_end
#endif`,yP=`float getShadowMask() {
	float shadow = 1.0;
	#ifdef USE_SHADOWMAP
	#if NUM_DIR_LIGHT_SHADOWS > 0
	DirectionalLightShadow directionalLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
		directionalLight = directionalLightShadows[ i ];
		shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;
	}
	#pragma unroll_loop_end
	#endif
	#if NUM_SPOT_LIGHT_SHADOWS > 0
	SpotLightShadow spotLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {
		spotLight = spotLightShadows[ i ];
		shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;
	}
	#pragma unroll_loop_end
	#endif
	#if NUM_POINT_LIGHT_SHADOWS > 0
	PointLightShadow pointLight;
	#pragma unroll_loop_start
	for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {
		pointLight = pointLightShadows[ i ];
		shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;
	}
	#pragma unroll_loop_end
	#endif
	#endif
	return shadow;
}`,vP=`#ifdef USE_SKINNING
	mat4 boneMatX = getBoneMatrix( skinIndex.x );
	mat4 boneMatY = getBoneMatrix( skinIndex.y );
	mat4 boneMatZ = getBoneMatrix( skinIndex.z );
	mat4 boneMatW = getBoneMatrix( skinIndex.w );
#endif`,xP=`#ifdef USE_SKINNING
	uniform mat4 bindMatrix;
	uniform mat4 bindMatrixInverse;
	uniform highp sampler2D boneTexture;
	mat4 getBoneMatrix( const in float i ) {
		int size = textureSize( boneTexture, 0 ).x;
		int j = int( i ) * 4;
		int x = j % size;
		int y = j / size;
		vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );
		vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );
		vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );
		vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );
		return mat4( v1, v2, v3, v4 );
	}
#endif`,bP=`#ifdef USE_SKINNING
	vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );
	vec4 skinned = vec4( 0.0 );
	skinned += boneMatX * skinVertex * skinWeight.x;
	skinned += boneMatY * skinVertex * skinWeight.y;
	skinned += boneMatZ * skinVertex * skinWeight.z;
	skinned += boneMatW * skinVertex * skinWeight.w;
	transformed = ( bindMatrixInverse * skinned ).xyz;
#endif`,wP=`#ifdef USE_SKINNING
	mat4 skinMatrix = mat4( 0.0 );
	skinMatrix += skinWeight.x * boneMatX;
	skinMatrix += skinWeight.y * boneMatY;
	skinMatrix += skinWeight.z * boneMatZ;
	skinMatrix += skinWeight.w * boneMatW;
	skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;
	objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;
	#ifdef USE_TANGENT
		objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz;
	#endif
#endif`,_P=`float specularStrength;
#ifdef USE_SPECULARMAP
	vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
	specularStrength = texelSpecular.r;
#else
	specularStrength = 1.0;
#endif`,EP=`#ifdef USE_SPECULARMAP
	uniform sampler2D specularMap;
#endif`,SP=`#if defined( TONE_MAPPING )
	gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
#endif`,MP=`#ifndef saturate
#define saturate( a ) clamp( a, 0.0, 1.0 )
#endif
uniform float toneMappingExposure;
vec3 LinearToneMapping( vec3 color ) {
	return saturate( toneMappingExposure * color );
}
vec3 ReinhardToneMapping( vec3 color ) {
	color *= toneMappingExposure;
	return saturate( color / ( vec3( 1.0 ) + color ) );
}
vec3 CineonToneMapping( vec3 color ) {
	color *= toneMappingExposure;
	color = max( vec3( 0.0 ), color - 0.004 );
	return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );
}
vec3 RRTAndODTFit( vec3 v ) {
	vec3 a = v * ( v + 0.0245786 ) - 0.000090537;
	vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;
	return a / b;
}
vec3 ACESFilmicToneMapping( vec3 color ) {
	const mat3 ACESInputMat = mat3(
		vec3( 0.59719, 0.07600, 0.02840 ),		vec3( 0.35458, 0.90834, 0.13383 ),
		vec3( 0.04823, 0.01566, 0.83777 )
	);
	const mat3 ACESOutputMat = mat3(
		vec3(  1.60475, -0.10208, -0.00327 ),		vec3( -0.53108,  1.10813, -0.07276 ),
		vec3( -0.07367, -0.00605,  1.07602 )
	);
	color *= toneMappingExposure / 0.6;
	color = ACESInputMat * color;
	color = RRTAndODTFit( color );
	color = ACESOutputMat * color;
	return saturate( color );
}
const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(
	vec3( 1.6605, - 0.1246, - 0.0182 ),
	vec3( - 0.5876, 1.1329, - 0.1006 ),
	vec3( - 0.0728, - 0.0083, 1.1187 )
);
const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(
	vec3( 0.6274, 0.0691, 0.0164 ),
	vec3( 0.3293, 0.9195, 0.0880 ),
	vec3( 0.0433, 0.0113, 0.8956 )
);
vec3 agxDefaultContrastApprox( vec3 x ) {
	vec3 x2 = x * x;
	vec3 x4 = x2 * x2;
	return + 15.5 * x4 * x2
		- 40.14 * x4 * x
		+ 31.96 * x4
		- 6.868 * x2 * x
		+ 0.4298 * x2
		+ 0.1191 * x
		- 0.00232;
}
vec3 AgXToneMapping( vec3 color ) {
	const mat3 AgXInsetMatrix = mat3(
		vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),
		vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),
		vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )
	);
	const mat3 AgXOutsetMatrix = mat3(
		vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),
		vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),
		vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )
	);
	const float AgxMinEv = - 12.47393;	const float AgxMaxEv = 4.026069;
	color *= toneMappingExposure;
	color = LINEAR_SRGB_TO_LINEAR_REC2020 * color;
	color = AgXInsetMatrix * color;
	color = max( color, 1e-10 );	color = log2( color );
	color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );
	color = clamp( color, 0.0, 1.0 );
	color = agxDefaultContrastApprox( color );
	color = AgXOutsetMatrix * color;
	color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );
	color = LINEAR_REC2020_TO_LINEAR_SRGB * color;
	color = clamp( color, 0.0, 1.0 );
	return color;
}
vec3 NeutralToneMapping( vec3 color ) {
	const float StartCompression = 0.8 - 0.04;
	const float Desaturation = 0.15;
	color *= toneMappingExposure;
	float x = min( color.r, min( color.g, color.b ) );
	float offset = x < 0.08 ? x - 6.25 * x * x : 0.04;
	color -= offset;
	float peak = max( color.r, max( color.g, color.b ) );
	if ( peak < StartCompression ) return color;
	float d = 1. - StartCompression;
	float newPeak = 1. - d * d / ( peak + d - StartCompression );
	color *= newPeak / peak;
	float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );
	return mix( color, vec3( newPeak ), g );
}
vec3 CustomToneMapping( vec3 color ) { return color; }`,AP=`#ifdef USE_TRANSMISSION
	material.transmission = transmission;
	material.transmissionAlpha = 1.0;
	material.thickness = thickness;
	material.attenuationDistance = attenuationDistance;
	material.attenuationColor = attenuationColor;
	#ifdef USE_TRANSMISSIONMAP
		material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;
	#endif
	#ifdef USE_THICKNESSMAP
		material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;
	#endif
	vec3 pos = vWorldPosition;
	vec3 v = normalize( cameraPosition - pos );
	vec3 n = inverseTransformDirection( normal, viewMatrix );
	vec4 transmitted = getIBLVolumeRefraction(
		n, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90,
		pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,
		material.attenuationColor, material.attenuationDistance );
	material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );
	totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );
#endif`,TP=`#ifdef USE_TRANSMISSION
	uniform float transmission;
	uniform float thickness;
	uniform float attenuationDistance;
	uniform vec3 attenuationColor;
	#ifdef USE_TRANSMISSIONMAP
		uniform sampler2D transmissionMap;
	#endif
	#ifdef USE_THICKNESSMAP
		uniform sampler2D thicknessMap;
	#endif
	uniform vec2 transmissionSamplerSize;
	uniform sampler2D transmissionSamplerMap;
	uniform mat4 modelMatrix;
	uniform mat4 projectionMatrix;
	varying vec3 vWorldPosition;
	float w0( float a ) {
		return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );
	}
	float w1( float a ) {
		return ( 1.0 / 6.0 ) * ( a *  a * ( 3.0 * a - 6.0 ) + 4.0 );
	}
	float w2( float a ){
		return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );
	}
	float w3( float a ) {
		return ( 1.0 / 6.0 ) * ( a * a * a );
	}
	float g0( float a ) {
		return w0( a ) + w1( a );
	}
	float g1( float a ) {
		return w2( a ) + w3( a );
	}
	float h0( float a ) {
		return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );
	}
	float h1( float a ) {
		return 1.0 + w3( a ) / ( w2( a ) + w3( a ) );
	}
	vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {
		uv = uv * texelSize.zw + 0.5;
		vec2 iuv = floor( uv );
		vec2 fuv = fract( uv );
		float g0x = g0( fuv.x );
		float g1x = g1( fuv.x );
		float h0x = h0( fuv.x );
		float h1x = h1( fuv.x );
		float h0y = h0( fuv.y );
		float h1y = h1( fuv.y );
		vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
		vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;
		vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
		vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;
		return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +
			g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );
	}
	vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {
		vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );
		vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );
		vec2 fLodSizeInv = 1.0 / fLodSize;
		vec2 cLodSizeInv = 1.0 / cLodSize;
		vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );
		vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );
		return mix( fSample, cSample, fract( lod ) );
	}
	vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {
		vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );
		vec3 modelScale;
		modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );
		modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );
		modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );
		return normalize( refractionVector ) * thickness * modelScale;
	}
	float applyIorToRoughness( const in float roughness, const in float ior ) {
		return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );
	}
	vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {
		float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );
		return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );
	}
	vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {
		if ( isinf( attenuationDistance ) ) {
			return vec3( 1.0 );
		} else {
			vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;
			vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );			return transmittance;
		}
	}
	vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,
		const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,
		const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,
		const in vec3 attenuationColor, const in float attenuationDistance ) {
		vec4 transmittedLight;
		vec3 transmittance;
		#ifdef USE_DISPERSION
			float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;
			vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );
			for ( int i = 0; i < 3; i ++ ) {
				vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );
				vec3 refractedRayExit = position + transmissionRay;
		
				vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
				vec2 refractionCoords = ndcPos.xy / ndcPos.w;
				refractionCoords += 1.0;
				refractionCoords /= 2.0;
		
				vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );
				transmittedLight[ i ] = transmissionSample[ i ];
				transmittedLight.a += transmissionSample.a;
				transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];
			}
			transmittedLight.a /= 3.0;
		
		#else
		
			vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
			vec3 refractedRayExit = position + transmissionRay;
			vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );
			vec2 refractionCoords = ndcPos.xy / ndcPos.w;
			refractionCoords += 1.0;
			refractionCoords /= 2.0;
			transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
			transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );
		
		#endif
		vec3 attenuatedColor = transmittance * transmittedLight.rgb;
		vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );
		float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;
		return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );
	}
#endif`,CP=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
	varying vec2 vUv;
#endif
#ifdef USE_MAP
	varying vec2 vMapUv;
#endif
#ifdef USE_ALPHAMAP
	varying vec2 vAlphaMapUv;
#endif
#ifdef USE_LIGHTMAP
	varying vec2 vLightMapUv;
#endif
#ifdef USE_AOMAP
	varying vec2 vAoMapUv;
#endif
#ifdef USE_BUMPMAP
	varying vec2 vBumpMapUv;
#endif
#ifdef USE_NORMALMAP
	varying vec2 vNormalMapUv;
#endif
#ifdef USE_EMISSIVEMAP
	varying vec2 vEmissiveMapUv;
#endif
#ifdef USE_METALNESSMAP
	varying vec2 vMetalnessMapUv;
#endif
#ifdef USE_ROUGHNESSMAP
	varying vec2 vRoughnessMapUv;
#endif
#ifdef USE_ANISOTROPYMAP
	varying vec2 vAnisotropyMapUv;
#endif
#ifdef USE_CLEARCOATMAP
	varying vec2 vClearcoatMapUv;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	varying vec2 vClearcoatNormalMapUv;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	varying vec2 vClearcoatRoughnessMapUv;
#endif
#ifdef USE_IRIDESCENCEMAP
	varying vec2 vIridescenceMapUv;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	varying vec2 vIridescenceThicknessMapUv;
#endif
#ifdef USE_SHEEN_COLORMAP
	varying vec2 vSheenColorMapUv;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
	varying vec2 vSheenRoughnessMapUv;
#endif
#ifdef USE_SPECULARMAP
	varying vec2 vSpecularMapUv;
#endif
#ifdef USE_SPECULAR_COLORMAP
	varying vec2 vSpecularColorMapUv;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
	varying vec2 vSpecularIntensityMapUv;
#endif
#ifdef USE_TRANSMISSIONMAP
	uniform mat3 transmissionMapTransform;
	varying vec2 vTransmissionMapUv;
#endif
#ifdef USE_THICKNESSMAP
	uniform mat3 thicknessMapTransform;
	varying vec2 vThicknessMapUv;
#endif`,RP=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
	varying vec2 vUv;
#endif
#ifdef USE_MAP
	uniform mat3 mapTransform;
	varying vec2 vMapUv;
#endif
#ifdef USE_ALPHAMAP
	uniform mat3 alphaMapTransform;
	varying vec2 vAlphaMapUv;
#endif
#ifdef USE_LIGHTMAP
	uniform mat3 lightMapTransform;
	varying vec2 vLightMapUv;
#endif
#ifdef USE_AOMAP
	uniform mat3 aoMapTransform;
	varying vec2 vAoMapUv;
#endif
#ifdef USE_BUMPMAP
	uniform mat3 bumpMapTransform;
	varying vec2 vBumpMapUv;
#endif
#ifdef USE_NORMALMAP
	uniform mat3 normalMapTransform;
	varying vec2 vNormalMapUv;
#endif
#ifdef USE_DISPLACEMENTMAP
	uniform mat3 displacementMapTransform;
	varying vec2 vDisplacementMapUv;
#endif
#ifdef USE_EMISSIVEMAP
	uniform mat3 emissiveMapTransform;
	varying vec2 vEmissiveMapUv;
#endif
#ifdef USE_METALNESSMAP
	uniform mat3 metalnessMapTransform;
	varying vec2 vMetalnessMapUv;
#endif
#ifdef USE_ROUGHNESSMAP
	uniform mat3 roughnessMapTransform;
	varying vec2 vRoughnessMapUv;
#endif
#ifdef USE_ANISOTROPYMAP
	uniform mat3 anisotropyMapTransform;
	varying vec2 vAnisotropyMapUv;
#endif
#ifdef USE_CLEARCOATMAP
	uniform mat3 clearcoatMapTransform;
	varying vec2 vClearcoatMapUv;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	uniform mat3 clearcoatNormalMapTransform;
	varying vec2 vClearcoatNormalMapUv;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	uniform mat3 clearcoatRoughnessMapTransform;
	varying vec2 vClearcoatRoughnessMapUv;
#endif
#ifdef USE_SHEEN_COLORMAP
	uniform mat3 sheenColorMapTransform;
	varying vec2 vSheenColorMapUv;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
	uniform mat3 sheenRoughnessMapTransform;
	varying vec2 vSheenRoughnessMapUv;
#endif
#ifdef USE_IRIDESCENCEMAP
	uniform mat3 iridescenceMapTransform;
	varying vec2 vIridescenceMapUv;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	uniform mat3 iridescenceThicknessMapTransform;
	varying vec2 vIridescenceThicknessMapUv;
#endif
#ifdef USE_SPECULARMAP
	uniform mat3 specularMapTransform;
	varying vec2 vSpecularMapUv;
#endif
#ifdef USE_SPECULAR_COLORMAP
	uniform mat3 specularColorMapTransform;
	varying vec2 vSpecularColorMapUv;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
	uniform mat3 specularIntensityMapTransform;
	varying vec2 vSpecularIntensityMapUv;
#endif
#ifdef USE_TRANSMISSIONMAP
	uniform mat3 transmissionMapTransform;
	varying vec2 vTransmissionMapUv;
#endif
#ifdef USE_THICKNESSMAP
	uniform mat3 thicknessMapTransform;
	varying vec2 vThicknessMapUv;
#endif`,PP=`#if defined( USE_UV ) || defined( USE_ANISOTROPY )
	vUv = vec3( uv, 1 ).xy;
#endif
#ifdef USE_MAP
	vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ALPHAMAP
	vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_LIGHTMAP
	vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_AOMAP
	vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_BUMPMAP
	vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_NORMALMAP
	vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_DISPLACEMENTMAP
	vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_EMISSIVEMAP
	vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_METALNESSMAP
	vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ROUGHNESSMAP
	vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_ANISOTROPYMAP
	vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOATMAP
	vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOAT_NORMALMAP
	vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_CLEARCOAT_ROUGHNESSMAP
	vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_IRIDESCENCEMAP
	vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
	vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SHEEN_COLORMAP
	vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SHEEN_ROUGHNESSMAP
	vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULARMAP
	vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULAR_COLORMAP
	vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_SPECULAR_INTENSITYMAP
	vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_TRANSMISSIONMAP
	vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;
#endif
#ifdef USE_THICKNESSMAP
	vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;
#endif`,IP=`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0
	vec4 worldPosition = vec4( transformed, 1.0 );
	#ifdef USE_BATCHING
		worldPosition = batchingMatrix * worldPosition;
	#endif
	#ifdef USE_INSTANCING
		worldPosition = instanceMatrix * worldPosition;
	#endif
	worldPosition = modelMatrix * worldPosition;
#endif`,NP=`varying vec2 vUv;
uniform mat3 uvTransform;
void main() {
	vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
	gl_Position = vec4( position.xy, 1.0, 1.0 );
}`,LP=`uniform sampler2D t2D;
uniform float backgroundIntensity;
varying vec2 vUv;
void main() {
	vec4 texColor = texture2D( t2D, vUv );
	#ifdef DECODE_VIDEO_TEXTURE
		texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );
	#endif
	texColor.rgb *= backgroundIntensity;
	gl_FragColor = texColor;
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`,kP=`varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
	gl_Position.z = gl_Position.w;
}`,OP=`#ifdef ENVMAP_TYPE_CUBE
	uniform samplerCube envMap;
#elif defined( ENVMAP_TYPE_CUBE_UV )
	uniform sampler2D envMap;
#endif
uniform float flipEnvMap;
uniform float backgroundBlurriness;
uniform float backgroundIntensity;
uniform mat3 backgroundRotation;
varying vec3 vWorldDirection;
#include <cube_uv_reflection_fragment>
void main() {
	#ifdef ENVMAP_TYPE_CUBE
		vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );
	#elif defined( ENVMAP_TYPE_CUBE_UV )
		vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );
	#else
		vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );
	#endif
	texColor.rgb *= backgroundIntensity;
	gl_FragColor = texColor;
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`,DP=`varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
	gl_Position.z = gl_Position.w;
}`,UP=`uniform samplerCube tCube;
uniform float tFlip;
uniform float opacity;
varying vec3 vWorldDirection;
void main() {
	vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );
	gl_FragColor = texColor;
	gl_FragColor.a *= opacity;
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`,FP=`#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
varying vec2 vHighPrecisionZW;
void main() {
	#include <uv_vertex>
	#include <batching_vertex>
	#include <skinbase_vertex>
	#include <morphinstance_vertex>
	#ifdef USE_DISPLACEMENTMAP
		#include <beginnormal_vertex>
		#include <morphnormal_vertex>
		#include <skinnormal_vertex>
	#endif
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vHighPrecisionZW = gl_Position.zw;
}`,zP=`#if DEPTH_PACKING == 3200
	uniform float opacity;
#endif
#include <common>
#include <packing>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
varying vec2 vHighPrecisionZW;
void main() {
	vec4 diffuseColor = vec4( 1.0 );
	#include <clipping_planes_fragment>
	#if DEPTH_PACKING == 3200
		diffuseColor.a = opacity;
	#endif
	#include <map_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <logdepthbuf_fragment>
	float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;
	#if DEPTH_PACKING == 3200
		gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );
	#elif DEPTH_PACKING == 3201
		gl_FragColor = packDepthToRGBA( fragCoordZ );
	#elif DEPTH_PACKING == 3202
		gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );
	#elif DEPTH_PACKING == 3203
		gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );
	#endif
}`,BP=`#define DISTANCE
varying vec3 vWorldPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <batching_vertex>
	#include <skinbase_vertex>
	#include <morphinstance_vertex>
	#ifdef USE_DISPLACEMENTMAP
		#include <beginnormal_vertex>
		#include <morphnormal_vertex>
		#include <skinnormal_vertex>
	#endif
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <worldpos_vertex>
	#include <clipping_planes_vertex>
	vWorldPosition = worldPosition.xyz;
}`,jP=`#define DISTANCE
uniform vec3 referencePosition;
uniform float nearDistance;
uniform float farDistance;
varying vec3 vWorldPosition;
#include <common>
#include <packing>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <clipping_planes_pars_fragment>
void main () {
	vec4 diffuseColor = vec4( 1.0 );
	#include <clipping_planes_fragment>
	#include <map_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	float dist = length( vWorldPosition - referencePosition );
	dist = ( dist - nearDistance ) / ( farDistance - nearDistance );
	dist = saturate( dist );
	gl_FragColor = packDepthToRGBA( dist );
}`,VP=`varying vec3 vWorldDirection;
#include <common>
void main() {
	vWorldDirection = transformDirection( position, modelMatrix );
	#include <begin_vertex>
	#include <project_vertex>
}`,HP=`uniform sampler2D tEquirect;
varying vec3 vWorldDirection;
#include <common>
void main() {
	vec3 direction = normalize( vWorldDirection );
	vec2 sampleUV = equirectUv( direction );
	gl_FragColor = texture2D( tEquirect, sampleUV );
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
}`,GP=`uniform float scale;
attribute float lineDistance;
varying float vLineDistance;
#include <common>
#include <uv_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	vLineDistance = scale * lineDistance;
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <fog_vertex>
}`,WP=`uniform vec3 diffuse;
uniform float opacity;
uniform float dashSize;
uniform float totalSize;
varying float vLineDistance;
#include <common>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	if ( mod( vLineDistance, totalSize ) > dashSize ) {
		discard;
	}
	vec3 outgoingLight = vec3( 0.0 );
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	outgoingLight = diffuseColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
}`,XP=`#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )
		#include <beginnormal_vertex>
		#include <morphnormal_vertex>
		#include <skinbase_vertex>
		#include <skinnormal_vertex>
		#include <defaultnormal_vertex>
	#endif
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <worldpos_vertex>
	#include <envmap_vertex>
	#include <fog_vertex>
}`,YP=`uniform vec3 diffuse;
uniform float opacity;
#ifndef FLAT_SHADED
	varying vec3 vNormal;
#endif
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <fog_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <specularmap_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	#ifdef USE_LIGHTMAP
		vec4 lightMapTexel = texture2D( lightMap, vLightMapUv );
		reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;
	#else
		reflectedLight.indirectDiffuse += vec3( 1.0 );
	#endif
	#include <aomap_fragment>
	reflectedLight.indirectDiffuse *= diffuseColor.rgb;
	vec3 outgoingLight = reflectedLight.indirectDiffuse;
	#include <envmap_fragment>
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`,qP=`#define LAMBERT
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <envmap_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`,KP=`#define LAMBERT
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float opacity;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_lambert_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <specularmap_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_lambert_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
	#include <envmap_fragment>
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`,ZP=`#define MATCAP
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <color_pars_vertex>
#include <displacementmap_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <fog_vertex>
	vViewPosition = - mvPosition.xyz;
}`,$P=`#define MATCAP
uniform vec3 diffuse;
uniform float opacity;
uniform sampler2D matcap;
varying vec3 vViewPosition;
#include <common>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <normal_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	vec3 viewDir = normalize( vViewPosition );
	vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );
	vec3 y = cross( viewDir, x );
	vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;
	#ifdef USE_MATCAP
		vec4 matcapColor = texture2D( matcap, uv );
	#else
		vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );
	#endif
	vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`,JP=`#define NORMAL
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
	varying vec3 vViewPosition;
#endif
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphinstance_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
	vViewPosition = - mvPosition.xyz;
#endif
}`,QP=`#define NORMAL
uniform float opacity;
#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )
	varying vec3 vViewPosition;
#endif
#include <packing>
#include <uv_pars_fragment>
#include <normal_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );
	#include <clipping_planes_fragment>
	#include <logdepthbuf_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	gl_FragColor = vec4( packNormalToRGB( normal ), diffuseColor.a );
	#ifdef OPAQUE
		gl_FragColor.a = 1.0;
	#endif
}`,eI=`#define PHONG
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <envmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphinstance_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <envmap_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`,tI=`#define PHONG
uniform vec3 diffuse;
uniform vec3 emissive;
uniform vec3 specular;
uniform float shininess;
uniform float opacity;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_phong_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <specularmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <specularmap_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_phong_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;
	#include <envmap_fragment>
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`,rI=`#define STANDARD
varying vec3 vViewPosition;
#ifdef USE_TRANSMISSION
	varying vec3 vWorldPosition;
#endif
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
#ifdef USE_TRANSMISSION
	vWorldPosition = worldPosition.xyz;
#endif
}`,iI=`#define STANDARD
#ifdef PHYSICAL
	#define IOR
	#define USE_SPECULAR
#endif
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float roughness;
uniform float metalness;
uniform float opacity;
#ifdef IOR
	uniform float ior;
#endif
#ifdef USE_SPECULAR
	uniform float specularIntensity;
	uniform vec3 specularColor;
	#ifdef USE_SPECULAR_COLORMAP
		uniform sampler2D specularColorMap;
	#endif
	#ifdef USE_SPECULAR_INTENSITYMAP
		uniform sampler2D specularIntensityMap;
	#endif
#endif
#ifdef USE_CLEARCOAT
	uniform float clearcoat;
	uniform float clearcoatRoughness;
#endif
#ifdef USE_DISPERSION
	uniform float dispersion;
#endif
#ifdef USE_IRIDESCENCE
	uniform float iridescence;
	uniform float iridescenceIOR;
	uniform float iridescenceThicknessMinimum;
	uniform float iridescenceThicknessMaximum;
#endif
#ifdef USE_SHEEN
	uniform vec3 sheenColor;
	uniform float sheenRoughness;
	#ifdef USE_SHEEN_COLORMAP
		uniform sampler2D sheenColorMap;
	#endif
	#ifdef USE_SHEEN_ROUGHNESSMAP
		uniform sampler2D sheenRoughnessMap;
	#endif
#endif
#ifdef USE_ANISOTROPY
	uniform vec2 anisotropyVector;
	#ifdef USE_ANISOTROPYMAP
		uniform sampler2D anisotropyMap;
	#endif
#endif
varying vec3 vViewPosition;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <iridescence_fragment>
#include <cube_uv_reflection_fragment>
#include <envmap_common_pars_fragment>
#include <envmap_physical_pars_fragment>
#include <fog_pars_fragment>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_physical_pars_fragment>
#include <transmission_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <clearcoat_pars_fragment>
#include <iridescence_pars_fragment>
#include <roughnessmap_pars_fragment>
#include <metalnessmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <roughnessmap_fragment>
	#include <metalnessmap_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <clearcoat_normal_fragment_begin>
	#include <clearcoat_normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_physical_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;
	vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;
	#include <transmission_fragment>
	vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;
	#ifdef USE_SHEEN
		float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );
		outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;
	#endif
	#ifdef USE_CLEARCOAT
		float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );
		vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );
		outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;
	#endif
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`,nI=`#define TOON
varying vec3 vViewPosition;
#include <common>
#include <batching_pars_vertex>
#include <uv_pars_vertex>
#include <displacementmap_pars_vertex>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <normal_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <shadowmap_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <normal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <displacementmap_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	vViewPosition = - mvPosition.xyz;
	#include <worldpos_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`,sI=`#define TOON
uniform vec3 diffuse;
uniform vec3 emissive;
uniform float opacity;
#include <common>
#include <packing>
#include <dithering_pars_fragment>
#include <color_pars_fragment>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <aomap_pars_fragment>
#include <lightmap_pars_fragment>
#include <emissivemap_pars_fragment>
#include <gradientmap_pars_fragment>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <normal_pars_fragment>
#include <lights_toon_pars_fragment>
#include <shadowmap_pars_fragment>
#include <bumpmap_pars_fragment>
#include <normalmap_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
	vec3 totalEmissiveRadiance = emissive;
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <color_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	#include <normal_fragment_begin>
	#include <normal_fragment_maps>
	#include <emissivemap_fragment>
	#include <lights_toon_fragment>
	#include <lights_fragment_begin>
	#include <lights_fragment_maps>
	#include <lights_fragment_end>
	#include <aomap_fragment>
	vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
	#include <dithering_fragment>
}`,aI=`uniform float size;
uniform float scale;
#include <common>
#include <color_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
#ifdef USE_POINTS_UV
	varying vec2 vUv;
	uniform mat3 uvTransform;
#endif
void main() {
	#ifdef USE_POINTS_UV
		vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
	#endif
	#include <color_vertex>
	#include <morphinstance_vertex>
	#include <morphcolor_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <project_vertex>
	gl_PointSize = size;
	#ifdef USE_SIZEATTENUATION
		bool isPerspective = isPerspectiveMatrix( projectionMatrix );
		if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );
	#endif
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <worldpos_vertex>
	#include <fog_vertex>
}`,oI=`uniform vec3 diffuse;
uniform float opacity;
#include <common>
#include <color_pars_fragment>
#include <map_particle_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	vec3 outgoingLight = vec3( 0.0 );
	#include <logdepthbuf_fragment>
	#include <map_particle_fragment>
	#include <color_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	outgoingLight = diffuseColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
	#include <premultiplied_alpha_fragment>
}`,lI=`#include <common>
#include <batching_pars_vertex>
#include <fog_pars_vertex>
#include <morphtarget_pars_vertex>
#include <skinning_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <shadowmap_pars_vertex>
void main() {
	#include <batching_vertex>
	#include <beginnormal_vertex>
	#include <morphinstance_vertex>
	#include <morphnormal_vertex>
	#include <skinbase_vertex>
	#include <skinnormal_vertex>
	#include <defaultnormal_vertex>
	#include <begin_vertex>
	#include <morphtarget_vertex>
	#include <skinning_vertex>
	#include <project_vertex>
	#include <logdepthbuf_vertex>
	#include <worldpos_vertex>
	#include <shadowmap_vertex>
	#include <fog_vertex>
}`,cI=`uniform vec3 color;
uniform float opacity;
#include <common>
#include <packing>
#include <fog_pars_fragment>
#include <bsdfs>
#include <lights_pars_begin>
#include <logdepthbuf_pars_fragment>
#include <shadowmap_pars_fragment>
#include <shadowmask_pars_fragment>
void main() {
	#include <logdepthbuf_fragment>
	gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
}`,hI=`uniform float rotation;
uniform vec2 center;
#include <common>
#include <uv_pars_vertex>
#include <fog_pars_vertex>
#include <logdepthbuf_pars_vertex>
#include <clipping_planes_pars_vertex>
void main() {
	#include <uv_vertex>
	vec4 mvPosition = modelViewMatrix[ 3 ];
	vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );
	#ifndef USE_SIZEATTENUATION
		bool isPerspective = isPerspectiveMatrix( projectionMatrix );
		if ( isPerspective ) scale *= - mvPosition.z;
	#endif
	vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale;
	vec2 rotatedPosition;
	rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;
	rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;
	mvPosition.xy += rotatedPosition;
	gl_Position = projectionMatrix * mvPosition;
	#include <logdepthbuf_vertex>
	#include <clipping_planes_vertex>
	#include <fog_vertex>
}`,uI=`uniform vec3 diffuse;
uniform float opacity;
#include <common>
#include <uv_pars_fragment>
#include <map_pars_fragment>
#include <alphamap_pars_fragment>
#include <alphatest_pars_fragment>
#include <alphahash_pars_fragment>
#include <fog_pars_fragment>
#include <logdepthbuf_pars_fragment>
#include <clipping_planes_pars_fragment>
void main() {
	vec4 diffuseColor = vec4( diffuse, opacity );
	#include <clipping_planes_fragment>
	vec3 outgoingLight = vec3( 0.0 );
	#include <logdepthbuf_fragment>
	#include <map_fragment>
	#include <alphamap_fragment>
	#include <alphatest_fragment>
	#include <alphahash_fragment>
	outgoingLight = diffuseColor.rgb;
	#include <opaque_fragment>
	#include <tonemapping_fragment>
	#include <colorspace_fragment>
	#include <fog_fragment>
}`,ai={alphahash_fragment:LC,alphahash_pars_fragment:kC,alphamap_fragment:OC,alphamap_pars_fragment:DC,alphatest_fragment:UC,alphatest_pars_fragment:FC,aomap_fragment:zC,aomap_pars_fragment:BC,batching_pars_vertex:jC,batching_vertex:VC,begin_vertex:HC,beginnormal_vertex:GC,bsdfs:WC,iridescence_fragment:XC,bumpmap_pars_fragment:YC,clipping_planes_fragment:qC,clipping_planes_pars_fragment:KC,clipping_planes_pars_vertex:ZC,clipping_planes_vertex:$C,color_fragment:JC,color_pars_fragment:QC,color_pars_vertex:eR,color_vertex:tR,common:rR,cube_uv_reflection_fragment:iR,defaultnormal_vertex:nR,displacementmap_pars_vertex:sR,displacementmap_vertex:aR,emissivemap_fragment:oR,emissivemap_pars_fragment:lR,colorspace_fragment:cR,colorspace_pars_fragment:hR,envmap_fragment:uR,envmap_common_pars_fragment:dR,envmap_pars_fragment:pR,envmap_pars_vertex:fR,envmap_physical_pars_fragment:MR,envmap_vertex:mR,fog_vertex:gR,fog_pars_vertex:yR,fog_fragment:vR,fog_pars_fragment:xR,gradientmap_pars_fragment:bR,lightmap_pars_fragment:wR,lights_lambert_fragment:_R,lights_lambert_pars_fragment:ER,lights_pars_begin:SR,lights_toon_fragment:AR,lights_toon_pars_fragment:TR,lights_phong_fragment:CR,lights_phong_pars_fragment:RR,lights_physical_fragment:PR,lights_physical_pars_fragment:IR,lights_fragment_begin:NR,lights_fragment_maps:LR,lights_fragment_end:kR,logdepthbuf_fragment:OR,logdepthbuf_pars_fragment:DR,logdepthbuf_pars_vertex:UR,logdepthbuf_vertex:FR,map_fragment:zR,map_pars_fragment:BR,map_particle_fragment:jR,map_particle_pars_fragment:VR,metalnessmap_fragment:HR,metalnessmap_pars_fragment:GR,morphinstance_vertex:WR,morphcolor_vertex:XR,morphnormal_vertex:YR,morphtarget_pars_vertex:qR,morphtarget_vertex:KR,normal_fragment_begin:ZR,normal_fragment_maps:$R,normal_pars_fragment:JR,normal_pars_vertex:QR,normal_vertex:eP,normalmap_pars_fragment:tP,clearcoat_normal_fragment_begin:rP,clearcoat_normal_fragment_maps:iP,clearcoat_pars_fragment:nP,iridescence_pars_fragment:sP,opaque_fragment:aP,packing:oP,premultiplied_alpha_fragment:lP,project_vertex:cP,dithering_fragment:hP,dithering_pars_fragment:uP,roughnessmap_fragment:dP,roughnessmap_pars_fragment:pP,shadowmap_pars_fragment:fP,shadowmap_pars_vertex:mP,shadowmap_vertex:gP,shadowmask_pars_fragment:yP,skinbase_vertex:vP,skinning_pars_vertex:xP,skinning_vertex:bP,skinnormal_vertex:wP,specularmap_fragment:_P,specularmap_pars_fragment:EP,tonemapping_fragment:SP,tonemapping_pars_fragment:MP,transmission_fragment:AP,transmission_pars_fragment:TP,uv_pars_fragment:CP,uv_pars_vertex:RP,uv_vertex:PP,worldpos_vertex:IP,background_vert:NP,background_frag:LP,backgroundCube_vert:kP,backgroundCube_frag:OP,cube_vert:DP,cube_frag:UP,depth_vert:FP,depth_frag:zP,distanceRGBA_vert:BP,distanceRGBA_frag:jP,equirect_vert:VP,equirect_frag:HP,linedashed_vert:GP,linedashed_frag:WP,meshbasic_vert:XP,meshbasic_frag:YP,meshlambert_vert:qP,meshlambert_frag:KP,meshmatcap_vert:ZP,meshmatcap_frag:$P,meshnormal_vert:JP,meshnormal_frag:QP,meshphong_vert:eI,meshphong_frag:tI,meshphysical_vert:rI,meshphysical_frag:iI,meshtoon_vert:nI,meshtoon_frag:sI,points_vert:aI,points_frag:oI,shadow_vert:lI,shadow_frag:cI,sprite_vert:hI,sprite_frag:uI},vr={common:{diffuse:{value:new or(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new si},alphaMap:{value:null},alphaMapTransform:{value:new si},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new si}},envmap:{envMap:{value:null},envMapRotation:{value:new si},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new si}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new si}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new si},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new si},normalScale:{value:new Ft(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new si},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new si}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new si}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new si}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new or(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMap:{value:[]},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotShadowMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMap:{value:[]},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new or(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new si},alphaTest:{value:0},uvTransform:{value:new si}},sprite:{diffuse:{value:new or(16777215)},opacity:{value:1},center:{value:new Ft(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new si},alphaMap:{value:null},alphaMapTransform:{value:new si},alphaTest:{value:0}}},$s={basic:{uniforms:qn([vr.common,vr.specularmap,vr.envmap,vr.aomap,vr.lightmap,vr.fog]),vertexShader:ai.meshbasic_vert,fragmentShader:ai.meshbasic_frag},lambert:{uniforms:qn([vr.common,vr.specularmap,vr.envmap,vr.aomap,vr.lightmap,vr.emissivemap,vr.bumpmap,vr.normalmap,vr.displacementmap,vr.fog,vr.lights,{emissive:{value:new or(0)}}]),vertexShader:ai.meshlambert_vert,fragmentShader:ai.meshlambert_frag},phong:{uniforms:qn([vr.common,vr.specularmap,vr.envmap,vr.aomap,vr.lightmap,vr.emissivemap,vr.bumpmap,vr.normalmap,vr.displacementmap,vr.fog,vr.lights,{emissive:{value:new or(0)},specular:{value:new or(1118481)},shininess:{value:30}}]),vertexShader:ai.meshphong_vert,fragmentShader:ai.meshphong_frag},standard:{uniforms:qn([vr.common,vr.envmap,vr.aomap,vr.lightmap,vr.emissivemap,vr.bumpmap,vr.normalmap,vr.displacementmap,vr.roughnessmap,vr.metalnessmap,vr.fog,vr.lights,{emissive:{value:new or(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:ai.meshphysical_vert,fragmentShader:ai.meshphysical_frag},toon:{uniforms:qn([vr.common,vr.aomap,vr.lightmap,vr.emissivemap,vr.bumpmap,vr.normalmap,vr.displacementmap,vr.gradientmap,vr.fog,vr.lights,{emissive:{value:new or(0)}}]),vertexShader:ai.meshtoon_vert,fragmentShader:ai.meshtoon_frag},matcap:{uniforms:qn([vr.common,vr.bumpmap,vr.normalmap,vr.displacementmap,vr.fog,{matcap:{value:null}}]),vertexShader:ai.meshmatcap_vert,fragmentShader:ai.meshmatcap_frag},points:{uniforms:qn([vr.points,vr.fog]),vertexShader:ai.points_vert,fragmentShader:ai.points_frag},dashed:{uniforms:qn([vr.common,vr.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:ai.linedashed_vert,fragmentShader:ai.linedashed_frag},depth:{uniforms:qn([vr.common,vr.displacementmap]),vertexShader:ai.depth_vert,fragmentShader:ai.depth_frag},normal:{uniforms:qn([vr.common,vr.bumpmap,vr.normalmap,vr.displacementmap,{opacity:{value:1}}]),vertexShader:ai.meshnormal_vert,fragmentShader:ai.meshnormal_frag},sprite:{uniforms:qn([vr.sprite,vr.fog]),vertexShader:ai.sprite_vert,fragmentShader:ai.sprite_frag},background:{uniforms:{uvTransform:{value:new si},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:ai.background_vert,fragmentShader:ai.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new si}},vertexShader:ai.backgroundCube_vert,fragmentShader:ai.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:ai.cube_vert,fragmentShader:ai.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:ai.equirect_vert,fragmentShader:ai.equirect_frag},distanceRGBA:{uniforms:qn([vr.common,vr.displacementmap,{referencePosition:{value:new je},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:ai.distanceRGBA_vert,fragmentShader:ai.distanceRGBA_frag},shadow:{uniforms:qn([vr.lights,vr.fog,{color:{value:new or(0)},opacity:{value:1}}]),vertexShader:ai.shadow_vert,fragmentShader:ai.shadow_frag}};$s.physical={uniforms:qn([$s.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new si},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new si},clearcoatNormalScale:{value:new Ft(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new si},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new si},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new si},sheen:{value:0},sheenColor:{value:new or(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new si},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new si},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new si},transmissionSamplerSize:{value:new Ft},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new si},attenuationDistance:{value:0},attenuationColor:{value:new or(0)},specularColor:{value:new or(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new si},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new si},anisotropyVector:{value:new Ft},anisotropyMap:{value:null},anisotropyMapTransform:{value:new si}}]),vertexShader:ai.meshphysical_vert,fragmentShader:ai.meshphysical_frag};var af={r:0,b:0,g:0},hl=new Ys,dI=new Ir;function pI(e,t,r,i,n,s,a){let o=new or(0),l=s===!0?0:1,c,u,d=null,f=0,y=null;function b(E){let M=E.isScene===!0?E.background:null;return M&&M.isTexture&&(M=(E.backgroundBlurriness>0?r:t).get(M)),M}function x(E){let M=!1,P=b(E);P===null?v(o,l):P&&P.isColor&&(v(P,1),M=!0);let k=e.xr.getEnvironmentBlendMode();k==="additive"?i.buffers.color.setClear(0,0,0,1,a):k==="alpha-blend"&&i.buffers.color.setClear(0,0,0,0,a),(e.autoClear||M)&&(i.buffers.depth.setTest(!0),i.buffers.depth.setMask(!0),i.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))}function g(E,M){let P=b(M);P&&(P.isCubeTexture||P.mapping===vi)?(u===void 0&&(u=new qr(new Da(1,1,1),new ln({name:"BackgroundCubeMaterial",uniforms:ac($s.backgroundCube.uniforms),vertexShader:$s.backgroundCube.vertexShader,fragmentShader:$s.backgroundCube.fragmentShader,side:tt,depthTest:!1,depthWrite:!1,fog:!1})),u.geometry.deleteAttribute("normal"),u.geometry.deleteAttribute("uv"),u.onBeforeRender=function(k,z,D){this.matrixWorld.copyPosition(D.matrixWorld)},Object.defineProperty(u.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),n.update(u)),hl.copy(M.backgroundRotation),hl.x*=-1,hl.y*=-1,hl.z*=-1,P.isCubeTexture&&P.isRenderTargetTexture===!1&&(hl.y*=-1,hl.z*=-1),u.material.uniforms.envMap.value=P,u.material.uniforms.flipEnvMap.value=P.isCubeTexture&&P.isRenderTargetTexture===!1?-1:1,u.material.uniforms.backgroundBlurriness.value=M.backgroundBlurriness,u.material.uniforms.backgroundIntensity.value=M.backgroundIntensity,u.material.uniforms.backgroundRotation.value.setFromMatrix4(dI.makeRotationFromEuler(hl)),u.material.toneMapped=li.getTransfer(P.colorSpace)!==Ii,(d!==P||f!==P.version||y!==e.toneMapping)&&(u.material.needsUpdate=!0,d=P,f=P.version,y=e.toneMapping),u.layers.enableAll(),E.unshift(u,u.geometry,u.material,0,0,null)):P&&P.isTexture&&(c===void 0&&(c=new qr(new vc(2,2),new ln({name:"BackgroundMaterial",uniforms:ac($s.background.uniforms),vertexShader:$s.background.vertexShader,fragmentShader:$s.background.fragmentShader,side:Ce,depthTest:!1,depthWrite:!1,fog:!1})),c.geometry.deleteAttribute("normal"),Object.defineProperty(c.material,"map",{get:function(){return this.uniforms.t2D.value}}),n.update(c)),c.material.uniforms.t2D.value=P,c.material.uniforms.backgroundIntensity.value=M.backgroundIntensity,c.material.toneMapped=li.getTransfer(P.colorSpace)!==Ii,P.matrixAutoUpdate===!0&&P.updateMatrix(),c.material.uniforms.uvTransform.value.copy(P.matrix),(d!==P||f!==P.version||y!==e.toneMapping)&&(c.material.needsUpdate=!0,d=P,f=P.version,y=e.toneMapping),c.layers.enableAll(),E.unshift(c,c.geometry,c.material,0,0,null))}function v(E,M){E.getRGB(af,Zx(e)),i.buffers.color.setClear(af.r,af.g,af.b,M,a)}function _(){u!==void 0&&(u.geometry.dispose(),u.material.dispose()),c!==void 0&&(c.geometry.dispose(),c.material.dispose())}return{getClearColor:function(){return o},setClearColor:function(E,M=1){o.set(E),l=M,v(o,l)},getClearAlpha:function(){return l},setClearAlpha:function(E){l=E,v(o,l)},render:x,addToRenderList:g,dispose:_}}function fI(e,t){let r=e.getParameter(e.MAX_VERTEX_ATTRIBS),i={},n=f(null),s=n,a=!1;function o(L,Z,se,ce,fe){let ze=!1,Fe=d(ce,se,Z);s!==Fe&&(s=Fe,c(s.object)),ze=y(L,ce,se,fe),ze&&b(L,ce,se,fe),fe!==null&&t.update(fe,e.ELEMENT_ARRAY_BUFFER),(ze||a)&&(a=!1,M(L,Z,se,ce),fe!==null&&e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t.get(fe).buffer))}function l(){return e.createVertexArray()}function c(L){return e.bindVertexArray(L)}function u(L){return e.deleteVertexArray(L)}function d(L,Z,se){let ce=se.wireframe===!0,fe=i[L.id];fe===void 0&&(fe={},i[L.id]=fe);let ze=fe[Z.id];ze===void 0&&(ze={},fe[Z.id]=ze);let Fe=ze[ce];return Fe===void 0&&(Fe=f(l()),ze[ce]=Fe),Fe}function f(L){let Z=[],se=[],ce=[];for(let fe=0;fe<r;fe++)Z[fe]=0,se[fe]=0,ce[fe]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:Z,enabledAttributes:se,attributeDivisors:ce,object:L,attributes:{},index:null}}function y(L,Z,se,ce){let fe=s.attributes,ze=Z.attributes,Fe=0,Pe=se.getAttributes();for(let ue in Pe)if(Pe[ue].location>=0){let Te=fe[ue],de=ze[ue];if(de===void 0&&(ue==="instanceMatrix"&&L.instanceMatrix&&(de=L.instanceMatrix),ue==="instanceColor"&&L.instanceColor&&(de=L.instanceColor)),Te===void 0||Te.attribute!==de||de&&Te.data!==de.data)return!0;Fe++}return s.attributesNum!==Fe||s.index!==ce}function b(L,Z,se,ce){let fe={},ze=Z.attributes,Fe=0,Pe=se.getAttributes();for(let ue in Pe)if(Pe[ue].location>=0){let Te=ze[ue];Te===void 0&&(ue==="instanceMatrix"&&L.instanceMatrix&&(Te=L.instanceMatrix),ue==="instanceColor"&&L.instanceColor&&(Te=L.instanceColor));let de={};de.attribute=Te,Te&&Te.data&&(de.data=Te.data),fe[ue]=de,Fe++}s.attributes=fe,s.attributesNum=Fe,s.index=ce}function x(){let L=s.newAttributes;for(let Z=0,se=L.length;Z<se;Z++)L[Z]=0}function g(L){v(L,0)}function v(L,Z){let se=s.newAttributes,ce=s.enabledAttributes,fe=s.attributeDivisors;se[L]=1,ce[L]===0&&(e.enableVertexAttribArray(L),ce[L]=1),fe[L]!==Z&&(e.vertexAttribDivisor(L,Z),fe[L]=Z)}function _(){let L=s.newAttributes,Z=s.enabledAttributes;for(let se=0,ce=Z.length;se<ce;se++)Z[se]!==L[se]&&(e.disableVertexAttribArray(se),Z[se]=0)}function E(L,Z,se,ce,fe,ze,Fe){Fe===!0?e.vertexAttribIPointer(L,Z,se,fe,ze):e.vertexAttribPointer(L,Z,se,ce,fe,ze)}function M(L,Z,se,ce){x();let fe=ce.attributes,ze=se.getAttributes(),Fe=Z.defaultAttributeValues;for(let Pe in ze){let ue=ze[Pe];if(ue.location>=0){let Te=fe[Pe];if(Te===void 0&&(Pe==="instanceMatrix"&&L.instanceMatrix&&(Te=L.instanceMatrix),Pe==="instanceColor"&&L.instanceColor&&(Te=L.instanceColor)),Te!==void 0){let de=Te.normalized,Ie=Te.itemSize,Re=t.get(Te);if(Re===void 0)continue;let Be=Re.buffer,Se=Re.type,U=Re.bytesPerElement,ie=Se===e.INT||Se===e.UNSIGNED_INT||Te.gpuType===Do;if(Te.isInterleavedBufferAttribute){let Ae=Te.data,Ue=Ae.stride,Ge=Te.offset;if(Ae.isInstancedInterleavedBuffer){for(let nt=0;nt<ue.locationSize;nt++)v(ue.location+nt,Ae.meshPerAttribute);L.isInstancedMesh!==!0&&ce._maxInstanceCount===void 0&&(ce._maxInstanceCount=Ae.meshPerAttribute*Ae.count)}else for(let nt=0;nt<ue.locationSize;nt++)g(ue.location+nt);e.bindBuffer(e.ARRAY_BUFFER,Be);for(let nt=0;nt<ue.locationSize;nt++)E(ue.location+nt,Ie/ue.locationSize,Se,de,Ue*U,(Ge+Ie/ue.locationSize*nt)*U,ie)}else{if(Te.isInstancedBufferAttribute){for(let Ae=0;Ae<ue.locationSize;Ae++)v(ue.location+Ae,Te.meshPerAttribute);L.isInstancedMesh!==!0&&ce._maxInstanceCount===void 0&&(ce._maxInstanceCount=Te.meshPerAttribute*Te.count)}else for(let Ae=0;Ae<ue.locationSize;Ae++)g(ue.location+Ae);e.bindBuffer(e.ARRAY_BUFFER,Be);for(let Ae=0;Ae<ue.locationSize;Ae++)E(ue.location+Ae,Ie/ue.locationSize,Se,de,Ie*U,Ie/ue.locationSize*Ae*U,ie)}}else if(Fe!==void 0){let de=Fe[Pe];if(de!==void 0)switch(de.length){case 2:e.vertexAttrib2fv(ue.location,de);break;case 3:e.vertexAttrib3fv(ue.location,de);break;case 4:e.vertexAttrib4fv(ue.location,de);break;default:e.vertexAttrib1fv(ue.location,de)}}}}_()}function P(){D();for(let L in i){let Z=i[L];for(let se in Z){let ce=Z[se];for(let fe in ce)u(ce[fe].object),delete ce[fe];delete Z[se]}delete i[L]}}function k(L){if(i[L.id]===void 0)return;let Z=i[L.id];for(let se in Z){let ce=Z[se];for(let fe in ce)u(ce[fe].object),delete ce[fe];delete Z[se]}delete i[L.id]}function z(L){for(let Z in i){let se=i[Z];if(se[L.id]===void 0)continue;let ce=se[L.id];for(let fe in ce)u(ce[fe].object),delete ce[fe];delete se[L.id]}}function D(){I(),a=!0,s!==n&&(s=n,c(s.object))}function I(){n.geometry=null,n.program=null,n.wireframe=!1}return{setup:o,reset:D,resetDefaultState:I,dispose:P,releaseStatesOfGeometry:k,releaseStatesOfProgram:z,initAttributes:x,enableAttribute:g,disableUnusedAttributes:_}}function mI(e,t,r){let i;function n(c){i=c}function s(c,u){e.drawArrays(i,c,u),r.update(u,i,1)}function a(c,u,d){d!==0&&(e.drawArraysInstanced(i,c,u,d),r.update(u,i,d))}function o(c,u,d){if(d===0)return;t.get("WEBGL_multi_draw").multiDrawArraysWEBGL(i,c,0,u,0,d);let f=0;for(let y=0;y<d;y++)f+=u[y];r.update(f,i,1)}function l(c,u,d,f){if(d===0)return;let y=t.get("WEBGL_multi_draw");if(y===null)for(let b=0;b<c.length;b++)a(c[b],u[b],f[b]);else{y.multiDrawArraysInstancedWEBGL(i,c,0,u,0,f,0,d);let b=0;for(let x=0;x<d;x++)b+=u[x]*f[x];r.update(b,i,1)}}this.setMode=n,this.render=s,this.renderInstances=a,this.renderMultiDraw=o,this.renderMultiDrawInstances=l}function gI(e,t,r,i){let n;function s(){if(n!==void 0)return n;if(t.has("EXT_texture_filter_anisotropic")===!0){let z=t.get("EXT_texture_filter_anisotropic");n=e.getParameter(z.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else n=0;return n}function a(z){return!(z!==Ln&&i.convert(z)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT))}function o(z){let D=z===Ts&&(t.has("EXT_color_buffer_half_float")||t.has("EXT_color_buffer_float"));return!(z!==Ji&&i.convert(z)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)&&z!==es&&!D)}function l(z){if(z==="highp"){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return"highp";z="mediump"}return z==="mediump"&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?"mediump":"lowp"}let c=r.precision!==void 0?r.precision:"highp",u=l(c);u!==c&&(console.warn("THREE.WebGLRenderer:",c,"not supported, using",u,"instead."),c=u);let d=r.logarithmicDepthBuffer===!0,f=r.reverseDepthBuffer===!0&&t.has("EXT_clip_control"),y=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),b=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),x=e.getParameter(e.MAX_TEXTURE_SIZE),g=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),v=e.getParameter(e.MAX_VERTEX_ATTRIBS),_=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),E=e.getParameter(e.MAX_VARYING_VECTORS),M=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),P=b>0,k=e.getParameter(e.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:s,getMaxPrecision:l,textureFormatReadable:a,textureTypeReadable:o,precision:c,logarithmicDepthBuffer:d,reverseDepthBuffer:f,maxTextures:y,maxVertexTextures:b,maxTextureSize:x,maxCubemapSize:g,maxAttributes:v,maxVertexUniforms:_,maxVaryings:E,maxFragmentUniforms:M,vertexTextures:P,maxSamples:k}}function yI(e){let t=this,r=null,i=0,n=!1,s=!1,a=new Ua,o=new si,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(d,f){let y=d.length!==0||f||i!==0||n;return n=f,i=d.length,y},this.beginShadows=function(){s=!0,u(null)},this.endShadows=function(){s=!1},this.setGlobalState=function(d,f){r=u(d,f,0)},this.setState=function(d,f,y){let b=d.clippingPlanes,x=d.clipIntersection,g=d.clipShadows,v=e.get(d);if(!n||b===null||b.length===0||s&&!g)s?u(null):c();else{let _=s?0:i,E=_*4,M=v.clippingState||null;l.value=M,M=u(b,f,E,y);for(let P=0;P!==E;++P)M[P]=r[P];v.clippingState=M,this.numIntersection=x?this.numPlanes:0,this.numPlanes+=_}};function c(){l.value!==r&&(l.value=r,l.needsUpdate=i>0),t.numPlanes=i,t.numIntersection=0}function u(d,f,y,b){let x=d!==null?d.length:0,g=null;if(x!==0){if(g=l.value,b!==!0||g===null){let v=y+x*4,_=f.matrixWorldInverse;o.getNormalMatrix(_),(g===null||g.length<v)&&(g=new Float32Array(v));for(let E=0,M=y;E!==x;++E,M+=4)a.copy(d[E]).applyMatrix4(_,o),a.normal.toArray(g,M),g[M+3]=a.constant}l.value=g,l.needsUpdate=!0}return t.numPlanes=x,t.numIntersection=0,g}}function vI(e){let t=new WeakMap;function r(a,o){return o===an?a.mapping=br:o===Rn&&(a.mapping=wi),a}function i(a){if(a&&a.isTexture){let o=a.mapping;if(o===an||o===Rn)if(t.has(a)){let l=t.get(a).texture;return r(l,a.mapping)}else{let l=a.image;if(l&&l.height>0){let c=new eb(l.height);return c.fromEquirectangularTexture(e,a),t.set(a,c),a.addEventListener("dispose",n),r(c.texture,a.mapping)}else return null}}return a}function n(a){let o=a.target;o.removeEventListener("dispose",n);let l=t.get(o);l!==void 0&&(t.delete(o),l.dispose())}function s(){t=new WeakMap}return{get:i,dispose:s}}var _c=4,j1=[.125,.215,.35,.446,.526,.582],ul=20,Iy=new wc,V1=new or,Ny=null,Ly=0,ky=0,Oy=!1,dl=(1+Math.sqrt(5))/2,Ec=1/dl,H1=[new je(-dl,Ec,0),new je(dl,Ec,0),new je(-Ec,0,dl),new je(Ec,0,dl),new je(0,dl,-Ec),new je(0,dl,Ec),new je(-1,1,-1),new je(1,1,-1),new je(-1,1,1),new je(1,1,1)],of=class{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._lodPlanes=[],this._sizeLods=[],this._sigmas=[],this._blurMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._compileMaterial(this._blurMaterial)}fromScene(e,t=0,r=.1,i=100){Ny=this._renderer.getRenderTarget(),Ly=this._renderer.getActiveCubeFace(),ky=this._renderer.getActiveMipmapLevel(),Oy=this._renderer.xr.enabled,this._renderer.xr.enabled=!1,this._setSize(256);let n=this._allocateTargets();return n.depthBuffer=!0,this._sceneToCubeUV(e,r,i,n),t>0&&this._blur(n,0,0,t),this._applyPMREM(n),this._cleanup(n),n}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=X1(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=W1(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose()}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodPlanes.length;e++)this._lodPlanes[e].dispose()}_cleanup(e){this._renderer.setRenderTarget(Ny,Ly,ky),this._renderer.xr.enabled=Oy,e.scissorTest=!1,lf(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===br||e.mapping===wi?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),Ny=this._renderer.getRenderTarget(),Ly=this._renderer.getActiveCubeFace(),ky=this._renderer.getActiveMipmapLevel(),Oy=this._renderer.xr.enabled,this._renderer.xr.enabled=!1;let r=t||this._allocateTargets();return this._textureToCubeUV(e,r),this._applyPMREM(r),this._cleanup(r),r}_allocateTargets(){let e=3*Math.max(this._cubeSize,112),t=4*this._cubeSize,r={magFilter:Pi,minFilter:Pi,generateMipmaps:!1,type:Ts,format:Ln,colorSpace:kn,depthBuffer:!1},i=G1(e,t,r);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=G1(e,t,r);let{_lodMax:n}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas}=xI(n)),this._blurMaterial=bI(n,e,t)}return i}_compileMaterial(e){let t=new qr(this._lodPlanes[0],e);this._renderer.compile(t,Iy)}_sceneToCubeUV(e,t,r,i){let n=new cn(90,1,t,r),s=[1,-1,1,1,1,1],a=[1,1,1,-1,-1,-1],o=this._renderer,l=o.autoClear,c=o.toneMapping;o.getClearColor(V1),o.toneMapping=hi,o.autoClear=!1;let u=new en({name:"PMREM.Background",side:tt,depthWrite:!1,depthTest:!1}),d=new qr(new Da,u),f=!1,y=e.background;y?y.isColor&&(u.color.copy(y),e.background=null,f=!0):(u.color.copy(V1),f=!0);for(let b=0;b<6;b++){let x=b%3;x===0?(n.up.set(0,s[b],0),n.lookAt(a[b],0,0)):x===1?(n.up.set(0,0,s[b]),n.lookAt(0,a[b],0)):(n.up.set(0,s[b],0),n.lookAt(0,0,a[b]));let g=this._cubeSize;lf(i,x*g,b>2?g:0,g,g),o.setRenderTarget(i),f&&o.render(d,n),o.render(e,n)}d.geometry.dispose(),d.material.dispose(),o.toneMapping=c,o.autoClear=l,e.background=y}_textureToCubeUV(e,t){let r=this._renderer,i=e.mapping===br||e.mapping===wi;i?(this._cubemapMaterial===null&&(this._cubemapMaterial=X1()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=W1());let n=i?this._cubemapMaterial:this._equirectMaterial,s=new qr(this._lodPlanes[0],n),a=n.uniforms;a.envMap.value=e;let o=this._cubeSize;lf(t,0,0,3*o,2*o),r.setRenderTarget(t),r.render(s,Iy)}_applyPMREM(e){let t=this._renderer,r=t.autoClear;t.autoClear=!1;let i=this._lodPlanes.length;for(let n=1;n<i;n++){let s=Math.sqrt(this._sigmas[n]*this._sigmas[n]-this._sigmas[n-1]*this._sigmas[n-1]),a=H1[(i-n-1)%H1.length];this._blur(e,n-1,n,s,a)}t.autoClear=r}_blur(e,t,r,i,n){let s=this._pingPongRenderTarget;this._halfBlur(e,s,t,r,i,"latitudinal",n),this._halfBlur(s,e,r,r,i,"longitudinal",n)}_halfBlur(e,t,r,i,n,s,a){let o=this._renderer,l=this._blurMaterial;s!=="latitudinal"&&s!=="longitudinal"&&console.error("blur direction must be either latitudinal or longitudinal!");let c=3,u=new qr(this._lodPlanes[i],l),d=l.uniforms,f=this._sizeLods[r]-1,y=isFinite(n)?Math.PI/(2*f):2*Math.PI/(2*ul-1),b=n/y,x=isFinite(n)?1+Math.floor(c*b):ul;x>ul&&console.warn(`sigmaRadians, ${n}, is too large and will clip, as it requested ${x} samples when the maximum is set to ${ul}`);let g=[],v=0;for(let k=0;k<ul;++k){let z=k/b,D=Math.exp(-z*z/2);g.push(D),k===0?v+=D:k<x&&(v+=2*D)}for(let k=0;k<g.length;k++)g[k]=g[k]/v;d.envMap.value=e.texture,d.samples.value=x,d.weights.value=g,d.latitudinal.value=s==="latitudinal",a&&(d.poleAxis.value=a);let{_lodMax:_}=this;d.dTheta.value=y,d.mipInt.value=_-r;let E=this._sizeLods[i],M=3*E*(i>_-_c?i-_+_c:0),P=4*(this._cubeSize-E);lf(t,M,P,3*E,2*E),o.setRenderTarget(t),o.render(u,Iy)}};function xI(e){let t=[],r=[],i=[],n=e,s=e-_c+1+j1.length;for(let a=0;a<s;a++){let o=Math.pow(2,n);r.push(o);let l=1/o;a>e-_c?l=j1[a-e+_c-1]:a===0&&(l=0),i.push(l);let c=1/(o-2),u=-c,d=1+c,f=[u,u,d,u,d,d,u,u,d,d,u,d],y=6,b=6,x=3,g=2,v=1,_=new Float32Array(x*b*y),E=new Float32Array(g*b*y),M=new Float32Array(v*b*y);for(let k=0;k<y;k++){let z=k%3*2/3-1,D=k>2?0:-1,I=[z,D,0,z+2/3,D,0,z+2/3,D+1,0,z,D,0,z+2/3,D+1,0,z,D+1,0];_.set(I,x*b*k),E.set(f,g*b*k);let L=[k,k,k,k,k,k];M.set(L,v*b*k)}let P=new Hr;P.setAttribute("position",new ui(_,x)),P.setAttribute("uv",new ui(E,g)),P.setAttribute("faceIndex",new ui(M,v)),t.push(P),n>_c&&n--}return{lodPlanes:t,sizeLods:r,sigmas:i}}function G1(e,t,r){let i=new In(e,t,r);return i.texture.mapping=vi,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function lf(e,t,r,i,n){e.viewport.set(t,r,i,n),e.scissor.set(t,r,i,n)}function bI(e,t,r){let i=new Float32Array(ul),n=new je(0,1,0);return new ln({name:"SphericalGaussianBlur",defines:{n:ul,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/r,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:i},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:n}},vertexShader:Dy(),fragmentShader:`

			precision mediump float;
			precision mediump int;

			varying vec3 vOutputDirection;

			uniform sampler2D envMap;
			uniform int samples;
			uniform float weights[ n ];
			uniform bool latitudinal;
			uniform float dTheta;
			uniform float mipInt;
			uniform vec3 poleAxis;

			#define ENVMAP_TYPE_CUBE_UV
			#include <cube_uv_reflection_fragment>

			vec3 getSample( float theta, vec3 axis ) {

				float cosTheta = cos( theta );
				// Rodrigues' axis-angle rotation
				vec3 sampleDirection = vOutputDirection * cosTheta
					+ cross( axis, vOutputDirection ) * sin( theta )
					+ axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );

				return bilinearCubeUV( envMap, sampleDirection, mipInt );

			}

			void main() {

				vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );

				if ( all( equal( axis, vec3( 0.0 ) ) ) ) {

					axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );

				}

				axis = normalize( axis );

				gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
				gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );

				for ( int i = 1; i < n; i++ ) {

					if ( i >= samples ) {

						break;

					}

					float theta = dTheta * float( i );
					gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
					gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );

				}

			}
		`,blending:Ye,depthTest:!1,depthWrite:!1})}function W1(){return new ln({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Dy(),fragmentShader:`

			precision mediump float;
			precision mediump int;

			varying vec3 vOutputDirection;

			uniform sampler2D envMap;

			#include <common>

			void main() {

				vec3 outputDirection = normalize( vOutputDirection );
				vec2 uv = equirectUv( outputDirection );

				gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );

			}
		`,blending:Ye,depthTest:!1,depthWrite:!1})}function X1(){return new ln({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Dy(),fragmentShader:`

			precision mediump float;
			precision mediump int;

			uniform float flipEnvMap;

			varying vec3 vOutputDirection;

			uniform samplerCube envMap;

			void main() {

				gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );

			}
		`,blending:Ye,depthTest:!1,depthWrite:!1})}function Dy(){return`

		precision mediump float;
		precision mediump int;

		attribute float faceIndex;

		varying vec3 vOutputDirection;

		// RH coordinate system; PMREM face-indexing convention
		vec3 getDirection( vec2 uv, float face ) {

			uv = 2.0 * uv - 1.0;

			vec3 direction = vec3( uv, 1.0 );

			if ( face == 0.0 ) {

				direction = direction.zyx; // ( 1, v, u ) pos x

			} else if ( face == 1.0 ) {

				direction = direction.xzy;
				direction.xz *= -1.0; // ( -u, 1, -v ) pos y

			} else if ( face == 2.0 ) {

				direction.x *= -1.0; // ( -u, v, 1 ) pos z

			} else if ( face == 3.0 ) {

				direction = direction.zyx;
				direction.xz *= -1.0; // ( -1, v, -u ) neg x

			} else if ( face == 4.0 ) {

				direction = direction.xzy;
				direction.xy *= -1.0; // ( -u, -1, v ) neg y

			} else if ( face == 5.0 ) {

				direction.z *= -1.0; // ( u, v, -1 ) neg z

			}

			return direction;

		}

		void main() {

			vOutputDirection = getDirection( uv, faceIndex );
			gl_Position = vec4( position, 1.0 );

		}
	`}function wI(e){let t=new WeakMap,r=null;function i(o){if(o&&o.isTexture){let l=o.mapping,c=l===an||l===Rn,u=l===br||l===wi;if(c||u){let d=t.get(o),f=d!==void 0?d.texture.pmremVersion:0;if(o.isRenderTargetTexture&&o.pmremVersion!==f)return r===null&&(r=new of(e)),d=c?r.fromEquirectangular(o,d):r.fromCubemap(o,d),d.texture.pmremVersion=o.pmremVersion,t.set(o,d),d.texture;if(d!==void 0)return d.texture;{let y=o.image;return c&&y&&y.height>0||u&&y&&n(y)?(r===null&&(r=new of(e)),d=c?r.fromEquirectangular(o):r.fromCubemap(o),d.texture.pmremVersion=o.pmremVersion,t.set(o,d),o.addEventListener("dispose",s),d.texture):null}}}return o}function n(o){let l=0,c=6;for(let u=0;u<c;u++)o[u]!==void 0&&l++;return l===c}function s(o){let l=o.target;l.removeEventListener("dispose",s);let c=t.get(l);c!==void 0&&(t.delete(l),c.dispose())}function a(){t=new WeakMap,r!==null&&(r.dispose(),r=null)}return{get:i,dispose:a}}function _I(e){let t={};function r(i){if(t[i]!==void 0)return t[i];let n;switch(i){case"WEBGL_depth_texture":n=e.getExtension("WEBGL_depth_texture")||e.getExtension("MOZ_WEBGL_depth_texture")||e.getExtension("WEBKIT_WEBGL_depth_texture");break;case"EXT_texture_filter_anisotropic":n=e.getExtension("EXT_texture_filter_anisotropic")||e.getExtension("MOZ_EXT_texture_filter_anisotropic")||e.getExtension("WEBKIT_EXT_texture_filter_anisotropic");break;case"WEBGL_compressed_texture_s3tc":n=e.getExtension("WEBGL_compressed_texture_s3tc")||e.getExtension("MOZ_WEBGL_compressed_texture_s3tc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_s3tc");break;case"WEBGL_compressed_texture_pvrtc":n=e.getExtension("WEBGL_compressed_texture_pvrtc")||e.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc");break;default:n=e.getExtension(i)}return t[i]=n,n}return{has:function(i){return r(i)!==null},init:function(){r("EXT_color_buffer_float"),r("WEBGL_clip_cull_distance"),r("OES_texture_float_linear"),r("EXT_color_buffer_half_float"),r("WEBGL_multisampled_render_to_texture"),r("WEBGL_render_shared_exponent")},get:function(i){let n=r(i);return n===null&&ql("THREE.WebGLRenderer: "+i+" extension not supported."),n}}}function EI(e,t,r,i){let n={},s=new WeakMap;function a(d){let f=d.target;f.index!==null&&t.remove(f.index);for(let b in f.attributes)t.remove(f.attributes[b]);f.removeEventListener("dispose",a),delete n[f.id];let y=s.get(f);y&&(t.remove(y),s.delete(f)),i.releaseStatesOfGeometry(f),f.isInstancedBufferGeometry===!0&&delete f._maxInstanceCount,r.memory.geometries--}function o(d,f){return n[f.id]===!0||(f.addEventListener("dispose",a),n[f.id]=!0,r.memory.geometries++),f}function l(d){let f=d.attributes;for(let y in f)t.update(f[y],e.ARRAY_BUFFER)}function c(d){let f=[],y=d.index,b=d.attributes.position,x=0;if(y!==null){let _=y.array;x=y.version;for(let E=0,M=_.length;E<M;E+=3){let P=_[E+0],k=_[E+1],z=_[E+2];f.push(P,k,k,z,z,P)}}else if(b!==void 0){let _=b.array;x=b.version;for(let E=0,M=_.length/3-1;E<M;E+=3){let P=E+0,k=E+1,z=E+2;f.push(P,k,k,z,z,P)}}else return;let g=new(Px(f)?Pg:Rg)(f,1);g.version=x;let v=s.get(d);v&&t.remove(v),s.set(d,g)}function u(d){let f=s.get(d);if(f){let y=d.index;y!==null&&f.version<y.version&&c(d)}else c(d);return s.get(d)}return{get:o,update:l,getWireframeAttribute:u}}function SI(e,t,r){let i;function n(f){i=f}let s,a;function o(f){s=f.type,a=f.bytesPerElement}function l(f,y){e.drawElements(i,y,s,f*a),r.update(y,i,1)}function c(f,y,b){b!==0&&(e.drawElementsInstanced(i,y,s,f*a,b),r.update(y,i,b))}function u(f,y,b){if(b===0)return;t.get("WEBGL_multi_draw").multiDrawElementsWEBGL(i,y,0,s,f,0,b);let x=0;for(let g=0;g<b;g++)x+=y[g];r.update(x,i,1)}function d(f,y,b,x){if(b===0)return;let g=t.get("WEBGL_multi_draw");if(g===null)for(let v=0;v<f.length;v++)c(f[v]/a,y[v],x[v]);else{g.multiDrawElementsInstancedWEBGL(i,y,0,s,f,0,x,0,b);let v=0;for(let _=0;_<b;_++)v+=y[_]*x[_];r.update(v,i,1)}}this.setMode=n,this.setIndex=o,this.render=l,this.renderInstances=c,this.renderMultiDraw=u,this.renderMultiDrawInstances=d}function MI(e){let t={geometries:0,textures:0},r={frame:0,calls:0,triangles:0,points:0,lines:0};function i(s,a,o){switch(r.calls++,a){case e.TRIANGLES:r.triangles+=o*(s/3);break;case e.LINES:r.lines+=o*(s/2);break;case e.LINE_STRIP:r.lines+=o*(s-1);break;case e.LINE_LOOP:r.lines+=o*s;break;case e.POINTS:r.points+=o*s;break;default:console.error("THREE.WebGLInfo: Unknown draw mode:",a);break}}function n(){r.calls=0,r.triangles=0,r.points=0,r.lines=0}return{memory:t,render:r,programs:null,autoReset:!0,reset:n,update:i}}function AI(e,t,r){let i=new WeakMap,n=new _i;function s(a,o,l){let c=a.morphTargetInfluences,u=o.morphAttributes.position||o.morphAttributes.normal||o.morphAttributes.color,d=u!==void 0?u.length:0,f=i.get(o);if(f===void 0||f.count!==d){let y=function(){D.dispose(),i.delete(o),o.removeEventListener("dispose",y)};f!==void 0&&f.texture.dispose();let b=o.morphAttributes.position!==void 0,x=o.morphAttributes.normal!==void 0,g=o.morphAttributes.color!==void 0,v=o.morphAttributes.position||[],_=o.morphAttributes.normal||[],E=o.morphAttributes.color||[],M=0;b===!0&&(M=1),x===!0&&(M=2),g===!0&&(M=3);let P=o.attributes.position.count*M,k=1;P>t.maxTextureSize&&(k=Math.ceil(P/t.maxTextureSize),P=t.maxTextureSize);let z=new Float32Array(P*k*4*d),D=new Jd(z,P,k,d);D.type=es,D.needsUpdate=!0;let I=M*4;for(let L=0;L<d;L++){let Z=v[L],se=_[L],ce=E[L],fe=P*k*4*L;for(let ze=0;ze<Z.count;ze++){let Fe=ze*I;b===!0&&(n.fromBufferAttribute(Z,ze),z[fe+Fe+0]=n.x,z[fe+Fe+1]=n.y,z[fe+Fe+2]=n.z,z[fe+Fe+3]=0),x===!0&&(n.fromBufferAttribute(se,ze),z[fe+Fe+4]=n.x,z[fe+Fe+5]=n.y,z[fe+Fe+6]=n.z,z[fe+Fe+7]=0),g===!0&&(n.fromBufferAttribute(ce,ze),z[fe+Fe+8]=n.x,z[fe+Fe+9]=n.y,z[fe+Fe+10]=n.z,z[fe+Fe+11]=ce.itemSize===4?n.w:1)}}f={count:d,texture:D,size:new Ft(P,k)},i.set(o,f),o.addEventListener("dispose",y)}if(a.isInstancedMesh===!0&&a.morphTexture!==null)l.getUniforms().setValue(e,"morphTexture",a.morphTexture,r);else{let y=0;for(let x=0;x<c.length;x++)y+=c[x];let b=o.morphTargetsRelative?1:1-y;l.getUniforms().setValue(e,"morphTargetBaseInfluence",b),l.getUniforms().setValue(e,"morphTargetInfluences",c)}l.getUniforms().setValue(e,"morphTargetsTexture",f.texture,r),l.getUniforms().setValue(e,"morphTargetsTextureSize",f.size)}return{update:s}}function TI(e,t,r,i){let n=new WeakMap;function s(l){let c=i.render.frame,u=l.geometry,d=t.get(l,u);if(n.get(d)!==c&&(t.update(d),n.set(d,c)),l.isInstancedMesh&&(l.hasEventListener("dispose",o)===!1&&l.addEventListener("dispose",o),n.get(l)!==c&&(r.update(l.instanceMatrix,e.ARRAY_BUFFER),l.instanceColor!==null&&r.update(l.instanceColor,e.ARRAY_BUFFER),n.set(l,c))),l.isSkinnedMesh){let f=l.skeleton;n.get(f)!==c&&(f.update(),n.set(f,c))}return d}function a(){n=new WeakMap}function o(l){let c=l.target;c.removeEventListener("dispose",o),r.remove(c.instanceMatrix),c.instanceColor!==null&&r.remove(c.instanceColor)}return{update:s,dispose:a}}var Y1=new Qi,q1=new zp(1,1),K1=new Jd,Z1=new pg,$1=new jh,J1=[],Q1=[],ew=new Float32Array(16),tw=new Float32Array(9),rw=new Float32Array(4);function Sc(e,t,r){let i=e[0];if(i<=0||i>0)return e;let n=t*r,s=J1[n];if(s===void 0&&(s=new Float32Array(n),J1[n]=s),t!==0){i.toArray(s,0);for(let a=1,o=0;a!==t;++a)o+=r,e[a].toArray(s,o)}return s}function wn(e,t){if(e.length!==t.length)return!1;for(let r=0,i=e.length;r<i;r++)if(e[r]!==t[r])return!1;return!0}function _n(e,t){for(let r=0,i=t.length;r<i;r++)e[r]=t[r]}function cf(e,t){let r=Q1[t];r===void 0&&(r=new Int32Array(t),Q1[t]=r);for(let i=0;i!==t;++i)r[i]=e.allocateTextureUnit();return r}function CI(e,t){let r=this.cache;r[0]!==t&&(e.uniform1f(this.addr,t),r[0]=t)}function RI(e,t){let r=this.cache;if(t.x!==void 0)(r[0]!==t.x||r[1]!==t.y)&&(e.uniform2f(this.addr,t.x,t.y),r[0]=t.x,r[1]=t.y);else{if(wn(r,t))return;e.uniform2fv(this.addr,t),_n(r,t)}}function PI(e,t){let r=this.cache;if(t.x!==void 0)(r[0]!==t.x||r[1]!==t.y||r[2]!==t.z)&&(e.uniform3f(this.addr,t.x,t.y,t.z),r[0]=t.x,r[1]=t.y,r[2]=t.z);else if(t.r!==void 0)(r[0]!==t.r||r[1]!==t.g||r[2]!==t.b)&&(e.uniform3f(this.addr,t.r,t.g,t.b),r[0]=t.r,r[1]=t.g,r[2]=t.b);else{if(wn(r,t))return;e.uniform3fv(this.addr,t),_n(r,t)}}function II(e,t){let r=this.cache;if(t.x!==void 0)(r[0]!==t.x||r[1]!==t.y||r[2]!==t.z||r[3]!==t.w)&&(e.uniform4f(this.addr,t.x,t.y,t.z,t.w),r[0]=t.x,r[1]=t.y,r[2]=t.z,r[3]=t.w);else{if(wn(r,t))return;e.uniform4fv(this.addr,t),_n(r,t)}}function NI(e,t){let r=this.cache,i=t.elements;if(i===void 0){if(wn(r,t))return;e.uniformMatrix2fv(this.addr,!1,t),_n(r,t)}else{if(wn(r,i))return;rw.set(i),e.uniformMatrix2fv(this.addr,!1,rw),_n(r,i)}}function LI(e,t){let r=this.cache,i=t.elements;if(i===void 0){if(wn(r,t))return;e.uniformMatrix3fv(this.addr,!1,t),_n(r,t)}else{if(wn(r,i))return;tw.set(i),e.uniformMatrix3fv(this.addr,!1,tw),_n(r,i)}}function kI(e,t){let r=this.cache,i=t.elements;if(i===void 0){if(wn(r,t))return;e.uniformMatrix4fv(this.addr,!1,t),_n(r,t)}else{if(wn(r,i))return;ew.set(i),e.uniformMatrix4fv(this.addr,!1,ew),_n(r,i)}}function OI(e,t){let r=this.cache;r[0]!==t&&(e.uniform1i(this.addr,t),r[0]=t)}function DI(e,t){let r=this.cache;if(t.x!==void 0)(r[0]!==t.x||r[1]!==t.y)&&(e.uniform2i(this.addr,t.x,t.y),r[0]=t.x,r[1]=t.y);else{if(wn(r,t))return;e.uniform2iv(this.addr,t),_n(r,t)}}function UI(e,t){let r=this.cache;if(t.x!==void 0)(r[0]!==t.x||r[1]!==t.y||r[2]!==t.z)&&(e.uniform3i(this.addr,t.x,t.y,t.z),r[0]=t.x,r[1]=t.y,r[2]=t.z);else{if(wn(r,t))return;e.uniform3iv(this.addr,t),_n(r,t)}}function FI(e,t){let r=this.cache;if(t.x!==void 0)(r[0]!==t.x||r[1]!==t.y||r[2]!==t.z||r[3]!==t.w)&&(e.uniform4i(this.addr,t.x,t.y,t.z,t.w),r[0]=t.x,r[1]=t.y,r[2]=t.z,r[3]=t.w);else{if(wn(r,t))return;e.uniform4iv(this.addr,t),_n(r,t)}}function zI(e,t){let r=this.cache;r[0]!==t&&(e.uniform1ui(this.addr,t),r[0]=t)}function BI(e,t){let r=this.cache;if(t.x!==void 0)(r[0]!==t.x||r[1]!==t.y)&&(e.uniform2ui(this.addr,t.x,t.y),r[0]=t.x,r[1]=t.y);else{if(wn(r,t))return;e.uniform2uiv(this.addr,t),_n(r,t)}}function jI(e,t){let r=this.cache;if(t.x!==void 0)(r[0]!==t.x||r[1]!==t.y||r[2]!==t.z)&&(e.uniform3ui(this.addr,t.x,t.y,t.z),r[0]=t.x,r[1]=t.y,r[2]=t.z);else{if(wn(r,t))return;e.uniform3uiv(this.addr,t),_n(r,t)}}function VI(e,t){let r=this.cache;if(t.x!==void 0)(r[0]!==t.x||r[1]!==t.y||r[2]!==t.z||r[3]!==t.w)&&(e.uniform4ui(this.addr,t.x,t.y,t.z,t.w),r[0]=t.x,r[1]=t.y,r[2]=t.z,r[3]=t.w);else{if(wn(r,t))return;e.uniform4uiv(this.addr,t),_n(r,t)}}function HI(e,t,r){let i=this.cache,n=r.allocateTextureUnit();i[0]!==n&&(e.uniform1i(this.addr,n),i[0]=n);let s;this.type===e.SAMPLER_2D_SHADOW?(q1.compareFunction=lg,s=q1):s=Y1,r.setTexture2D(t||s,n)}function GI(e,t,r){let i=this.cache,n=r.allocateTextureUnit();i[0]!==n&&(e.uniform1i(this.addr,n),i[0]=n),r.setTexture3D(t||Z1,n)}function WI(e,t,r){let i=this.cache,n=r.allocateTextureUnit();i[0]!==n&&(e.uniform1i(this.addr,n),i[0]=n),r.setTextureCube(t||$1,n)}function XI(e,t,r){let i=this.cache,n=r.allocateTextureUnit();i[0]!==n&&(e.uniform1i(this.addr,n),i[0]=n),r.setTexture2DArray(t||K1,n)}function YI(e){switch(e){case 5126:return CI;case 35664:return RI;case 35665:return PI;case 35666:return II;case 35674:return NI;case 35675:return LI;case 35676:return kI;case 5124:case 35670:return OI;case 35667:case 35671:return DI;case 35668:case 35672:return UI;case 35669:case 35673:return FI;case 5125:return zI;case 36294:return BI;case 36295:return jI;case 36296:return VI;case 35678:case 36198:case 36298:case 36306:case 35682:return HI;case 35679:case 36299:case 36307:return GI;case 35680:case 36300:case 36308:case 36293:return WI;case 36289:case 36303:case 36311:case 36292:return XI}}function qI(e,t){e.uniform1fv(this.addr,t)}function KI(e,t){let r=Sc(t,this.size,2);e.uniform2fv(this.addr,r)}function ZI(e,t){let r=Sc(t,this.size,3);e.uniform3fv(this.addr,r)}function $I(e,t){let r=Sc(t,this.size,4);e.uniform4fv(this.addr,r)}function JI(e,t){let r=Sc(t,this.size,4);e.uniformMatrix2fv(this.addr,!1,r)}function QI(e,t){let r=Sc(t,this.size,9);e.uniformMatrix3fv(this.addr,!1,r)}function eN(e,t){let r=Sc(t,this.size,16);e.uniformMatrix4fv(this.addr,!1,r)}function tN(e,t){e.uniform1iv(this.addr,t)}function rN(e,t){e.uniform2iv(this.addr,t)}function iN(e,t){e.uniform3iv(this.addr,t)}function nN(e,t){e.uniform4iv(this.addr,t)}function sN(e,t){e.uniform1uiv(this.addr,t)}function aN(e,t){e.uniform2uiv(this.addr,t)}function oN(e,t){e.uniform3uiv(this.addr,t)}function lN(e,t){e.uniform4uiv(this.addr,t)}function cN(e,t,r){let i=this.cache,n=t.length,s=cf(r,n);wn(i,s)||(e.uniform1iv(this.addr,s),_n(i,s));for(let a=0;a!==n;++a)r.setTexture2D(t[a]||Y1,s[a])}function hN(e,t,r){let i=this.cache,n=t.length,s=cf(r,n);wn(i,s)||(e.uniform1iv(this.addr,s),_n(i,s));for(let a=0;a!==n;++a)r.setTexture3D(t[a]||Z1,s[a])}function uN(e,t,r){let i=this.cache,n=t.length,s=cf(r,n);wn(i,s)||(e.uniform1iv(this.addr,s),_n(i,s));for(let a=0;a!==n;++a)r.setTextureCube(t[a]||$1,s[a])}function dN(e,t,r){let i=this.cache,n=t.length,s=cf(r,n);wn(i,s)||(e.uniform1iv(this.addr,s),_n(i,s));for(let a=0;a!==n;++a)r.setTexture2DArray(t[a]||K1,s[a])}function pN(e){switch(e){case 5126:return qI;case 35664:return KI;case 35665:return ZI;case 35666:return $I;case 35674:return JI;case 35675:return QI;case 35676:return eN;case 5124:case 35670:return tN;case 35667:case 35671:return rN;case 35668:case 35672:return iN;case 35669:case 35673:return nN;case 5125:return sN;case 36294:return aN;case 36295:return oN;case 36296:return lN;case 35678:case 36198:case 36298:case 36306:case 35682:return cN;case 35679:case 36299:case 36307:return hN;case 35680:case 36300:case 36308:case 36293:return uN;case 36289:case 36303:case 36311:case 36292:return dN}}var fN=class{constructor(e,t,r){this.id=e,this.addr=r,this.cache=[],this.type=t.type,this.setValue=YI(t.type)}},mN=class{constructor(e,t,r){this.id=e,this.addr=r,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=pN(t.type)}},gN=class{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,r){let i=this.seq;for(let n=0,s=i.length;n!==s;++n){let a=i[n];a.setValue(e,t[a.id],r)}}},Uy=/(\w+)(\])?(\[|\.)?/g;function iw(e,t){e.seq.push(t),e.map[t.id]=t}function yN(e,t,r){let i=e.name,n=i.length;for(Uy.lastIndex=0;;){let s=Uy.exec(i),a=Uy.lastIndex,o=s[1],l=s[2]==="]",c=s[3];if(l&&(o=o|0),c===void 0||c==="["&&a+2===n){iw(r,c===void 0?new fN(o,e,t):new mN(o,e,t));break}else{let u=r.map[o];u===void 0&&(u=new gN(o),iw(r,u)),r=u}}}var hf=class{constructor(e,t){this.seq=[],this.map={};let r=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let i=0;i<r;++i){let n=e.getActiveUniform(t,i),s=e.getUniformLocation(t,n.name);yN(n,s,this)}}setValue(e,t,r,i){let n=this.map[t];n!==void 0&&n.setValue(e,r,i)}setOptional(e,t,r){let i=t[r];i!==void 0&&this.setValue(e,r,i)}static upload(e,t,r,i){for(let n=0,s=t.length;n!==s;++n){let a=t[n],o=r[a.id];o.needsUpdate!==!1&&a.setValue(e,o.value,i)}}static seqWithValue(e,t){let r=[];for(let i=0,n=e.length;i!==n;++i){let s=e[i];s.id in t&&r.push(s)}return r}};function nw(e,t,r){let i=e.createShader(t);return e.shaderSource(i,r),e.compileShader(i),i}var vN=37297,xN=0;function bN(e,t){let r=e.split(`
`),i=[],n=Math.max(t-6,0),s=Math.min(t+6,r.length);for(let a=n;a<s;a++){let o=a+1;i.push(`${o===t?">":" "} ${o}: ${r[a]}`)}return i.join(`
`)}var sw=new si;function wN(e){li._getMatrix(sw,li.workingColorSpace,e);let t=`mat3( ${sw.elements.map(r=>r.toFixed(4))} )`;switch(li.getTransfer(e)){case Ih:return[t,"LinearTransferOETF"];case Ii:return[t,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",e),[t,"LinearTransferOETF"]}}function aw(e,t,r){let i=e.getShaderParameter(t,e.COMPILE_STATUS),n=e.getShaderInfoLog(t).trim();if(i&&n==="")return"";let s=/ERROR: 0:(\d+)/.exec(n);if(s){let a=parseInt(s[1]);return r.toUpperCase()+`

`+n+`

`+bN(e.getShaderSource(t),a)}else return n}function _N(e,t){let r=wN(t);return[`vec4 ${e}( vec4 value ) {`,`	return ${r[1]}( vec4( value.rgb * ${r[0]}, value.a ) );`,"}"].join(`
`)}function EN(e,t){let r;switch(t){case Si:r="Linear";break;case Vr:r="Reinhard";break;case Yr:r="Cineon";break;case Cr:r="ACESFilmic";break;case Ur:r="AgX";break;case ni:r="Neutral";break;case Or:r="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",t),r="Linear"}return"vec3 "+e+"( vec3 color ) { return "+r+"ToneMapping( color ); }"}var uf=new je;function SN(){li.getLuminanceCoefficients(uf);let e=uf.x.toFixed(4),t=uf.y.toFixed(4),r=uf.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",`	const vec3 weights = vec3( ${e}, ${t}, ${r} );`,"	return dot( weights, rgb );","}"].join(`
`)}function MN(e){return[e.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",e.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(lu).join(`
`)}function AN(e){let t=[];for(let r in e){let i=e[r];i!==!1&&t.push("#define "+r+" "+i)}return t.join(`
`)}function TN(e,t){let r={},i=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let n=0;n<i;n++){let s=e.getActiveAttrib(t,n),a=s.name,o=1;s.type===e.FLOAT_MAT2&&(o=2),s.type===e.FLOAT_MAT3&&(o=3),s.type===e.FLOAT_MAT4&&(o=4),r[a]={type:s.type,location:e.getAttribLocation(t,a),locationSize:o}}return r}function lu(e){return e!==""}function ow(e,t){let r=t.numSpotLightShadows+t.numSpotLightMaps-t.numSpotLightShadowsWithMaps;return e.replace(/NUM_DIR_LIGHTS/g,t.numDirLights).replace(/NUM_SPOT_LIGHTS/g,t.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g,t.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g,r).replace(/NUM_RECT_AREA_LIGHTS/g,t.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g,t.numPointLights).replace(/NUM_HEMI_LIGHTS/g,t.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g,t.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g,t.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g,t.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g,t.numPointLightShadows)}function lw(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}var CN=/^[ \t]*#include +<([\w\d./]+)>/gm;function Fy(e){return e.replace(CN,PN)}var RN=new Map;function PN(e,t){let r=ai[t];if(r===void 0){let i=RN.get(t);if(i!==void 0)r=ai[i],console.warn('THREE.WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.',t,i);else throw new Error("Can not resolve #include <"+t+">")}return Fy(r)}var IN=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function cw(e){return e.replace(IN,NN)}function NN(e,t,r,i){let n="";for(let s=parseInt(t);s<parseInt(r);s++)n+=i.replace(/\[\s*i\s*\]/g,"[ "+s+" ]").replace(/UNROLLED_LOOP_INDEX/g,s);return n}function hw(e){let t=`precision ${e.precision} float;
	precision ${e.precision} int;
	precision ${e.precision} sampler2D;
	precision ${e.precision} samplerCube;
	precision ${e.precision} sampler3D;
	precision ${e.precision} sampler2DArray;
	precision ${e.precision} sampler2DShadow;
	precision ${e.precision} samplerCubeShadow;
	precision ${e.precision} sampler2DArrayShadow;
	precision ${e.precision} isampler2D;
	precision ${e.precision} isampler3D;
	precision ${e.precision} isamplerCube;
	precision ${e.precision} isampler2DArray;
	precision ${e.precision} usampler2D;
	precision ${e.precision} usampler3D;
	precision ${e.precision} usamplerCube;
	precision ${e.precision} usampler2DArray;
	`;return e.precision==="highp"?t+=`
#define HIGH_PRECISION`:e.precision==="mediump"?t+=`
#define MEDIUM_PRECISION`:e.precision==="lowp"&&(t+=`
#define LOW_PRECISION`),t}function LN(e){let t="SHADOWMAP_TYPE_BASIC";return e.shadowMapType===xe?t="SHADOWMAP_TYPE_PCF":e.shadowMapType===ke?t="SHADOWMAP_TYPE_PCF_SOFT":e.shadowMapType===Me&&(t="SHADOWMAP_TYPE_VSM"),t}function kN(e){let t="ENVMAP_TYPE_CUBE";if(e.envMap)switch(e.envMapMode){case br:case wi:t="ENVMAP_TYPE_CUBE";break;case vi:t="ENVMAP_TYPE_CUBE_UV";break}return t}function ON(e){let t="ENVMAP_MODE_REFLECTION";if(e.envMap)switch(e.envMapMode){case wi:t="ENVMAP_MODE_REFRACTION";break}return t}function DN(e){let t="ENVMAP_BLENDING_NONE";if(e.envMap)switch(e.combine){case mr:t="ENVMAP_BLENDING_MULTIPLY";break;case Br:t="ENVMAP_BLENDING_MIX";break;case Dr:t="ENVMAP_BLENDING_ADD";break}return t}function UN(e){let t=e.envMapCubeUVHeight;if(t===null)return null;let r=Math.log2(t)-2,i=1/t;return{texelWidth:1/(3*Math.max(Math.pow(2,r),112)),texelHeight:i,maxMip:r}}function FN(e,t,r,i){let n=e.getContext(),s=r.defines,a=r.vertexShader,o=r.fragmentShader,l=LN(r),c=kN(r),u=ON(r),d=DN(r),f=UN(r),y=MN(r),b=AN(s),x=n.createProgram(),g,v,_=r.glslVersion?"#version "+r.glslVersion+`
`:"";r.isRawShaderMaterial?(g=["#define SHADER_TYPE "+r.shaderType,"#define SHADER_NAME "+r.shaderName,b].filter(lu).join(`
`),g.length>0&&(g+=`
`),v=["#define SHADER_TYPE "+r.shaderType,"#define SHADER_NAME "+r.shaderName,b].filter(lu).join(`
`),v.length>0&&(v+=`
`)):(g=[hw(r),"#define SHADER_TYPE "+r.shaderType,"#define SHADER_NAME "+r.shaderName,b,r.extensionClipCullDistance?"#define USE_CLIP_DISTANCE":"",r.batching?"#define USE_BATCHING":"",r.batchingColor?"#define USE_BATCHING_COLOR":"",r.instancing?"#define USE_INSTANCING":"",r.instancingColor?"#define USE_INSTANCING_COLOR":"",r.instancingMorph?"#define USE_INSTANCING_MORPH":"",r.useFog&&r.fog?"#define USE_FOG":"",r.useFog&&r.fogExp2?"#define FOG_EXP2":"",r.map?"#define USE_MAP":"",r.envMap?"#define USE_ENVMAP":"",r.envMap?"#define "+u:"",r.lightMap?"#define USE_LIGHTMAP":"",r.aoMap?"#define USE_AOMAP":"",r.bumpMap?"#define USE_BUMPMAP":"",r.normalMap?"#define USE_NORMALMAP":"",r.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",r.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",r.displacementMap?"#define USE_DISPLACEMENTMAP":"",r.emissiveMap?"#define USE_EMISSIVEMAP":"",r.anisotropy?"#define USE_ANISOTROPY":"",r.anisotropyMap?"#define USE_ANISOTROPYMAP":"",r.clearcoatMap?"#define USE_CLEARCOATMAP":"",r.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",r.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",r.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",r.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",r.specularMap?"#define USE_SPECULARMAP":"",r.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",r.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",r.roughnessMap?"#define USE_ROUGHNESSMAP":"",r.metalnessMap?"#define USE_METALNESSMAP":"",r.alphaMap?"#define USE_ALPHAMAP":"",r.alphaHash?"#define USE_ALPHAHASH":"",r.transmission?"#define USE_TRANSMISSION":"",r.transmissionMap?"#define USE_TRANSMISSIONMAP":"",r.thicknessMap?"#define USE_THICKNESSMAP":"",r.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",r.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",r.mapUv?"#define MAP_UV "+r.mapUv:"",r.alphaMapUv?"#define ALPHAMAP_UV "+r.alphaMapUv:"",r.lightMapUv?"#define LIGHTMAP_UV "+r.lightMapUv:"",r.aoMapUv?"#define AOMAP_UV "+r.aoMapUv:"",r.emissiveMapUv?"#define EMISSIVEMAP_UV "+r.emissiveMapUv:"",r.bumpMapUv?"#define BUMPMAP_UV "+r.bumpMapUv:"",r.normalMapUv?"#define NORMALMAP_UV "+r.normalMapUv:"",r.displacementMapUv?"#define DISPLACEMENTMAP_UV "+r.displacementMapUv:"",r.metalnessMapUv?"#define METALNESSMAP_UV "+r.metalnessMapUv:"",r.roughnessMapUv?"#define ROUGHNESSMAP_UV "+r.roughnessMapUv:"",r.anisotropyMapUv?"#define ANISOTROPYMAP_UV "+r.anisotropyMapUv:"",r.clearcoatMapUv?"#define CLEARCOATMAP_UV "+r.clearcoatMapUv:"",r.clearcoatNormalMapUv?"#define CLEARCOAT_NORMALMAP_UV "+r.clearcoatNormalMapUv:"",r.clearcoatRoughnessMapUv?"#define CLEARCOAT_ROUGHNESSMAP_UV "+r.clearcoatRoughnessMapUv:"",r.iridescenceMapUv?"#define IRIDESCENCEMAP_UV "+r.iridescenceMapUv:"",r.iridescenceThicknessMapUv?"#define IRIDESCENCE_THICKNESSMAP_UV "+r.iridescenceThicknessMapUv:"",r.sheenColorMapUv?"#define SHEEN_COLORMAP_UV "+r.sheenColorMapUv:"",r.sheenRoughnessMapUv?"#define SHEEN_ROUGHNESSMAP_UV "+r.sheenRoughnessMapUv:"",r.specularMapUv?"#define SPECULARMAP_UV "+r.specularMapUv:"",r.specularColorMapUv?"#define SPECULAR_COLORMAP_UV "+r.specularColorMapUv:"",r.specularIntensityMapUv?"#define SPECULAR_INTENSITYMAP_UV "+r.specularIntensityMapUv:"",r.transmissionMapUv?"#define TRANSMISSIONMAP_UV "+r.transmissionMapUv:"",r.thicknessMapUv?"#define THICKNESSMAP_UV "+r.thicknessMapUv:"",r.vertexTangents&&r.flatShading===!1?"#define USE_TANGENT":"",r.vertexColors?"#define USE_COLOR":"",r.vertexAlphas?"#define USE_COLOR_ALPHA":"",r.vertexUv1s?"#define USE_UV1":"",r.vertexUv2s?"#define USE_UV2":"",r.vertexUv3s?"#define USE_UV3":"",r.pointsUvs?"#define USE_POINTS_UV":"",r.flatShading?"#define FLAT_SHADED":"",r.skinning?"#define USE_SKINNING":"",r.morphTargets?"#define USE_MORPHTARGETS":"",r.morphNormals&&r.flatShading===!1?"#define USE_MORPHNORMALS":"",r.morphColors?"#define USE_MORPHCOLORS":"",r.morphTargetsCount>0?"#define MORPHTARGETS_TEXTURE_STRIDE "+r.morphTextureStride:"",r.morphTargetsCount>0?"#define MORPHTARGETS_COUNT "+r.morphTargetsCount:"",r.doubleSided?"#define DOUBLE_SIDED":"",r.flipSided?"#define FLIP_SIDED":"",r.shadowMapEnabled?"#define USE_SHADOWMAP":"",r.shadowMapEnabled?"#define "+l:"",r.sizeAttenuation?"#define USE_SIZEATTENUATION":"",r.numLightProbes>0?"#define USE_LIGHT_PROBES":"",r.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",r.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 modelMatrix;","uniform mat4 modelViewMatrix;","uniform mat4 projectionMatrix;","uniform mat4 viewMatrix;","uniform mat3 normalMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;","#ifdef USE_INSTANCING","	attribute mat4 instanceMatrix;","#endif","#ifdef USE_INSTANCING_COLOR","	attribute vec3 instanceColor;","#endif","#ifdef USE_INSTANCING_MORPH","	uniform sampler2D morphTexture;","#endif","attribute vec3 position;","attribute vec3 normal;","attribute vec2 uv;","#ifdef USE_UV1","	attribute vec2 uv1;","#endif","#ifdef USE_UV2","	attribute vec2 uv2;","#endif","#ifdef USE_UV3","	attribute vec2 uv3;","#endif","#ifdef USE_TANGENT","	attribute vec4 tangent;","#endif","#if defined( USE_COLOR_ALPHA )","	attribute vec4 color;","#elif defined( USE_COLOR )","	attribute vec3 color;","#endif","#ifdef USE_SKINNING","	attribute vec4 skinIndex;","	attribute vec4 skinWeight;","#endif",`
`].filter(lu).join(`
`),v=[hw(r),"#define SHADER_TYPE "+r.shaderType,"#define SHADER_NAME "+r.shaderName,b,r.useFog&&r.fog?"#define USE_FOG":"",r.useFog&&r.fogExp2?"#define FOG_EXP2":"",r.alphaToCoverage?"#define ALPHA_TO_COVERAGE":"",r.map?"#define USE_MAP":"",r.matcap?"#define USE_MATCAP":"",r.envMap?"#define USE_ENVMAP":"",r.envMap?"#define "+c:"",r.envMap?"#define "+u:"",r.envMap?"#define "+d:"",f?"#define CUBEUV_TEXEL_WIDTH "+f.texelWidth:"",f?"#define CUBEUV_TEXEL_HEIGHT "+f.texelHeight:"",f?"#define CUBEUV_MAX_MIP "+f.maxMip+".0":"",r.lightMap?"#define USE_LIGHTMAP":"",r.aoMap?"#define USE_AOMAP":"",r.bumpMap?"#define USE_BUMPMAP":"",r.normalMap?"#define USE_NORMALMAP":"",r.normalMapObjectSpace?"#define USE_NORMALMAP_OBJECTSPACE":"",r.normalMapTangentSpace?"#define USE_NORMALMAP_TANGENTSPACE":"",r.emissiveMap?"#define USE_EMISSIVEMAP":"",r.anisotropy?"#define USE_ANISOTROPY":"",r.anisotropyMap?"#define USE_ANISOTROPYMAP":"",r.clearcoat?"#define USE_CLEARCOAT":"",r.clearcoatMap?"#define USE_CLEARCOATMAP":"",r.clearcoatRoughnessMap?"#define USE_CLEARCOAT_ROUGHNESSMAP":"",r.clearcoatNormalMap?"#define USE_CLEARCOAT_NORMALMAP":"",r.dispersion?"#define USE_DISPERSION":"",r.iridescence?"#define USE_IRIDESCENCE":"",r.iridescenceMap?"#define USE_IRIDESCENCEMAP":"",r.iridescenceThicknessMap?"#define USE_IRIDESCENCE_THICKNESSMAP":"",r.specularMap?"#define USE_SPECULARMAP":"",r.specularColorMap?"#define USE_SPECULAR_COLORMAP":"",r.specularIntensityMap?"#define USE_SPECULAR_INTENSITYMAP":"",r.roughnessMap?"#define USE_ROUGHNESSMAP":"",r.metalnessMap?"#define USE_METALNESSMAP":"",r.alphaMap?"#define USE_ALPHAMAP":"",r.alphaTest?"#define USE_ALPHATEST":"",r.alphaHash?"#define USE_ALPHAHASH":"",r.sheen?"#define USE_SHEEN":"",r.sheenColorMap?"#define USE_SHEEN_COLORMAP":"",r.sheenRoughnessMap?"#define USE_SHEEN_ROUGHNESSMAP":"",r.transmission?"#define USE_TRANSMISSION":"",r.transmissionMap?"#define USE_TRANSMISSIONMAP":"",r.thicknessMap?"#define USE_THICKNESSMAP":"",r.vertexTangents&&r.flatShading===!1?"#define USE_TANGENT":"",r.vertexColors||r.instancingColor||r.batchingColor?"#define USE_COLOR":"",r.vertexAlphas?"#define USE_COLOR_ALPHA":"",r.vertexUv1s?"#define USE_UV1":"",r.vertexUv2s?"#define USE_UV2":"",r.vertexUv3s?"#define USE_UV3":"",r.pointsUvs?"#define USE_POINTS_UV":"",r.gradientMap?"#define USE_GRADIENTMAP":"",r.flatShading?"#define FLAT_SHADED":"",r.doubleSided?"#define DOUBLE_SIDED":"",r.flipSided?"#define FLIP_SIDED":"",r.shadowMapEnabled?"#define USE_SHADOWMAP":"",r.shadowMapEnabled?"#define "+l:"",r.premultipliedAlpha?"#define PREMULTIPLIED_ALPHA":"",r.numLightProbes>0?"#define USE_LIGHT_PROBES":"",r.decodeVideoTexture?"#define DECODE_VIDEO_TEXTURE":"",r.decodeVideoTextureEmissive?"#define DECODE_VIDEO_TEXTURE_EMISSIVE":"",r.logarithmicDepthBuffer?"#define USE_LOGDEPTHBUF":"",r.reverseDepthBuffer?"#define USE_REVERSEDEPTHBUF":"","uniform mat4 viewMatrix;","uniform vec3 cameraPosition;","uniform bool isOrthographic;",r.toneMapping!==hi?"#define TONE_MAPPING":"",r.toneMapping!==hi?ai.tonemapping_pars_fragment:"",r.toneMapping!==hi?EN("toneMapping",r.toneMapping):"",r.dithering?"#define DITHERING":"",r.opaque?"#define OPAQUE":"",ai.colorspace_pars_fragment,_N("linearToOutputTexel",r.outputColorSpace),SN(),r.useDepthPacking?"#define DEPTH_PACKING "+r.depthPacking:"",`
`].filter(lu).join(`
`)),a=Fy(a),a=ow(a,r),a=lw(a,r),o=Fy(o),o=ow(o,r),o=lw(o,r),a=cw(a),o=cw(o),r.isRawShaderMaterial!==!0&&(_=`#version 300 es
`,g=[y,"#define attribute in","#define varying out","#define texture2D texture"].join(`
`)+`
`+g,v=["#define varying in",r.glslVersion===cg?"":"layout(location = 0) out highp vec4 pc_fragColor;",r.glslVersion===cg?"":"#define gl_FragColor pc_fragColor","#define gl_FragDepthEXT gl_FragDepth","#define texture2D texture","#define textureCube texture","#define texture2DProj textureProj","#define texture2DLodEXT textureLod","#define texture2DProjLodEXT textureProjLod","#define textureCubeLodEXT textureLod","#define texture2DGradEXT textureGrad","#define texture2DProjGradEXT textureProjGrad","#define textureCubeGradEXT textureGrad"].join(`
`)+`
`+v);let E=_+g+a,M=_+v+o,P=nw(n,n.VERTEX_SHADER,E),k=nw(n,n.FRAGMENT_SHADER,M);n.attachShader(x,P),n.attachShader(x,k),r.index0AttributeName!==void 0?n.bindAttribLocation(x,0,r.index0AttributeName):r.morphTargets===!0&&n.bindAttribLocation(x,0,"position"),n.linkProgram(x);function z(Z){if(e.debug.checkShaderErrors){let se=n.getProgramInfoLog(x).trim(),ce=n.getShaderInfoLog(P).trim(),fe=n.getShaderInfoLog(k).trim(),ze=!0,Fe=!0;if(n.getProgramParameter(x,n.LINK_STATUS)===!1)if(ze=!1,typeof e.debug.onShaderError=="function")e.debug.onShaderError(n,x,P,k);else{let Pe=aw(n,P,"vertex"),ue=aw(n,k,"fragment");console.error("THREE.WebGLProgram: Shader Error "+n.getError()+" - VALIDATE_STATUS "+n.getProgramParameter(x,n.VALIDATE_STATUS)+`

Material Name: `+Z.name+`
Material Type: `+Z.type+`

Program Info Log: `+se+`
`+Pe+`
`+ue)}else se!==""?console.warn("THREE.WebGLProgram: Program Info Log:",se):(ce===""||fe==="")&&(Fe=!1);Fe&&(Z.diagnostics={runnable:ze,programLog:se,vertexShader:{log:ce,prefix:g},fragmentShader:{log:fe,prefix:v}})}n.deleteShader(P),n.deleteShader(k),D=new hf(n,x),I=TN(n,x)}let D;this.getUniforms=function(){return D===void 0&&z(this),D};let I;this.getAttributes=function(){return I===void 0&&z(this),I};let L=r.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return L===!1&&(L=n.getProgramParameter(x,vN)),L},this.destroy=function(){i.releaseStatesOfProgram(this),n.deleteProgram(x),this.program=void 0},this.type=r.shaderType,this.name=r.shaderName,this.id=xN++,this.cacheKey=t,this.usedTimes=1,this.program=x,this.vertexShader=P,this.fragmentShader=k,this}var zN=0,BN=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){let t=e.vertexShader,r=e.fragmentShader,i=this._getShaderStage(t),n=this._getShaderStage(r),s=this._getShaderCacheForMaterial(e);return s.has(i)===!1&&(s.add(i),i.usedTimes++),s.has(n)===!1&&(s.add(n),n.usedTimes++),this}remove(e){let t=this.materialCache.get(e);for(let r of t)r.usedTimes--,r.usedTimes===0&&this.shaderCache.delete(r.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){let t=this.materialCache,r=t.get(e);return r===void 0&&(r=new Set,t.set(e,r)),r}_getShaderStage(e){let t=this.shaderCache,r=t.get(e);return r===void 0&&(r=new jN(e),t.set(e,r)),r}},jN=class{constructor(e){this.id=zN++,this.code=e,this.usedTimes=0}};function VN(e,t,r,i,n,s,a){let o=new sp,l=new BN,c=new Set,u=[],d=n.logarithmicDepthBuffer,f=n.vertexTextures,y=n.precision,b={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distanceRGBA",MeshNormalMaterial:"normal",MeshBasicMaterial:"basic",MeshLambertMaterial:"lambert",MeshPhongMaterial:"phong",MeshToonMaterial:"toon",MeshStandardMaterial:"physical",MeshPhysicalMaterial:"physical",MeshMatcapMaterial:"matcap",LineBasicMaterial:"basic",LineDashedMaterial:"dashed",PointsMaterial:"points",ShadowMaterial:"shadow",SpriteMaterial:"sprite"};function x(I){return c.add(I),I===0?"uv":`uv${I}`}function g(I,L,Z,se,ce){let fe=se.fog,ze=ce.geometry,Fe=I.isMeshStandardMaterial?se.environment:null,Pe=(I.isMeshStandardMaterial?r:t).get(I.envMap||Fe),ue=Pe&&Pe.mapping===vi?Pe.image.height:null,Te=b[I.type];I.precision!==null&&(y=n.getMaxPrecision(I.precision),y!==I.precision&&console.warn("THREE.WebGLProgram.getParameters:",I.precision,"not supported, using",y,"instead."));let de=ze.morphAttributes.position||ze.morphAttributes.normal||ze.morphAttributes.color,Ie=de!==void 0?de.length:0,Re=0;ze.morphAttributes.position!==void 0&&(Re=1),ze.morphAttributes.normal!==void 0&&(Re=2),ze.morphAttributes.color!==void 0&&(Re=3);let Be,Se,U,ie;if(Te){let ir=$s[Te];Be=ir.vertexShader,Se=ir.fragmentShader}else Be=I.vertexShader,Se=I.fragmentShader,l.update(I),U=l.getVertexShaderID(I),ie=l.getFragmentShaderID(I);let Ae=e.getRenderTarget(),Ue=e.state.buffers.depth.getReversed(),Ge=ce.isInstancedMesh===!0,nt=ce.isBatchedMesh===!0,Qe=!!I.map,ct=!!I.matcap,ye=!!Pe,dt=!!I.aoMap,xt=!!I.lightMap,Dt=!!I.bumpMap,We=!!I.normalMap,mt=!!I.displacementMap,it=!!I.emissiveMap,st=!!I.metalnessMap,oe=!!I.roughnessMap,F=I.anisotropy>0,le=I.clearcoat>0,pe=I.dispersion>0,Le=I.iridescence>0,He=I.sheen>0,at=I.transmission>0,rt=F&&!!I.anisotropyMap,ht=le&&!!I.clearcoatMap,Tt=le&&!!I.clearcoatNormalMap,Mt=le&&!!I.clearcoatRoughnessMap,Ut=Le&&!!I.iridescenceMap,Kt=Le&&!!I.iridescenceThicknessMap,fr=He&&!!I.sheenColorMap,er=He&&!!I.sheenRoughnessMap,Zt=!!I.specularMap,Gt=!!I.specularColorMap,Er=!!I.specularIntensityMap,ut=at&&!!I.transmissionMap,zt=at&&!!I.thicknessMap,It=!!I.gradientMap,Ct=!!I.alphaMap,rr=I.alphaTest>0,$t=!!I.alphaHash,xr=!!I.extensions,cr=hi;I.toneMapped&&(Ae===null||Ae.isXRRenderTarget===!0)&&(cr=e.toneMapping);let yr={shaderID:Te,shaderType:I.type,shaderName:I.name,vertexShader:Be,fragmentShader:Se,defines:I.defines,customVertexShaderID:U,customFragmentShaderID:ie,isRawShaderMaterial:I.isRawShaderMaterial===!0,glslVersion:I.glslVersion,precision:y,batching:nt,batchingColor:nt&&ce._colorsTexture!==null,instancing:Ge,instancingColor:Ge&&ce.instanceColor!==null,instancingMorph:Ge&&ce.morphTexture!==null,supportsVertexTextures:f,outputColorSpace:Ae===null?e.outputColorSpace:Ae.isXRRenderTarget===!0?Ae.texture.colorSpace:kn,alphaToCoverage:!!I.alphaToCoverage,map:Qe,matcap:ct,envMap:ye,envMapMode:ye&&Pe.mapping,envMapCubeUVHeight:ue,aoMap:dt,lightMap:xt,bumpMap:Dt,normalMap:We,displacementMap:f&&mt,emissiveMap:it,normalMapObjectSpace:We&&I.normalMapType===bx,normalMapTangentSpace:We&&I.normalMapType===so,metalnessMap:st,roughnessMap:oe,anisotropy:F,anisotropyMap:rt,clearcoat:le,clearcoatMap:ht,clearcoatNormalMap:Tt,clearcoatRoughnessMap:Mt,dispersion:pe,iridescence:Le,iridescenceMap:Ut,iridescenceThicknessMap:Kt,sheen:He,sheenColorMap:fr,sheenRoughnessMap:er,specularMap:Zt,specularColorMap:Gt,specularIntensityMap:Er,transmission:at,transmissionMap:ut,thicknessMap:zt,gradientMap:It,opaque:I.transparent===!1&&I.blending===vt&&I.alphaToCoverage===!1,alphaMap:Ct,alphaTest:rr,alphaHash:$t,combine:I.combine,mapUv:Qe&&x(I.map.channel),aoMapUv:dt&&x(I.aoMap.channel),lightMapUv:xt&&x(I.lightMap.channel),bumpMapUv:Dt&&x(I.bumpMap.channel),normalMapUv:We&&x(I.normalMap.channel),displacementMapUv:mt&&x(I.displacementMap.channel),emissiveMapUv:it&&x(I.emissiveMap.channel),metalnessMapUv:st&&x(I.metalnessMap.channel),roughnessMapUv:oe&&x(I.roughnessMap.channel),anisotropyMapUv:rt&&x(I.anisotropyMap.channel),clearcoatMapUv:ht&&x(I.clearcoatMap.channel),clearcoatNormalMapUv:Tt&&x(I.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Mt&&x(I.clearcoatRoughnessMap.channel),iridescenceMapUv:Ut&&x(I.iridescenceMap.channel),iridescenceThicknessMapUv:Kt&&x(I.iridescenceThicknessMap.channel),sheenColorMapUv:fr&&x(I.sheenColorMap.channel),sheenRoughnessMapUv:er&&x(I.sheenRoughnessMap.channel),specularMapUv:Zt&&x(I.specularMap.channel),specularColorMapUv:Gt&&x(I.specularColorMap.channel),specularIntensityMapUv:Er&&x(I.specularIntensityMap.channel),transmissionMapUv:ut&&x(I.transmissionMap.channel),thicknessMapUv:zt&&x(I.thicknessMap.channel),alphaMapUv:Ct&&x(I.alphaMap.channel),vertexTangents:!!ze.attributes.tangent&&(We||F),vertexColors:I.vertexColors,vertexAlphas:I.vertexColors===!0&&!!ze.attributes.color&&ze.attributes.color.itemSize===4,pointsUvs:ce.isPoints===!0&&!!ze.attributes.uv&&(Qe||Ct),fog:!!fe,useFog:I.fog===!0,fogExp2:!!fe&&fe.isFogExp2,flatShading:I.flatShading===!0,sizeAttenuation:I.sizeAttenuation===!0,logarithmicDepthBuffer:d,reverseDepthBuffer:Ue,skinning:ce.isSkinnedMesh===!0,morphTargets:ze.morphAttributes.position!==void 0,morphNormals:ze.morphAttributes.normal!==void 0,morphColors:ze.morphAttributes.color!==void 0,morphTargetsCount:Ie,morphTextureStride:Re,numDirLights:L.directional.length,numPointLights:L.point.length,numSpotLights:L.spot.length,numSpotLightMaps:L.spotLightMap.length,numRectAreaLights:L.rectArea.length,numHemiLights:L.hemi.length,numDirLightShadows:L.directionalShadowMap.length,numPointLightShadows:L.pointShadowMap.length,numSpotLightShadows:L.spotShadowMap.length,numSpotLightShadowsWithMaps:L.numSpotLightShadowsWithMaps,numLightProbes:L.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:I.dithering,shadowMapEnabled:e.shadowMap.enabled&&Z.length>0,shadowMapType:e.shadowMap.type,toneMapping:cr,decodeVideoTexture:Qe&&I.map.isVideoTexture===!0&&li.getTransfer(I.map.colorSpace)===Ii,decodeVideoTextureEmissive:it&&I.emissiveMap.isVideoTexture===!0&&li.getTransfer(I.emissiveMap.colorSpace)===Ii,premultipliedAlpha:I.premultipliedAlpha,doubleSided:I.side===Ze,flipSided:I.side===tt,useDepthPacking:I.depthPacking>=0,depthPacking:I.depthPacking||0,index0AttributeName:I.index0AttributeName,extensionClipCullDistance:xr&&I.extensions.clipCullDistance===!0&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(xr&&I.extensions.multiDraw===!0||nt)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:I.customProgramCacheKey()};return yr.vertexUv1s=c.has(1),yr.vertexUv2s=c.has(2),yr.vertexUv3s=c.has(3),c.clear(),yr}function v(I){let L=[];if(I.shaderID?L.push(I.shaderID):(L.push(I.customVertexShaderID),L.push(I.customFragmentShaderID)),I.defines!==void 0)for(let Z in I.defines)L.push(Z),L.push(I.defines[Z]);return I.isRawShaderMaterial===!1&&(_(L,I),E(L,I),L.push(e.outputColorSpace)),L.push(I.customProgramCacheKey),L.join()}function _(I,L){I.push(L.precision),I.push(L.outputColorSpace),I.push(L.envMapMode),I.push(L.envMapCubeUVHeight),I.push(L.mapUv),I.push(L.alphaMapUv),I.push(L.lightMapUv),I.push(L.aoMapUv),I.push(L.bumpMapUv),I.push(L.normalMapUv),I.push(L.displacementMapUv),I.push(L.emissiveMapUv),I.push(L.metalnessMapUv),I.push(L.roughnessMapUv),I.push(L.anisotropyMapUv),I.push(L.clearcoatMapUv),I.push(L.clearcoatNormalMapUv),I.push(L.clearcoatRoughnessMapUv),I.push(L.iridescenceMapUv),I.push(L.iridescenceThicknessMapUv),I.push(L.sheenColorMapUv),I.push(L.sheenRoughnessMapUv),I.push(L.specularMapUv),I.push(L.specularColorMapUv),I.push(L.specularIntensityMapUv),I.push(L.transmissionMapUv),I.push(L.thicknessMapUv),I.push(L.combine),I.push(L.fogExp2),I.push(L.sizeAttenuation),I.push(L.morphTargetsCount),I.push(L.morphAttributeCount),I.push(L.numDirLights),I.push(L.numPointLights),I.push(L.numSpotLights),I.push(L.numSpotLightMaps),I.push(L.numHemiLights),I.push(L.numRectAreaLights),I.push(L.numDirLightShadows),I.push(L.numPointLightShadows),I.push(L.numSpotLightShadows),I.push(L.numSpotLightShadowsWithMaps),I.push(L.numLightProbes),I.push(L.shadowMapType),I.push(L.toneMapping),I.push(L.numClippingPlanes),I.push(L.numClipIntersection),I.push(L.depthPacking)}function E(I,L){o.disableAll(),L.supportsVertexTextures&&o.enable(0),L.instancing&&o.enable(1),L.instancingColor&&o.enable(2),L.instancingMorph&&o.enable(3),L.matcap&&o.enable(4),L.envMap&&o.enable(5),L.normalMapObjectSpace&&o.enable(6),L.normalMapTangentSpace&&o.enable(7),L.clearcoat&&o.enable(8),L.iridescence&&o.enable(9),L.alphaTest&&o.enable(10),L.vertexColors&&o.enable(11),L.vertexAlphas&&o.enable(12),L.vertexUv1s&&o.enable(13),L.vertexUv2s&&o.enable(14),L.vertexUv3s&&o.enable(15),L.vertexTangents&&o.enable(16),L.anisotropy&&o.enable(17),L.alphaHash&&o.enable(18),L.batching&&o.enable(19),L.dispersion&&o.enable(20),L.batchingColor&&o.enable(21),I.push(o.mask),o.disableAll(),L.fog&&o.enable(0),L.useFog&&o.enable(1),L.flatShading&&o.enable(2),L.logarithmicDepthBuffer&&o.enable(3),L.reverseDepthBuffer&&o.enable(4),L.skinning&&o.enable(5),L.morphTargets&&o.enable(6),L.morphNormals&&o.enable(7),L.morphColors&&o.enable(8),L.premultipliedAlpha&&o.enable(9),L.shadowMapEnabled&&o.enable(10),L.doubleSided&&o.enable(11),L.flipSided&&o.enable(12),L.useDepthPacking&&o.enable(13),L.dithering&&o.enable(14),L.transmission&&o.enable(15),L.sheen&&o.enable(16),L.opaque&&o.enable(17),L.pointsUvs&&o.enable(18),L.decodeVideoTexture&&o.enable(19),L.decodeVideoTextureEmissive&&o.enable(20),L.alphaToCoverage&&o.enable(21),I.push(o.mask)}function M(I){let L=b[I.type],Z;if(L){let se=$s[L];Z=Rs.clone(se.uniforms)}else Z=I.uniforms;return Z}function P(I,L){let Z;for(let se=0,ce=u.length;se<ce;se++){let fe=u[se];if(fe.cacheKey===L){Z=fe,++Z.usedTimes;break}}return Z===void 0&&(Z=new FN(e,L,I,s),u.push(Z)),Z}function k(I){if(--I.usedTimes===0){let L=u.indexOf(I);u[L]=u[u.length-1],u.pop(),I.destroy()}}function z(I){l.remove(I)}function D(){l.dispose()}return{getParameters:g,getProgramCacheKey:v,getUniforms:M,acquireProgram:P,releaseProgram:k,releaseShaderCache:z,programs:u,dispose:D}}function HN(){let e=new WeakMap;function t(a){return e.has(a)}function r(a){let o=e.get(a);return o===void 0&&(o={},e.set(a,o)),o}function i(a){e.delete(a)}function n(a,o,l){e.get(a)[o]=l}function s(){e=new WeakMap}return{has:t,get:r,remove:i,update:n,dispose:s}}function GN(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.material.id!==t.material.id?e.material.id-t.material.id:e.z!==t.z?e.z-t.z:e.id-t.id}function uw(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.z!==t.z?t.z-e.z:e.id-t.id}function dw(){let e=[],t=0,r=[],i=[],n=[];function s(){t=0,r.length=0,i.length=0,n.length=0}function a(d,f,y,b,x,g){let v=e[t];return v===void 0?(v={id:d.id,object:d,geometry:f,material:y,groupOrder:b,renderOrder:d.renderOrder,z:x,group:g},e[t]=v):(v.id=d.id,v.object=d,v.geometry=f,v.material=y,v.groupOrder=b,v.renderOrder=d.renderOrder,v.z=x,v.group=g),t++,v}function o(d,f,y,b,x,g){let v=a(d,f,y,b,x,g);y.transmission>0?i.push(v):y.transparent===!0?n.push(v):r.push(v)}function l(d,f,y,b,x,g){let v=a(d,f,y,b,x,g);y.transmission>0?i.unshift(v):y.transparent===!0?n.unshift(v):r.unshift(v)}function c(d,f){r.length>1&&r.sort(d||GN),i.length>1&&i.sort(f||uw),n.length>1&&n.sort(f||uw)}function u(){for(let d=t,f=e.length;d<f;d++){let y=e[d];if(y.id===null)break;y.id=null,y.object=null,y.geometry=null,y.material=null,y.group=null}}return{opaque:r,transmissive:i,transparent:n,init:s,push:o,unshift:l,finish:u,sort:c}}function WN(){let e=new WeakMap;function t(i,n){let s=e.get(i),a;return s===void 0?(a=new dw,e.set(i,[a])):n>=s.length?(a=new dw,s.push(a)):a=s[n],a}function r(){e=new WeakMap}return{get:t,dispose:r}}function XN(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let r;switch(t.type){case"DirectionalLight":r={direction:new je,color:new or};break;case"SpotLight":r={position:new je,direction:new je,color:new or,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":r={position:new je,color:new or,distance:0,decay:0};break;case"HemisphereLight":r={direction:new je,skyColor:new or,groundColor:new or};break;case"RectAreaLight":r={color:new or,position:new je,halfWidth:new je,halfHeight:new je};break}return e[t.id]=r,r}}}function YN(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let r;switch(t.type){case"DirectionalLight":r={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Ft};break;case"SpotLight":r={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Ft};break;case"PointLight":r={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Ft,shadowCameraNear:1,shadowCameraFar:1e3};break}return e[t.id]=r,r}}}var qN=0;function KN(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+(t.map?1:0)-(e.map?1:0)}function ZN(e){let t=new XN,r=YN(),i={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let c=0;c<9;c++)i.probe.push(new je);let n=new je,s=new Ir,a=new Ir;function o(c){let u=0,d=0,f=0;for(let I=0;I<9;I++)i.probe[I].set(0,0,0);let y=0,b=0,x=0,g=0,v=0,_=0,E=0,M=0,P=0,k=0,z=0;c.sort(KN);for(let I=0,L=c.length;I<L;I++){let Z=c[I],se=Z.color,ce=Z.intensity,fe=Z.distance,ze=Z.shadow&&Z.shadow.map?Z.shadow.map.texture:null;if(Z.isAmbientLight)u+=se.r*ce,d+=se.g*ce,f+=se.b*ce;else if(Z.isLightProbe){for(let Fe=0;Fe<9;Fe++)i.probe[Fe].addScaledVector(Z.sh.coefficients[Fe],ce);z++}else if(Z.isDirectionalLight){let Fe=t.get(Z);if(Fe.color.copy(Z.color).multiplyScalar(Z.intensity),Z.castShadow){let Pe=Z.shadow,ue=r.get(Z);ue.shadowIntensity=Pe.intensity,ue.shadowBias=Pe.bias,ue.shadowNormalBias=Pe.normalBias,ue.shadowRadius=Pe.radius,ue.shadowMapSize=Pe.mapSize,i.directionalShadow[y]=ue,i.directionalShadowMap[y]=ze,i.directionalShadowMatrix[y]=Z.shadow.matrix,_++}i.directional[y]=Fe,y++}else if(Z.isSpotLight){let Fe=t.get(Z);Fe.position.setFromMatrixPosition(Z.matrixWorld),Fe.color.copy(se).multiplyScalar(ce),Fe.distance=fe,Fe.coneCos=Math.cos(Z.angle),Fe.penumbraCos=Math.cos(Z.angle*(1-Z.penumbra)),Fe.decay=Z.decay,i.spot[x]=Fe;let Pe=Z.shadow;if(Z.map&&(i.spotLightMap[P]=Z.map,P++,Pe.updateMatrices(Z),Z.castShadow&&k++),i.spotLightMatrix[x]=Pe.matrix,Z.castShadow){let ue=r.get(Z);ue.shadowIntensity=Pe.intensity,ue.shadowBias=Pe.bias,ue.shadowNormalBias=Pe.normalBias,ue.shadowRadius=Pe.radius,ue.shadowMapSize=Pe.mapSize,i.spotShadow[x]=ue,i.spotShadowMap[x]=ze,M++}x++}else if(Z.isRectAreaLight){let Fe=t.get(Z);Fe.color.copy(se).multiplyScalar(ce),Fe.halfWidth.set(Z.width*.5,0,0),Fe.halfHeight.set(0,Z.height*.5,0),i.rectArea[g]=Fe,g++}else if(Z.isPointLight){let Fe=t.get(Z);if(Fe.color.copy(Z.color).multiplyScalar(Z.intensity),Fe.distance=Z.distance,Fe.decay=Z.decay,Z.castShadow){let Pe=Z.shadow,ue=r.get(Z);ue.shadowIntensity=Pe.intensity,ue.shadowBias=Pe.bias,ue.shadowNormalBias=Pe.normalBias,ue.shadowRadius=Pe.radius,ue.shadowMapSize=Pe.mapSize,ue.shadowCameraNear=Pe.camera.near,ue.shadowCameraFar=Pe.camera.far,i.pointShadow[b]=ue,i.pointShadowMap[b]=ze,i.pointShadowMatrix[b]=Z.shadow.matrix,E++}i.point[b]=Fe,b++}else if(Z.isHemisphereLight){let Fe=t.get(Z);Fe.skyColor.copy(Z.color).multiplyScalar(ce),Fe.groundColor.copy(Z.groundColor).multiplyScalar(ce),i.hemi[v]=Fe,v++}}g>0&&(e.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=vr.LTC_FLOAT_1,i.rectAreaLTC2=vr.LTC_FLOAT_2):(i.rectAreaLTC1=vr.LTC_HALF_1,i.rectAreaLTC2=vr.LTC_HALF_2)),i.ambient[0]=u,i.ambient[1]=d,i.ambient[2]=f;let D=i.hash;(D.directionalLength!==y||D.pointLength!==b||D.spotLength!==x||D.rectAreaLength!==g||D.hemiLength!==v||D.numDirectionalShadows!==_||D.numPointShadows!==E||D.numSpotShadows!==M||D.numSpotMaps!==P||D.numLightProbes!==z)&&(i.directional.length=y,i.spot.length=x,i.rectArea.length=g,i.point.length=b,i.hemi.length=v,i.directionalShadow.length=_,i.directionalShadowMap.length=_,i.pointShadow.length=E,i.pointShadowMap.length=E,i.spotShadow.length=M,i.spotShadowMap.length=M,i.directionalShadowMatrix.length=_,i.pointShadowMatrix.length=E,i.spotLightMatrix.length=M+P-k,i.spotLightMap.length=P,i.numSpotLightShadowsWithMaps=k,i.numLightProbes=z,D.directionalLength=y,D.pointLength=b,D.spotLength=x,D.rectAreaLength=g,D.hemiLength=v,D.numDirectionalShadows=_,D.numPointShadows=E,D.numSpotShadows=M,D.numSpotMaps=P,D.numLightProbes=z,i.version=qN++)}function l(c,u){let d=0,f=0,y=0,b=0,x=0,g=u.matrixWorldInverse;for(let v=0,_=c.length;v<_;v++){let E=c[v];if(E.isDirectionalLight){let M=i.directional[d];M.direction.setFromMatrixPosition(E.matrixWorld),n.setFromMatrixPosition(E.target.matrixWorld),M.direction.sub(n),M.direction.transformDirection(g),d++}else if(E.isSpotLight){let M=i.spot[y];M.position.setFromMatrixPosition(E.matrixWorld),M.position.applyMatrix4(g),M.direction.setFromMatrixPosition(E.matrixWorld),n.setFromMatrixPosition(E.target.matrixWorld),M.direction.sub(n),M.direction.transformDirection(g),y++}else if(E.isRectAreaLight){let M=i.rectArea[b];M.position.setFromMatrixPosition(E.matrixWorld),M.position.applyMatrix4(g),a.identity(),s.copy(E.matrixWorld),s.premultiply(g),a.extractRotation(s),M.halfWidth.set(E.width*.5,0,0),M.halfHeight.set(0,E.height*.5,0),M.halfWidth.applyMatrix4(a),M.halfHeight.applyMatrix4(a),b++}else if(E.isPointLight){let M=i.point[f];M.position.setFromMatrixPosition(E.matrixWorld),M.position.applyMatrix4(g),f++}else if(E.isHemisphereLight){let M=i.hemi[x];M.direction.setFromMatrixPosition(E.matrixWorld),M.direction.transformDirection(g),x++}}}return{setup:o,setupView:l,state:i}}function pw(e){let t=new ZN(e),r=[],i=[];function n(u){c.camera=u,r.length=0,i.length=0}function s(u){r.push(u)}function a(u){i.push(u)}function o(){t.setup(r)}function l(u){t.setupView(r,u)}let c={lightsArray:r,shadowsArray:i,camera:null,lights:t,transmissionRenderTarget:{}};return{init:n,state:c,setupLights:o,setupLightsView:l,pushLight:s,pushShadow:a}}function $N(e){let t=new WeakMap;function r(n,s=0){let a=t.get(n),o;return a===void 0?(o=new pw(e),t.set(n,[o])):s>=a.length?(o=new pw(e),a.push(o)):o=a[s],o}function i(){t=new WeakMap}return{get:r,dispose:i}}var JN=`void main() {
	gl_Position = vec4( position, 1.0 );
}`,QN=`uniform sampler2D shadow_pass;
uniform vec2 resolution;
uniform float radius;
#include <packing>
void main() {
	const float samples = float( VSM_SAMPLES );
	float mean = 0.0;
	float squared_mean = 0.0;
	float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 );
	float uvStart = samples <= 1.0 ? 0.0 : - 1.0;
	for ( float i = 0.0; i < samples; i ++ ) {
		float uvOffset = uvStart + i * uvStride;
		#ifdef HORIZONTAL_PASS
			vec2 distribution = unpackRGBATo2Half( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ) );
			mean += distribution.x;
			squared_mean += distribution.y * distribution.y + distribution.x * distribution.x;
		#else
			float depth = unpackRGBAToDepth( texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ) );
			mean += depth;
			squared_mean += depth * depth;
		#endif
	}
	mean = mean / samples;
	squared_mean = squared_mean / samples;
	float std_dev = sqrt( squared_mean - mean * mean );
	gl_FragColor = pack2HalfToRGBA( vec2( mean, std_dev ) );
}`;function eL(e,t,r){let i=new qh,n=new Ft,s=new Ft,a=new _i,o=new cy({depthPacking:xx}),l=new hy,c={},u=r.maxTextureSize,d={[Ce]:tt,[tt]:Ce,[Ze]:Ze},f=new ln({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Ft},radius:{value:4}},vertexShader:JN,fragmentShader:QN}),y=f.clone();y.defines.HORIZONTAL_PASS=1;let b=new Hr;b.setAttribute("position",new ui(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let x=new qr(b,f),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=xe;let v=this.type;this.render=function(k,z,D){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||k.length===0)return;let I=e.getRenderTarget(),L=e.getActiveCubeFace(),Z=e.getActiveMipmapLevel(),se=e.state;se.setBlending(Ye),se.buffers.color.setClear(1,1,1,1),se.buffers.depth.setTest(!0),se.setScissorTest(!1);let ce=v!==Me&&this.type===Me,fe=v===Me&&this.type!==Me;for(let ze=0,Fe=k.length;ze<Fe;ze++){let Pe=k[ze],ue=Pe.shadow;if(ue===void 0){console.warn("THREE.WebGLShadowMap:",Pe,"has no shadow.");continue}if(ue.autoUpdate===!1&&ue.needsUpdate===!1)continue;n.copy(ue.mapSize);let Te=ue.getFrameExtents();if(n.multiply(Te),s.copy(ue.mapSize),(n.x>u||n.y>u)&&(n.x>u&&(s.x=Math.floor(u/Te.x),n.x=s.x*Te.x,ue.mapSize.x=s.x),n.y>u&&(s.y=Math.floor(u/Te.y),n.y=s.y*Te.y,ue.mapSize.y=s.y)),ue.map===null||ce===!0||fe===!0){let Ie=this.type!==Me?{minFilter:oi,magFilter:oi}:{};ue.map!==null&&ue.map.dispose(),ue.map=new In(n.x,n.y,Ie),ue.map.texture.name=Pe.name+".shadowMap",ue.camera.updateProjectionMatrix()}e.setRenderTarget(ue.map),e.clear();let de=ue.getViewportCount();for(let Ie=0;Ie<de;Ie++){let Re=ue.getViewport(Ie);a.set(s.x*Re.x,s.y*Re.y,s.x*Re.z,s.y*Re.w),se.viewport(a),ue.updateMatrices(Pe,Ie),i=ue.getFrustum(),M(z,D,ue.camera,Pe,this.type)}ue.isPointLightShadow!==!0&&this.type===Me&&_(ue,D),ue.needsUpdate=!1}v=this.type,g.needsUpdate=!1,e.setRenderTarget(I,L,Z)};function _(k,z){let D=t.update(x);f.defines.VSM_SAMPLES!==k.blurSamples&&(f.defines.VSM_SAMPLES=k.blurSamples,y.defines.VSM_SAMPLES=k.blurSamples,f.needsUpdate=!0,y.needsUpdate=!0),k.mapPass===null&&(k.mapPass=new In(n.x,n.y)),f.uniforms.shadow_pass.value=k.map.texture,f.uniforms.resolution.value=k.mapSize,f.uniforms.radius.value=k.radius,e.setRenderTarget(k.mapPass),e.clear(),e.renderBufferDirect(z,null,D,f,x,null),y.uniforms.shadow_pass.value=k.mapPass.texture,y.uniforms.resolution.value=k.mapSize,y.uniforms.radius.value=k.radius,e.setRenderTarget(k.map),e.clear(),e.renderBufferDirect(z,null,D,y,x,null)}function E(k,z,D,I){let L=null,Z=D.isPointLight===!0?k.customDistanceMaterial:k.customDepthMaterial;if(Z!==void 0)L=Z;else if(L=D.isPointLight===!0?l:o,e.localClippingEnabled&&z.clipShadows===!0&&Array.isArray(z.clippingPlanes)&&z.clippingPlanes.length!==0||z.displacementMap&&z.displacementScale!==0||z.alphaMap&&z.alphaTest>0||z.map&&z.alphaTest>0){let se=L.uuid,ce=z.uuid,fe=c[se];fe===void 0&&(fe={},c[se]=fe);let ze=fe[ce];ze===void 0&&(ze=L.clone(),fe[ce]=ze,z.addEventListener("dispose",P)),L=ze}if(L.visible=z.visible,L.wireframe=z.wireframe,I===Me?L.side=z.shadowSide!==null?z.shadowSide:z.side:L.side=z.shadowSide!==null?z.shadowSide:d[z.side],L.alphaMap=z.alphaMap,L.alphaTest=z.alphaTest,L.map=z.map,L.clipShadows=z.clipShadows,L.clippingPlanes=z.clippingPlanes,L.clipIntersection=z.clipIntersection,L.displacementMap=z.displacementMap,L.displacementScale=z.displacementScale,L.displacementBias=z.displacementBias,L.wireframeLinewidth=z.wireframeLinewidth,L.linewidth=z.linewidth,D.isPointLight===!0&&L.isMeshDistanceMaterial===!0){let se=e.properties.get(L);se.light=D}return L}function M(k,z,D,I,L){if(k.visible===!1)return;if(k.layers.test(z.layers)&&(k.isMesh||k.isLine||k.isPoints)&&(k.castShadow||k.receiveShadow&&L===Me)&&(!k.frustumCulled||i.intersectsObject(k))){k.modelViewMatrix.multiplyMatrices(D.matrixWorldInverse,k.matrixWorld);let se=t.update(k),ce=k.material;if(Array.isArray(ce)){let fe=se.groups;for(let ze=0,Fe=fe.length;ze<Fe;ze++){let Pe=fe[ze],ue=ce[Pe.materialIndex];if(ue&&ue.visible){let Te=E(k,ue,I,L);k.onBeforeShadow(e,k,z,D,se,Te,Pe),e.renderBufferDirect(D,null,se,Te,k,Pe),k.onAfterShadow(e,k,z,D,se,Te,Pe)}}}else if(ce.visible){let fe=E(k,ce,I,L);k.onBeforeShadow(e,k,z,D,se,fe,null),e.renderBufferDirect(D,null,se,fe,k,null),k.onAfterShadow(e,k,z,D,se,fe,null)}}let Z=k.children;for(let se=0,ce=Z.length;se<ce;se++)M(Z[se],z,D,I,L)}function P(k){k.target.removeEventListener("dispose",P);for(let z in c){let D=c[z],I=k.target.uuid;I in D&&(D[I].dispose(),delete D[I])}}}var tL={[jt]:Jt,[sr]:ar,[qt]:Ar,[Xt]:gr,[Jt]:jt,[ar]:sr,[Ar]:qt,[gr]:Xt};function rL(e,t){function r(){let ut=!1,zt=new _i,It=null,Ct=new _i(0,0,0,0);return{setMask:function(rr){It!==rr&&!ut&&(e.colorMask(rr,rr,rr,rr),It=rr)},setLocked:function(rr){ut=rr},setClear:function(rr,$t,xr,cr,yr){yr===!0&&(rr*=cr,$t*=cr,xr*=cr),zt.set(rr,$t,xr,cr),Ct.equals(zt)===!1&&(e.clearColor(rr,$t,xr,cr),Ct.copy(zt))},reset:function(){ut=!1,It=null,Ct.set(-1,0,0,0)}}}function i(){let ut=!1,zt=!1,It=null,Ct=null,rr=null;return{setReversed:function($t){if(zt!==$t){let xr=t.get("EXT_clip_control");zt?xr.clipControlEXT(xr.LOWER_LEFT_EXT,xr.ZERO_TO_ONE_EXT):xr.clipControlEXT(xr.LOWER_LEFT_EXT,xr.NEGATIVE_ONE_TO_ONE_EXT);let cr=rr;rr=null,this.setClear(cr)}zt=$t},getReversed:function(){return zt},setTest:function($t){$t?Ae(e.DEPTH_TEST):Ue(e.DEPTH_TEST)},setMask:function($t){It!==$t&&!ut&&(e.depthMask($t),It=$t)},setFunc:function($t){if(zt&&($t=tL[$t]),Ct!==$t){switch($t){case jt:e.depthFunc(e.NEVER);break;case Jt:e.depthFunc(e.ALWAYS);break;case sr:e.depthFunc(e.LESS);break;case Xt:e.depthFunc(e.LEQUAL);break;case qt:e.depthFunc(e.EQUAL);break;case gr:e.depthFunc(e.GEQUAL);break;case ar:e.depthFunc(e.GREATER);break;case Ar:e.depthFunc(e.NOTEQUAL);break;default:e.depthFunc(e.LEQUAL)}Ct=$t}},setLocked:function($t){ut=$t},setClear:function($t){rr!==$t&&(zt&&($t=1-$t),e.clearDepth($t),rr=$t)},reset:function(){ut=!1,It=null,Ct=null,rr=null,zt=!1}}}function n(){let ut=!1,zt=null,It=null,Ct=null,rr=null,$t=null,xr=null,cr=null,yr=null;return{setTest:function(ir){ut||(ir?Ae(e.STENCIL_TEST):Ue(e.STENCIL_TEST))},setMask:function(ir){zt!==ir&&!ut&&(e.stencilMask(ir),zt=ir)},setFunc:function(ir,_r,Vt){(It!==ir||Ct!==_r||rr!==Vt)&&(e.stencilFunc(ir,_r,Vt),It=ir,Ct=_r,rr=Vt)},setOp:function(ir,_r,Vt){($t!==ir||xr!==_r||cr!==Vt)&&(e.stencilOp(ir,_r,Vt),$t=ir,xr=_r,cr=Vt)},setLocked:function(ir){ut=ir},setClear:function(ir){yr!==ir&&(e.clearStencil(ir),yr=ir)},reset:function(){ut=!1,zt=null,It=null,Ct=null,rr=null,$t=null,xr=null,cr=null,yr=null}}}let s=new r,a=new i,o=new n,l=new WeakMap,c=new WeakMap,u={},d={},f=new WeakMap,y=[],b=null,x=!1,g=null,v=null,_=null,E=null,M=null,P=null,k=null,z=new or(0,0,0),D=0,I=!1,L=null,Z=null,se=null,ce=null,fe=null,ze=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),Fe=!1,Pe=0,ue=e.getParameter(e.VERSION);ue.indexOf("WebGL")!==-1?(Pe=parseFloat(/^WebGL (\d)/.exec(ue)[1]),Fe=Pe>=1):ue.indexOf("OpenGL ES")!==-1&&(Pe=parseFloat(/^OpenGL ES (\d)/.exec(ue)[1]),Fe=Pe>=2);let Te=null,de={},Ie=e.getParameter(e.SCISSOR_BOX),Re=e.getParameter(e.VIEWPORT),Be=new _i().fromArray(Ie),Se=new _i().fromArray(Re);function U(ut,zt,It,Ct){let rr=new Uint8Array(4),$t=e.createTexture();e.bindTexture(ut,$t),e.texParameteri(ut,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(ut,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let xr=0;xr<It;xr++)ut===e.TEXTURE_3D||ut===e.TEXTURE_2D_ARRAY?e.texImage3D(zt,0,e.RGBA,1,1,Ct,0,e.RGBA,e.UNSIGNED_BYTE,rr):e.texImage2D(zt+xr,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,rr);return $t}let ie={};ie[e.TEXTURE_2D]=U(e.TEXTURE_2D,e.TEXTURE_2D,1),ie[e.TEXTURE_CUBE_MAP]=U(e.TEXTURE_CUBE_MAP,e.TEXTURE_CUBE_MAP_POSITIVE_X,6),ie[e.TEXTURE_2D_ARRAY]=U(e.TEXTURE_2D_ARRAY,e.TEXTURE_2D_ARRAY,1,1),ie[e.TEXTURE_3D]=U(e.TEXTURE_3D,e.TEXTURE_3D,1,1),s.setClear(0,0,0,1),a.setClear(1),o.setClear(0),Ae(e.DEPTH_TEST),a.setFunc(Xt),Dt(!1),We(ge),Ae(e.CULL_FACE),dt(Ye);function Ae(ut){u[ut]!==!0&&(e.enable(ut),u[ut]=!0)}function Ue(ut){u[ut]!==!1&&(e.disable(ut),u[ut]=!1)}function Ge(ut,zt){return d[ut]!==zt?(e.bindFramebuffer(ut,zt),d[ut]=zt,ut===e.DRAW_FRAMEBUFFER&&(d[e.FRAMEBUFFER]=zt),ut===e.FRAMEBUFFER&&(d[e.DRAW_FRAMEBUFFER]=zt),!0):!1}function nt(ut,zt){let It=y,Ct=!1;if(ut){It=f.get(zt),It===void 0&&(It=[],f.set(zt,It));let rr=ut.textures;if(It.length!==rr.length||It[0]!==e.COLOR_ATTACHMENT0){for(let $t=0,xr=rr.length;$t<xr;$t++)It[$t]=e.COLOR_ATTACHMENT0+$t;It.length=rr.length,Ct=!0}}else It[0]!==e.BACK&&(It[0]=e.BACK,Ct=!0);Ct&&e.drawBuffers(It)}function Qe(ut){return b!==ut?(e.useProgram(ut),b=ut,!0):!1}let ct={[gt]:e.FUNC_ADD,[Ht]:e.FUNC_SUBTRACT,[lt]:e.FUNC_REVERSE_SUBTRACT};ct[et]=e.MIN,ct[St]=e.MAX;let ye={[At]:e.ZERO,[Wt]:e.ONE,[nr]:e.SRC_COLOR,[ft]:e.SRC_ALPHA,[Zr]:e.SRC_ALPHA_SATURATE,[Gr]:e.DST_COLOR,[Yt]:e.DST_ALPHA,[pt]:e.ONE_MINUS_SRC_COLOR,[Bt]:e.ONE_MINUS_SRC_ALPHA,[Qr]:e.ONE_MINUS_DST_COLOR,[kr]:e.ONE_MINUS_DST_ALPHA,[ii]:e.CONSTANT_COLOR,[ur]:e.ONE_MINUS_CONSTANT_COLOR,[Gi]:e.CONSTANT_ALPHA,[yt]:e.ONE_MINUS_CONSTANT_ALPHA};function dt(ut,zt,It,Ct,rr,$t,xr,cr,yr,ir){if(ut===Ye){x===!0&&(Ue(e.BLEND),x=!1);return}if(x===!1&&(Ae(e.BLEND),x=!0),ut!==Et){if(ut!==g||ir!==I){if((v!==gt||M!==gt)&&(e.blendEquation(e.FUNC_ADD),v=gt,M=gt),ir)switch(ut){case vt:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case Rt:e.blendFunc(e.ONE,e.ONE);break;case Je:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case _t:e.blendFuncSeparate(e.ZERO,e.SRC_COLOR,e.ZERO,e.SRC_ALPHA);break;default:console.error("THREE.WebGLState: Invalid blending: ",ut);break}else switch(ut){case vt:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case Rt:e.blendFunc(e.SRC_ALPHA,e.ONE);break;case Je:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case _t:e.blendFunc(e.ZERO,e.SRC_COLOR);break;default:console.error("THREE.WebGLState: Invalid blending: ",ut);break}_=null,E=null,P=null,k=null,z.set(0,0,0),D=0,g=ut,I=ir}return}rr=rr||zt,$t=$t||It,xr=xr||Ct,(zt!==v||rr!==M)&&(e.blendEquationSeparate(ct[zt],ct[rr]),v=zt,M=rr),(It!==_||Ct!==E||$t!==P||xr!==k)&&(e.blendFuncSeparate(ye[It],ye[Ct],ye[$t],ye[xr]),_=It,E=Ct,P=$t,k=xr),(cr.equals(z)===!1||yr!==D)&&(e.blendColor(cr.r,cr.g,cr.b,yr),z.copy(cr),D=yr),g=ut,I=!1}function xt(ut,zt){ut.side===Ze?Ue(e.CULL_FACE):Ae(e.CULL_FACE);let It=ut.side===tt;zt&&(It=!It),Dt(It),ut.blending===vt&&ut.transparent===!1?dt(Ye):dt(ut.blending,ut.blendEquation,ut.blendSrc,ut.blendDst,ut.blendEquationAlpha,ut.blendSrcAlpha,ut.blendDstAlpha,ut.blendColor,ut.blendAlpha,ut.premultipliedAlpha),a.setFunc(ut.depthFunc),a.setTest(ut.depthTest),a.setMask(ut.depthWrite),s.setMask(ut.colorWrite);let Ct=ut.stencilWrite;o.setTest(Ct),Ct&&(o.setMask(ut.stencilWriteMask),o.setFunc(ut.stencilFunc,ut.stencilRef,ut.stencilFuncMask),o.setOp(ut.stencilFail,ut.stencilZFail,ut.stencilZPass)),it(ut.polygonOffset,ut.polygonOffsetFactor,ut.polygonOffsetUnits),ut.alphaToCoverage===!0?Ae(e.SAMPLE_ALPHA_TO_COVERAGE):Ue(e.SAMPLE_ALPHA_TO_COVERAGE)}function Dt(ut){L!==ut&&(ut?e.frontFace(e.CW):e.frontFace(e.CCW),L=ut)}function We(ut){ut!==K?(Ae(e.CULL_FACE),ut!==Z&&(ut===ge?e.cullFace(e.BACK):ut===Ne?e.cullFace(e.FRONT):e.cullFace(e.FRONT_AND_BACK))):Ue(e.CULL_FACE),Z=ut}function mt(ut){ut!==se&&(Fe&&e.lineWidth(ut),se=ut)}function it(ut,zt,It){ut?(Ae(e.POLYGON_OFFSET_FILL),(ce!==zt||fe!==It)&&(e.polygonOffset(zt,It),ce=zt,fe=It)):Ue(e.POLYGON_OFFSET_FILL)}function st(ut){ut?Ae(e.SCISSOR_TEST):Ue(e.SCISSOR_TEST)}function oe(ut){ut===void 0&&(ut=e.TEXTURE0+ze-1),Te!==ut&&(e.activeTexture(ut),Te=ut)}function F(ut,zt,It){It===void 0&&(Te===null?It=e.TEXTURE0+ze-1:It=Te);let Ct=de[It];Ct===void 0&&(Ct={type:void 0,texture:void 0},de[It]=Ct),(Ct.type!==ut||Ct.texture!==zt)&&(Te!==It&&(e.activeTexture(It),Te=It),e.bindTexture(ut,zt||ie[ut]),Ct.type=ut,Ct.texture=zt)}function le(){let ut=de[Te];ut!==void 0&&ut.type!==void 0&&(e.bindTexture(ut.type,null),ut.type=void 0,ut.texture=void 0)}function pe(){try{e.compressedTexImage2D.apply(e,arguments)}catch(ut){console.error("THREE.WebGLState:",ut)}}function Le(){try{e.compressedTexImage3D.apply(e,arguments)}catch(ut){console.error("THREE.WebGLState:",ut)}}function He(){try{e.texSubImage2D.apply(e,arguments)}catch(ut){console.error("THREE.WebGLState:",ut)}}function at(){try{e.texSubImage3D.apply(e,arguments)}catch(ut){console.error("THREE.WebGLState:",ut)}}function rt(){try{e.compressedTexSubImage2D.apply(e,arguments)}catch(ut){console.error("THREE.WebGLState:",ut)}}function ht(){try{e.compressedTexSubImage3D.apply(e,arguments)}catch(ut){console.error("THREE.WebGLState:",ut)}}function Tt(){try{e.texStorage2D.apply(e,arguments)}catch(ut){console.error("THREE.WebGLState:",ut)}}function Mt(){try{e.texStorage3D.apply(e,arguments)}catch(ut){console.error("THREE.WebGLState:",ut)}}function Ut(){try{e.texImage2D.apply(e,arguments)}catch(ut){console.error("THREE.WebGLState:",ut)}}function Kt(){try{e.texImage3D.apply(e,arguments)}catch(ut){console.error("THREE.WebGLState:",ut)}}function fr(ut){Be.equals(ut)===!1&&(e.scissor(ut.x,ut.y,ut.z,ut.w),Be.copy(ut))}function er(ut){Se.equals(ut)===!1&&(e.viewport(ut.x,ut.y,ut.z,ut.w),Se.copy(ut))}function Zt(ut,zt){let It=c.get(zt);It===void 0&&(It=new WeakMap,c.set(zt,It));let Ct=It.get(ut);Ct===void 0&&(Ct=e.getUniformBlockIndex(zt,ut.name),It.set(ut,Ct))}function Gt(ut,zt){let It=c.get(zt).get(ut);l.get(zt)!==It&&(e.uniformBlockBinding(zt,It,ut.__bindingPointIndex),l.set(zt,It))}function Er(){e.disable(e.BLEND),e.disable(e.CULL_FACE),e.disable(e.DEPTH_TEST),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SCISSOR_TEST),e.disable(e.STENCIL_TEST),e.disable(e.SAMPLE_ALPHA_TO_COVERAGE),e.blendEquation(e.FUNC_ADD),e.blendFunc(e.ONE,e.ZERO),e.blendFuncSeparate(e.ONE,e.ZERO,e.ONE,e.ZERO),e.blendColor(0,0,0,0),e.colorMask(!0,!0,!0,!0),e.clearColor(0,0,0,0),e.depthMask(!0),e.depthFunc(e.LESS),a.setReversed(!1),e.clearDepth(1),e.stencilMask(4294967295),e.stencilFunc(e.ALWAYS,0,4294967295),e.stencilOp(e.KEEP,e.KEEP,e.KEEP),e.clearStencil(0),e.cullFace(e.BACK),e.frontFace(e.CCW),e.polygonOffset(0,0),e.activeTexture(e.TEXTURE0),e.bindFramebuffer(e.FRAMEBUFFER,null),e.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),e.bindFramebuffer(e.READ_FRAMEBUFFER,null),e.useProgram(null),e.lineWidth(1),e.scissor(0,0,e.canvas.width,e.canvas.height),e.viewport(0,0,e.canvas.width,e.canvas.height),u={},Te=null,de={},d={},f=new WeakMap,y=[],b=null,x=!1,g=null,v=null,_=null,E=null,M=null,P=null,k=null,z=new or(0,0,0),D=0,I=!1,L=null,Z=null,se=null,ce=null,fe=null,Be.set(0,0,e.canvas.width,e.canvas.height),Se.set(0,0,e.canvas.width,e.canvas.height),s.reset(),a.reset(),o.reset()}return{buffers:{color:s,depth:a,stencil:o},enable:Ae,disable:Ue,bindFramebuffer:Ge,drawBuffers:nt,useProgram:Qe,setBlending:dt,setMaterial:xt,setFlipSided:Dt,setCullFace:We,setLineWidth:mt,setPolygonOffset:it,setScissorTest:st,activeTexture:oe,bindTexture:F,unbindTexture:le,compressedTexImage2D:pe,compressedTexImage3D:Le,texImage2D:Ut,texImage3D:Kt,updateUBOMapping:Zt,uniformBlockBinding:Gt,texStorage2D:Tt,texStorage3D:Mt,texSubImage2D:He,texSubImage3D:at,compressedTexSubImage2D:rt,compressedTexSubImage3D:ht,scissor:fr,viewport:er,reset:Er}}function iL(e,t,r,i,n,s,a){let o=t.has("WEBGL_multisampled_render_to_texture")?t.get("WEBGL_multisampled_render_to_texture"):null,l=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new Ft,u=new WeakMap,d,f=new WeakMap,y=!1;try{y=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function b(oe,F){return y?new OffscreenCanvas(oe,F):Oh("canvas")}function x(oe,F,le){let pe=1,Le=st(oe);if((Le.width>le||Le.height>le)&&(pe=le/Math.max(Le.width,Le.height)),pe<1)if(typeof HTMLImageElement<"u"&&oe instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&oe instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&oe instanceof ImageBitmap||typeof VideoFrame<"u"&&oe instanceof VideoFrame){let He=Math.floor(pe*Le.width),at=Math.floor(pe*Le.height);d===void 0&&(d=b(He,at));let rt=F?b(He,at):d;return rt.width=He,rt.height=at,rt.getContext("2d").drawImage(oe,0,0,He,at),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+Le.width+"x"+Le.height+") to ("+He+"x"+at+")."),rt}else return"data"in oe&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+Le.width+"x"+Le.height+")."),oe;return oe}function g(oe){return oe.generateMipmaps}function v(oe){e.generateMipmap(oe)}function _(oe){return oe.isWebGLCubeRenderTarget?e.TEXTURE_CUBE_MAP:oe.isWebGL3DRenderTarget?e.TEXTURE_3D:oe.isWebGLArrayRenderTarget||oe.isCompressedArrayTexture?e.TEXTURE_2D_ARRAY:e.TEXTURE_2D}function E(oe,F,le,pe,Le=!1){if(oe!==null){if(e[oe]!==void 0)return e[oe];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+oe+"'")}let He=F;if(F===e.RED&&(le===e.FLOAT&&(He=e.R32F),le===e.HALF_FLOAT&&(He=e.R16F),le===e.UNSIGNED_BYTE&&(He=e.R8)),F===e.RED_INTEGER&&(le===e.UNSIGNED_BYTE&&(He=e.R8UI),le===e.UNSIGNED_SHORT&&(He=e.R16UI),le===e.UNSIGNED_INT&&(He=e.R32UI),le===e.BYTE&&(He=e.R8I),le===e.SHORT&&(He=e.R16I),le===e.INT&&(He=e.R32I)),F===e.RG&&(le===e.FLOAT&&(He=e.RG32F),le===e.HALF_FLOAT&&(He=e.RG16F),le===e.UNSIGNED_BYTE&&(He=e.RG8)),F===e.RG_INTEGER&&(le===e.UNSIGNED_BYTE&&(He=e.RG8UI),le===e.UNSIGNED_SHORT&&(He=e.RG16UI),le===e.UNSIGNED_INT&&(He=e.RG32UI),le===e.BYTE&&(He=e.RG8I),le===e.SHORT&&(He=e.RG16I),le===e.INT&&(He=e.RG32I)),F===e.RGB_INTEGER&&(le===e.UNSIGNED_BYTE&&(He=e.RGB8UI),le===e.UNSIGNED_SHORT&&(He=e.RGB16UI),le===e.UNSIGNED_INT&&(He=e.RGB32UI),le===e.BYTE&&(He=e.RGB8I),le===e.SHORT&&(He=e.RGB16I),le===e.INT&&(He=e.RGB32I)),F===e.RGBA_INTEGER&&(le===e.UNSIGNED_BYTE&&(He=e.RGBA8UI),le===e.UNSIGNED_SHORT&&(He=e.RGBA16UI),le===e.UNSIGNED_INT&&(He=e.RGBA32UI),le===e.BYTE&&(He=e.RGBA8I),le===e.SHORT&&(He=e.RGBA16I),le===e.INT&&(He=e.RGBA32I)),F===e.RGB&&le===e.UNSIGNED_INT_5_9_9_9_REV&&(He=e.RGB9_E5),F===e.RGBA){let at=Le?Ih:li.getTransfer(pe);le===e.FLOAT&&(He=e.RGBA32F),le===e.HALF_FLOAT&&(He=e.RGBA16F),le===e.UNSIGNED_BYTE&&(He=at===Ii?e.SRGB8_ALPHA8:e.RGBA8),le===e.UNSIGNED_SHORT_4_4_4_4&&(He=e.RGBA4),le===e.UNSIGNED_SHORT_5_5_5_1&&(He=e.RGB5_A1)}return(He===e.R16F||He===e.R32F||He===e.RG16F||He===e.RG32F||He===e.RGBA16F||He===e.RGBA32F)&&t.get("EXT_color_buffer_float"),He}function M(oe,F){let le;return oe?F===null||F===Aa||F===io?le=e.DEPTH24_STENCIL8:F===es?le=e.DEPTH32F_STENCIL8:F===Ma&&(le=e.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):F===null||F===Aa||F===io?le=e.DEPTH_COMPONENT24:F===es?le=e.DEPTH_COMPONENT32F:F===Ma&&(le=e.DEPTH_COMPONENT16),le}function P(oe,F){return g(oe)===!0||oe.isFramebufferTexture&&oe.minFilter!==oi&&oe.minFilter!==Pi?Math.log2(Math.max(F.width,F.height))+1:oe.mipmaps!==void 0&&oe.mipmaps.length>0?oe.mipmaps.length:oe.isCompressedTexture&&Array.isArray(oe.image)?F.mipmaps.length:1}function k(oe){let F=oe.target;F.removeEventListener("dispose",k),D(F),F.isVideoTexture&&u.delete(F)}function z(oe){let F=oe.target;F.removeEventListener("dispose",z),L(F)}function D(oe){let F=i.get(oe);if(F.__webglInit===void 0)return;let le=oe.source,pe=f.get(le);if(pe){let Le=pe[F.__cacheKey];Le.usedTimes--,Le.usedTimes===0&&I(oe),Object.keys(pe).length===0&&f.delete(le)}i.remove(oe)}function I(oe){let F=i.get(oe);e.deleteTexture(F.__webglTexture);let le=oe.source,pe=f.get(le);delete pe[F.__cacheKey],a.memory.textures--}function L(oe){let F=i.get(oe);if(oe.depthTexture&&(oe.depthTexture.dispose(),i.remove(oe.depthTexture)),oe.isWebGLCubeRenderTarget)for(let pe=0;pe<6;pe++){if(Array.isArray(F.__webglFramebuffer[pe]))for(let Le=0;Le<F.__webglFramebuffer[pe].length;Le++)e.deleteFramebuffer(F.__webglFramebuffer[pe][Le]);else e.deleteFramebuffer(F.__webglFramebuffer[pe]);F.__webglDepthbuffer&&e.deleteRenderbuffer(F.__webglDepthbuffer[pe])}else{if(Array.isArray(F.__webglFramebuffer))for(let pe=0;pe<F.__webglFramebuffer.length;pe++)e.deleteFramebuffer(F.__webglFramebuffer[pe]);else e.deleteFramebuffer(F.__webglFramebuffer);if(F.__webglDepthbuffer&&e.deleteRenderbuffer(F.__webglDepthbuffer),F.__webglMultisampledFramebuffer&&e.deleteFramebuffer(F.__webglMultisampledFramebuffer),F.__webglColorRenderbuffer)for(let pe=0;pe<F.__webglColorRenderbuffer.length;pe++)F.__webglColorRenderbuffer[pe]&&e.deleteRenderbuffer(F.__webglColorRenderbuffer[pe]);F.__webglDepthRenderbuffer&&e.deleteRenderbuffer(F.__webglDepthRenderbuffer)}let le=oe.textures;for(let pe=0,Le=le.length;pe<Le;pe++){let He=i.get(le[pe]);He.__webglTexture&&(e.deleteTexture(He.__webglTexture),a.memory.textures--),i.remove(le[pe])}i.remove(oe)}let Z=0;function se(){Z=0}function ce(){let oe=Z;return oe>=n.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+oe+" texture units while this GPU supports only "+n.maxTextures),Z+=1,oe}function fe(oe){let F=[];return F.push(oe.wrapS),F.push(oe.wrapT),F.push(oe.wrapR||0),F.push(oe.magFilter),F.push(oe.minFilter),F.push(oe.anisotropy),F.push(oe.internalFormat),F.push(oe.format),F.push(oe.type),F.push(oe.generateMipmaps),F.push(oe.premultiplyAlpha),F.push(oe.flipY),F.push(oe.unpackAlignment),F.push(oe.colorSpace),F.join()}function ze(oe,F){let le=i.get(oe);if(oe.isVideoTexture&&mt(oe),oe.isRenderTargetTexture===!1&&oe.version>0&&le.__version!==oe.version){let pe=oe.image;if(pe===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(pe.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{Se(le,oe,F);return}}r.bindTexture(e.TEXTURE_2D,le.__webglTexture,e.TEXTURE0+F)}function Fe(oe,F){let le=i.get(oe);if(oe.version>0&&le.__version!==oe.version){Se(le,oe,F);return}r.bindTexture(e.TEXTURE_2D_ARRAY,le.__webglTexture,e.TEXTURE0+F)}function Pe(oe,F){let le=i.get(oe);if(oe.version>0&&le.__version!==oe.version){Se(le,oe,F);return}r.bindTexture(e.TEXTURE_3D,le.__webglTexture,e.TEXTURE0+F)}function ue(oe,F){let le=i.get(oe);if(oe.version>0&&le.__version!==oe.version){U(le,oe,F);return}r.bindTexture(e.TEXTURE_CUBE_MAP,le.__webglTexture,e.TEXTURE0+F)}let Te={[Wr]:e.REPEAT,[ei]:e.CLAMP_TO_EDGE,[Ri]:e.MIRRORED_REPEAT},de={[oi]:e.NEAREST,[Pn]:e.NEAREST_MIPMAP_NEAREST,[Qn]:e.NEAREST_MIPMAP_LINEAR,[Pi]:e.LINEAR,[Wn]:e.LINEAR_MIPMAP_NEAREST,[Fi]:e.LINEAR_MIPMAP_LINEAR},Ie={[wx]:e.NEVER,[Tx]:e.ALWAYS,[_x]:e.LESS,[lg]:e.LEQUAL,[Ex]:e.EQUAL,[Ax]:e.GEQUAL,[Sx]:e.GREATER,[Mx]:e.NOTEQUAL};function Re(oe,F){if(F.type===es&&t.has("OES_texture_float_linear")===!1&&(F.magFilter===Pi||F.magFilter===Wn||F.magFilter===Qn||F.magFilter===Fi||F.minFilter===Pi||F.minFilter===Wn||F.minFilter===Qn||F.minFilter===Fi)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),e.texParameteri(oe,e.TEXTURE_WRAP_S,Te[F.wrapS]),e.texParameteri(oe,e.TEXTURE_WRAP_T,Te[F.wrapT]),(oe===e.TEXTURE_3D||oe===e.TEXTURE_2D_ARRAY)&&e.texParameteri(oe,e.TEXTURE_WRAP_R,Te[F.wrapR]),e.texParameteri(oe,e.TEXTURE_MAG_FILTER,de[F.magFilter]),e.texParameteri(oe,e.TEXTURE_MIN_FILTER,de[F.minFilter]),F.compareFunction&&(e.texParameteri(oe,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(oe,e.TEXTURE_COMPARE_FUNC,Ie[F.compareFunction])),t.has("EXT_texture_filter_anisotropic")===!0){if(F.magFilter===oi||F.minFilter!==Qn&&F.minFilter!==Fi||F.type===es&&t.has("OES_texture_float_linear")===!1)return;if(F.anisotropy>1||i.get(F).__currentAnisotropy){let le=t.get("EXT_texture_filter_anisotropic");e.texParameterf(oe,le.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(F.anisotropy,n.getMaxAnisotropy())),i.get(F).__currentAnisotropy=F.anisotropy}}}function Be(oe,F){let le=!1;oe.__webglInit===void 0&&(oe.__webglInit=!0,F.addEventListener("dispose",k));let pe=F.source,Le=f.get(pe);Le===void 0&&(Le={},f.set(pe,Le));let He=fe(F);if(He!==oe.__cacheKey){Le[He]===void 0&&(Le[He]={texture:e.createTexture(),usedTimes:0},a.memory.textures++,le=!0),Le[He].usedTimes++;let at=Le[oe.__cacheKey];at!==void 0&&(Le[oe.__cacheKey].usedTimes--,at.usedTimes===0&&I(F)),oe.__cacheKey=He,oe.__webglTexture=Le[He].texture}return le}function Se(oe,F,le){let pe=e.TEXTURE_2D;(F.isDataArrayTexture||F.isCompressedArrayTexture)&&(pe=e.TEXTURE_2D_ARRAY),F.isData3DTexture&&(pe=e.TEXTURE_3D);let Le=Be(oe,F),He=F.source;r.bindTexture(pe,oe.__webglTexture,e.TEXTURE0+le);let at=i.get(He);if(He.version!==at.__version||Le===!0){r.activeTexture(e.TEXTURE0+le);let rt=li.getPrimaries(li.workingColorSpace),ht=F.colorSpace===Ta?null:li.getPrimaries(F.colorSpace),Tt=F.colorSpace===Ta||rt===ht?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,F.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,F.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,F.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,Tt);let Mt=x(F.image,!1,n.maxTextureSize);Mt=it(F,Mt);let Ut=s.convert(F.format,F.colorSpace),Kt=s.convert(F.type),fr=E(F.internalFormat,Ut,Kt,F.colorSpace,F.isVideoTexture);Re(pe,F);let er,Zt=F.mipmaps,Gt=F.isVideoTexture!==!0,Er=at.__version===void 0||Le===!0,ut=He.dataReady,zt=P(F,Mt);if(F.isDepthTexture)fr=M(F.format===no,F.type),Er&&(Gt?r.texStorage2D(e.TEXTURE_2D,1,fr,Mt.width,Mt.height):r.texImage2D(e.TEXTURE_2D,0,fr,Mt.width,Mt.height,0,Ut,Kt,null));else if(F.isDataTexture)if(Zt.length>0){Gt&&Er&&r.texStorage2D(e.TEXTURE_2D,zt,fr,Zt[0].width,Zt[0].height);for(let It=0,Ct=Zt.length;It<Ct;It++)er=Zt[It],Gt?ut&&r.texSubImage2D(e.TEXTURE_2D,It,0,0,er.width,er.height,Ut,Kt,er.data):r.texImage2D(e.TEXTURE_2D,It,fr,er.width,er.height,0,Ut,Kt,er.data);F.generateMipmaps=!1}else Gt?(Er&&r.texStorage2D(e.TEXTURE_2D,zt,fr,Mt.width,Mt.height),ut&&r.texSubImage2D(e.TEXTURE_2D,0,0,0,Mt.width,Mt.height,Ut,Kt,Mt.data)):r.texImage2D(e.TEXTURE_2D,0,fr,Mt.width,Mt.height,0,Ut,Kt,Mt.data);else if(F.isCompressedTexture)if(F.isCompressedArrayTexture){Gt&&Er&&r.texStorage3D(e.TEXTURE_2D_ARRAY,zt,fr,Zt[0].width,Zt[0].height,Mt.depth);for(let It=0,Ct=Zt.length;It<Ct;It++)if(er=Zt[It],F.format!==Ln)if(Ut!==null)if(Gt){if(ut)if(F.layerUpdates.size>0){let rr=Py(er.width,er.height,F.format,F.type);for(let $t of F.layerUpdates){let xr=er.data.subarray($t*rr/er.data.BYTES_PER_ELEMENT,($t+1)*rr/er.data.BYTES_PER_ELEMENT);r.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,It,0,0,$t,er.width,er.height,1,Ut,xr)}F.clearLayerUpdates()}else r.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,It,0,0,0,er.width,er.height,Mt.depth,Ut,er.data)}else r.compressedTexImage3D(e.TEXTURE_2D_ARRAY,It,fr,er.width,er.height,Mt.depth,0,er.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else Gt?ut&&r.texSubImage3D(e.TEXTURE_2D_ARRAY,It,0,0,0,er.width,er.height,Mt.depth,Ut,Kt,er.data):r.texImage3D(e.TEXTURE_2D_ARRAY,It,fr,er.width,er.height,Mt.depth,0,Ut,Kt,er.data)}else{Gt&&Er&&r.texStorage2D(e.TEXTURE_2D,zt,fr,Zt[0].width,Zt[0].height);for(let It=0,Ct=Zt.length;It<Ct;It++)er=Zt[It],F.format!==Ln?Ut!==null?Gt?ut&&r.compressedTexSubImage2D(e.TEXTURE_2D,It,0,0,er.width,er.height,Ut,er.data):r.compressedTexImage2D(e.TEXTURE_2D,It,fr,er.width,er.height,0,er.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):Gt?ut&&r.texSubImage2D(e.TEXTURE_2D,It,0,0,er.width,er.height,Ut,Kt,er.data):r.texImage2D(e.TEXTURE_2D,It,fr,er.width,er.height,0,Ut,Kt,er.data)}else if(F.isDataArrayTexture)if(Gt){if(Er&&r.texStorage3D(e.TEXTURE_2D_ARRAY,zt,fr,Mt.width,Mt.height,Mt.depth),ut)if(F.layerUpdates.size>0){let It=Py(Mt.width,Mt.height,F.format,F.type);for(let Ct of F.layerUpdates){let rr=Mt.data.subarray(Ct*It/Mt.data.BYTES_PER_ELEMENT,(Ct+1)*It/Mt.data.BYTES_PER_ELEMENT);r.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,Ct,Mt.width,Mt.height,1,Ut,Kt,rr)}F.clearLayerUpdates()}else r.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,Mt.width,Mt.height,Mt.depth,Ut,Kt,Mt.data)}else r.texImage3D(e.TEXTURE_2D_ARRAY,0,fr,Mt.width,Mt.height,Mt.depth,0,Ut,Kt,Mt.data);else if(F.isData3DTexture)Gt?(Er&&r.texStorage3D(e.TEXTURE_3D,zt,fr,Mt.width,Mt.height,Mt.depth),ut&&r.texSubImage3D(e.TEXTURE_3D,0,0,0,0,Mt.width,Mt.height,Mt.depth,Ut,Kt,Mt.data)):r.texImage3D(e.TEXTURE_3D,0,fr,Mt.width,Mt.height,Mt.depth,0,Ut,Kt,Mt.data);else if(F.isFramebufferTexture){if(Er)if(Gt)r.texStorage2D(e.TEXTURE_2D,zt,fr,Mt.width,Mt.height);else{let It=Mt.width,Ct=Mt.height;for(let rr=0;rr<zt;rr++)r.texImage2D(e.TEXTURE_2D,rr,fr,It,Ct,0,Ut,Kt,null),It>>=1,Ct>>=1}}else if(Zt.length>0){if(Gt&&Er){let It=st(Zt[0]);r.texStorage2D(e.TEXTURE_2D,zt,fr,It.width,It.height)}for(let It=0,Ct=Zt.length;It<Ct;It++)er=Zt[It],Gt?ut&&r.texSubImage2D(e.TEXTURE_2D,It,0,0,Ut,Kt,er):r.texImage2D(e.TEXTURE_2D,It,fr,Ut,Kt,er);F.generateMipmaps=!1}else if(Gt){if(Er){let It=st(Mt);r.texStorage2D(e.TEXTURE_2D,zt,fr,It.width,It.height)}ut&&r.texSubImage2D(e.TEXTURE_2D,0,0,0,Ut,Kt,Mt)}else r.texImage2D(e.TEXTURE_2D,0,fr,Ut,Kt,Mt);g(F)&&v(pe),at.__version=He.version,F.onUpdate&&F.onUpdate(F)}oe.__version=F.version}function U(oe,F,le){if(F.image.length!==6)return;let pe=Be(oe,F),Le=F.source;r.bindTexture(e.TEXTURE_CUBE_MAP,oe.__webglTexture,e.TEXTURE0+le);let He=i.get(Le);if(Le.version!==He.__version||pe===!0){r.activeTexture(e.TEXTURE0+le);let at=li.getPrimaries(li.workingColorSpace),rt=F.colorSpace===Ta?null:li.getPrimaries(F.colorSpace),ht=F.colorSpace===Ta||at===rt?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,F.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,F.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,F.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,ht);let Tt=F.isCompressedTexture||F.image[0].isCompressedTexture,Mt=F.image[0]&&F.image[0].isDataTexture,Ut=[];for(let Ct=0;Ct<6;Ct++)!Tt&&!Mt?Ut[Ct]=x(F.image[Ct],!0,n.maxCubemapSize):Ut[Ct]=Mt?F.image[Ct].image:F.image[Ct],Ut[Ct]=it(F,Ut[Ct]);let Kt=Ut[0],fr=s.convert(F.format,F.colorSpace),er=s.convert(F.type),Zt=E(F.internalFormat,fr,er,F.colorSpace),Gt=F.isVideoTexture!==!0,Er=He.__version===void 0||pe===!0,ut=Le.dataReady,zt=P(F,Kt);Re(e.TEXTURE_CUBE_MAP,F);let It;if(Tt){Gt&&Er&&r.texStorage2D(e.TEXTURE_CUBE_MAP,zt,Zt,Kt.width,Kt.height);for(let Ct=0;Ct<6;Ct++){It=Ut[Ct].mipmaps;for(let rr=0;rr<It.length;rr++){let $t=It[rr];F.format!==Ln?fr!==null?Gt?ut&&r.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+Ct,rr,0,0,$t.width,$t.height,fr,$t.data):r.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+Ct,rr,Zt,$t.width,$t.height,0,$t.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):Gt?ut&&r.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+Ct,rr,0,0,$t.width,$t.height,fr,er,$t.data):r.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+Ct,rr,Zt,$t.width,$t.height,0,fr,er,$t.data)}}}else{if(It=F.mipmaps,Gt&&Er){It.length>0&&zt++;let Ct=st(Ut[0]);r.texStorage2D(e.TEXTURE_CUBE_MAP,zt,Zt,Ct.width,Ct.height)}for(let Ct=0;Ct<6;Ct++)if(Mt){Gt?ut&&r.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+Ct,0,0,0,Ut[Ct].width,Ut[Ct].height,fr,er,Ut[Ct].data):r.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+Ct,0,Zt,Ut[Ct].width,Ut[Ct].height,0,fr,er,Ut[Ct].data);for(let rr=0;rr<It.length;rr++){let $t=It[rr].image[Ct].image;Gt?ut&&r.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+Ct,rr+1,0,0,$t.width,$t.height,fr,er,$t.data):r.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+Ct,rr+1,Zt,$t.width,$t.height,0,fr,er,$t.data)}}else{Gt?ut&&r.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+Ct,0,0,0,fr,er,Ut[Ct]):r.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+Ct,0,Zt,fr,er,Ut[Ct]);for(let rr=0;rr<It.length;rr++){let $t=It[rr];Gt?ut&&r.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+Ct,rr+1,0,0,fr,er,$t.image[Ct]):r.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+Ct,rr+1,Zt,fr,er,$t.image[Ct])}}}g(F)&&v(e.TEXTURE_CUBE_MAP),He.__version=Le.version,F.onUpdate&&F.onUpdate(F)}oe.__version=F.version}function ie(oe,F,le,pe,Le,He){let at=s.convert(le.format,le.colorSpace),rt=s.convert(le.type),ht=E(le.internalFormat,at,rt,le.colorSpace),Tt=i.get(F),Mt=i.get(le);if(Mt.__renderTarget=F,!Tt.__hasExternalTextures){let Ut=Math.max(1,F.width>>He),Kt=Math.max(1,F.height>>He);Le===e.TEXTURE_3D||Le===e.TEXTURE_2D_ARRAY?r.texImage3D(Le,He,ht,Ut,Kt,F.depth,0,at,rt,null):r.texImage2D(Le,He,ht,Ut,Kt,0,at,rt,null)}r.bindFramebuffer(e.FRAMEBUFFER,oe),We(F)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,pe,Le,Mt.__webglTexture,0,Dt(F)):(Le===e.TEXTURE_2D||Le>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&Le<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,pe,Le,Mt.__webglTexture,He),r.bindFramebuffer(e.FRAMEBUFFER,null)}function Ae(oe,F,le){if(e.bindRenderbuffer(e.RENDERBUFFER,oe),F.depthBuffer){let pe=F.depthTexture,Le=pe&&pe.isDepthTexture?pe.type:null,He=M(F.stencilBuffer,Le),at=F.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,rt=Dt(F);We(F)?o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,rt,He,F.width,F.height):le?e.renderbufferStorageMultisample(e.RENDERBUFFER,rt,He,F.width,F.height):e.renderbufferStorage(e.RENDERBUFFER,He,F.width,F.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,at,e.RENDERBUFFER,oe)}else{let pe=F.textures;for(let Le=0;Le<pe.length;Le++){let He=pe[Le],at=s.convert(He.format,He.colorSpace),rt=s.convert(He.type),ht=E(He.internalFormat,at,rt,He.colorSpace),Tt=Dt(F);le&&We(F)===!1?e.renderbufferStorageMultisample(e.RENDERBUFFER,Tt,ht,F.width,F.height):We(F)?o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,Tt,ht,F.width,F.height):e.renderbufferStorage(e.RENDERBUFFER,ht,F.width,F.height)}}e.bindRenderbuffer(e.RENDERBUFFER,null)}function Ue(oe,F){if(F&&F.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(r.bindFramebuffer(e.FRAMEBUFFER,oe),!(F.depthTexture&&F.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");let le=i.get(F.depthTexture);le.__renderTarget=F,(!le.__webglTexture||F.depthTexture.image.width!==F.width||F.depthTexture.image.height!==F.height)&&(F.depthTexture.image.width=F.width,F.depthTexture.image.height=F.height,F.depthTexture.needsUpdate=!0),ze(F.depthTexture,0);let pe=le.__webglTexture,Le=Dt(F);if(F.depthTexture.format===Uo)We(F)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,pe,0,Le):e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,pe,0);else if(F.depthTexture.format===no)We(F)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.TEXTURE_2D,pe,0,Le):e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.TEXTURE_2D,pe,0);else throw new Error("Unknown depthTexture format")}function Ge(oe){let F=i.get(oe),le=oe.isWebGLCubeRenderTarget===!0;if(F.__boundDepthTexture!==oe.depthTexture){let pe=oe.depthTexture;if(F.__depthDisposeCallback&&F.__depthDisposeCallback(),pe){let Le=()=>{delete F.__boundDepthTexture,delete F.__depthDisposeCallback,pe.removeEventListener("dispose",Le)};pe.addEventListener("dispose",Le),F.__depthDisposeCallback=Le}F.__boundDepthTexture=pe}if(oe.depthTexture&&!F.__autoAllocateDepthBuffer){if(le)throw new Error("target.depthTexture not supported in Cube render targets");Ue(F.__webglFramebuffer,oe)}else if(le){F.__webglDepthbuffer=[];for(let pe=0;pe<6;pe++)if(r.bindFramebuffer(e.FRAMEBUFFER,F.__webglFramebuffer[pe]),F.__webglDepthbuffer[pe]===void 0)F.__webglDepthbuffer[pe]=e.createRenderbuffer(),Ae(F.__webglDepthbuffer[pe],oe,!1);else{let Le=oe.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,He=F.__webglDepthbuffer[pe];e.bindRenderbuffer(e.RENDERBUFFER,He),e.framebufferRenderbuffer(e.FRAMEBUFFER,Le,e.RENDERBUFFER,He)}}else if(r.bindFramebuffer(e.FRAMEBUFFER,F.__webglFramebuffer),F.__webglDepthbuffer===void 0)F.__webglDepthbuffer=e.createRenderbuffer(),Ae(F.__webglDepthbuffer,oe,!1);else{let pe=oe.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,Le=F.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,Le),e.framebufferRenderbuffer(e.FRAMEBUFFER,pe,e.RENDERBUFFER,Le)}r.bindFramebuffer(e.FRAMEBUFFER,null)}function nt(oe,F,le){let pe=i.get(oe);F!==void 0&&ie(pe.__webglFramebuffer,oe,oe.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0),le!==void 0&&Ge(oe)}function Qe(oe){let F=oe.texture,le=i.get(oe),pe=i.get(F);oe.addEventListener("dispose",z);let Le=oe.textures,He=oe.isWebGLCubeRenderTarget===!0,at=Le.length>1;if(at||(pe.__webglTexture===void 0&&(pe.__webglTexture=e.createTexture()),pe.__version=F.version,a.memory.textures++),He){le.__webglFramebuffer=[];for(let rt=0;rt<6;rt++)if(F.mipmaps&&F.mipmaps.length>0){le.__webglFramebuffer[rt]=[];for(let ht=0;ht<F.mipmaps.length;ht++)le.__webglFramebuffer[rt][ht]=e.createFramebuffer()}else le.__webglFramebuffer[rt]=e.createFramebuffer()}else{if(F.mipmaps&&F.mipmaps.length>0){le.__webglFramebuffer=[];for(let rt=0;rt<F.mipmaps.length;rt++)le.__webglFramebuffer[rt]=e.createFramebuffer()}else le.__webglFramebuffer=e.createFramebuffer();if(at)for(let rt=0,ht=Le.length;rt<ht;rt++){let Tt=i.get(Le[rt]);Tt.__webglTexture===void 0&&(Tt.__webglTexture=e.createTexture(),a.memory.textures++)}if(oe.samples>0&&We(oe)===!1){le.__webglMultisampledFramebuffer=e.createFramebuffer(),le.__webglColorRenderbuffer=[],r.bindFramebuffer(e.FRAMEBUFFER,le.__webglMultisampledFramebuffer);for(let rt=0;rt<Le.length;rt++){let ht=Le[rt];le.__webglColorRenderbuffer[rt]=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,le.__webglColorRenderbuffer[rt]);let Tt=s.convert(ht.format,ht.colorSpace),Mt=s.convert(ht.type),Ut=E(ht.internalFormat,Tt,Mt,ht.colorSpace,oe.isXRRenderTarget===!0),Kt=Dt(oe);e.renderbufferStorageMultisample(e.RENDERBUFFER,Kt,Ut,oe.width,oe.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+rt,e.RENDERBUFFER,le.__webglColorRenderbuffer[rt])}e.bindRenderbuffer(e.RENDERBUFFER,null),oe.depthBuffer&&(le.__webglDepthRenderbuffer=e.createRenderbuffer(),Ae(le.__webglDepthRenderbuffer,oe,!0)),r.bindFramebuffer(e.FRAMEBUFFER,null)}}if(He){r.bindTexture(e.TEXTURE_CUBE_MAP,pe.__webglTexture),Re(e.TEXTURE_CUBE_MAP,F);for(let rt=0;rt<6;rt++)if(F.mipmaps&&F.mipmaps.length>0)for(let ht=0;ht<F.mipmaps.length;ht++)ie(le.__webglFramebuffer[rt][ht],oe,F,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+rt,ht);else ie(le.__webglFramebuffer[rt],oe,F,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+rt,0);g(F)&&v(e.TEXTURE_CUBE_MAP),r.unbindTexture()}else if(at){for(let rt=0,ht=Le.length;rt<ht;rt++){let Tt=Le[rt],Mt=i.get(Tt);r.bindTexture(e.TEXTURE_2D,Mt.__webglTexture),Re(e.TEXTURE_2D,Tt),ie(le.__webglFramebuffer,oe,Tt,e.COLOR_ATTACHMENT0+rt,e.TEXTURE_2D,0),g(Tt)&&v(e.TEXTURE_2D)}r.unbindTexture()}else{let rt=e.TEXTURE_2D;if((oe.isWebGL3DRenderTarget||oe.isWebGLArrayRenderTarget)&&(rt=oe.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),r.bindTexture(rt,pe.__webglTexture),Re(rt,F),F.mipmaps&&F.mipmaps.length>0)for(let ht=0;ht<F.mipmaps.length;ht++)ie(le.__webglFramebuffer[ht],oe,F,e.COLOR_ATTACHMENT0,rt,ht);else ie(le.__webglFramebuffer,oe,F,e.COLOR_ATTACHMENT0,rt,0);g(F)&&v(rt),r.unbindTexture()}oe.depthBuffer&&Ge(oe)}function ct(oe){let F=oe.textures;for(let le=0,pe=F.length;le<pe;le++){let Le=F[le];if(g(Le)){let He=_(oe),at=i.get(Le).__webglTexture;r.bindTexture(He,at),v(He),r.unbindTexture()}}}let ye=[],dt=[];function xt(oe){if(oe.samples>0){if(We(oe)===!1){let F=oe.textures,le=oe.width,pe=oe.height,Le=e.COLOR_BUFFER_BIT,He=oe.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,at=i.get(oe),rt=F.length>1;if(rt)for(let ht=0;ht<F.length;ht++)r.bindFramebuffer(e.FRAMEBUFFER,at.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+ht,e.RENDERBUFFER,null),r.bindFramebuffer(e.FRAMEBUFFER,at.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+ht,e.TEXTURE_2D,null,0);r.bindFramebuffer(e.READ_FRAMEBUFFER,at.__webglMultisampledFramebuffer),r.bindFramebuffer(e.DRAW_FRAMEBUFFER,at.__webglFramebuffer);for(let ht=0;ht<F.length;ht++){if(oe.resolveDepthBuffer&&(oe.depthBuffer&&(Le|=e.DEPTH_BUFFER_BIT),oe.stencilBuffer&&oe.resolveStencilBuffer&&(Le|=e.STENCIL_BUFFER_BIT)),rt){e.framebufferRenderbuffer(e.READ_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,at.__webglColorRenderbuffer[ht]);let Tt=i.get(F[ht]).__webglTexture;e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,Tt,0)}e.blitFramebuffer(0,0,le,pe,0,0,le,pe,Le,e.NEAREST),l===!0&&(ye.length=0,dt.length=0,ye.push(e.COLOR_ATTACHMENT0+ht),oe.depthBuffer&&oe.resolveDepthBuffer===!1&&(ye.push(He),dt.push(He),e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,dt)),e.invalidateFramebuffer(e.READ_FRAMEBUFFER,ye))}if(r.bindFramebuffer(e.READ_FRAMEBUFFER,null),r.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),rt)for(let ht=0;ht<F.length;ht++){r.bindFramebuffer(e.FRAMEBUFFER,at.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+ht,e.RENDERBUFFER,at.__webglColorRenderbuffer[ht]);let Tt=i.get(F[ht]).__webglTexture;r.bindFramebuffer(e.FRAMEBUFFER,at.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+ht,e.TEXTURE_2D,Tt,0)}r.bindFramebuffer(e.DRAW_FRAMEBUFFER,at.__webglMultisampledFramebuffer)}else if(oe.depthBuffer&&oe.resolveDepthBuffer===!1&&l){let F=oe.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,[F])}}}function Dt(oe){return Math.min(n.maxSamples,oe.samples)}function We(oe){let F=i.get(oe);return oe.samples>0&&t.has("WEBGL_multisampled_render_to_texture")===!0&&F.__useRenderToTexture!==!1}function mt(oe){let F=a.render.frame;u.get(oe)!==F&&(u.set(oe,F),oe.update())}function it(oe,F){let le=oe.colorSpace,pe=oe.format,Le=oe.type;return oe.isCompressedTexture===!0||oe.isVideoTexture===!0||le!==kn&&le!==Ta&&(li.getTransfer(le)===Ii?(pe!==Ln||Le!==Ji)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",le)),F}function st(oe){return typeof HTMLImageElement<"u"&&oe instanceof HTMLImageElement?(c.width=oe.naturalWidth||oe.width,c.height=oe.naturalHeight||oe.height):typeof VideoFrame<"u"&&oe instanceof VideoFrame?(c.width=oe.displayWidth,c.height=oe.displayHeight):(c.width=oe.width,c.height=oe.height),c}this.allocateTextureUnit=ce,this.resetTextureUnits=se,this.setTexture2D=ze,this.setTexture2DArray=Fe,this.setTexture3D=Pe,this.setTextureCube=ue,this.rebindTextures=nt,this.setupRenderTarget=Qe,this.updateRenderTargetMipmap=ct,this.updateMultisampleRenderTarget=xt,this.setupDepthRenderbuffer=Ge,this.setupFrameBufferTexture=ie,this.useMultisampledRTT=We}function fw(e,t){function r(i,n=Ta){let s,a=li.getTransfer(n);if(i===Ji)return e.UNSIGNED_BYTE;if(i===yd)return e.UNSIGNED_SHORT_4_4_4_4;if(i===vd)return e.UNSIGNED_SHORT_5_5_5_1;if(i===Jm)return e.UNSIGNED_INT_5_9_9_9_REV;if(i===Sa)return e.BYTE;if(i===Eh)return e.SHORT;if(i===Ma)return e.UNSIGNED_SHORT;if(i===Do)return e.INT;if(i===Aa)return e.UNSIGNED_INT;if(i===es)return e.FLOAT;if(i===Ts)return e.HALF_FLOAT;if(i===Qm)return e.ALPHA;if(i===eg)return e.RGB;if(i===Ln)return e.RGBA;if(i===tg)return e.LUMINANCE;if(i===rg)return e.LUMINANCE_ALPHA;if(i===Uo)return e.DEPTH_COMPONENT;if(i===no)return e.DEPTH_STENCIL;if(i===xd)return e.RED;if(i===Sh)return e.RED_INTEGER;if(i===ig)return e.RG;if(i===bd)return e.RG_INTEGER;if(i===wd)return e.RGBA_INTEGER;if(i===Mh||i===Ah||i===Th||i===Ch)if(a===Ii)if(s=t.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(i===Mh)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===Ah)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===Th)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===Ch)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=t.get("WEBGL_compressed_texture_s3tc"),s!==null){if(i===Mh)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===Ah)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===Th)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===Ch)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===_d||i===Ed||i===Sd||i===Md)if(s=t.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(i===_d)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===Ed)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===Sd)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===Md)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===Ad||i===Td||i===Cd)if(s=t.get("WEBGL_compressed_texture_etc"),s!==null){if(i===Ad||i===Td)return a===Ii?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(i===Cd)return a===Ii?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(i===Rd||i===Pd||i===Id||i===Nd||i===Ld||i===kd||i===Od||i===Dd||i===Ud||i===Fd||i===zd||i===Bd||i===jd||i===Vd)if(s=t.get("WEBGL_compressed_texture_astc"),s!==null){if(i===Rd)return a===Ii?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===Pd)return a===Ii?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===Id)return a===Ii?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===Nd)return a===Ii?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===Ld)return a===Ii?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===kd)return a===Ii?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===Od)return a===Ii?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===Dd)return a===Ii?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===Ud)return a===Ii?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===Fd)return a===Ii?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===zd)return a===Ii?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===Bd)return a===Ii?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===jd)return a===Ii?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===Vd)return a===Ii?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===Rh||i===Hd||i===Gd)if(s=t.get("EXT_texture_compression_bptc"),s!==null){if(i===Rh)return a===Ii?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===Hd)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===Gd)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===ng||i===Wd||i===Xd||i===Yd)if(s=t.get("EXT_texture_compression_rgtc"),s!==null){if(i===Rh)return s.COMPRESSED_RED_RGTC1_EXT;if(i===Wd)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===Xd)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===Yd)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===io?e.UNSIGNED_INT_24_8:e[i]!==void 0?e[i]:null}return{convert:r}}var nL={type:"move"},zy=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new Wi,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return this._targetRay===null&&(this._targetRay=new Wi,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new je,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new je),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new Wi,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new je,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new je),this._grip}dispatchEvent(e){return this._targetRay!==null&&this._targetRay.dispatchEvent(e),this._grip!==null&&this._grip.dispatchEvent(e),this._hand!==null&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){let t=this._hand;if(t)for(let r of e.hand.values())this._getHandJoint(t,r)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),this._targetRay!==null&&(this._targetRay.visible=!1),this._grip!==null&&(this._grip.visible=!1),this._hand!==null&&(this._hand.visible=!1),this}update(e,t,r){let i=null,n=null,s=null,a=this._targetRay,o=this._grip,l=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(l&&e.hand){s=!0;for(let b of e.hand.values()){let x=t.getJointPose(b,r),g=this._getHandJoint(l,b);x!==null&&(g.matrix.fromArray(x.transform.matrix),g.matrix.decompose(g.position,g.rotation,g.scale),g.matrixWorldNeedsUpdate=!0,g.jointRadius=x.radius),g.visible=x!==null}let c=l.joints["index-finger-tip"],u=l.joints["thumb-tip"],d=c.position.distanceTo(u.position),f=.02,y=.005;l.inputState.pinching&&d>f+y?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&d<=f-y&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else o!==null&&e.gripSpace&&(n=t.getPose(e.gripSpace,r),n!==null&&(o.matrix.fromArray(n.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,n.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(n.linearVelocity)):o.hasLinearVelocity=!1,n.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(n.angularVelocity)):o.hasAngularVelocity=!1));a!==null&&(i=t.getPose(e.targetRaySpace,r),i===null&&n!==null&&(i=n),i!==null&&(a.matrix.fromArray(i.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,i.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(i.linearVelocity)):a.hasLinearVelocity=!1,i.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(i.angularVelocity)):a.hasAngularVelocity=!1,this.dispatchEvent(nL)))}return a!==null&&(a.visible=i!==null),o!==null&&(o.visible=n!==null),l!==null&&(l.visible=s!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let r=new Wi;r.matrixAutoUpdate=!1,r.visible=!1,e.joints[t.jointName]=r,e.add(r)}return e.joints[t.jointName]}},sL=`
void main() {

	gl_Position = vec4( position, 1.0 );

}`,aL=`
uniform sampler2DArray depthColor;
uniform float depthWidth;
uniform float depthHeight;

void main() {

	vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );

	if ( coord.x >= 1.0 ) {

		gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;

	} else {

		gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;

	}

}`,oL=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t,r){if(this.texture===null){let i=new Qi,n=e.properties.get(i);n.__webglTexture=t.texture,(t.depthNear!=r.depthNear||t.depthFar!=r.depthFar)&&(this.depthNear=t.depthNear,this.depthFar=t.depthFar),this.texture=i}}getMesh(e){if(this.texture!==null&&this.mesh===null){let t=e.cameras[0].viewport,r=new ln({vertexShader:sL,fragmentShader:aL,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new qr(new vc(20,20),r)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},lL=class extends ha{constructor(e,t){super();let r=this,i=null,n=1,s=null,a="local-floor",o=1,l=null,c=null,u=null,d=null,f=null,y=null,b=new oL,x=t.getContextAttributes(),g=null,v=null,_=[],E=[],M=new Ft,P=null,k=new cn;k.viewport=new _i;let z=new cn;z.viewport=new _i;let D=[k,z],I=new w1,L=null,Z=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(Be){let Se=_[Be];return Se===void 0&&(Se=new zy,_[Be]=Se),Se.getTargetRaySpace()},this.getControllerGrip=function(Be){let Se=_[Be];return Se===void 0&&(Se=new zy,_[Be]=Se),Se.getGripSpace()},this.getHand=function(Be){let Se=_[Be];return Se===void 0&&(Se=new zy,_[Be]=Se),Se.getHandSpace()};function se(Be){let Se=E.indexOf(Be.inputSource);if(Se===-1)return;let U=_[Se];U!==void 0&&(U.update(Be.inputSource,Be.frame,l||s),U.dispatchEvent({type:Be.type,data:Be.inputSource}))}function ce(){i.removeEventListener("select",se),i.removeEventListener("selectstart",se),i.removeEventListener("selectend",se),i.removeEventListener("squeeze",se),i.removeEventListener("squeezestart",se),i.removeEventListener("squeezeend",se),i.removeEventListener("end",ce),i.removeEventListener("inputsourceschange",fe);for(let Be=0;Be<_.length;Be++){let Se=E[Be];Se!==null&&(E[Be]=null,_[Be].disconnect(Se))}L=null,Z=null,b.reset(),e.setRenderTarget(g),f=null,d=null,u=null,i=null,v=null,Re.stop(),r.isPresenting=!1,e.setPixelRatio(P),e.setSize(M.width,M.height,!1),r.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(Be){n=Be,r.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(Be){a=Be,r.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||s},this.setReferenceSpace=function(Be){l=Be},this.getBaseLayer=function(){return d!==null?d:f},this.getBinding=function(){return u},this.getFrame=function(){return y},this.getSession=function(){return i},this.setSession=async function(Be){if(i=Be,i!==null){if(g=e.getRenderTarget(),i.addEventListener("select",se),i.addEventListener("selectstart",se),i.addEventListener("selectend",se),i.addEventListener("squeeze",se),i.addEventListener("squeezestart",se),i.addEventListener("squeezeend",se),i.addEventListener("end",ce),i.addEventListener("inputsourceschange",fe),x.xrCompatible!==!0&&await t.makeXRCompatible(),P=e.getPixelRatio(),e.getSize(M),i.renderState.layers===void 0){let Se={antialias:x.antialias,alpha:!0,depth:x.depth,stencil:x.stencil,framebufferScaleFactor:n};f=new XRWebGLLayer(i,t,Se),i.updateRenderState({baseLayer:f}),e.setPixelRatio(1),e.setSize(f.framebufferWidth,f.framebufferHeight,!1),v=new In(f.framebufferWidth,f.framebufferHeight,{format:Ln,type:Ji,colorSpace:e.outputColorSpace,stencilBuffer:x.stencil})}else{let Se=null,U=null,ie=null;x.depth&&(ie=x.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,Se=x.stencil?no:Uo,U=x.stencil?io:Aa);let Ae={colorFormat:t.RGBA8,depthFormat:ie,scaleFactor:n};u=new XRWebGLBinding(i,t),d=u.createProjectionLayer(Ae),i.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),v=new In(d.textureWidth,d.textureHeight,{format:Ln,type:Ji,depthTexture:new zp(d.textureWidth,d.textureHeight,U,void 0,void 0,void 0,void 0,void 0,void 0,Se),stencilBuffer:x.stencil,colorSpace:e.outputColorSpace,samples:x.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1})}v.isXRRenderTarget=!0,this.setFoveation(o),l=null,s=await i.requestReferenceSpace(a),Re.setContext(i),Re.start(),r.isPresenting=!0,r.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(i!==null)return i.environmentBlendMode},this.getDepthTexture=function(){return b.getDepthTexture()};function fe(Be){for(let Se=0;Se<Be.removed.length;Se++){let U=Be.removed[Se],ie=E.indexOf(U);ie>=0&&(E[ie]=null,_[ie].disconnect(U))}for(let Se=0;Se<Be.added.length;Se++){let U=Be.added[Se],ie=E.indexOf(U);if(ie===-1){for(let Ue=0;Ue<_.length;Ue++)if(Ue>=E.length){E.push(U),ie=Ue;break}else if(E[Ue]===null){E[Ue]=U,ie=Ue;break}if(ie===-1)break}let Ae=_[ie];Ae&&Ae.connect(U)}}let ze=new je,Fe=new je;function Pe(Be,Se,U){ze.setFromMatrixPosition(Se.matrixWorld),Fe.setFromMatrixPosition(U.matrixWorld);let ie=ze.distanceTo(Fe),Ae=Se.projectionMatrix.elements,Ue=U.projectionMatrix.elements,Ge=Ae[14]/(Ae[10]-1),nt=Ae[14]/(Ae[10]+1),Qe=(Ae[9]+1)/Ae[5],ct=(Ae[9]-1)/Ae[5],ye=(Ae[8]-1)/Ae[0],dt=(Ue[8]+1)/Ue[0],xt=Ge*ye,Dt=Ge*dt,We=ie/(-ye+dt),mt=We*-ye;if(Se.matrixWorld.decompose(Be.position,Be.quaternion,Be.scale),Be.translateX(mt),Be.translateZ(We),Be.matrixWorld.compose(Be.position,Be.quaternion,Be.scale),Be.matrixWorldInverse.copy(Be.matrixWorld).invert(),Ae[10]===-1)Be.projectionMatrix.copy(Se.projectionMatrix),Be.projectionMatrixInverse.copy(Se.projectionMatrixInverse);else{let it=Ge+We,st=nt+We,oe=xt-mt,F=Dt+(ie-mt),le=Qe*nt/st*it,pe=ct*nt/st*it;Be.projectionMatrix.makePerspective(oe,F,le,pe,it,st),Be.projectionMatrixInverse.copy(Be.projectionMatrix).invert()}}function ue(Be,Se){Se===null?Be.matrixWorld.copy(Be.matrix):Be.matrixWorld.multiplyMatrices(Se.matrixWorld,Be.matrix),Be.matrixWorldInverse.copy(Be.matrixWorld).invert()}this.updateCamera=function(Be){if(i===null)return;let Se=Be.near,U=Be.far;b.texture!==null&&(b.depthNear>0&&(Se=b.depthNear),b.depthFar>0&&(U=b.depthFar)),I.near=z.near=k.near=Se,I.far=z.far=k.far=U,(L!==I.near||Z!==I.far)&&(i.updateRenderState({depthNear:I.near,depthFar:I.far}),L=I.near,Z=I.far),k.layers.mask=Be.layers.mask|2,z.layers.mask=Be.layers.mask|4,I.layers.mask=k.layers.mask|z.layers.mask;let ie=Be.parent,Ae=I.cameras;ue(I,ie);for(let Ue=0;Ue<Ae.length;Ue++)ue(Ae[Ue],ie);Ae.length===2?Pe(I,k,z):I.projectionMatrix.copy(k.projectionMatrix),Te(Be,I,ie)};function Te(Be,Se,U){U===null?Be.matrix.copy(Se.matrixWorld):(Be.matrix.copy(U.matrixWorld),Be.matrix.invert(),Be.matrix.multiply(Se.matrixWorld)),Be.matrix.decompose(Be.position,Be.quaternion,Be.scale),Be.updateMatrixWorld(!0),Be.projectionMatrix.copy(Se.projectionMatrix),Be.projectionMatrixInverse.copy(Se.projectionMatrixInverse),Be.isPerspectiveCamera&&(Be.fov=Xl*2*Math.atan(1/Be.projectionMatrix.elements[5]),Be.zoom=1)}this.getCamera=function(){return I},this.getFoveation=function(){if(!(d===null&&f===null))return o},this.setFoveation=function(Be){o=Be,d!==null&&(d.fixedFoveation=Be),f!==null&&f.fixedFoveation!==void 0&&(f.fixedFoveation=Be)},this.hasDepthSensing=function(){return b.texture!==null},this.getDepthSensingMesh=function(){return b.getMesh(I)};let de=null;function Ie(Be,Se){if(c=Se.getViewerPose(l||s),y=Se,c!==null){let U=c.views;f!==null&&(e.setRenderTargetFramebuffer(v,f.framebuffer),e.setRenderTarget(v));let ie=!1;U.length!==I.cameras.length&&(I.cameras.length=0,ie=!0);for(let Ue=0;Ue<U.length;Ue++){let Ge=U[Ue],nt=null;if(f!==null)nt=f.getViewport(Ge);else{let ct=u.getViewSubImage(d,Ge);nt=ct.viewport,Ue===0&&(e.setRenderTargetTextures(v,ct.colorTexture,d.ignoreDepthValues?void 0:ct.depthStencilTexture),e.setRenderTarget(v))}let Qe=D[Ue];Qe===void 0&&(Qe=new cn,Qe.layers.enable(Ue),Qe.viewport=new _i,D[Ue]=Qe),Qe.matrix.fromArray(Ge.transform.matrix),Qe.matrix.decompose(Qe.position,Qe.quaternion,Qe.scale),Qe.projectionMatrix.fromArray(Ge.projectionMatrix),Qe.projectionMatrixInverse.copy(Qe.projectionMatrix).invert(),Qe.viewport.set(nt.x,nt.y,nt.width,nt.height),Ue===0&&(I.matrix.copy(Qe.matrix),I.matrix.decompose(I.position,I.quaternion,I.scale)),ie===!0&&I.cameras.push(Qe)}let Ae=i.enabledFeatures;if(Ae&&Ae.includes("depth-sensing")){let Ue=u.getDepthInformation(U[0]);Ue&&Ue.isValid&&Ue.texture&&b.init(e,Ue,i.renderState)}}for(let U=0;U<_.length;U++){let ie=E[U],Ae=_[U];ie!==null&&Ae!==void 0&&Ae.update(ie,Se,l||s)}de&&de(Be,Se),Se.detectedPlanes&&r.dispatchEvent({type:"planesdetected",data:Se}),y=null}let Re=new B1;Re.setAnimationLoop(Ie),this.setAnimationLoop=function(Be){de=Be},this.dispose=function(){}}},pl=new Ys,cL=new Ir;function hL(e,t){function r(g,v){g.matrixAutoUpdate===!0&&g.updateMatrix(),v.value.copy(g.matrix)}function i(g,v){v.color.getRGB(g.fogColor.value,Zx(e)),v.isFog?(g.fogNear.value=v.near,g.fogFar.value=v.far):v.isFogExp2&&(g.fogDensity.value=v.density)}function n(g,v,_,E,M){v.isMeshBasicMaterial||v.isMeshLambertMaterial?s(g,v):v.isMeshToonMaterial?(s(g,v),d(g,v)):v.isMeshPhongMaterial?(s(g,v),u(g,v)):v.isMeshStandardMaterial?(s(g,v),f(g,v),v.isMeshPhysicalMaterial&&y(g,v,M)):v.isMeshMatcapMaterial?(s(g,v),b(g,v)):v.isMeshDepthMaterial?s(g,v):v.isMeshDistanceMaterial?(s(g,v),x(g,v)):v.isMeshNormalMaterial?s(g,v):v.isLineBasicMaterial?(a(g,v),v.isLineDashedMaterial&&o(g,v)):v.isPointsMaterial?l(g,v,_,E):v.isSpriteMaterial?c(g,v):v.isShadowMaterial?(g.color.value.copy(v.color),g.opacity.value=v.opacity):v.isShaderMaterial&&(v.uniformsNeedUpdate=!1)}function s(g,v){g.opacity.value=v.opacity,v.color&&g.diffuse.value.copy(v.color),v.emissive&&g.emissive.value.copy(v.emissive).multiplyScalar(v.emissiveIntensity),v.map&&(g.map.value=v.map,r(v.map,g.mapTransform)),v.alphaMap&&(g.alphaMap.value=v.alphaMap,r(v.alphaMap,g.alphaMapTransform)),v.bumpMap&&(g.bumpMap.value=v.bumpMap,r(v.bumpMap,g.bumpMapTransform),g.bumpScale.value=v.bumpScale,v.side===tt&&(g.bumpScale.value*=-1)),v.normalMap&&(g.normalMap.value=v.normalMap,r(v.normalMap,g.normalMapTransform),g.normalScale.value.copy(v.normalScale),v.side===tt&&g.normalScale.value.negate()),v.displacementMap&&(g.displacementMap.value=v.displacementMap,r(v.displacementMap,g.displacementMapTransform),g.displacementScale.value=v.displacementScale,g.displacementBias.value=v.displacementBias),v.emissiveMap&&(g.emissiveMap.value=v.emissiveMap,r(v.emissiveMap,g.emissiveMapTransform)),v.specularMap&&(g.specularMap.value=v.specularMap,r(v.specularMap,g.specularMapTransform)),v.alphaTest>0&&(g.alphaTest.value=v.alphaTest);let _=t.get(v),E=_.envMap,M=_.envMapRotation;E&&(g.envMap.value=E,pl.copy(M),pl.x*=-1,pl.y*=-1,pl.z*=-1,E.isCubeTexture&&E.isRenderTargetTexture===!1&&(pl.y*=-1,pl.z*=-1),g.envMapRotation.value.setFromMatrix4(cL.makeRotationFromEuler(pl)),g.flipEnvMap.value=E.isCubeTexture&&E.isRenderTargetTexture===!1?-1:1,g.reflectivity.value=v.reflectivity,g.ior.value=v.ior,g.refractionRatio.value=v.refractionRatio),v.lightMap&&(g.lightMap.value=v.lightMap,g.lightMapIntensity.value=v.lightMapIntensity,r(v.lightMap,g.lightMapTransform)),v.aoMap&&(g.aoMap.value=v.aoMap,g.aoMapIntensity.value=v.aoMapIntensity,r(v.aoMap,g.aoMapTransform))}function a(g,v){g.diffuse.value.copy(v.color),g.opacity.value=v.opacity,v.map&&(g.map.value=v.map,r(v.map,g.mapTransform))}function o(g,v){g.dashSize.value=v.dashSize,g.totalSize.value=v.dashSize+v.gapSize,g.scale.value=v.scale}function l(g,v,_,E){g.diffuse.value.copy(v.color),g.opacity.value=v.opacity,g.size.value=v.size*_,g.scale.value=E*.5,v.map&&(g.map.value=v.map,r(v.map,g.uvTransform)),v.alphaMap&&(g.alphaMap.value=v.alphaMap,r(v.alphaMap,g.alphaMapTransform)),v.alphaTest>0&&(g.alphaTest.value=v.alphaTest)}function c(g,v){g.diffuse.value.copy(v.color),g.opacity.value=v.opacity,g.rotation.value=v.rotation,v.map&&(g.map.value=v.map,r(v.map,g.mapTransform)),v.alphaMap&&(g.alphaMap.value=v.alphaMap,r(v.alphaMap,g.alphaMapTransform)),v.alphaTest>0&&(g.alphaTest.value=v.alphaTest)}function u(g,v){g.specular.value.copy(v.specular),g.shininess.value=Math.max(v.shininess,1e-4)}function d(g,v){v.gradientMap&&(g.gradientMap.value=v.gradientMap)}function f(g,v){g.metalness.value=v.metalness,v.metalnessMap&&(g.metalnessMap.value=v.metalnessMap,r(v.metalnessMap,g.metalnessMapTransform)),g.roughness.value=v.roughness,v.roughnessMap&&(g.roughnessMap.value=v.roughnessMap,r(v.roughnessMap,g.roughnessMapTransform)),v.envMap&&(g.envMapIntensity.value=v.envMapIntensity)}function y(g,v,_){g.ior.value=v.ior,v.sheen>0&&(g.sheenColor.value.copy(v.sheenColor).multiplyScalar(v.sheen),g.sheenRoughness.value=v.sheenRoughness,v.sheenColorMap&&(g.sheenColorMap.value=v.sheenColorMap,r(v.sheenColorMap,g.sheenColorMapTransform)),v.sheenRoughnessMap&&(g.sheenRoughnessMap.value=v.sheenRoughnessMap,r(v.sheenRoughnessMap,g.sheenRoughnessMapTransform))),v.clearcoat>0&&(g.clearcoat.value=v.clearcoat,g.clearcoatRoughness.value=v.clearcoatRoughness,v.clearcoatMap&&(g.clearcoatMap.value=v.clearcoatMap,r(v.clearcoatMap,g.clearcoatMapTransform)),v.clearcoatRoughnessMap&&(g.clearcoatRoughnessMap.value=v.clearcoatRoughnessMap,r(v.clearcoatRoughnessMap,g.clearcoatRoughnessMapTransform)),v.clearcoatNormalMap&&(g.clearcoatNormalMap.value=v.clearcoatNormalMap,r(v.clearcoatNormalMap,g.clearcoatNormalMapTransform),g.clearcoatNormalScale.value.copy(v.clearcoatNormalScale),v.side===tt&&g.clearcoatNormalScale.value.negate())),v.dispersion>0&&(g.dispersion.value=v.dispersion),v.iridescence>0&&(g.iridescence.value=v.iridescence,g.iridescenceIOR.value=v.iridescenceIOR,g.iridescenceThicknessMinimum.value=v.iridescenceThicknessRange[0],g.iridescenceThicknessMaximum.value=v.iridescenceThicknessRange[1],v.iridescenceMap&&(g.iridescenceMap.value=v.iridescenceMap,r(v.iridescenceMap,g.iridescenceMapTransform)),v.iridescenceThicknessMap&&(g.iridescenceThicknessMap.value=v.iridescenceThicknessMap,r(v.iridescenceThicknessMap,g.iridescenceThicknessMapTransform))),v.transmission>0&&(g.transmission.value=v.transmission,g.transmissionSamplerMap.value=_.texture,g.transmissionSamplerSize.value.set(_.width,_.height),v.transmissionMap&&(g.transmissionMap.value=v.transmissionMap,r(v.transmissionMap,g.transmissionMapTransform)),g.thickness.value=v.thickness,v.thicknessMap&&(g.thicknessMap.value=v.thicknessMap,r(v.thicknessMap,g.thicknessMapTransform)),g.attenuationDistance.value=v.attenuationDistance,g.attenuationColor.value.copy(v.attenuationColor)),v.anisotropy>0&&(g.anisotropyVector.value.set(v.anisotropy*Math.cos(v.anisotropyRotation),v.anisotropy*Math.sin(v.anisotropyRotation)),v.anisotropyMap&&(g.anisotropyMap.value=v.anisotropyMap,r(v.anisotropyMap,g.anisotropyMapTransform))),g.specularIntensity.value=v.specularIntensity,g.specularColor.value.copy(v.specularColor),v.specularColorMap&&(g.specularColorMap.value=v.specularColorMap,r(v.specularColorMap,g.specularColorMapTransform)),v.specularIntensityMap&&(g.specularIntensityMap.value=v.specularIntensityMap,r(v.specularIntensityMap,g.specularIntensityMapTransform))}function b(g,v){v.matcap&&(g.matcap.value=v.matcap)}function x(g,v){let _=t.get(v).light;g.referencePosition.value.setFromMatrixPosition(_.matrixWorld),g.nearDistance.value=_.shadow.camera.near,g.farDistance.value=_.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:n}}function uL(e,t,r,i){let n={},s={},a=[],o=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function l(_,E){let M=E.program;i.uniformBlockBinding(_,M)}function c(_,E){let M=n[_.id];M===void 0&&(b(_),M=u(_),n[_.id]=M,_.addEventListener("dispose",g));let P=E.program;i.updateUBOMapping(_,P);let k=t.render.frame;s[_.id]!==k&&(f(_),s[_.id]=k)}function u(_){let E=d();_.__bindingPointIndex=E;let M=e.createBuffer(),P=_.__size,k=_.usage;return e.bindBuffer(e.UNIFORM_BUFFER,M),e.bufferData(e.UNIFORM_BUFFER,P,k),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,E,M),M}function d(){for(let _=0;_<o;_++)if(a.indexOf(_)===-1)return a.push(_),_;return console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function f(_){let E=n[_.id],M=_.uniforms,P=_.__cache;e.bindBuffer(e.UNIFORM_BUFFER,E);for(let k=0,z=M.length;k<z;k++){let D=Array.isArray(M[k])?M[k]:[M[k]];for(let I=0,L=D.length;I<L;I++){let Z=D[I];if(y(Z,k,I,P)===!0){let se=Z.__offset,ce=Array.isArray(Z.value)?Z.value:[Z.value],fe=0;for(let ze=0;ze<ce.length;ze++){let Fe=ce[ze],Pe=x(Fe);typeof Fe=="number"||typeof Fe=="boolean"?(Z.__data[0]=Fe,e.bufferSubData(e.UNIFORM_BUFFER,se+fe,Z.__data)):Fe.isMatrix3?(Z.__data[0]=Fe.elements[0],Z.__data[1]=Fe.elements[1],Z.__data[2]=Fe.elements[2],Z.__data[3]=0,Z.__data[4]=Fe.elements[3],Z.__data[5]=Fe.elements[4],Z.__data[6]=Fe.elements[5],Z.__data[7]=0,Z.__data[8]=Fe.elements[6],Z.__data[9]=Fe.elements[7],Z.__data[10]=Fe.elements[8],Z.__data[11]=0):(Fe.toArray(Z.__data,fe),fe+=Pe.storage/Float32Array.BYTES_PER_ELEMENT)}e.bufferSubData(e.UNIFORM_BUFFER,se,Z.__data)}}}e.bindBuffer(e.UNIFORM_BUFFER,null)}function y(_,E,M,P){let k=_.value,z=E+"_"+M;if(P[z]===void 0)return typeof k=="number"||typeof k=="boolean"?P[z]=k:P[z]=k.clone(),!0;{let D=P[z];if(typeof k=="number"||typeof k=="boolean"){if(D!==k)return P[z]=k,!0}else if(D.equals(k)===!1)return D.copy(k),!0}return!1}function b(_){let E=_.uniforms,M=0,P=16;for(let z=0,D=E.length;z<D;z++){let I=Array.isArray(E[z])?E[z]:[E[z]];for(let L=0,Z=I.length;L<Z;L++){let se=I[L],ce=Array.isArray(se.value)?se.value:[se.value];for(let fe=0,ze=ce.length;fe<ze;fe++){let Fe=ce[fe],Pe=x(Fe),ue=M%P,Te=ue%Pe.boundary,de=ue+Te;M+=Te,de!==0&&P-de<Pe.storage&&(M+=P-de),se.__data=new Float32Array(Pe.storage/Float32Array.BYTES_PER_ELEMENT),se.__offset=M,M+=Pe.storage}}}let k=M%P;return k>0&&(M+=P-k),_.__size=M,_.__cache={},this}function x(_){let E={boundary:0,storage:0};return typeof _=="number"||typeof _=="boolean"?(E.boundary=4,E.storage=4):_.isVector2?(E.boundary=8,E.storage=8):_.isVector3||_.isColor?(E.boundary=16,E.storage=12):_.isVector4?(E.boundary=16,E.storage=16):_.isMatrix3?(E.boundary=48,E.storage=48):_.isMatrix4?(E.boundary=64,E.storage=64):_.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",_),E}function g(_){let E=_.target;E.removeEventListener("dispose",g);let M=a.indexOf(E.__bindingPointIndex);a.splice(M,1),e.deleteBuffer(n[E.id]),delete n[E.id],delete s[E.id]}function v(){for(let _ in n)e.deleteBuffer(n[_]);a=[],n={},s={}}return{bind:l,update:c,dispose:v}}var df=class{constructor(e={}){let{canvas:t=Ix(),context:r=null,depth:i=!0,stencil:n=!1,alpha:s=!1,antialias:a=!1,premultipliedAlpha:o=!0,preserveDrawingBuffer:l=!1,powerPreference:c="default",failIfMajorPerformanceCaveat:u=!1,reverseDepthBuffer:d=!1}=e;this.isWebGLRenderer=!0;let f;if(r!==null){if(typeof WebGLRenderingContext<"u"&&r instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");f=r.getContextAttributes().alpha}else f=s;let y=new Uint32Array(4),b=new Int32Array(4),x=null,g=null,v=[],_=[];this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this._outputColorSpace=xi,this.toneMapping=hi,this.toneMappingExposure=1;let E=this,M=!1,P=0,k=0,z=null,D=-1,I=null,L=new _i,Z=new _i,se=null,ce=new or(0),fe=0,ze=t.width,Fe=t.height,Pe=1,ue=null,Te=null,de=new _i(0,0,ze,Fe),Ie=new _i(0,0,ze,Fe),Re=!1,Be=new qh,Se=!1,U=!1,ie=new Ir,Ae=new Ir,Ue=new je,Ge=new _i,nt={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},Qe=!1;function ct(){return z===null?Pe:1}let ye=r;function dt(Ve,wt){return t.getContext(Ve,wt)}try{let Ve={alpha:!0,depth:i,stencil:n,antialias:a,premultipliedAlpha:o,preserveDrawingBuffer:l,powerPreference:c,failIfMajorPerformanceCaveat:u};if("setAttribute"in t&&t.setAttribute("data-engine","three.js r171"),t.addEventListener("webglcontextlost",It,!1),t.addEventListener("webglcontextrestored",Ct,!1),t.addEventListener("webglcontextcreationerror",rr,!1),ye===null){let wt="webgl2";if(ye=dt(wt,Ve),ye===null)throw dt(wt)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(Ve){throw console.error("THREE.WebGLRenderer: "+Ve.message),Ve}let xt,Dt,We,mt,it,st,oe,F,le,pe,Le,He,at,rt,ht,Tt,Mt,Ut,Kt,fr,er,Zt,Gt,Er;function ut(){xt=new _I(ye),xt.init(),Zt=new fw(ye,xt),Dt=new gI(ye,xt,e,Zt),We=new rL(ye,xt),Dt.reverseDepthBuffer&&d&&We.buffers.depth.setReversed(!0),mt=new MI(ye),it=new HN,st=new iL(ye,xt,We,it,Dt,Zt,mt),oe=new vI(E),F=new wI(E),le=new NC(ye),Gt=new fI(ye,le),pe=new EI(ye,le,mt,Gt),Le=new TI(ye,pe,le,mt),Kt=new AI(ye,Dt,st),Tt=new yI(it),He=new VN(E,oe,F,xt,Dt,Gt,Tt),at=new hL(E,it),rt=new WN,ht=new $N(xt),Ut=new pI(E,oe,F,We,Le,f,o),Mt=new eL(E,Le,Dt),Er=new uL(ye,mt,Dt,We),fr=new mI(ye,xt,mt),er=new SI(ye,xt,mt),mt.programs=He.programs,E.capabilities=Dt,E.extensions=xt,E.properties=it,E.renderLists=rt,E.shadowMap=Mt,E.state=We,E.info=mt}ut();let zt=new lL(E,ye);this.xr=zt,this.getContext=function(){return ye},this.getContextAttributes=function(){return ye.getContextAttributes()},this.forceContextLoss=function(){let Ve=xt.get("WEBGL_lose_context");Ve&&Ve.loseContext()},this.forceContextRestore=function(){let Ve=xt.get("WEBGL_lose_context");Ve&&Ve.restoreContext()},this.getPixelRatio=function(){return Pe},this.setPixelRatio=function(Ve){Ve!==void 0&&(Pe=Ve,this.setSize(ze,Fe,!1))},this.getSize=function(Ve){return Ve.set(ze,Fe)},this.setSize=function(Ve,wt,Pt=!0){if(zt.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}ze=Ve,Fe=wt,t.width=Math.floor(Ve*Pe),t.height=Math.floor(wt*Pe),Pt===!0&&(t.style.width=Ve+"px",t.style.height=wt+"px"),this.setViewport(0,0,Ve,wt)},this.getDrawingBufferSize=function(Ve){return Ve.set(ze*Pe,Fe*Pe).floor()},this.setDrawingBufferSize=function(Ve,wt,Pt){ze=Ve,Fe=wt,Pe=Pt,t.width=Math.floor(Ve*Pt),t.height=Math.floor(wt*Pt),this.setViewport(0,0,Ve,wt)},this.getCurrentViewport=function(Ve){return Ve.copy(L)},this.getViewport=function(Ve){return Ve.copy(de)},this.setViewport=function(Ve,wt,Pt,kt){Ve.isVector4?de.set(Ve.x,Ve.y,Ve.z,Ve.w):de.set(Ve,wt,Pt,kt),We.viewport(L.copy(de).multiplyScalar(Pe).round())},this.getScissor=function(Ve){return Ve.copy(Ie)},this.setScissor=function(Ve,wt,Pt,kt){Ve.isVector4?Ie.set(Ve.x,Ve.y,Ve.z,Ve.w):Ie.set(Ve,wt,Pt,kt),We.scissor(Z.copy(Ie).multiplyScalar(Pe).round())},this.getScissorTest=function(){return Re},this.setScissorTest=function(Ve){We.setScissorTest(Re=Ve)},this.setOpaqueSort=function(Ve){ue=Ve},this.setTransparentSort=function(Ve){Te=Ve},this.getClearColor=function(Ve){return Ve.copy(Ut.getClearColor())},this.setClearColor=function(){Ut.setClearColor.apply(Ut,arguments)},this.getClearAlpha=function(){return Ut.getClearAlpha()},this.setClearAlpha=function(){Ut.setClearAlpha.apply(Ut,arguments)},this.clear=function(Ve=!0,wt=!0,Pt=!0){let kt=0;if(Ve){let bt=!1;if(z!==null){let tr=z.texture.format;bt=tr===wd||tr===bd||tr===Sh}if(bt){let tr=z.texture.type,Sr=tr===Ji||tr===Aa||tr===Ma||tr===io||tr===yd||tr===vd,Mr=Ut.getClearColor(),Lr=Ut.getClearAlpha(),Nr=Mr.r,Xr=Mr.g,dr=Mr.b;Sr?(y[0]=Nr,y[1]=Xr,y[2]=dr,y[3]=Lr,ye.clearBufferuiv(ye.COLOR,0,y)):(b[0]=Nr,b[1]=Xr,b[2]=dr,b[3]=Lr,ye.clearBufferiv(ye.COLOR,0,b))}else kt|=ye.COLOR_BUFFER_BIT}wt&&(kt|=ye.DEPTH_BUFFER_BIT),Pt&&(kt|=ye.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),ye.clear(kt)},this.clearColor=function(){this.clear(!0,!1,!1)},this.clearDepth=function(){this.clear(!1,!0,!1)},this.clearStencil=function(){this.clear(!1,!1,!0)},this.dispose=function(){t.removeEventListener("webglcontextlost",It,!1),t.removeEventListener("webglcontextrestored",Ct,!1),t.removeEventListener("webglcontextcreationerror",rr,!1),Ut.dispose(),rt.dispose(),ht.dispose(),it.dispose(),oe.dispose(),F.dispose(),Le.dispose(),Gt.dispose(),Er.dispose(),He.dispose(),zt.dispose(),zt.removeEventListener("sessionstart",Vt),zt.removeEventListener("sessionend",pi),nn.stop()};function It(Ve){Ve.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),M=!0}function Ct(){console.log("THREE.WebGLRenderer: Context Restored."),M=!1;let Ve=mt.autoReset,wt=Mt.enabled,Pt=Mt.autoUpdate,kt=Mt.needsUpdate,bt=Mt.type;ut(),mt.autoReset=Ve,Mt.enabled=wt,Mt.autoUpdate=Pt,Mt.needsUpdate=kt,Mt.type=bt}function rr(Ve){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",Ve.statusMessage)}function $t(Ve){let wt=Ve.target;wt.removeEventListener("dispose",$t),xr(wt)}function xr(Ve){cr(Ve),it.remove(Ve)}function cr(Ve){let wt=it.get(Ve).programs;wt!==void 0&&(wt.forEach(function(Pt){He.releaseProgram(Pt)}),Ve.isShaderMaterial&&He.releaseShaderCache(Ve))}this.renderBufferDirect=function(Ve,wt,Pt,kt,bt,tr){wt===null&&(wt=nt);let Sr=bt.isMesh&&bt.matrixWorld.determinant()<0,Mr=zn(Ve,wt,Pt,kt,bt);We.setMaterial(kt,Sr);let Lr=Pt.index,Nr=1;if(kt.wireframe===!0){if(Lr=pe.getWireframeAttribute(Pt),Lr===void 0)return;Nr=2}let Xr=Pt.drawRange,dr=Pt.attributes.position,gi=Xr.start*Nr,Li=(Xr.start+Xr.count)*Nr;tr!==null&&(gi=Math.max(gi,tr.start*Nr),Li=Math.min(Li,(tr.start+tr.count)*Nr)),Lr!==null?(gi=Math.max(gi,0),Li=Math.min(Li,Lr.count)):dr!=null&&(gi=Math.max(gi,0),Li=Math.min(Li,dr.count));let Oi=Li-gi;if(Oi<0||Oi===1/0)return;Gt.setup(bt,kt,Mr,Pt,Lr);let bi,Kr=fr;if(Lr!==null&&(bi=le.get(Lr),Kr=er,Kr.setIndex(bi)),bt.isMesh)kt.wireframe===!0?(We.setLineWidth(kt.wireframeLinewidth*ct()),Kr.setMode(ye.LINES)):Kr.setMode(ye.TRIANGLES);else if(bt.isLine){let Fr=kt.linewidth;Fr===void 0&&(Fr=1),We.setLineWidth(Fr*ct()),bt.isLineSegments?Kr.setMode(ye.LINES):bt.isLineLoop?Kr.setMode(ye.LINE_LOOP):Kr.setMode(ye.LINE_STRIP)}else bt.isPoints?Kr.setMode(ye.POINTS):bt.isSprite&&Kr.setMode(ye.TRIANGLES);if(bt.isBatchedMesh)if(bt._multiDrawInstances!==null)Kr.renderMultiDrawInstances(bt._multiDrawStarts,bt._multiDrawCounts,bt._multiDrawCount,bt._multiDrawInstances);else if(xt.get("WEBGL_multi_draw"))Kr.renderMultiDraw(bt._multiDrawStarts,bt._multiDrawCounts,bt._multiDrawCount);else{let Fr=bt._multiDrawStarts,Mn=bt._multiDrawCounts,ta=bt._multiDrawCount,Zn=Lr?le.get(Lr).bytesPerElement:1,ma=it.get(kt).currentProgram.getUniforms();for(let vn=0;vn<ta;vn++)ma.setValue(ye,"_gl_DrawID",vn),Kr.render(Fr[vn]/Zn,Mn[vn])}else if(bt.isInstancedMesh)Kr.renderInstances(gi,Oi,bt.count);else if(Pt.isInstancedBufferGeometry){let Fr=Pt._maxInstanceCount!==void 0?Pt._maxInstanceCount:1/0,Mn=Math.min(Pt.instanceCount,Fr);Kr.renderInstances(gi,Oi,Mn)}else Kr.render(gi,Oi)};function yr(Ve,wt,Pt){Ve.transparent===!0&&Ve.side===Ze&&Ve.forceSinglePass===!1?(Ve.side=tt,Ve.needsUpdate=!0,Sn(Ve,wt,Pt),Ve.side=Ce,Ve.needsUpdate=!0,Sn(Ve,wt,Pt),Ve.side=Ze):Sn(Ve,wt,Pt)}this.compile=function(Ve,wt,Pt=null){Pt===null&&(Pt=Ve),g=ht.get(Pt),g.init(wt),_.push(g),Pt.traverseVisible(function(bt){bt.isLight&&bt.layers.test(wt.layers)&&(g.pushLight(bt),bt.castShadow&&g.pushShadow(bt))}),Ve!==Pt&&Ve.traverseVisible(function(bt){bt.isLight&&bt.layers.test(wt.layers)&&(g.pushLight(bt),bt.castShadow&&g.pushShadow(bt))}),g.setupLights();let kt=new Set;return Ve.traverse(function(bt){if(!(bt.isMesh||bt.isPoints||bt.isLine||bt.isSprite))return;let tr=bt.material;if(tr)if(Array.isArray(tr))for(let Sr=0;Sr<tr.length;Sr++){let Mr=tr[Sr];yr(Mr,Pt,bt),kt.add(Mr)}else yr(tr,Pt,bt),kt.add(tr)}),_.pop(),g=null,kt},this.compileAsync=function(Ve,wt,Pt=null){let kt=this.compile(Ve,wt,Pt);return new Promise(bt=>{function tr(){if(kt.forEach(function(Sr){it.get(Sr).currentProgram.isReady()&&kt.delete(Sr)}),kt.size===0){bt(Ve);return}setTimeout(tr,10)}xt.get("KHR_parallel_shader_compile")!==null?tr():setTimeout(tr,10)})};let ir=null;function _r(Ve){ir&&ir(Ve)}function Vt(){nn.stop()}function pi(){nn.start()}let nn=new B1;nn.setAnimationLoop(_r),typeof self<"u"&&nn.setContext(self),this.setAnimationLoop=function(Ve){ir=Ve,zt.setAnimationLoop(Ve),Ve===null?nn.stop():nn.start()},zt.addEventListener("sessionstart",Vt),zt.addEventListener("sessionend",pi),this.render=function(Ve,wt){if(wt!==void 0&&wt.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(M===!0)return;if(Ve.matrixWorldAutoUpdate===!0&&Ve.updateMatrixWorld(),wt.parent===null&&wt.matrixWorldAutoUpdate===!0&&wt.updateMatrixWorld(),zt.enabled===!0&&zt.isPresenting===!0&&(zt.cameraAutoUpdate===!0&&zt.updateCamera(wt),wt=zt.getCamera()),Ve.isScene===!0&&Ve.onBeforeRender(E,Ve,wt,z),g=ht.get(Ve,_.length),g.init(wt),_.push(g),Ae.multiplyMatrices(wt.projectionMatrix,wt.matrixWorldInverse),Be.setFromProjectionMatrix(Ae),U=this.localClippingEnabled,Se=Tt.init(this.clippingPlanes,U),x=rt.get(Ve,v.length),x.init(),v.push(x),zt.enabled===!0&&zt.isPresenting===!0){let tr=E.xr.getDepthSensingMesh();tr!==null&&$i(tr,wt,-1/0,E.sortObjects)}$i(Ve,wt,0,E.sortObjects),x.finish(),E.sortObjects===!0&&x.sort(ue,Te),Qe=zt.enabled===!1||zt.isPresenting===!1||zt.hasDepthSensing()===!1,Qe&&Ut.addToRenderList(x,Ve),this.info.render.frame++,Se===!0&&Tt.beginShadows();let Pt=g.state.shadowsArray;Mt.render(Pt,Ve,wt),Se===!0&&Tt.endShadows(),this.info.autoReset===!0&&this.info.reset();let kt=x.opaque,bt=x.transmissive;if(g.setupLights(),wt.isArrayCamera){let tr=wt.cameras;if(bt.length>0)for(let Sr=0,Mr=tr.length;Sr<Mr;Sr++){let Lr=tr[Sr];kc(kt,bt,Ve,Lr)}Qe&&Ut.render(Ve);for(let Sr=0,Mr=tr.length;Sr<Mr;Sr++){let Lr=tr[Sr];fa(x,Ve,Lr,Lr.viewport)}}else bt.length>0&&kc(kt,bt,Ve,wt),Qe&&Ut.render(Ve),fa(x,Ve,wt);z!==null&&(st.updateMultisampleRenderTarget(z),st.updateRenderTargetMipmap(z)),Ve.isScene===!0&&Ve.onAfterRender(E,Ve,wt),Gt.resetDefaultState(),D=-1,I=null,_.pop(),_.length>0?(g=_[_.length-1],Se===!0&&Tt.setGlobalState(E.clippingPlanes,g.state.camera)):g=null,v.pop(),v.length>0?x=v[v.length-1]:x=null};function $i(Ve,wt,Pt,kt){if(Ve.visible===!1)return;if(Ve.layers.test(wt.layers)){if(Ve.isGroup)Pt=Ve.renderOrder;else if(Ve.isLOD)Ve.autoUpdate===!0&&Ve.update(wt);else if(Ve.isLight)g.pushLight(Ve),Ve.castShadow&&g.pushShadow(Ve);else if(Ve.isSprite){if(!Ve.frustumCulled||Be.intersectsSprite(Ve)){kt&&Ge.setFromMatrixPosition(Ve.matrixWorld).applyMatrix4(Ae);let tr=Le.update(Ve),Sr=Ve.material;Sr.visible&&x.push(Ve,tr,Sr,Pt,Ge.z,null)}}else if((Ve.isMesh||Ve.isLine||Ve.isPoints)&&(!Ve.frustumCulled||Be.intersectsObject(Ve))){let tr=Le.update(Ve),Sr=Ve.material;if(kt&&(Ve.boundingSphere!==void 0?(Ve.boundingSphere===null&&Ve.computeBoundingSphere(),Ge.copy(Ve.boundingSphere.center)):(tr.boundingSphere===null&&tr.computeBoundingSphere(),Ge.copy(tr.boundingSphere.center)),Ge.applyMatrix4(Ve.matrixWorld).applyMatrix4(Ae)),Array.isArray(Sr)){let Mr=tr.groups;for(let Lr=0,Nr=Mr.length;Lr<Nr;Lr++){let Xr=Mr[Lr],dr=Sr[Xr.materialIndex];dr&&dr.visible&&x.push(Ve,tr,dr,Pt,Ge.z,Xr)}}else Sr.visible&&x.push(Ve,tr,Sr,Pt,Ge.z,null)}}let bt=Ve.children;for(let tr=0,Sr=bt.length;tr<Sr;tr++)$i(bt[tr],wt,Pt,kt)}function fa(Ve,wt,Pt,kt){let bt=Ve.opaque,tr=Ve.transmissive,Sr=Ve.transparent;g.setupLightsView(Pt),Se===!0&&Tt.setGlobalState(E.clippingPlanes,Pt),kt&&We.viewport(L.copy(kt)),bt.length>0&&vo(bt,wt,Pt),tr.length>0&&vo(tr,wt,Pt),Sr.length>0&&vo(Sr,wt,Pt),We.buffers.depth.setTest(!0),We.buffers.depth.setMask(!0),We.buffers.color.setMask(!0),We.setPolygonOffset(!1)}function kc(Ve,wt,Pt,kt){if((Pt.isScene===!0?Pt.overrideMaterial:null)!==null)return;g.state.transmissionRenderTarget[kt.id]===void 0&&(g.state.transmissionRenderTarget[kt.id]=new In(1,1,{generateMipmaps:!0,type:xt.has("EXT_color_buffer_half_float")||xt.has("EXT_color_buffer_float")?Ts:Ji,minFilter:Fi,samples:4,stencilBuffer:n,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:li.workingColorSpace}));let bt=g.state.transmissionRenderTarget[kt.id],tr=kt.viewport||L;bt.setSize(tr.z,tr.w);let Sr=E.getRenderTarget();E.setRenderTarget(bt),E.getClearColor(ce),fe=E.getClearAlpha(),fe<1&&E.setClearColor(16777215,.5),E.clear(),Qe&&Ut.render(Pt);let Mr=E.toneMapping;E.toneMapping=hi;let Lr=kt.viewport;if(kt.viewport!==void 0&&(kt.viewport=void 0),g.setupLightsView(kt),Se===!0&&Tt.setGlobalState(E.clippingPlanes,kt),vo(Ve,Pt,kt),st.updateMultisampleRenderTarget(bt),st.updateRenderTargetMipmap(bt),xt.has("WEBGL_multisampled_render_to_texture")===!1){let Nr=!1;for(let Xr=0,dr=wt.length;Xr<dr;Xr++){let gi=wt[Xr],Li=gi.object,Oi=gi.geometry,bi=gi.material,Kr=gi.group;if(bi.side===Ze&&Li.layers.test(kt.layers)){let Fr=bi.side;bi.side=tt,bi.needsUpdate=!0,ea(Li,Pt,kt,Oi,bi,Kr),bi.side=Fr,bi.needsUpdate=!0,Nr=!0}}Nr===!0&&(st.updateMultisampleRenderTarget(bt),st.updateRenderTargetMipmap(bt))}E.setRenderTarget(Sr),E.setClearColor(ce,fe),Lr!==void 0&&(kt.viewport=Lr),E.toneMapping=Mr}function vo(Ve,wt,Pt){let kt=wt.isScene===!0?wt.overrideMaterial:null;for(let bt=0,tr=Ve.length;bt<tr;bt++){let Sr=Ve[bt],Mr=Sr.object,Lr=Sr.geometry,Nr=kt===null?Sr.material:kt,Xr=Sr.group;Mr.layers.test(Pt.layers)&&ea(Mr,wt,Pt,Lr,Nr,Xr)}}function ea(Ve,wt,Pt,kt,bt,tr){Ve.onBeforeRender(E,wt,Pt,kt,bt,tr),Ve.modelViewMatrix.multiplyMatrices(Pt.matrixWorldInverse,Ve.matrixWorld),Ve.normalMatrix.getNormalMatrix(Ve.modelViewMatrix),bt.onBeforeRender(E,wt,Pt,kt,Ve,tr),bt.transparent===!0&&bt.side===Ze&&bt.forceSinglePass===!1?(bt.side=tt,bt.needsUpdate=!0,E.renderBufferDirect(Pt,wt,kt,bt,Ve,tr),bt.side=Ce,bt.needsUpdate=!0,E.renderBufferDirect(Pt,wt,kt,bt,Ve,tr),bt.side=Ze):E.renderBufferDirect(Pt,wt,kt,bt,Ve,tr),Ve.onAfterRender(E,wt,Pt,kt,bt,tr)}function Sn(Ve,wt,Pt){wt.isScene!==!0&&(wt=nt);let kt=it.get(Ve),bt=g.state.lights,tr=g.state.shadowsArray,Sr=bt.state.version,Mr=He.getParameters(Ve,bt.state,tr,wt,Pt),Lr=He.getProgramCacheKey(Mr),Nr=kt.programs;kt.environment=Ve.isMeshStandardMaterial?wt.environment:null,kt.fog=wt.fog,kt.envMap=(Ve.isMeshStandardMaterial?F:oe).get(Ve.envMap||kt.environment),kt.envMapRotation=kt.environment!==null&&Ve.envMap===null?wt.environmentRotation:Ve.envMapRotation,Nr===void 0&&(Ve.addEventListener("dispose",$t),Nr=new Map,kt.programs=Nr);let Xr=Nr.get(Lr);if(Xr!==void 0){if(kt.currentProgram===Xr&&kt.lightsStateVersion===Sr)return sn(Ve,Mr),Xr}else Mr.uniforms=He.getUniforms(Ve),Ve.onBeforeCompile(Mr,E),Xr=He.acquireProgram(Mr,Lr),Nr.set(Lr,Xr),kt.uniforms=Mr.uniforms;let dr=kt.uniforms;return(!Ve.isShaderMaterial&&!Ve.isRawShaderMaterial||Ve.clipping===!0)&&(dr.clippingPlanes=Tt.uniform),sn(Ve,Mr),kt.needsLights=Ga(Ve),kt.lightsStateVersion=Sr,kt.needsLights&&(dr.ambientLightColor.value=bt.state.ambient,dr.lightProbe.value=bt.state.probe,dr.directionalLights.value=bt.state.directional,dr.directionalLightShadows.value=bt.state.directionalShadow,dr.spotLights.value=bt.state.spot,dr.spotLightShadows.value=bt.state.spotShadow,dr.rectAreaLights.value=bt.state.rectArea,dr.ltc_1.value=bt.state.rectAreaLTC1,dr.ltc_2.value=bt.state.rectAreaLTC2,dr.pointLights.value=bt.state.point,dr.pointLightShadows.value=bt.state.pointShadow,dr.hemisphereLights.value=bt.state.hemi,dr.directionalShadowMap.value=bt.state.directionalShadowMap,dr.directionalShadowMatrix.value=bt.state.directionalShadowMatrix,dr.spotShadowMap.value=bt.state.spotShadowMap,dr.spotLightMatrix.value=bt.state.spotLightMatrix,dr.spotLightMap.value=bt.state.spotLightMap,dr.pointShadowMap.value=bt.state.pointShadowMap,dr.pointShadowMatrix.value=bt.state.pointShadowMatrix),kt.currentProgram=Xr,kt.uniformsList=null,Xr}function Os(Ve){if(Ve.uniformsList===null){let wt=Ve.currentProgram.getUniforms();Ve.uniformsList=hf.seqWithValue(wt.seq,Ve.uniforms)}return Ve.uniformsList}function sn(Ve,wt){let Pt=it.get(Ve);Pt.outputColorSpace=wt.outputColorSpace,Pt.batching=wt.batching,Pt.batchingColor=wt.batchingColor,Pt.instancing=wt.instancing,Pt.instancingColor=wt.instancingColor,Pt.instancingMorph=wt.instancingMorph,Pt.skinning=wt.skinning,Pt.morphTargets=wt.morphTargets,Pt.morphNormals=wt.morphNormals,Pt.morphColors=wt.morphColors,Pt.morphTargetsCount=wt.morphTargetsCount,Pt.numClippingPlanes=wt.numClippingPlanes,Pt.numIntersection=wt.numClipIntersection,Pt.vertexAlphas=wt.vertexAlphas,Pt.vertexTangents=wt.vertexTangents,Pt.toneMapping=wt.toneMapping}function zn(Ve,wt,Pt,kt,bt){wt.isScene!==!0&&(wt=nt),st.resetTextureUnits();let tr=wt.fog,Sr=kt.isMeshStandardMaterial?wt.environment:null,Mr=z===null?E.outputColorSpace:z.isXRRenderTarget===!0?z.texture.colorSpace:kn,Lr=(kt.isMeshStandardMaterial?F:oe).get(kt.envMap||Sr),Nr=kt.vertexColors===!0&&!!Pt.attributes.color&&Pt.attributes.color.itemSize===4,Xr=!!Pt.attributes.tangent&&(!!kt.normalMap||kt.anisotropy>0),dr=!!Pt.morphAttributes.position,gi=!!Pt.morphAttributes.normal,Li=!!Pt.morphAttributes.color,Oi=hi;kt.toneMapped&&(z===null||z.isXRRenderTarget===!0)&&(Oi=E.toneMapping);let bi=Pt.morphAttributes.position||Pt.morphAttributes.normal||Pt.morphAttributes.color,Kr=bi!==void 0?bi.length:0,Fr=it.get(kt),Mn=g.state.lights;if(Se===!0&&(U===!0||Ve!==I)){let xn=Ve===I&&kt.id===D;Tt.setState(kt,Ve,xn)}let ta=!1;kt.version===Fr.__version?(Fr.needsLights&&Fr.lightsStateVersion!==Mn.state.version||Fr.outputColorSpace!==Mr||bt.isBatchedMesh&&Fr.batching===!1||!bt.isBatchedMesh&&Fr.batching===!0||bt.isBatchedMesh&&Fr.batchingColor===!0&&bt.colorTexture===null||bt.isBatchedMesh&&Fr.batchingColor===!1&&bt.colorTexture!==null||bt.isInstancedMesh&&Fr.instancing===!1||!bt.isInstancedMesh&&Fr.instancing===!0||bt.isSkinnedMesh&&Fr.skinning===!1||!bt.isSkinnedMesh&&Fr.skinning===!0||bt.isInstancedMesh&&Fr.instancingColor===!0&&bt.instanceColor===null||bt.isInstancedMesh&&Fr.instancingColor===!1&&bt.instanceColor!==null||bt.isInstancedMesh&&Fr.instancingMorph===!0&&bt.morphTexture===null||bt.isInstancedMesh&&Fr.instancingMorph===!1&&bt.morphTexture!==null||Fr.envMap!==Lr||kt.fog===!0&&Fr.fog!==tr||Fr.numClippingPlanes!==void 0&&(Fr.numClippingPlanes!==Tt.numPlanes||Fr.numIntersection!==Tt.numIntersection)||Fr.vertexAlphas!==Nr||Fr.vertexTangents!==Xr||Fr.morphTargets!==dr||Fr.morphNormals!==gi||Fr.morphColors!==Li||Fr.toneMapping!==Oi||Fr.morphTargetsCount!==Kr)&&(ta=!0):(ta=!0,Fr.__version=kt.version);let Zn=Fr.currentProgram;ta===!0&&(Zn=Sn(kt,wt,bt));let ma=!1,vn=!1,Wa=!1,Ti=Zn.getUniforms(),An=Fr.uniforms;if(We.useProgram(Zn.program)&&(ma=!0,vn=!0,Wa=!0),kt.id!==D&&(D=kt.id,vn=!0),ma||I!==Ve){We.buffers.depth.getReversed()?(ie.copy(Ve.projectionMatrix),aT(ie),oT(ie),Ti.setValue(ye,"projectionMatrix",ie)):Ti.setValue(ye,"projectionMatrix",Ve.projectionMatrix),Ti.setValue(ye,"viewMatrix",Ve.matrixWorldInverse);let xn=Ti.map.cameraPosition;xn!==void 0&&xn.setValue(ye,Ue.setFromMatrixPosition(Ve.matrixWorld)),Dt.logarithmicDepthBuffer&&Ti.setValue(ye,"logDepthBufFC",2/(Math.log(Ve.far+1)/Math.LN2)),(kt.isMeshPhongMaterial||kt.isMeshToonMaterial||kt.isMeshLambertMaterial||kt.isMeshBasicMaterial||kt.isMeshStandardMaterial||kt.isShaderMaterial)&&Ti.setValue(ye,"isOrthographic",Ve.isOrthographicCamera===!0),I!==Ve&&(I=Ve,vn=!0,Wa=!0)}if(bt.isSkinnedMesh){Ti.setOptional(ye,bt,"bindMatrix"),Ti.setOptional(ye,bt,"bindMatrixInverse");let xn=bt.skeleton;xn&&(xn.boneTexture===null&&xn.computeBoneTexture(),Ti.setValue(ye,"boneTexture",xn.boneTexture,st))}bt.isBatchedMesh&&(Ti.setOptional(ye,bt,"batchingTexture"),Ti.setValue(ye,"batchingTexture",bt._matricesTexture,st),Ti.setOptional(ye,bt,"batchingIdTexture"),Ti.setValue(ye,"batchingIdTexture",bt._indirectTexture,st),Ti.setOptional(ye,bt,"batchingColorTexture"),bt._colorsTexture!==null&&Ti.setValue(ye,"batchingColorTexture",bt._colorsTexture,st));let Bn=Pt.morphAttributes;if((Bn.position!==void 0||Bn.normal!==void 0||Bn.color!==void 0)&&Kt.update(bt,Pt,Zn),(vn||Fr.receiveShadow!==bt.receiveShadow)&&(Fr.receiveShadow=bt.receiveShadow,Ti.setValue(ye,"receiveShadow",bt.receiveShadow)),kt.isMeshGouraudMaterial&&kt.envMap!==null&&(An.envMap.value=Lr,An.flipEnvMap.value=Lr.isCubeTexture&&Lr.isRenderTargetTexture===!1?-1:1),kt.isMeshStandardMaterial&&kt.envMap===null&&wt.environment!==null&&(An.envMapIntensity.value=wt.environmentIntensity),vn&&(Ti.setValue(ye,"toneMappingExposure",E.toneMappingExposure),Fr.needsLights&&wl(An,Wa),tr&&kt.fog===!0&&at.refreshFogUniforms(An,tr),at.refreshMaterialUniforms(An,kt,Pe,Fe,g.state.transmissionRenderTarget[Ve.id]),hf.upload(ye,Os(Fr),An,st)),kt.isShaderMaterial&&kt.uniformsNeedUpdate===!0&&(hf.upload(ye,Os(Fr),An,st),kt.uniformsNeedUpdate=!1),kt.isSpriteMaterial&&Ti.setValue(ye,"center",bt.center),Ti.setValue(ye,"modelViewMatrix",bt.modelViewMatrix),Ti.setValue(ye,"normalMatrix",bt.normalMatrix),Ti.setValue(ye,"modelMatrix",bt.matrixWorld),kt.isShaderMaterial||kt.isRawShaderMaterial){let xn=kt.uniformsGroups;for(let ss=0,Oc=xn.length;ss<Oc;ss++){let Ds=xn[ss];Er.update(Ds,Zn),Er.bind(Ds,Zn)}}return Zn}function wl(Ve,wt){Ve.ambientLightColor.needsUpdate=wt,Ve.lightProbe.needsUpdate=wt,Ve.directionalLights.needsUpdate=wt,Ve.directionalLightShadows.needsUpdate=wt,Ve.pointLights.needsUpdate=wt,Ve.pointLightShadows.needsUpdate=wt,Ve.spotLights.needsUpdate=wt,Ve.spotLightShadows.needsUpdate=wt,Ve.rectAreaLights.needsUpdate=wt,Ve.hemisphereLights.needsUpdate=wt}function Ga(Ve){return Ve.isMeshLambertMaterial||Ve.isMeshToonMaterial||Ve.isMeshPhongMaterial||Ve.isMeshStandardMaterial||Ve.isShadowMaterial||Ve.isShaderMaterial&&Ve.lights===!0}this.getActiveCubeFace=function(){return P},this.getActiveMipmapLevel=function(){return k},this.getRenderTarget=function(){return z},this.setRenderTargetTextures=function(Ve,wt,Pt){it.get(Ve.texture).__webglTexture=wt,it.get(Ve.depthTexture).__webglTexture=Pt;let kt=it.get(Ve);kt.__hasExternalTextures=!0,kt.__autoAllocateDepthBuffer=Pt===void 0,kt.__autoAllocateDepthBuffer||xt.has("WEBGL_multisampled_render_to_texture")===!0&&(console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"),kt.__useRenderToTexture=!1)},this.setRenderTargetFramebuffer=function(Ve,wt){let Pt=it.get(Ve);Pt.__webglFramebuffer=wt,Pt.__useDefaultFramebuffer=wt===void 0},this.setRenderTarget=function(Ve,wt=0,Pt=0){z=Ve,P=wt,k=Pt;let kt=!0,bt=null,tr=!1,Sr=!1;if(Ve){let Mr=it.get(Ve);if(Mr.__useDefaultFramebuffer!==void 0)We.bindFramebuffer(ye.FRAMEBUFFER,null),kt=!1;else if(Mr.__webglFramebuffer===void 0)st.setupRenderTarget(Ve);else if(Mr.__hasExternalTextures)st.rebindTextures(Ve,it.get(Ve.texture).__webglTexture,it.get(Ve.depthTexture).__webglTexture);else if(Ve.depthBuffer){let Xr=Ve.depthTexture;if(Mr.__boundDepthTexture!==Xr){if(Xr!==null&&it.has(Xr)&&(Ve.width!==Xr.image.width||Ve.height!==Xr.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");st.setupDepthRenderbuffer(Ve)}}let Lr=Ve.texture;(Lr.isData3DTexture||Lr.isDataArrayTexture||Lr.isCompressedArrayTexture)&&(Sr=!0);let Nr=it.get(Ve).__webglFramebuffer;Ve.isWebGLCubeRenderTarget?(Array.isArray(Nr[wt])?bt=Nr[wt][Pt]:bt=Nr[wt],tr=!0):Ve.samples>0&&st.useMultisampledRTT(Ve)===!1?bt=it.get(Ve).__webglMultisampledFramebuffer:Array.isArray(Nr)?bt=Nr[Pt]:bt=Nr,L.copy(Ve.viewport),Z.copy(Ve.scissor),se=Ve.scissorTest}else L.copy(de).multiplyScalar(Pe).floor(),Z.copy(Ie).multiplyScalar(Pe).floor(),se=Re;if(We.bindFramebuffer(ye.FRAMEBUFFER,bt)&&kt&&We.drawBuffers(Ve,bt),We.viewport(L),We.scissor(Z),We.setScissorTest(se),tr){let Mr=it.get(Ve.texture);ye.framebufferTexture2D(ye.FRAMEBUFFER,ye.COLOR_ATTACHMENT0,ye.TEXTURE_CUBE_MAP_POSITIVE_X+wt,Mr.__webglTexture,Pt)}else if(Sr){let Mr=it.get(Ve.texture),Lr=wt||0;ye.framebufferTextureLayer(ye.FRAMEBUFFER,ye.COLOR_ATTACHMENT0,Mr.__webglTexture,Pt||0,Lr)}D=-1},this.readRenderTargetPixels=function(Ve,wt,Pt,kt,bt,tr,Sr){if(!(Ve&&Ve.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Mr=it.get(Ve).__webglFramebuffer;if(Ve.isWebGLCubeRenderTarget&&Sr!==void 0&&(Mr=Mr[Sr]),Mr){We.bindFramebuffer(ye.FRAMEBUFFER,Mr);try{let Lr=Ve.texture,Nr=Lr.format,Xr=Lr.type;if(!Dt.textureFormatReadable(Nr)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!Dt.textureTypeReadable(Xr)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}wt>=0&&wt<=Ve.width-kt&&Pt>=0&&Pt<=Ve.height-bt&&ye.readPixels(wt,Pt,kt,bt,Zt.convert(Nr),Zt.convert(Xr),tr)}finally{let Lr=z!==null?it.get(z).__webglFramebuffer:null;We.bindFramebuffer(ye.FRAMEBUFFER,Lr)}}},this.readRenderTargetPixelsAsync=async function(Ve,wt,Pt,kt,bt,tr,Sr){if(!(Ve&&Ve.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Mr=it.get(Ve).__webglFramebuffer;if(Ve.isWebGLCubeRenderTarget&&Sr!==void 0&&(Mr=Mr[Sr]),Mr){let Lr=Ve.texture,Nr=Lr.format,Xr=Lr.type;if(!Dt.textureFormatReadable(Nr))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!Dt.textureTypeReadable(Xr))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");if(wt>=0&&wt<=Ve.width-kt&&Pt>=0&&Pt<=Ve.height-bt){We.bindFramebuffer(ye.FRAMEBUFFER,Mr);let dr=ye.createBuffer();ye.bindBuffer(ye.PIXEL_PACK_BUFFER,dr),ye.bufferData(ye.PIXEL_PACK_BUFFER,tr.byteLength,ye.STREAM_READ),ye.readPixels(wt,Pt,kt,bt,Zt.convert(Nr),Zt.convert(Xr),0);let gi=z!==null?it.get(z).__webglFramebuffer:null;We.bindFramebuffer(ye.FRAMEBUFFER,gi);let Li=ye.fenceSync(ye.SYNC_GPU_COMMANDS_COMPLETE,0);return ye.flush(),await sT(ye,Li,4),ye.bindBuffer(ye.PIXEL_PACK_BUFFER,dr),ye.getBufferSubData(ye.PIXEL_PACK_BUFFER,0,tr),ye.deleteBuffer(dr),ye.deleteSync(Li),tr}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(Ve,wt=null,Pt=0){Ve.isTexture!==!0&&(ql("WebGLRenderer: copyFramebufferToTexture function signature has changed."),wt=arguments[0]||null,Ve=arguments[1]);let kt=Math.pow(2,-Pt),bt=Math.floor(Ve.image.width*kt),tr=Math.floor(Ve.image.height*kt),Sr=wt!==null?wt.x:0,Mr=wt!==null?wt.y:0;st.setTexture2D(Ve,0),ye.copyTexSubImage2D(ye.TEXTURE_2D,Pt,0,0,Sr,Mr,bt,tr),We.unbindTexture()};let Bf=ye.createFramebuffer(),R0=ye.createFramebuffer();this.copyTextureToTexture=function(Ve,wt,Pt=null,kt=null,bt=0,tr=null){Ve.isTexture!==!0&&(ql("WebGLRenderer: copyTextureToTexture function signature has changed."),kt=arguments[0]||null,Ve=arguments[1],wt=arguments[2],tr=arguments[3]||0,Pt=null),tr===null&&(bt!==0?(ql("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),tr=bt,bt=0):tr=0);let Sr,Mr,Lr,Nr,Xr,dr,gi,Li,Oi,bi=Ve.isCompressedTexture?Ve.mipmaps[tr]:Ve.image;if(Pt!==null)Sr=Pt.max.x-Pt.min.x,Mr=Pt.max.y-Pt.min.y,Lr=Pt.isBox3?Pt.max.z-Pt.min.z:1,Nr=Pt.min.x,Xr=Pt.min.y,dr=Pt.isBox3?Pt.min.z:0;else{let Bn=Math.pow(2,-bt);Sr=Math.floor(bi.width*Bn),Mr=Math.floor(bi.height*Bn),Ve.isDataArrayTexture?Lr=bi.depth:Ve.isData3DTexture?Lr=Math.floor(bi.depth*Bn):Lr=1,Nr=0,Xr=0,dr=0}kt!==null?(gi=kt.x,Li=kt.y,Oi=kt.z):(gi=0,Li=0,Oi=0);let Kr=Zt.convert(wt.format),Fr=Zt.convert(wt.type),Mn;wt.isData3DTexture?(st.setTexture3D(wt,0),Mn=ye.TEXTURE_3D):wt.isDataArrayTexture||wt.isCompressedArrayTexture?(st.setTexture2DArray(wt,0),Mn=ye.TEXTURE_2D_ARRAY):(st.setTexture2D(wt,0),Mn=ye.TEXTURE_2D),ye.pixelStorei(ye.UNPACK_FLIP_Y_WEBGL,wt.flipY),ye.pixelStorei(ye.UNPACK_PREMULTIPLY_ALPHA_WEBGL,wt.premultiplyAlpha),ye.pixelStorei(ye.UNPACK_ALIGNMENT,wt.unpackAlignment);let ta=ye.getParameter(ye.UNPACK_ROW_LENGTH),Zn=ye.getParameter(ye.UNPACK_IMAGE_HEIGHT),ma=ye.getParameter(ye.UNPACK_SKIP_PIXELS),vn=ye.getParameter(ye.UNPACK_SKIP_ROWS),Wa=ye.getParameter(ye.UNPACK_SKIP_IMAGES);ye.pixelStorei(ye.UNPACK_ROW_LENGTH,bi.width),ye.pixelStorei(ye.UNPACK_IMAGE_HEIGHT,bi.height),ye.pixelStorei(ye.UNPACK_SKIP_PIXELS,Nr),ye.pixelStorei(ye.UNPACK_SKIP_ROWS,Xr),ye.pixelStorei(ye.UNPACK_SKIP_IMAGES,dr);let Ti=Ve.isDataArrayTexture||Ve.isData3DTexture,An=wt.isDataArrayTexture||wt.isData3DTexture;if(Ve.isDepthTexture){let Bn=it.get(Ve),xn=it.get(wt),ss=it.get(Bn.__renderTarget),Oc=it.get(xn.__renderTarget);We.bindFramebuffer(ye.READ_FRAMEBUFFER,ss.__webglFramebuffer),We.bindFramebuffer(ye.DRAW_FRAMEBUFFER,Oc.__webglFramebuffer);for(let Ds=0;Ds<Lr;Ds++)Ti&&(ye.framebufferTextureLayer(ye.READ_FRAMEBUFFER,ye.COLOR_ATTACHMENT0,it.get(Ve).__webglTexture,bt,dr+Ds),ye.framebufferTextureLayer(ye.DRAW_FRAMEBUFFER,ye.COLOR_ATTACHMENT0,it.get(wt).__webglTexture,tr,Oi+Ds)),ye.blitFramebuffer(Nr,Xr,Sr,Mr,gi,Li,Sr,Mr,ye.DEPTH_BUFFER_BIT,ye.NEAREST);We.bindFramebuffer(ye.READ_FRAMEBUFFER,null),We.bindFramebuffer(ye.DRAW_FRAMEBUFFER,null)}else if(bt!==0||Ve.isRenderTargetTexture||it.has(Ve)){let Bn=it.get(Ve),xn=it.get(wt);We.bindFramebuffer(ye.READ_FRAMEBUFFER,Bf),We.bindFramebuffer(ye.DRAW_FRAMEBUFFER,R0);for(let ss=0;ss<Lr;ss++)Ti?ye.framebufferTextureLayer(ye.READ_FRAMEBUFFER,ye.COLOR_ATTACHMENT0,Bn.__webglTexture,bt,dr+ss):ye.framebufferTexture2D(ye.READ_FRAMEBUFFER,ye.COLOR_ATTACHMENT0,ye.TEXTURE_2D,Bn.__webglTexture,bt),An?ye.framebufferTextureLayer(ye.DRAW_FRAMEBUFFER,ye.COLOR_ATTACHMENT0,xn.__webglTexture,tr,Oi+ss):ye.framebufferTexture2D(ye.DRAW_FRAMEBUFFER,ye.COLOR_ATTACHMENT0,ye.TEXTURE_2D,xn.__webglTexture,tr),bt!==0?ye.blitFramebuffer(Nr,Xr,Sr,Mr,gi,Li,Sr,Mr,ye.COLOR_BUFFER_BIT,ye.NEAREST):An?ye.copyTexSubImage3D(Mn,tr,gi,Li,Oi+ss,Nr,Xr,Sr,Mr):ye.copyTexSubImage2D(Mn,tr,gi,Li,Nr,Xr,Sr,Mr);We.bindFramebuffer(ye.READ_FRAMEBUFFER,null),We.bindFramebuffer(ye.DRAW_FRAMEBUFFER,null)}else An?Ve.isDataTexture||Ve.isData3DTexture?ye.texSubImage3D(Mn,tr,gi,Li,Oi,Sr,Mr,Lr,Kr,Fr,bi.data):wt.isCompressedArrayTexture?ye.compressedTexSubImage3D(Mn,tr,gi,Li,Oi,Sr,Mr,Lr,Kr,bi.data):ye.texSubImage3D(Mn,tr,gi,Li,Oi,Sr,Mr,Lr,Kr,Fr,bi):Ve.isDataTexture?ye.texSubImage2D(ye.TEXTURE_2D,tr,gi,Li,Sr,Mr,Kr,Fr,bi.data):Ve.isCompressedTexture?ye.compressedTexSubImage2D(ye.TEXTURE_2D,tr,gi,Li,bi.width,bi.height,Kr,bi.data):ye.texSubImage2D(ye.TEXTURE_2D,tr,gi,Li,Sr,Mr,Kr,Fr,bi);ye.pixelStorei(ye.UNPACK_ROW_LENGTH,ta),ye.pixelStorei(ye.UNPACK_IMAGE_HEIGHT,Zn),ye.pixelStorei(ye.UNPACK_SKIP_PIXELS,ma),ye.pixelStorei(ye.UNPACK_SKIP_ROWS,vn),ye.pixelStorei(ye.UNPACK_SKIP_IMAGES,Wa),tr===0&&wt.generateMipmaps&&ye.generateMipmap(Mn),We.unbindTexture()},this.copyTextureToTexture3D=function(Ve,wt,Pt=null,kt=null,bt=0){return Ve.isTexture!==!0&&(ql("WebGLRenderer: copyTextureToTexture3D function signature has changed."),Pt=arguments[0]||null,kt=arguments[1]||null,Ve=arguments[2],wt=arguments[3],bt=arguments[4]||0),ql('WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.'),this.copyTextureToTexture(Ve,wt,Pt,kt,bt)},this.initRenderTarget=function(Ve){it.get(Ve).__webglFramebuffer===void 0&&st.setupRenderTarget(Ve)},this.initTexture=function(Ve){Ve.isCubeTexture?st.setTextureCube(Ve,0):Ve.isData3DTexture?st.setTexture3D(Ve,0):Ve.isDataArrayTexture||Ve.isCompressedArrayTexture?st.setTexture2DArray(Ve,0):st.setTexture2D(Ve,0),We.unbindTexture()},this.resetState=function(){P=0,k=0,z=null,We.reset(),Gt.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return ca}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;let t=this.getContext();t.drawingBufferColorspace=li._getDrawingBufferColorSpace(e),t.unpackColorSpace=li._getUnpackColorSpace()}},dL={triangulate:function(e,t,r=2){let i=t&&t.length,n=i?t[0]*r:e.length,s=mw(e,0,n,r,!0),a=[];if(!s||s.next===s.prev)return a;let o,l,c,u,d,f,y;if(i&&(s=yL(e,t,s,r)),e.length>80*r){o=c=e[0],l=u=e[1];for(let b=r;b<n;b+=r)d=e[b],f=e[b+1],d<o&&(o=d),f<l&&(l=f),d>c&&(c=d),f>u&&(u=f);y=Math.max(c-o,u-l),y=y!==0?32767/y:0}return cu(s,a,r,o,l,y,0),a}};function mw(e,t,r,i,n){let s,a;if(n===CL(e,t,r,i)>0)for(s=t;s<r;s+=i)a=vw(s,e[s],e[s+1],a);else for(s=r-i;s>=t;s-=i)a=vw(s,e[s],e[s+1],a);return a&&pf(a,a.next)&&(uu(a),a=a.next),a}function fl(e,t){if(!e)return e;t||(t=e);let r=e,i;do if(i=!1,!r.steiner&&(pf(r,r.next)||Zi(r.prev,r,r.next)===0)){if(uu(r),r=t=r.prev,r===r.next)break;i=!0}else r=r.next;while(i||r!==t);return t}function cu(e,t,r,i,n,s,a){if(!e)return;!a&&s&&_L(e,i,n,s);let o=e,l,c;for(;e.prev!==e.next;){if(l=e.prev,c=e.next,s?fL(e,i,n,s):pL(e)){t.push(l.i/r|0),t.push(e.i/r|0),t.push(c.i/r|0),uu(e),e=c.next,o=c.next;continue}if(e=c,e===o){a?a===1?(e=mL(fl(e),t,r),cu(e,t,r,i,n,s,2)):a===2&&gL(e,t,r,i,n,s):cu(fl(e),t,r,i,n,s,1);break}}}function pL(e){let t=e.prev,r=e,i=e.next;if(Zi(t,r,i)>=0)return!1;let n=t.x,s=r.x,a=i.x,o=t.y,l=r.y,c=i.y,u=n<s?n<a?n:a:s<a?s:a,d=o<l?o<c?o:c:l<c?l:c,f=n>s?n>a?n:a:s>a?s:a,y=o>l?o>c?o:c:l>c?l:c,b=i.next;for(;b!==t;){if(b.x>=u&&b.x<=f&&b.y>=d&&b.y<=y&&Mc(n,o,s,l,a,c,b.x,b.y)&&Zi(b.prev,b,b.next)>=0)return!1;b=b.next}return!0}function fL(e,t,r,i){let n=e.prev,s=e,a=e.next;if(Zi(n,s,a)>=0)return!1;let o=n.x,l=s.x,c=a.x,u=n.y,d=s.y,f=a.y,y=o<l?o<c?o:c:l<c?l:c,b=u<d?u<f?u:f:d<f?d:f,x=o>l?o>c?o:c:l>c?l:c,g=u>d?u>f?u:f:d>f?d:f,v=By(y,b,t,r,i),_=By(x,g,t,r,i),E=e.prevZ,M=e.nextZ;for(;E&&E.z>=v&&M&&M.z<=_;){if(E.x>=y&&E.x<=x&&E.y>=b&&E.y<=g&&E!==n&&E!==a&&Mc(o,u,l,d,c,f,E.x,E.y)&&Zi(E.prev,E,E.next)>=0||(E=E.prevZ,M.x>=y&&M.x<=x&&M.y>=b&&M.y<=g&&M!==n&&M!==a&&Mc(o,u,l,d,c,f,M.x,M.y)&&Zi(M.prev,M,M.next)>=0))return!1;M=M.nextZ}for(;E&&E.z>=v;){if(E.x>=y&&E.x<=x&&E.y>=b&&E.y<=g&&E!==n&&E!==a&&Mc(o,u,l,d,c,f,E.x,E.y)&&Zi(E.prev,E,E.next)>=0)return!1;E=E.prevZ}for(;M&&M.z<=_;){if(M.x>=y&&M.x<=x&&M.y>=b&&M.y<=g&&M!==n&&M!==a&&Mc(o,u,l,d,c,f,M.x,M.y)&&Zi(M.prev,M,M.next)>=0)return!1;M=M.nextZ}return!0}function mL(e,t,r){let i=e;do{let n=i.prev,s=i.next.next;!pf(n,s)&&gw(n,i,i.next,s)&&hu(n,s)&&hu(s,n)&&(t.push(n.i/r|0),t.push(i.i/r|0),t.push(s.i/r|0),uu(i),uu(i.next),i=e=s),i=i.next}while(i!==e);return fl(i)}function gL(e,t,r,i,n,s){let a=e;do{let o=a.next.next;for(;o!==a.prev;){if(a.i!==o.i&&ML(a,o)){let l=yw(a,o);a=fl(a,a.next),l=fl(l,l.next),cu(a,t,r,i,n,s,0),cu(l,t,r,i,n,s,0);return}o=o.next}a=a.next}while(a!==e)}function yL(e,t,r,i){let n=[],s,a,o,l,c;for(s=0,a=t.length;s<a;s++)o=t[s]*i,l=s<a-1?t[s+1]*i:e.length,c=mw(e,o,l,i,!1),c===c.next&&(c.steiner=!0),n.push(SL(c));for(n.sort(vL),s=0;s<n.length;s++)r=xL(n[s],r);return r}function vL(e,t){return e.x-t.x}function xL(e,t){let r=bL(e,t);if(!r)return t;let i=yw(r,e);return fl(i,i.next),fl(r,r.next)}function bL(e,t){let r=t,i=-1/0,n,s=e.x,a=e.y;do{if(a<=r.y&&a>=r.next.y&&r.next.y!==r.y){let f=r.x+(a-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(f<=s&&f>i&&(i=f,n=r.x<r.next.x?r:r.next,f===s))return n}r=r.next}while(r!==t);if(!n)return null;let o=n,l=n.x,c=n.y,u=1/0,d;r=n;do s>=r.x&&r.x>=l&&s!==r.x&&Mc(a<c?s:i,a,l,c,a<c?i:s,a,r.x,r.y)&&(d=Math.abs(a-r.y)/(s-r.x),hu(r,e)&&(d<u||d===u&&(r.x>n.x||r.x===n.x&&wL(n,r)))&&(n=r,u=d)),r=r.next;while(r!==o);return n}function wL(e,t){return Zi(e.prev,e,t.prev)<0&&Zi(t.next,e,e.next)<0}function _L(e,t,r,i){let n=e;do n.z===0&&(n.z=By(n.x,n.y,t,r,i)),n.prevZ=n.prev,n.nextZ=n.next,n=n.next;while(n!==e);n.prevZ.nextZ=null,n.prevZ=null,EL(n)}function EL(e){let t,r,i,n,s,a,o,l,c=1;do{for(r=e,e=null,s=null,a=0;r;){for(a++,i=r,o=0,t=0;t<c&&(o++,i=i.nextZ,!!i);t++);for(l=c;o>0||l>0&&i;)o!==0&&(l===0||!i||r.z<=i.z)?(n=r,r=r.nextZ,o--):(n=i,i=i.nextZ,l--),s?s.nextZ=n:e=n,n.prevZ=s,s=n;r=i}s.nextZ=null,c*=2}while(a>1);return e}function By(e,t,r,i,n){return e=(e-r)*n|0,t=(t-i)*n|0,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,t=(t|t<<8)&16711935,t=(t|t<<4)&252645135,t=(t|t<<2)&858993459,t=(t|t<<1)&1431655765,e|t<<1}function SL(e){let t=e,r=e;do(t.x<r.x||t.x===r.x&&t.y<r.y)&&(r=t),t=t.next;while(t!==e);return r}function Mc(e,t,r,i,n,s,a,o){return(n-a)*(t-o)>=(e-a)*(s-o)&&(e-a)*(i-o)>=(r-a)*(t-o)&&(r-a)*(s-o)>=(n-a)*(i-o)}function ML(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!AL(e,t)&&(hu(e,t)&&hu(t,e)&&TL(e,t)&&(Zi(e.prev,e,t.prev)||Zi(e,t.prev,t))||pf(e,t)&&Zi(e.prev,e,e.next)>0&&Zi(t.prev,t,t.next)>0)}function Zi(e,t,r){return(t.y-e.y)*(r.x-t.x)-(t.x-e.x)*(r.y-t.y)}function pf(e,t){return e.x===t.x&&e.y===t.y}function gw(e,t,r,i){let n=mf(Zi(e,t,r)),s=mf(Zi(e,t,i)),a=mf(Zi(r,i,e)),o=mf(Zi(r,i,t));return!!(n!==s&&a!==o||n===0&&ff(e,r,t)||s===0&&ff(e,i,t)||a===0&&ff(r,e,i)||o===0&&ff(r,t,i))}function ff(e,t,r){return t.x<=Math.max(e.x,r.x)&&t.x>=Math.min(e.x,r.x)&&t.y<=Math.max(e.y,r.y)&&t.y>=Math.min(e.y,r.y)}function mf(e){return e>0?1:e<0?-1:0}function AL(e,t){let r=e;do{if(r.i!==e.i&&r.next.i!==e.i&&r.i!==t.i&&r.next.i!==t.i&&gw(r,r.next,e,t))return!0;r=r.next}while(r!==e);return!1}function hu(e,t){return Zi(e.prev,e,e.next)<0?Zi(e,t,e.next)>=0&&Zi(e,e.prev,t)>=0:Zi(e,t,e.prev)<0||Zi(e,e.next,t)<0}function TL(e,t){let r=e,i=!1,n=(e.x+t.x)/2,s=(e.y+t.y)/2;do r.y>s!=r.next.y>s&&r.next.y!==r.y&&n<(r.next.x-r.x)*(s-r.y)/(r.next.y-r.y)+r.x&&(i=!i),r=r.next;while(r!==e);return i}function yw(e,t){let r=new jy(e.i,e.x,e.y),i=new jy(t.i,t.x,t.y),n=e.next,s=t.prev;return e.next=t,t.prev=e,r.next=n,n.prev=r,i.next=r,r.prev=i,s.next=i,i.prev=s,i}function vw(e,t,r,i){let n=new jy(e,t,r);return i?(n.next=i.next,n.prev=i,i.next.prev=n,i.next=n):(n.prev=n,n.next=n),n}function uu(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function jy(e,t,r){this.i=e,this.x=t,this.y=r,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function CL(e,t,r,i){let n=0;for(let s=t,a=r-i;s<r;s+=i)n+=(e[a]-e[s])*(e[s+1]+e[a+1]),a=s;return n}var Vy=e=>e&&typeof e=="object"&&!Array.isArray(e)?e.quoted:e;function RL(e){let t=e.size;if(!Number.isSafeInteger(t)||t<3)throw Error("Invalid saved zone point count.");let r=e.filled?t*15+Math.max(0,t-2)*3*(t>65535?4:2):t*12;if(!Number.isSafeInteger(r))throw Error("Invalid saved zone geometry size.");return r}function PL(e,t,{world:r,triangulate:i,maxBytes:n=67108864}={}){if(typeof r!="function"||typeof i!="function"||!Number.isSafeInteger(n)||n<0)throw TypeError("Invalid saved zone geometry options.");if(RL(t)>n)throw Object.assign(Error("Saved zone exceeds the remaining typed-geometry byte budget."),{code:"ZONE_GEOMETRY_BUDGET"});let s=new Float64Array(t.size*2),a=0,o=(b,x)=>{let g=r([b,x]);if(!g.every(Number.isFinite)||a>=t.size)throw Error("Invalid saved zone coordinate.");s[a*2]=g[0],s[a*2+1]=g[1],a++},l=t.sourcePoints[1];if(l instanceof Float64Array)for(let b=0;b<l.length;b+=2)o(l[b],l[b+1]);else for(let b of t.sourcePoints)!Array.isArray(b)||Vy(b[0])!=="xy"||o(Number(Vy(b[1])),Number(Vy(b[2])));if(a!==t.size)throw Error("Saved zone point count changed.");a>3&&s[0]===s[(a-1)*2]&&s[1]===s[(a-1)*2+1]&&a--;let c=new Float32Array(a*3),u=t.filled?new Int8Array(a*3):null;for(let b=0;b<a;b++)c[b*3]=s[b*2],c[b*3+1]=s[b*2+1],u&&(u[b*3+2]=127);let d=null;if(t.filled){let b=i(s.subarray(0,a*2),void 0,2);if(!b.length||b.length%3||b.length>(a-2)*3)throw Error("Saved zone could not be triangulated faithfully.");let x=a>65535?Uint32Array:Uint16Array;d=new x(b.length);for(let g=0;g<b.length;g++){let v=b[g];if(!Number.isInteger(v)||v<0||v>=a)throw Error("Invalid saved zone triangulation index.");d[g]=v}}let f=c.byteLength+(u?.byteLength||0)+(d?.byteLength||0);if(f>n)throw Object.assign(Error("Saved zone exceeds its typed-geometry byte budget."),{code:"ZONE_GEOMETRY_BUDGET"});let y=new e.BufferGeometry;return y.setAttribute("position",new e.BufferAttribute(c,3)),u&&y.setAttribute("normal",new e.BufferAttribute(u,3,!0)),d&&y.setIndex(new e.BufferAttribute(d,1)),{geometry:y,bytes:f,vertices:a}}var xw={type:"change"},Hy={type:"start"},bw={type:"end"},gf=new Wo,ww=new Ua,IL=Math.cos(70*$d.DEG2RAD),En=new je,ns=2*Math.PI,Bi={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},Gy=1e-6,Wy=class extends z1{constructor(e,t=null){super(e,t),this.state=Bi.NONE,this.enabled=!0,this.target=new je,this.cursor=new je,this.minDistance=0,this.maxDistance=1/0,this.minZoom=0,this.maxZoom=1/0,this.minTargetRadius=0,this.maxTargetRadius=1/0,this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.enableDamping=!1,this.dampingFactor=.05,this.enableZoom=!0,this.zoomSpeed=1,this.enableRotate=!0,this.rotateSpeed=1,this.enablePan=!0,this.panSpeed=1,this.screenSpacePanning=!0,this.keyPanSpeed=7,this.zoomToCursor=!1,this.autoRotate=!1,this.autoRotateSpeed=2,this.keys={LEFT:"ArrowLeft",UP:"ArrowUp",RIGHT:"ArrowRight",BOTTOM:"ArrowDown"},this.mouseButtons={LEFT:B.ROTATE,MIDDLE:B.DOLLY,RIGHT:B.PAN},this.touches={ONE:W.ROTATE,TWO:W.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new je,this._lastQuaternion=new pn,this._lastTargetPosition=new je,this._quat=new pn().setFromUnitVectors(e.up,new je(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new Ty,this._sphericalDelta=new Ty,this._scale=1,this._panOffset=new je,this._rotateStart=new Ft,this._rotateEnd=new Ft,this._rotateDelta=new Ft,this._panStart=new Ft,this._panEnd=new Ft,this._panDelta=new Ft,this._dollyStart=new Ft,this._dollyEnd=new Ft,this._dollyDelta=new Ft,this._dollyDirection=new je,this._mouse=new Ft,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=LL.bind(this),this._onPointerDown=NL.bind(this),this._onPointerUp=kL.bind(this),this._onContextMenu=jL.bind(this),this._onMouseWheel=UL.bind(this),this._onKeyDown=FL.bind(this),this._onTouchStart=zL.bind(this),this._onTouchMove=BL.bind(this),this._onMouseDown=OL.bind(this),this._onMouseMove=DL.bind(this),this._interceptControlDown=VL.bind(this),this._interceptControlUp=HL.bind(this),this.domElement!==null&&this.connect(),this.update()}connect(){this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointercancel",this._onPointerUp),this.domElement.addEventListener("contextmenu",this._onContextMenu),this.domElement.addEventListener("wheel",this._onMouseWheel,{passive:!1}),this.domElement.getRootNode().addEventListener("keydown",this._interceptControlDown,{passive:!0,capture:!0}),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents(),this.domElement.getRootNode().removeEventListener("keydown",this._interceptControlDown,{capture:!0}),this.domElement.style.touchAction="auto"}dispose(){this.disconnect()}getPolarAngle(){return this._spherical.phi}getAzimuthalAngle(){return this._spherical.theta}getDistance(){return this.object.position.distanceTo(this.target)}listenToKeyEvents(e){e.addEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=e}stopListenToKeyEvents(){this._domElementKeyEvents!==null&&(this._domElementKeyEvents.removeEventListener("keydown",this._onKeyDown),this._domElementKeyEvents=null)}saveState(){this.target0.copy(this.target),this.position0.copy(this.object.position),this.zoom0=this.object.zoom}reset(){this.target.copy(this.target0),this.object.position.copy(this.position0),this.object.zoom=this.zoom0,this.object.updateProjectionMatrix(),this.dispatchEvent(xw),this.update(),this.state=Bi.NONE}update(e=null){let t=this.object.position;En.copy(t).sub(this.target),En.applyQuaternion(this._quat),this._spherical.setFromVector3(En),this.autoRotate&&this.state===Bi.NONE&&this._rotateLeft(this._getAutoRotationAngle(e)),this.enableDamping?(this._spherical.theta+=this._sphericalDelta.theta*this.dampingFactor,this._spherical.phi+=this._sphericalDelta.phi*this.dampingFactor):(this._spherical.theta+=this._sphericalDelta.theta,this._spherical.phi+=this._sphericalDelta.phi);let r=this.minAzimuthAngle,i=this.maxAzimuthAngle;isFinite(r)&&isFinite(i)&&(r<-Math.PI?r+=ns:r>Math.PI&&(r-=ns),i<-Math.PI?i+=ns:i>Math.PI&&(i-=ns),r<=i?this._spherical.theta=Math.max(r,Math.min(i,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(r+i)/2?Math.max(r,this._spherical.theta):Math.min(i,this._spherical.theta)),this._spherical.phi=Math.max(this.minPolarAngle,Math.min(this.maxPolarAngle,this._spherical.phi)),this._spherical.makeSafe(),this.enableDamping===!0?this.target.addScaledVector(this._panOffset,this.dampingFactor):this.target.add(this._panOffset),this.target.sub(this.cursor),this.target.clampLength(this.minTargetRadius,this.maxTargetRadius),this.target.add(this.cursor);let n=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{let s=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),n=s!=this._spherical.radius}if(En.setFromSpherical(this._spherical),En.applyQuaternion(this._quatInverse),t.copy(this.target).add(En),this.object.lookAt(this.target),this.enableDamping===!0?(this._sphericalDelta.theta*=1-this.dampingFactor,this._sphericalDelta.phi*=1-this.dampingFactor,this._panOffset.multiplyScalar(1-this.dampingFactor)):(this._sphericalDelta.set(0,0,0),this._panOffset.set(0,0,0)),this.zoomToCursor&&this._performCursorZoom){let s=null;if(this.object.isPerspectiveCamera){let a=En.length();s=this._clampDistance(a*this._scale);let o=a-s;this.object.position.addScaledVector(this._dollyDirection,o),this.object.updateMatrixWorld(),n=!!o}else if(this.object.isOrthographicCamera){let a=new je(this._mouse.x,this._mouse.y,0);a.unproject(this.object);let o=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),n=o!==this.object.zoom;let l=new je(this._mouse.x,this._mouse.y,0);l.unproject(this.object),this.object.position.sub(l).add(a),this.object.updateMatrixWorld(),s=En.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;s!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(s).add(this.object.position):(gf.origin.copy(this.object.position),gf.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(gf.direction))<IL?this.object.lookAt(this.target):(ww.setFromNormalAndCoplanarPoint(this.object.up,this.target),gf.intersectPlane(ww,this.target))))}else if(this.object.isOrthographicCamera){let s=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),s!==this.object.zoom&&(this.object.updateProjectionMatrix(),n=!0)}return this._scale=1,this._performCursorZoom=!1,n||this._lastPosition.distanceToSquared(this.object.position)>Gy||8*(1-this._lastQuaternion.dot(this.object.quaternion))>Gy||this._lastTargetPosition.distanceToSquared(this.target)>Gy?(this.dispatchEvent(xw),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?ns/60*this.autoRotateSpeed*e:ns/60/60*this.autoRotateSpeed}_getZoomScale(e){let t=Math.abs(e*.01);return Math.pow(.95,this.zoomSpeed*t)}_rotateLeft(e){this._sphericalDelta.theta-=e}_rotateUp(e){this._sphericalDelta.phi-=e}_panLeft(e,t){En.setFromMatrixColumn(t,0),En.multiplyScalar(-e),this._panOffset.add(En)}_panUp(e,t){this.screenSpacePanning===!0?En.setFromMatrixColumn(t,1):(En.setFromMatrixColumn(t,0),En.crossVectors(this.object.up,En)),En.multiplyScalar(e),this._panOffset.add(En)}_pan(e,t){let r=this.domElement;if(this.object.isPerspectiveCamera){let i=this.object.position;En.copy(i).sub(this.target);let n=En.length();n*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*n/r.clientHeight,this.object.matrix),this._panUp(2*t*n/r.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/r.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/r.clientHeight,this.object.matrix)):(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - pan disabled."),this.enablePan=!1)}_dollyOut(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale/=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_dollyIn(e){this.object.isPerspectiveCamera||this.object.isOrthographicCamera?this._scale*=e:(console.warn("WARNING: OrbitControls.js encountered an unknown camera type - dolly/zoom disabled."),this.enableZoom=!1)}_updateZoomParameters(e,t){if(!this.zoomToCursor)return;this._performCursorZoom=!0;let r=this.domElement.getBoundingClientRect(),i=e-r.left,n=t-r.top,s=r.width,a=r.height;this._mouse.x=i/s*2-1,this._mouse.y=-(n/a)*2+1,this._dollyDirection.set(this._mouse.x,this._mouse.y,1).unproject(this.object).sub(this.object.position).normalize()}_clampDistance(e){return Math.max(this.minDistance,Math.min(this.maxDistance,e))}_handleMouseDownRotate(e){this._rotateStart.set(e.clientX,e.clientY)}_handleMouseDownDolly(e){this._updateZoomParameters(e.clientX,e.clientX),this._dollyStart.set(e.clientX,e.clientY)}_handleMouseDownPan(e){this._panStart.set(e.clientX,e.clientY)}_handleMouseMoveRotate(e){this._rotateEnd.set(e.clientX,e.clientY),this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let t=this.domElement;this._rotateLeft(ns*this._rotateDelta.x/t.clientHeight),this._rotateUp(ns*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd),this.update()}_handleMouseMoveDolly(e){this._dollyEnd.set(e.clientX,e.clientY),this._dollyDelta.subVectors(this._dollyEnd,this._dollyStart),this._dollyDelta.y>0?this._dollyOut(this._getZoomScale(this._dollyDelta.y)):this._dollyDelta.y<0&&this._dollyIn(this._getZoomScale(this._dollyDelta.y)),this._dollyStart.copy(this._dollyEnd),this.update()}_handleMouseMovePan(e){this._panEnd.set(e.clientX,e.clientY),this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd),this.update()}_handleMouseWheel(e){this._updateZoomParameters(e.clientX,e.clientY),e.deltaY<0?this._dollyIn(this._getZoomScale(e.deltaY)):e.deltaY>0&&this._dollyOut(this._getZoomScale(e.deltaY)),this.update()}_handleKeyDown(e){let t=!1;switch(e.code){case this.keys.UP:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(ns*this.rotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,this.keyPanSpeed),t=!0;break;case this.keys.BOTTOM:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateUp(-ns*this.rotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(0,-this.keyPanSpeed),t=!0;break;case this.keys.LEFT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(ns*this.rotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(this.keyPanSpeed,0),t=!0;break;case this.keys.RIGHT:e.ctrlKey||e.metaKey||e.shiftKey?this.enableRotate&&this._rotateLeft(-ns*this.rotateSpeed/this.domElement.clientHeight):this.enablePan&&this._pan(-this.keyPanSpeed,0),t=!0;break}t&&(e.preventDefault(),this.update())}_handleTouchStartRotate(e){if(this._pointers.length===1)this._rotateStart.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),r=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._rotateStart.set(r,i)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),r=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panStart.set(r,i)}}_handleTouchStartDolly(e){let t=this._getSecondPointerPosition(e),r=e.pageX-t.x,i=e.pageY-t.y,n=Math.sqrt(r*r+i*i);this._dollyStart.set(0,n)}_handleTouchStartDollyPan(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enablePan&&this._handleTouchStartPan(e)}_handleTouchStartDollyRotate(e){this.enableZoom&&this._handleTouchStartDolly(e),this.enableRotate&&this._handleTouchStartRotate(e)}_handleTouchMoveRotate(e){if(this._pointers.length==1)this._rotateEnd.set(e.pageX,e.pageY);else{let r=this._getSecondPointerPosition(e),i=.5*(e.pageX+r.x),n=.5*(e.pageY+r.y);this._rotateEnd.set(i,n)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);let t=this.domElement;this._rotateLeft(ns*this._rotateDelta.x/t.clientHeight),this._rotateUp(ns*this._rotateDelta.y/t.clientHeight),this._rotateStart.copy(this._rotateEnd)}_handleTouchMovePan(e){if(this._pointers.length===1)this._panEnd.set(e.pageX,e.pageY);else{let t=this._getSecondPointerPosition(e),r=.5*(e.pageX+t.x),i=.5*(e.pageY+t.y);this._panEnd.set(r,i)}this._panDelta.subVectors(this._panEnd,this._panStart).multiplyScalar(this.panSpeed),this._pan(this._panDelta.x,this._panDelta.y),this._panStart.copy(this._panEnd)}_handleTouchMoveDolly(e){let t=this._getSecondPointerPosition(e),r=e.pageX-t.x,i=e.pageY-t.y,n=Math.sqrt(r*r+i*i);this._dollyEnd.set(0,n),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);let s=(e.pageX+t.x)*.5,a=(e.pageY+t.y)*.5;this._updateZoomParameters(s,a)}_handleTouchMoveDollyPan(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enablePan&&this._handleTouchMovePan(e)}_handleTouchMoveDollyRotate(e){this.enableZoom&&this._handleTouchMoveDolly(e),this.enableRotate&&this._handleTouchMoveRotate(e)}_addPointer(e){this._pointers.push(e.pointerId)}_removePointer(e){delete this._pointerPositions[e.pointerId];for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId){this._pointers.splice(t,1);return}}_isTrackingPointer(e){for(let t=0;t<this._pointers.length;t++)if(this._pointers[t]==e.pointerId)return!0;return!1}_trackPointer(e){let t=this._pointerPositions[e.pointerId];t===void 0&&(t=new Ft,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){let t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){let t=e.deltaMode,r={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:r.deltaY*=16;break;case 2:r.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(r.deltaY*=10),r}};function NL(e){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(e.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.domElement.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(e)&&(this._addPointer(e),e.pointerType==="touch"?this._onTouchStart(e):this._onMouseDown(e)))}function LL(e){this.enabled!==!1&&(e.pointerType==="touch"?this._onTouchMove(e):this._onMouseMove(e))}function kL(e){switch(this._removePointer(e),this._pointers.length){case 0:this.domElement.releasePointerCapture(e.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(bw),this.state=Bi.NONE;break;case 1:let t=this._pointers[0],r=this._pointerPositions[t];this._onTouchStart({pointerId:t,pageX:r.x,pageY:r.y});break}}function OL(e){let t;switch(e.button){case 0:t=this.mouseButtons.LEFT;break;case 1:t=this.mouseButtons.MIDDLE;break;case 2:t=this.mouseButtons.RIGHT;break;default:t=-1}switch(t){case B.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(e),this.state=Bi.DOLLY;break;case B.ROTATE:if(e.ctrlKey||e.metaKey||e.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(e),this.state=Bi.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(e),this.state=Bi.ROTATE}break;case B.PAN:if(e.ctrlKey||e.metaKey||e.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(e),this.state=Bi.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(e),this.state=Bi.PAN}break;default:this.state=Bi.NONE}this.state!==Bi.NONE&&this.dispatchEvent(Hy)}function DL(e){switch(this.state){case Bi.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(e);break;case Bi.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(e);break;case Bi.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(e);break}}function UL(e){this.enabled===!1||this.enableZoom===!1||this.state!==Bi.NONE||(e.preventDefault(),this.dispatchEvent(Hy),this._handleMouseWheel(this._customWheelEvent(e)),this.dispatchEvent(bw))}function FL(e){this.enabled!==!1&&this._handleKeyDown(e)}function zL(e){switch(this._trackPointer(e),this._pointers.length){case 1:switch(this.touches.ONE){case W.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(e),this.state=Bi.TOUCH_ROTATE;break;case W.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(e),this.state=Bi.TOUCH_PAN;break;default:this.state=Bi.NONE}break;case 2:switch(this.touches.TWO){case W.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(e),this.state=Bi.TOUCH_DOLLY_PAN;break;case W.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(e),this.state=Bi.TOUCH_DOLLY_ROTATE;break;default:this.state=Bi.NONE}break;default:this.state=Bi.NONE}this.state!==Bi.NONE&&this.dispatchEvent(Hy)}function BL(e){switch(this._trackPointer(e),this.state){case Bi.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(e),this.update();break;case Bi.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(e),this.update();break;case Bi.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(e),this.update();break;case Bi.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(e),this.update();break;default:this.state=Bi.NONE}}function jL(e){this.enabled!==!1&&e.preventDefault()}function VL(e){e.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function HL(e){e.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function GL(e){return class extends e{_viewFrame(){let t=this.object.position.clone().sub(this.target),r=t.clone().normalize(),i=this.object.up.clone().addScaledVector(r,-this.object.up.dot(r));return i.lengthSq()<1e-8&&(i.setFromMatrixColumn(this.object.matrix,1),i.addScaledVector(r,-i.dot(r))),i.lengthSq()<1e-8&&(i.set(Math.abs(r.y)<.9?0:1,Math.abs(r.y)<.9?1:0,0),i.addScaledVector(r,-i.dot(r))),i.normalize(),this.object.up.copy(i),{offset:t,up:i,right:i.clone().cross(r).normalize()}}_inputAngle(t){let r=this.domElement?.clientHeight||600,i=this.domElement?.clientWidth||600;return t*r/Math.max(600,i,r)}_rotateLeft(t){let{offset:r,up:i}=this._viewFrame();r.applyAxisAngle(i,-this._inputAngle(t)),this.object.position.copy(this.target).add(r)}_rotateUp(t){let{offset:r,up:i,right:n}=this._viewFrame(),s=-this._inputAngle(t);r.applyAxisAngle(n,s),i.applyAxisAngle(n,s),this.object.up.copy(i),this.object.position.copy(this.target).add(r)}update(t){let{up:r}=this._viewFrame();return this._quat.setFromUnitVectors(r,r.clone().set(0,1,0)),this._quatInverse.copy(this._quat).invert(),super.update(t)}}}function WL(e,t,r){e.mouseButtons.LEFT=r?t.MOUSE.PAN:t.MOUSE.ROTATE,e.touches.ONE=r?t.TOUCH.PAN:t.TOUCH.ROTATE}function _w(e,t){if(t===yx)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),e;if(t===Zd||t===ag){let r=e.getIndex();if(r===null){let a=[],o=e.getAttribute("position");if(o!==void 0){for(let l=0;l<o.count;l++)a.push(l);e.setIndex(a),r=e.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),e}let i=r.count-2,n=[];if(t===Zd)for(let a=1;a<=i;a++)n.push(r.getX(0)),n.push(r.getX(a)),n.push(r.getX(a+1));else for(let a=0;a<i;a++)a%2===0?(n.push(r.getX(a)),n.push(r.getX(a+1)),n.push(r.getX(a+2))):(n.push(r.getX(a+2)),n.push(r.getX(a+1)),n.push(r.getX(a)));n.length/3!==i&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");let s=e.clone();return s.setIndex(n),s.clearGroups(),s}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",t),e}var XL=class extends mn{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new $L(t)}),this.register(function(t){return new JL(t)}),this.register(function(t){return new ok(t)}),this.register(function(t){return new lk(t)}),this.register(function(t){return new ck(t)}),this.register(function(t){return new ek(t)}),this.register(function(t){return new tk(t)}),this.register(function(t){return new rk(t)}),this.register(function(t){return new ik(t)}),this.register(function(t){return new ZL(t)}),this.register(function(t){return new nk(t)}),this.register(function(t){return new QL(t)}),this.register(function(t){return new ak(t)}),this.register(function(t){return new sk(t)}),this.register(function(t){return new qL(t)}),this.register(function(t){return new hk(t)}),this.register(function(t){return new uk(t)})}load(e,t,r,i){let n=this,s;if(this.resourcePath!=="")s=this.resourcePath;else if(this.path!==""){let l=Va.extractUrlBase(e);s=Va.resolveURL(l,this.path)}else s=Va.extractUrlBase(e);this.manager.itemStart(e);let a=function(l){i?i(l):console.error(l),n.manager.itemError(e),n.manager.itemEnd(e)},o=new Ps(this.manager);o.setPath(this.path),o.setResponseType("arraybuffer"),o.setRequestHeader(this.requestHeader),o.setWithCredentials(this.withCredentials),o.load(e,function(l){try{n.parse(l,s,function(c){t(c),n.manager.itemEnd(e)},a)}catch(c){a(c)}},r,a)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,r,i){let n,s={},a={},o=new TextDecoder;if(typeof e=="string")n=JSON.parse(e);else if(e instanceof ArrayBuffer)if(o.decode(new Uint8Array(e,0,4))===Ew){try{s[di.KHR_BINARY_GLTF]=new dk(e)}catch(c){i&&i(c);return}n=JSON.parse(s[di.KHR_BINARY_GLTF].content)}else n=JSON.parse(o.decode(e));else n=e;if(n.asset===void 0||n.asset.version[0]<2){i&&i(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}let l=new Mk(n,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});l.fileLoader.setRequestHeader(this.requestHeader);for(let c=0;c<this.pluginCallbacks.length;c++){let u=this.pluginCallbacks[c](l);u.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),a[u.name]=u,s[u.name]=!0}if(n.extensionsUsed)for(let c=0;c<n.extensionsUsed.length;++c){let u=n.extensionsUsed[c],d=n.extensionsRequired||[];switch(u){case di.KHR_MATERIALS_UNLIT:s[u]=new KL;break;case di.KHR_DRACO_MESH_COMPRESSION:s[u]=new pk(n,this.dracoLoader);break;case di.KHR_TEXTURE_TRANSFORM:s[u]=new fk;break;case di.KHR_MESH_QUANTIZATION:s[u]=new mk;break;default:d.indexOf(u)>=0&&a[u]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+u+'".')}}l.setExtensions(s),l.setPlugins(a),l.parse(r,i)}parseAsync(e,t){let r=this;return new Promise(function(i,n){r.parse(e,t,i,n)})}};function YL(){let e={};return{get:function(t){return e[t]},add:function(t,r){e[t]=r},remove:function(t){delete e[t]},removeAll:function(){e={}}}}var di={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"},qL=class{constructor(e){this.parser=e,this.name=di.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let e=this.parser,t=this.parser.json.nodes||[];for(let r=0,i=t.length;r<i;r++){let n=t[r];n.extensions&&n.extensions[this.name]&&n.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,n.extensions[this.name].light)}}_loadLight(e){let t=this.parser,r="light:"+e,i=t.cache.get(r);if(i)return i;let n=t.json,s=((n.extensions&&n.extensions[this.name]||{}).lights||[])[e],a,o=new or(16777215);s.color!==void 0&&o.setRGB(s.color[0],s.color[1],s.color[2],kn);let l=s.range!==void 0?s.range:0;switch(s.type){case"directional":a=new $p(o),a.target.position.set(0,0,-1),a.add(a.target);break;case"point":a=new Zp(o),a.distance=l;break;case"spot":a=new xy(o),a.distance=l,s.spot=s.spot||{},s.spot.innerConeAngle=s.spot.innerConeAngle!==void 0?s.spot.innerConeAngle:0,s.spot.outerConeAngle=s.spot.outerConeAngle!==void 0?s.spot.outerConeAngle:Math.PI/4,a.angle=s.spot.outerConeAngle,a.penumbra=1-s.spot.innerConeAngle/s.spot.outerConeAngle,a.target.position.set(0,0,-1),a.add(a.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+s.type)}return a.position.set(0,0,0),a.decay=2,Ha(a,s),s.intensity!==void 0&&(a.intensity=s.intensity),a.name=t.createUniqueName(s.name||"light_"+e),i=Promise.resolve(a),t.cache.add(r,i),i}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){let t=this,r=this.parser,i=r.json.nodes[e],n=(i.extensions&&i.extensions[this.name]||{}).light;return n===void 0?null:this._loadLight(n).then(function(s){return r._getNodeRef(t.cache,n,s)})}},KL=class{constructor(){this.name=di.KHR_MATERIALS_UNLIT}getMaterialType(){return en}extendParams(e,t,r){let i=[];e.color=new or(1,1,1),e.opacity=1;let n=t.pbrMetallicRoughness;if(n){if(Array.isArray(n.baseColorFactor)){let s=n.baseColorFactor;e.color.setRGB(s[0],s[1],s[2],kn),e.opacity=s[3]}n.baseColorTexture!==void 0&&i.push(r.assignTexture(e,"map",n.baseColorTexture,xi))}return Promise.all(i)}},ZL=class{constructor(e){this.parser=e,this.name=di.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){let r=this.parser.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=r.extensions[this.name].emissiveStrength;return i!==void 0&&(t.emissiveIntensity=i),Promise.resolve()}},$L=class{constructor(e){this.parser=e,this.name=di.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:vs}extendMaterialParams(e,t){let r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let n=[],s=i.extensions[this.name];if(s.clearcoatFactor!==void 0&&(t.clearcoat=s.clearcoatFactor),s.clearcoatTexture!==void 0&&n.push(r.assignTexture(t,"clearcoatMap",s.clearcoatTexture)),s.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=s.clearcoatRoughnessFactor),s.clearcoatRoughnessTexture!==void 0&&n.push(r.assignTexture(t,"clearcoatRoughnessMap",s.clearcoatRoughnessTexture)),s.clearcoatNormalTexture!==void 0&&(n.push(r.assignTexture(t,"clearcoatNormalMap",s.clearcoatNormalTexture)),s.clearcoatNormalTexture.scale!==void 0)){let a=s.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new Ft(a,a)}return Promise.all(n)}},JL=class{constructor(e){this.parser=e,this.name=di.KHR_MATERIALS_DISPERSION}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:vs}extendMaterialParams(e,t){let r=this.parser.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=r.extensions[this.name];return t.dispersion=i.dispersion!==void 0?i.dispersion:0,Promise.resolve()}},QL=class{constructor(e){this.parser=e,this.name=di.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:vs}extendMaterialParams(e,t){let r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let n=[],s=i.extensions[this.name];return s.iridescenceFactor!==void 0&&(t.iridescence=s.iridescenceFactor),s.iridescenceTexture!==void 0&&n.push(r.assignTexture(t,"iridescenceMap",s.iridescenceTexture)),s.iridescenceIor!==void 0&&(t.iridescenceIOR=s.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),s.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=s.iridescenceThicknessMinimum),s.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=s.iridescenceThicknessMaximum),s.iridescenceThicknessTexture!==void 0&&n.push(r.assignTexture(t,"iridescenceThicknessMap",s.iridescenceThicknessTexture)),Promise.all(n)}},ek=class{constructor(e){this.parser=e,this.name=di.KHR_MATERIALS_SHEEN}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:vs}extendMaterialParams(e,t){let r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let n=[];t.sheenColor=new or(0,0,0),t.sheenRoughness=0,t.sheen=1;let s=i.extensions[this.name];if(s.sheenColorFactor!==void 0){let a=s.sheenColorFactor;t.sheenColor.setRGB(a[0],a[1],a[2],kn)}return s.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=s.sheenRoughnessFactor),s.sheenColorTexture!==void 0&&n.push(r.assignTexture(t,"sheenColorMap",s.sheenColorTexture,xi)),s.sheenRoughnessTexture!==void 0&&n.push(r.assignTexture(t,"sheenRoughnessMap",s.sheenRoughnessTexture)),Promise.all(n)}},tk=class{constructor(e){this.parser=e,this.name=di.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:vs}extendMaterialParams(e,t){let r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let n=[],s=i.extensions[this.name];return s.transmissionFactor!==void 0&&(t.transmission=s.transmissionFactor),s.transmissionTexture!==void 0&&n.push(r.assignTexture(t,"transmissionMap",s.transmissionTexture)),Promise.all(n)}},rk=class{constructor(e){this.parser=e,this.name=di.KHR_MATERIALS_VOLUME}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:vs}extendMaterialParams(e,t){let r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let n=[],s=i.extensions[this.name];t.thickness=s.thicknessFactor!==void 0?s.thicknessFactor:0,s.thicknessTexture!==void 0&&n.push(r.assignTexture(t,"thicknessMap",s.thicknessTexture)),t.attenuationDistance=s.attenuationDistance||1/0;let a=s.attenuationColor||[1,1,1];return t.attenuationColor=new or().setRGB(a[0],a[1],a[2],kn),Promise.all(n)}},ik=class{constructor(e){this.parser=e,this.name=di.KHR_MATERIALS_IOR}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:vs}extendMaterialParams(e,t){let r=this.parser.json.materials[e];if(!r.extensions||!r.extensions[this.name])return Promise.resolve();let i=r.extensions[this.name];return t.ior=i.ior!==void 0?i.ior:1.5,Promise.resolve()}},nk=class{constructor(e){this.parser=e,this.name=di.KHR_MATERIALS_SPECULAR}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:vs}extendMaterialParams(e,t){let r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let n=[],s=i.extensions[this.name];t.specularIntensity=s.specularFactor!==void 0?s.specularFactor:1,s.specularTexture!==void 0&&n.push(r.assignTexture(t,"specularIntensityMap",s.specularTexture));let a=s.specularColorFactor||[1,1,1];return t.specularColor=new or().setRGB(a[0],a[1],a[2],kn),s.specularColorTexture!==void 0&&n.push(r.assignTexture(t,"specularColorMap",s.specularColorTexture,xi)),Promise.all(n)}},sk=class{constructor(e){this.parser=e,this.name=di.EXT_MATERIALS_BUMP}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:vs}extendMaterialParams(e,t){let r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let n=[],s=i.extensions[this.name];return t.bumpScale=s.bumpFactor!==void 0?s.bumpFactor:1,s.bumpTexture!==void 0&&n.push(r.assignTexture(t,"bumpMap",s.bumpTexture)),Promise.all(n)}},ak=class{constructor(e){this.parser=e,this.name=di.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:vs}extendMaterialParams(e,t){let r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let n=[],s=i.extensions[this.name];return s.anisotropyStrength!==void 0&&(t.anisotropy=s.anisotropyStrength),s.anisotropyRotation!==void 0&&(t.anisotropyRotation=s.anisotropyRotation),s.anisotropyTexture!==void 0&&n.push(r.assignTexture(t,"anisotropyMap",s.anisotropyTexture)),Promise.all(n)}},ok=class{constructor(e){this.parser=e,this.name=di.KHR_TEXTURE_BASISU}loadTexture(e){let t=this.parser,r=t.json,i=r.textures[e];if(!i.extensions||!i.extensions[this.name])return null;let n=i.extensions[this.name],s=t.options.ktx2Loader;if(!s){if(r.extensionsRequired&&r.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,n.source,s)}},lk=class{constructor(e){this.parser=e,this.name=di.EXT_TEXTURE_WEBP,this.isSupported=null}loadTexture(e){let t=this.name,r=this.parser,i=r.json,n=i.textures[e];if(!n.extensions||!n.extensions[t])return null;let s=n.extensions[t],a=i.images[s.source],o=r.textureLoader;if(a.uri){let l=r.options.manager.getHandler(a.uri);l!==null&&(o=l)}return this.detectSupport().then(function(l){if(l)return r.loadTextureImage(e,s.source,o);if(i.extensionsRequired&&i.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: WebP required by asset but unsupported.");return r.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){let t=new Image;t.src="data:image/webp;base64,UklGRiIAAABXRUJQVlA4IBYAAAAwAQCdASoBAAEADsD+JaQAA3AAAAAA",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}},ck=class{constructor(e){this.parser=e,this.name=di.EXT_TEXTURE_AVIF,this.isSupported=null}loadTexture(e){let t=this.name,r=this.parser,i=r.json,n=i.textures[e];if(!n.extensions||!n.extensions[t])return null;let s=n.extensions[t],a=i.images[s.source],o=r.textureLoader;if(a.uri){let l=r.options.manager.getHandler(a.uri);l!==null&&(o=l)}return this.detectSupport().then(function(l){if(l)return r.loadTextureImage(e,s.source,o);if(i.extensionsRequired&&i.extensionsRequired.indexOf(t)>=0)throw new Error("THREE.GLTFLoader: AVIF required by asset but unsupported.");return r.loadTexture(e)})}detectSupport(){return this.isSupported||(this.isSupported=new Promise(function(e){let t=new Image;t.src="data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABcAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQAMAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB9tZGF0EgAKCBgABogQEDQgMgkQAAAAB8dSLfI=",t.onload=t.onerror=function(){e(t.height===1)}})),this.isSupported}},hk=class{constructor(e){this.name=di.EXT_MESHOPT_COMPRESSION,this.parser=e}loadBufferView(e){let t=this.parser.json,r=t.bufferViews[e];if(r.extensions&&r.extensions[this.name]){let i=r.extensions[this.name],n=this.parser.getDependency("buffer",i.buffer),s=this.parser.options.meshoptDecoder;if(!s||!s.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return n.then(function(a){let o=i.byteOffset||0,l=i.byteLength||0,c=i.count,u=i.byteStride,d=new Uint8Array(a,o,l);return s.decodeGltfBufferAsync?s.decodeGltfBufferAsync(c,u,d,i.mode,i.filter).then(function(f){return f.buffer}):s.ready.then(function(){let f=new ArrayBuffer(c*u);return s.decodeGltfBuffer(new Uint8Array(f),c,u,d,i.mode,i.filter),f})})}else return null}},uk=class{constructor(e){this.name=di.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){let t=this.parser.json,r=t.nodes[e];if(!r.extensions||!r.extensions[this.name]||r.mesh===void 0)return null;let i=t.meshes[r.mesh];for(let o of i.primitives)if(o.mode!==Is.TRIANGLES&&o.mode!==Is.TRIANGLE_STRIP&&o.mode!==Is.TRIANGLE_FAN&&o.mode!==void 0)return null;let n=r.extensions[this.name].attributes,s=[],a={};for(let o in n)s.push(this.parser.getDependency("accessor",n[o]).then(l=>(a[o]=l,a[o])));return s.length<1?null:(s.push(this.parser.createNodeMesh(e)),Promise.all(s).then(o=>{let l=o.pop(),c=l.isGroup?l.children:[l],u=o[0].count,d=[];for(let f of c){let y=new Ir,b=new je,x=new pn,g=new je(1,1,1),v=new Mp(f.geometry,f.material,u);for(let _=0;_<u;_++)a.TRANSLATION&&b.fromBufferAttribute(a.TRANSLATION,_),a.ROTATION&&x.fromBufferAttribute(a.ROTATION,_),a.SCALE&&g.fromBufferAttribute(a.SCALE,_),v.setMatrixAt(_,y.compose(b,x,g));for(let _ in a)if(_==="_COLOR_0"){let E=a[_];v.instanceColor=new qo(E.array,E.itemSize,E.normalized)}else _!=="TRANSLATION"&&_!=="ROTATION"&&_!=="SCALE"&&f.geometry.setAttribute(_,a[_]);mi.prototype.copy.call(v,f),this.parser.assignFinalMaterial(v),d.push(v)}return l.isGroup?(l.clear(),l.add(...d),l):d[0]}))}},Ew="glTF",du=12,Sw={JSON:1313821514,BIN:5130562},dk=class{constructor(e){this.name=di.KHR_BINARY_GLTF,this.content=null,this.body=null;let t=new DataView(e,0,du),r=new TextDecoder;if(this.header={magic:r.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==Ew)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");let i=this.header.length-du,n=new DataView(e,du),s=0;for(;s<i;){let a=n.getUint32(s,!0);s+=4;let o=n.getUint32(s,!0);if(s+=4,o===Sw.JSON){let l=new Uint8Array(e,du+s,a);this.content=r.decode(l)}else if(o===Sw.BIN){let l=du+s;this.body=e.slice(l,l+a)}s+=a}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}},pk=class{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=di.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){let r=this.json,i=this.dracoLoader,n=e.extensions[this.name].bufferView,s=e.extensions[this.name].attributes,a={},o={},l={};for(let c in s){let u=Yy[c]||c.toLowerCase();a[u]=s[c]}for(let c in e.attributes){let u=Yy[c]||c.toLowerCase();if(s[c]!==void 0){let d=r.accessors[e.attributes[c]],f=Ac[d.componentType];l[u]=f.name,o[u]=d.normalized===!0}}return t.getDependency("bufferView",n).then(function(c){return new Promise(function(u,d){i.decodeDracoFile(c,function(f){for(let y in f.attributes){let b=f.attributes[y],x=o[y];x!==void 0&&(b.normalized=x)}u(f)},a,l,kn,d)})})}},fk=class{constructor(){this.name=di.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}},mk=class{constructor(){this.name=di.KHR_MESH_QUANTIZATION}},Mw=class extends xc{constructor(e,t,r,i){super(e,t,r,i)}copySampleValue_(e){let t=this.resultBuffer,r=this.sampleValues,i=this.valueSize,n=e*i*3+i;for(let s=0;s!==i;s++)t[s]=r[n+s];return t}interpolate_(e,t,r,i){let n=this.resultBuffer,s=this.sampleValues,a=this.valueSize,o=a*2,l=a*3,c=i-t,u=(r-t)/c,d=u*u,f=d*u,y=e*l,b=y-l,x=-2*f+3*d,g=f-d,v=1-x,_=g-d+u;for(let E=0;E!==a;E++){let M=s[b+E+a],P=s[b+E+o]*c,k=s[y+E+a],z=s[y+E]*c;n[E]=v*M+_*P+x*k+g*z}return n}},gk=new pn,yk=class extends Mw{interpolate_(e,t,r,i){let n=super.interpolate_(e,t,r,i);return gk.fromArray(n).normalize().toArray(n),n}},Is={FLOAT:5126,FLOAT_MAT3:35675,FLOAT_MAT4:35676,FLOAT_VEC2:35664,FLOAT_VEC3:35665,FLOAT_VEC4:35666,LINEAR:9729,REPEAT:10497,SAMPLER_2D:35678,POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6,UNSIGNED_BYTE:5121,UNSIGNED_SHORT:5123},Ac={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},Aw={9728:oi,9729:Pi,9984:Pn,9985:Wn,9986:Qn,9987:Fi},Tw={33071:ei,33648:Ri,10497:Wr},Xy={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Yy={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},go={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},vk={CUBICSPLINE:void 0,LINEAR:Wl,STEP:Gl},qy={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function xk(e){return e.DefaultMaterial===void 0&&(e.DefaultMaterial=new is({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:Ce})),e.DefaultMaterial}function ml(e,t,r){for(let i in r.extensions)e[i]===void 0&&(t.userData.gltfExtensions=t.userData.gltfExtensions||{},t.userData.gltfExtensions[i]=r.extensions[i])}function Ha(e,t){t.extras!==void 0&&(typeof t.extras=="object"?Object.assign(e.userData,t.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+t.extras))}function bk(e,t,r){let i=!1,n=!1,s=!1;for(let c=0,u=t.length;c<u;c++){let d=t[c];if(d.POSITION!==void 0&&(i=!0),d.NORMAL!==void 0&&(n=!0),d.COLOR_0!==void 0&&(s=!0),i&&n&&s)break}if(!i&&!n&&!s)return Promise.resolve(e);let a=[],o=[],l=[];for(let c=0,u=t.length;c<u;c++){let d=t[c];if(i){let f=d.POSITION!==void 0?r.getDependency("accessor",d.POSITION):e.attributes.position;a.push(f)}if(n){let f=d.NORMAL!==void 0?r.getDependency("accessor",d.NORMAL):e.attributes.normal;o.push(f)}if(s){let f=d.COLOR_0!==void 0?r.getDependency("accessor",d.COLOR_0):e.attributes.color;l.push(f)}}return Promise.all([Promise.all(a),Promise.all(o),Promise.all(l)]).then(function(c){let u=c[0],d=c[1],f=c[2];return i&&(e.morphAttributes.position=u),n&&(e.morphAttributes.normal=d),s&&(e.morphAttributes.color=f),e.morphTargetsRelative=!0,e})}function wk(e,t){if(e.updateMorphTargets(),t.weights!==void 0)for(let r=0,i=t.weights.length;r<i;r++)e.morphTargetInfluences[r]=t.weights[r];if(t.extras&&Array.isArray(t.extras.targetNames)){let r=t.extras.targetNames;if(e.morphTargetInfluences.length===r.length){e.morphTargetDictionary={};for(let i=0,n=r.length;i<n;i++)e.morphTargetDictionary[r[i]]=i}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function _k(e){let t,r=e.extensions&&e.extensions[di.KHR_DRACO_MESH_COMPRESSION];if(r?t="draco:"+r.bufferView+":"+r.indices+":"+Ky(r.attributes):t=e.indices+":"+Ky(e.attributes)+":"+e.mode,e.targets!==void 0)for(let i=0,n=e.targets.length;i<n;i++)t+=":"+Ky(e.targets[i]);return t}function Ky(e){let t="",r=Object.keys(e).sort();for(let i=0,n=r.length;i<n;i++)t+=r[i]+":"+e[r[i]]+";";return t}function Zy(e){switch(e){case Int8Array:return .007874015748031496;case Uint8Array:return .00392156862745098;case Int16Array:return 3051850947599719e-20;case Uint16Array:return 15259021896696422e-21;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function Ek(e){return e.search(/\.jpe?g($|\?)/i)>0||e.search(/^data\:image\/jpeg/)===0?"image/jpeg":e.search(/\.webp($|\?)/i)>0||e.search(/^data\:image\/webp/)===0?"image/webp":e.search(/\.ktx2($|\?)/i)>0||e.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}var Sk=new Ir,Mk=class{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new YL,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let r=!1,i=-1,n=!1,s=-1;if(typeof navigator<"u"){let a=navigator.userAgent;r=/^((?!chrome|android).)*safari/i.test(a)===!0;let o=a.match(/Version\/(\d+)/);i=r&&o?parseInt(o[1],10):-1,n=a.indexOf("Firefox")>-1,s=n?a.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||r&&i<17||n&&s<98?this.textureLoader=new gy(this.options.manager):this.textureLoader=new v1(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new Ps(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){let r=this,i=this.json,n=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(s){return s._markDefs&&s._markDefs()}),Promise.all(this._invokeAll(function(s){return s.beforeRoot&&s.beforeRoot()})).then(function(){return Promise.all([r.getDependencies("scene"),r.getDependencies("animation"),r.getDependencies("camera")])}).then(function(s){let a={scene:s[0][i.scene||0],scenes:s[0],animations:s[1],cameras:s[2],asset:i.asset,parser:r,userData:{}};return ml(n,a,i),Ha(a,i),Promise.all(r._invokeAll(function(o){return o.afterRoot&&o.afterRoot(a)})).then(function(){for(let o of a.scenes)o.updateMatrixWorld();e(a)})}).catch(t)}_markDefs(){let e=this.json.nodes||[],t=this.json.skins||[],r=this.json.meshes||[];for(let i=0,n=t.length;i<n;i++){let s=t[i].joints;for(let a=0,o=s.length;a<o;a++)e[s[a]].isBone=!0}for(let i=0,n=e.length;i<n;i++){let s=e[i];s.mesh!==void 0&&(this._addNodeRef(this.meshCache,s.mesh),s.skin!==void 0&&(r[s.mesh].isSkinnedMesh=!0)),s.camera!==void 0&&this._addNodeRef(this.cameraCache,s.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,r){if(e.refs[t]<=1)return r;let i=r.clone(),n=(s,a)=>{let o=this.associations.get(s);o!=null&&this.associations.set(a,o);for(let[l,c]of s.children.entries())n(c,a.children[l])};return n(r,i),i.name+="_instance_"+e.uses[t]++,i}_invokeOne(e){let t=Object.values(this.plugins);t.push(this);for(let r=0;r<t.length;r++){let i=e(t[r]);if(i)return i}return null}_invokeAll(e){let t=Object.values(this.plugins);t.unshift(this);let r=[];for(let i=0;i<t.length;i++){let n=e(t[i]);n&&r.push(n)}return r}getDependency(e,t){let r=e+":"+t,i=this.cache.get(r);if(!i){switch(e){case"scene":i=this.loadScene(t);break;case"node":i=this._invokeOne(function(n){return n.loadNode&&n.loadNode(t)});break;case"mesh":i=this._invokeOne(function(n){return n.loadMesh&&n.loadMesh(t)});break;case"accessor":i=this.loadAccessor(t);break;case"bufferView":i=this._invokeOne(function(n){return n.loadBufferView&&n.loadBufferView(t)});break;case"buffer":i=this.loadBuffer(t);break;case"material":i=this._invokeOne(function(n){return n.loadMaterial&&n.loadMaterial(t)});break;case"texture":i=this._invokeOne(function(n){return n.loadTexture&&n.loadTexture(t)});break;case"skin":i=this.loadSkin(t);break;case"animation":i=this._invokeOne(function(n){return n.loadAnimation&&n.loadAnimation(t)});break;case"camera":i=this.loadCamera(t);break;default:if(i=this._invokeOne(function(n){return n!=this&&n.getDependency&&n.getDependency(e,t)}),!i)throw new Error("Unknown type: "+e);break}this.cache.add(r,i)}return i}getDependencies(e){let t=this.cache.get(e);if(!t){let r=this,i=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(i.map(function(n,s){return r.getDependency(e,s)})),this.cache.add(e,t)}return t}loadBuffer(e){let t=this.json.buffers[e],r=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[di.KHR_BINARY_GLTF].body);let i=this.options;return new Promise(function(n,s){r.load(Va.resolveURL(t.uri,i.path),n,void 0,function(){s(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){let t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(r){let i=t.byteLength||0,n=t.byteOffset||0;return r.slice(n,n+i)})}loadAccessor(e){let t=this,r=this.json,i=this.json.accessors[e];if(i.bufferView===void 0&&i.sparse===void 0){let s=Xy[i.type],a=Ac[i.componentType],o=i.normalized===!0,l=new a(i.count*s);return Promise.resolve(new ui(l,s,o))}let n=[];return i.bufferView!==void 0?n.push(this.getDependency("bufferView",i.bufferView)):n.push(null),i.sparse!==void 0&&(n.push(this.getDependency("bufferView",i.sparse.indices.bufferView)),n.push(this.getDependency("bufferView",i.sparse.values.bufferView))),Promise.all(n).then(function(s){let a=s[0],o=Xy[i.type],l=Ac[i.componentType],c=l.BYTES_PER_ELEMENT,u=c*o,d=i.byteOffset||0,f=i.bufferView!==void 0?r.bufferViews[i.bufferView].byteStride:void 0,y=i.normalized===!0,b,x;if(f&&f!==u){let g=Math.floor(d/f),v="InterleavedBuffer:"+i.bufferView+":"+i.componentType+":"+g+":"+i.count,_=t.cache.get(v);_||(b=new l(a,g*f,i.count*f/c),_=new Vh(b,f/c),t.cache.add(v,_)),x=new cc(_,o,d%f/c,y)}else a===null?b=new l(i.count*o):b=new l(a,d,i.count*o),x=new ui(b,o,y);if(i.sparse!==void 0){let g=Xy.SCALAR,v=Ac[i.sparse.indices.componentType],_=i.sparse.indices.byteOffset||0,E=i.sparse.values.byteOffset||0,M=new v(s[1],_,i.sparse.count*g),P=new l(s[2],E,i.sparse.count*o);a!==null&&(x=new ui(x.array.slice(),x.itemSize,x.normalized)),x.normalized=!1;for(let k=0,z=M.length;k<z;k++){let D=M[k];if(x.setX(D,P[k*o]),o>=2&&x.setY(D,P[k*o+1]),o>=3&&x.setZ(D,P[k*o+2]),o>=4&&x.setW(D,P[k*o+3]),o>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}x.normalized=y}return x})}loadTexture(e){let t=this.json,r=this.options,i=t.textures[e].source,n=t.images[i],s=this.textureLoader;if(n.uri){let a=r.manager.getHandler(n.uri);a!==null&&(s=a)}return this.loadTextureImage(e,i,s)}loadTextureImage(e,t,r){let i=this,n=this.json,s=n.textures[e],a=n.images[t],o=(a.uri||a.bufferView)+":"+s.sampler;if(this.textureCache[o])return this.textureCache[o];let l=this.loadImageSource(t,r).then(function(c){c.flipY=!1,c.name=s.name||a.name||"",c.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(c.name=a.uri);let u=(n.samplers||{})[s.sampler]||{};return c.magFilter=Aw[u.magFilter]||Pi,c.minFilter=Aw[u.minFilter]||Fi,c.wrapS=Tw[u.wrapS]||Wr,c.wrapT=Tw[u.wrapT]||Wr,c.generateMipmaps=!c.isCompressedTexture&&c.minFilter!==oi&&c.minFilter!==Pi,i.associations.set(c,{textures:e}),c}).catch(function(){return null});return this.textureCache[o]=l,l}loadImageSource(e,t){let r=this,i=this.json,n=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(u=>u.clone());let s=i.images[e],a=self.URL||self.webkitURL,o=s.uri||"",l=!1;if(s.bufferView!==void 0)o=r.getDependency("bufferView",s.bufferView).then(function(u){l=!0;let d=new Blob([u],{type:s.mimeType});return o=a.createObjectURL(d),o});else if(s.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");let c=Promise.resolve(o).then(function(u){return new Promise(function(d,f){let y=d;t.isImageBitmapLoader===!0&&(y=function(b){let x=new Qi(b);x.needsUpdate=!0,d(x)}),t.load(Va.resolveURL(u,n.path),y,void 0,f)})}).then(function(u){return l===!0&&a.revokeObjectURL(o),Ha(u,s),u.userData.mimeType=s.mimeType||Ek(s.uri),u}).catch(function(u){throw console.error("THREE.GLTFLoader: Couldn't load texture",o),u});return this.sourceCache[e]=c,c}assignTexture(e,t,r,i){let n=this;return this.getDependency("texture",r.index).then(function(s){if(!s)return null;if(r.texCoord!==void 0&&r.texCoord>0&&(s=s.clone(),s.channel=r.texCoord),n.extensions[di.KHR_TEXTURE_TRANSFORM]){let a=r.extensions!==void 0?r.extensions[di.KHR_TEXTURE_TRANSFORM]:void 0;if(a){let o=n.associations.get(s);s=n.extensions[di.KHR_TEXTURE_TRANSFORM].extendTexture(s,a),n.associations.set(s,o)}}return i!==void 0&&(s.colorSpace=i),e[t]=s,s})}assignFinalMaterial(e){let t=e.geometry,r=e.material,i=t.attributes.tangent===void 0,n=t.attributes.color!==void 0,s=t.attributes.normal===void 0;if(e.isPoints){let a="PointsMaterial:"+r.uuid,o=this.cache.get(a);o||(o=new $h,bn.prototype.copy.call(o,r),o.color.copy(r.color),o.map=r.map,o.sizeAttenuation=!1,this.cache.add(a,o)),r=o}else if(e.isLine){let a="LineBasicMaterial:"+r.uuid,o=this.cache.get(a);o||(o=new tn,bn.prototype.copy.call(o,r),o.color.copy(r.color),o.map=r.map,this.cache.add(a,o)),r=o}if(i||n||s){let a="ClonedMaterial:"+r.uuid+":";i&&(a+="derivative-tangents:"),n&&(a+="vertex-colors:"),s&&(a+="flat-shading:");let o=this.cache.get(a);o||(o=r.clone(),n&&(o.vertexColors=!0),s&&(o.flatShading=!0),i&&(o.normalScale&&(o.normalScale.y*=-1),o.clearcoatNormalScale&&(o.clearcoatNormalScale.y*=-1)),this.cache.add(a,o),this.associations.set(o,this.associations.get(r))),r=o}e.material=r}getMaterialType(){return is}loadMaterial(e){let t=this,r=this.json,i=this.extensions,n=r.materials[e],s,a={},o=n.extensions||{},l=[];if(o[di.KHR_MATERIALS_UNLIT]){let u=i[di.KHR_MATERIALS_UNLIT];s=u.getMaterialType(),l.push(u.extendParams(a,n,t))}else{let u=n.pbrMetallicRoughness||{};if(a.color=new or(1,1,1),a.opacity=1,Array.isArray(u.baseColorFactor)){let d=u.baseColorFactor;a.color.setRGB(d[0],d[1],d[2],kn),a.opacity=d[3]}u.baseColorTexture!==void 0&&l.push(t.assignTexture(a,"map",u.baseColorTexture,xi)),a.metalness=u.metallicFactor!==void 0?u.metallicFactor:1,a.roughness=u.roughnessFactor!==void 0?u.roughnessFactor:1,u.metallicRoughnessTexture!==void 0&&(l.push(t.assignTexture(a,"metalnessMap",u.metallicRoughnessTexture)),l.push(t.assignTexture(a,"roughnessMap",u.metallicRoughnessTexture))),s=this._invokeOne(function(d){return d.getMaterialType&&d.getMaterialType(e)}),l.push(Promise.all(this._invokeAll(function(d){return d.extendMaterialParams&&d.extendMaterialParams(e,a)})))}n.doubleSided===!0&&(a.side=Ze);let c=n.alphaMode||qy.OPAQUE;if(c===qy.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,c===qy.MASK&&(a.alphaTest=n.alphaCutoff!==void 0?n.alphaCutoff:.5)),n.normalTexture!==void 0&&s!==en&&(l.push(t.assignTexture(a,"normalMap",n.normalTexture)),a.normalScale=new Ft(1,1),n.normalTexture.scale!==void 0)){let u=n.normalTexture.scale;a.normalScale.set(u,u)}if(n.occlusionTexture!==void 0&&s!==en&&(l.push(t.assignTexture(a,"aoMap",n.occlusionTexture)),n.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=n.occlusionTexture.strength)),n.emissiveFactor!==void 0&&s!==en){let u=n.emissiveFactor;a.emissive=new or().setRGB(u[0],u[1],u[2],kn)}return n.emissiveTexture!==void 0&&s!==en&&l.push(t.assignTexture(a,"emissiveMap",n.emissiveTexture,xi)),Promise.all(l).then(function(){let u=new s(a);return n.name&&(u.name=n.name),Ha(u,n),t.associations.set(u,{materials:e}),n.extensions&&ml(i,u,n),u})}createUniqueName(e){let t=zi.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){let t=this,r=this.extensions,i=this.primitiveCache;function n(a){return r[di.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,t).then(function(o){return Cw(o,a,t)})}let s=[];for(let a=0,o=e.length;a<o;a++){let l=e[a],c=_k(l),u=i[c];if(u)s.push(u.promise);else{let d;l.extensions&&l.extensions[di.KHR_DRACO_MESH_COMPRESSION]?d=n(l):d=Cw(new Hr,l,t),i[c]={primitive:l,promise:d},s.push(d)}}return Promise.all(s)}loadMesh(e){let t=this,r=this.json,i=this.extensions,n=r.meshes[e],s=n.primitives,a=[];for(let o=0,l=s.length;o<l;o++){let c=s[o].material===void 0?xk(this.cache):this.getDependency("material",s[o].material);a.push(c)}return a.push(t.loadGeometries(s)),Promise.all(a).then(function(o){let l=o.slice(0,o.length-1),c=o[o.length-1],u=[];for(let f=0,y=c.length;f<y;f++){let b=c[f],x=s[f],g,v=l[f];if(x.mode===Is.TRIANGLES||x.mode===Is.TRIANGLE_STRIP||x.mode===Is.TRIANGLE_FAN||x.mode===void 0)g=n.isSkinnedMesh===!0?new Ug(b,v):new qr(b,v),g.isSkinnedMesh===!0&&g.normalizeSkinWeights(),x.mode===Is.TRIANGLE_STRIP?g.geometry=_w(g.geometry,ag):x.mode===Is.TRIANGLE_FAN&&(g.geometry=_w(g.geometry,Zd));else if(x.mode===Is.LINES)g=new Fn(b,v);else if(x.mode===Is.LINE_STRIP)g=new ua(b,v);else if(x.mode===Is.LINE_LOOP)g=new Lp(b,v);else if(x.mode===Is.POINTS)g=new Dp(b,v);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+x.mode);Object.keys(g.geometry.morphAttributes).length>0&&wk(g,n),g.name=t.createUniqueName(n.name||"mesh_"+e),Ha(g,n),x.extensions&&ml(i,g,x),t.assignFinalMaterial(g),u.push(g)}for(let f=0,y=u.length;f<y;f++)t.associations.set(u[f],{meshes:e,primitives:f});if(u.length===1)return n.extensions&&ml(i,u[0],n),u[0];let d=new Wi;n.extensions&&ml(i,d,n),t.associations.set(d,{meshes:e});for(let f=0,y=u.length;f<y;f++)d.add(u[f]);return d})}loadCamera(e){let t,r=this.json.cameras[e],i=r[r.type];if(!i){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return r.type==="perspective"?t=new cn($d.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2e6):r.type==="orthographic"&&(t=new wc(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar)),r.name&&(t.name=this.createUniqueName(r.name)),Ha(t,r),Promise.resolve(t)}loadSkin(e){let t=this.json.skins[e],r=[];for(let i=0,n=t.joints.length;i<n;i++)r.push(this._loadNodeShallow(t.joints[i]));return t.inverseBindMatrices!==void 0?r.push(this.getDependency("accessor",t.inverseBindMatrices)):r.push(null),Promise.all(r).then(function(i){let n=i.pop(),s=i,a=[],o=[];for(let l=0,c=s.length;l<c;l++){let u=s[l];if(u){a.push(u);let d=new Ir;n!==null&&d.fromArray(n.array,l*16),o.push(d)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[l])}return new Fg(a,o)})}loadAnimation(e){let t=this.json,r=this,i=t.animations[e],n=i.name?i.name:"animation_"+e,s=[],a=[],o=[],l=[],c=[];for(let u=0,d=i.channels.length;u<d;u++){let f=i.channels[u],y=i.samplers[f.sampler],b=f.target,x=b.node,g=i.parameters!==void 0?i.parameters[y.input]:y.input,v=i.parameters!==void 0?i.parameters[y.output]:y.output;b.node!==void 0&&(s.push(this.getDependency("node",x)),a.push(this.getDependency("accessor",g)),o.push(this.getDependency("accessor",v)),l.push(y),c.push(b))}return Promise.all([Promise.all(s),Promise.all(a),Promise.all(o),Promise.all(l),Promise.all(c)]).then(function(u){let d=u[0],f=u[1],y=u[2],b=u[3],x=u[4],g=[];for(let v=0,_=d.length;v<_;v++){let E=d[v],M=f[v],P=y[v],k=b[v],z=x[v];if(E===void 0)continue;E.updateMatrix&&E.updateMatrix();let D=r._createAnimationTracks(E,M,P,k,z);if(D)for(let I=0;I<D.length;I++)g.push(D[I])}return new bc(n,void 0,g)})}createNodeMesh(e){let t=this.json,r=this,i=t.nodes[e];return i.mesh===void 0?null:r.getDependency("mesh",i.mesh).then(function(n){let s=r._getNodeRef(r.meshCache,i.mesh,n);return i.weights!==void 0&&s.traverse(function(a){if(a.isMesh)for(let o=0,l=i.weights.length;o<l;o++)a.morphTargetInfluences[o]=i.weights[o]}),s})}loadNode(e){let t=this.json,r=this,i=t.nodes[e],n=r._loadNodeShallow(e),s=[],a=i.children||[];for(let l=0,c=a.length;l<c;l++)s.push(r.getDependency("node",a[l]));let o=i.skin===void 0?Promise.resolve(null):r.getDependency("skin",i.skin);return Promise.all([n,Promise.all(s),o]).then(function(l){let c=l[0],u=l[1],d=l[2];d!==null&&c.traverse(function(f){f.isSkinnedMesh&&f.bind(d,Sk)});for(let f=0,y=u.length;f<y;f++)c.add(u[f]);return c})}_loadNodeShallow(e){let t=this.json,r=this.extensions,i=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];let n=t.nodes[e],s=n.name?i.createUniqueName(n.name):"",a=[],o=i._invokeOne(function(l){return l.createNodeMesh&&l.createNodeMesh(e)});return o&&a.push(o),n.camera!==void 0&&a.push(i.getDependency("camera",n.camera).then(function(l){return i._getNodeRef(i.cameraCache,n.camera,l)})),i._invokeAll(function(l){return l.createNodeAttachment&&l.createNodeAttachment(e)}).forEach(function(l){a.push(l)}),this.nodeCache[e]=Promise.all(a).then(function(l){let c;if(n.isBone===!0?c=new Ep:l.length>1?c=new Wi:l.length===1?c=l[0]:c=new mi,c!==l[0])for(let u=0,d=l.length;u<d;u++)c.add(l[u]);if(n.name&&(c.userData.name=n.name,c.name=s),Ha(c,n),n.extensions&&ml(r,c,n),n.matrix!==void 0){let u=new Ir;u.fromArray(n.matrix),c.applyMatrix4(u)}else n.translation!==void 0&&c.position.fromArray(n.translation),n.rotation!==void 0&&c.quaternion.fromArray(n.rotation),n.scale!==void 0&&c.scale.fromArray(n.scale);return i.associations.has(c)||i.associations.set(c,{}),i.associations.get(c).nodes=e,c}),this.nodeCache[e]}loadScene(e){let t=this.extensions,r=this.json.scenes[e],i=this,n=new Wi;r.name&&(n.name=i.createUniqueName(r.name)),Ha(n,r),r.extensions&&ml(t,n,r);let s=r.nodes||[],a=[];for(let o=0,l=s.length;o<l;o++)a.push(i.getDependency("node",s[o]));return Promise.all(a).then(function(o){for(let c=0,u=o.length;c<u;c++)n.add(o[c]);let l=c=>{let u=new Map;for(let[d,f]of i.associations)(d instanceof bn||d instanceof Qi)&&u.set(d,f);return c.traverse(d=>{let f=i.associations.get(d);f!=null&&u.set(d,f)}),u};return i.associations=l(n),n})}_createAnimationTracks(e,t,r,i,n){let s=[],a=e.name?e.name:e.uuid,o=[];go[n.path]===go.weights?e.traverse(function(d){d.morphTargetInfluences&&o.push(d.name?d.name:d.uuid)}):o.push(a);let l;switch(go[n.path]){case go.weights:l=tl;break;case go.rotation:l=rl;break;case go.position:case go.scale:l=nl;break;default:switch(r.itemSize){case 1:l=tl;break;case 2:case 3:default:l=nl;break}break}let c=i.interpolation!==void 0?vk[i.interpolation]:Wl,u=this._getArrayFromAccessor(r);for(let d=0,f=o.length;d<f;d++){let y=new l(o[d]+"."+go[n.path],t.array,u,c);i.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(y),s.push(y)}return s}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){let r=Zy(t.constructor),i=new Float32Array(t.length);for(let n=0,s=t.length;n<s;n++)i[n]=t[n]*r;t=i}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(t){let r=this instanceof rl?yk:Mw;return new r(this.times,this.values,this.getValueSize()/3,t)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}};function Ak(e,t,r){let i=t.attributes,n=new Xi;if(i.POSITION!==void 0){let o=r.json.accessors[i.POSITION],l=o.min,c=o.max;if(l!==void 0&&c!==void 0){if(n.set(new je(l[0],l[1],l[2]),new je(c[0],c[1],c[2])),o.normalized){let u=Zy(Ac[o.componentType]);n.min.multiplyScalar(u),n.max.multiplyScalar(u)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;let s=t.targets;if(s!==void 0){let o=new je,l=new je;for(let c=0,u=s.length;c<u;c++){let d=s[c];if(d.POSITION!==void 0){let f=r.json.accessors[d.POSITION],y=f.min,b=f.max;if(y!==void 0&&b!==void 0){if(l.setX(Math.max(Math.abs(y[0]),Math.abs(b[0]))),l.setY(Math.max(Math.abs(y[1]),Math.abs(b[1]))),l.setZ(Math.max(Math.abs(y[2]),Math.abs(b[2]))),f.normalized){let x=Zy(Ac[f.componentType]);l.multiplyScalar(x)}o.max(l)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}n.expandByVector(o)}e.boundingBox=n;let a=new on;n.getCenter(a.center),a.radius=n.min.distanceTo(n.max)/2,e.boundingSphere=a}function Cw(e,t,r){let i=t.attributes,n=[];function s(a,o){return r.getDependency("accessor",a).then(function(l){e.setAttribute(o,l)})}for(let a in i){let o=Yy[a]||a.toLowerCase();o in e.attributes||n.push(s(i[a],o))}if(t.indices!==void 0&&!e.index){let a=r.getDependency("accessor",t.indices).then(function(o){e.setIndex(o)});n.push(a)}return li.workingColorSpace!==kn&&"COLOR_0"in i&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${li.workingColorSpace}" not supported.`),Ha(e,t),Ak(e,t,r),Promise.all(n).then(function(){return t.targets!==void 0?bk(e,t.targets,r):e})}var ri=(e,t)=>()=>(t||(t={exports:{}},e(t.exports,t)),t.exports),Rw=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.VERSION=void 0,e.VERSION="9.0.1"}),Ai=ri((e,t)=>{"use strict";var r=e&&e.__spreadArray||function(We,mt){for(var it=0,st=mt.length,oe=We.length;it<st;it++,oe++)We[oe]=mt[it];return We};Object.defineProperty(e,"__esModule",{value:!0}),e.toFastProperties=e.timer=e.peek=e.isES2015MapSupported=e.PRINT_WARNING=e.PRINT_ERROR=e.packArray=e.IDENTITY=e.NOOP=e.merge=e.groupBy=e.defaults=e.assignNoOverwrite=e.assign=e.zipObject=e.sortBy=e.indexOf=e.some=e.difference=e.every=e.isObject=e.isRegExp=e.isArray=e.partial=e.uniq=e.compact=e.reduce=e.findAll=e.find=e.cloneObj=e.cloneArr=e.contains=e.has=e.pick=e.reject=e.filter=e.dropRight=e.drop=e.isFunction=e.isUndefined=e.isString=e.forEach=e.last=e.first=e.flatten=e.map=e.mapValues=e.values=e.keys=e.isEmpty=void 0;function i(We){return We&&We.length===0}e.isEmpty=i;function n(We){return We==null?[]:Object.keys(We)}e.keys=n;function s(We){for(var mt=[],it=Object.keys(We),st=0;st<it.length;st++)mt.push(We[it[st]]);return mt}e.values=s;function a(We,mt){for(var it=[],st=n(We),oe=0;oe<st.length;oe++){var F=st[oe];it.push(mt.call(null,We[F],F))}return it}e.mapValues=a;function o(We,mt){for(var it=[],st=0;st<We.length;st++)it.push(mt.call(null,We[st],st));return it}e.map=o;function l(We){for(var mt=[],it=0;it<We.length;it++){var st=We[it];Array.isArray(st)?mt=mt.concat(l(st)):mt.push(st)}return mt}e.flatten=l;function c(We){return i(We)?void 0:We[0]}e.first=c;function u(We){var mt=We&&We.length;return mt?We[mt-1]:void 0}e.last=u;function d(We,mt){if(Array.isArray(We))for(var it=0;it<We.length;it++)mt.call(null,We[it],it);else if(Fe(We))for(var st=n(We),it=0;it<st.length;it++){var oe=st[it],F=We[oe];mt.call(null,F,oe)}else throw Error("non exhaustive match")}e.forEach=d;function f(We){return typeof We=="string"}e.isString=f;function y(We){return We===void 0}e.isUndefined=y;function b(We){return We instanceof Function}e.isFunction=b;function x(We,mt){return mt===void 0&&(mt=1),We.slice(mt,We.length)}e.drop=x;function g(We,mt){return mt===void 0&&(mt=1),We.slice(0,We.length-mt)}e.dropRight=g;function v(We,mt){var it=[];if(Array.isArray(We))for(var st=0;st<We.length;st++){var oe=We[st];mt.call(null,oe)&&it.push(oe)}return it}e.filter=v;function _(We,mt){return v(We,function(it){return!mt(it)})}e.reject=_;function E(We,mt){for(var it=Object.keys(We),st={},oe=0;oe<it.length;oe++){var F=it[oe],le=We[F];mt(le)&&(st[F]=le)}return st}e.pick=E;function M(We,mt){return Fe(We)?We.hasOwnProperty(mt):!1}e.has=M;function P(We,mt){return D(We,function(it){return it===mt})!==void 0}e.contains=P;function k(We){for(var mt=[],it=0;it<We.length;it++)mt.push(We[it]);return mt}e.cloneArr=k;function z(We){var mt={};for(var it in We)Object.prototype.hasOwnProperty.call(We,it)&&(mt[it]=We[it]);return mt}e.cloneObj=z;function D(We,mt){for(var it=0;it<We.length;it++){var st=We[it];if(mt.call(null,st))return st}}e.find=D;function I(We,mt){for(var it=[],st=0;st<We.length;st++){var oe=We[st];mt.call(null,oe)&&it.push(oe)}return it}e.findAll=I;function L(We,mt,it){for(var st=Array.isArray(We),oe=st?We:s(We),F=st?[]:n(We),le=it,pe=0;pe<oe.length;pe++)le=mt.call(null,le,oe[pe],st?pe:F[pe]);return le}e.reduce=L;function Z(We){return _(We,function(mt){return mt==null})}e.compact=Z;function se(We,mt){mt===void 0&&(mt=function(st){return st});var it=[];return L(We,function(st,oe){var F=mt(oe);return P(it,F)?st:(it.push(F),st.concat(oe))},[])}e.uniq=se;function ce(We){for(var mt=[],it=1;it<arguments.length;it++)mt[it-1]=arguments[it];var st=[null],oe=st.concat(mt);return Function.bind.apply(We,oe)}e.partial=ce;function fe(We){return Array.isArray(We)}e.isArray=fe;function ze(We){return We instanceof RegExp}e.isRegExp=ze;function Fe(We){return We instanceof Object}e.isObject=Fe;function Pe(We,mt){for(var it=0;it<We.length;it++)if(!mt(We[it],it))return!1;return!0}e.every=Pe;function ue(We,mt){return _(We,function(it){return P(mt,it)})}e.difference=ue;function Te(We,mt){for(var it=0;it<We.length;it++)if(mt(We[it]))return!0;return!1}e.some=Te;function de(We,mt){for(var it=0;it<We.length;it++)if(We[it]===mt)return it;return-1}e.indexOf=de;function Ie(We,mt){var it=k(We);return it.sort(function(st,oe){return mt(st)-mt(oe)}),it}e.sortBy=Ie;function Re(We,mt){if(We.length!==mt.length)throw Error("can't zipObject with different number of keys and values!");for(var it={},st=0;st<We.length;st++)it[We[st]]=mt[st];return it}e.zipObject=Re;function Be(We){for(var mt=[],it=1;it<arguments.length;it++)mt[it-1]=arguments[it];for(var st=0;st<mt.length;st++)for(var oe=mt[st],F=n(oe),le=0;le<F.length;le++){var pe=F[le];We[pe]=oe[pe]}return We}e.assign=Be;function Se(We){for(var mt=[],it=1;it<arguments.length;it++)mt[it-1]=arguments[it];for(var st=0;st<mt.length;st++)for(var oe=mt[st],F=n(oe),le=0;le<F.length;le++){var pe=F[le];M(We,pe)||(We[pe]=oe[pe])}return We}e.assignNoOverwrite=Se;function U(){for(var We=[],mt=0;mt<arguments.length;mt++)We[mt]=arguments[mt];return Se.apply(void 0,r([{}],We))}e.defaults=U;function ie(We,mt){var it={};return d(We,function(st){var oe=mt(st),F=it[oe];F?F.push(st):it[oe]=[st]}),it}e.groupBy=ie;function Ae(We,mt){for(var it=z(We),st=n(mt),oe=0;oe<st.length;oe++){var F=st[oe],le=mt[F];it[F]=le}return it}e.merge=Ae;function Ue(){}e.NOOP=Ue;function Ge(We){return We}e.IDENTITY=Ge;function nt(We){for(var mt=[],it=0;it<We.length;it++){var st=We[it];mt.push(st!==void 0?st:void 0)}return mt}e.packArray=nt;function Qe(We){console&&console.error&&console.error("Error: "+We)}e.PRINT_ERROR=Qe;function ct(We){console&&console.warn&&console.warn("Warning: "+We)}e.PRINT_WARNING=ct;function ye(){return typeof Map=="function"}e.isES2015MapSupported=ye;function dt(We){return We[We.length-1]}e.peek=dt;function xt(We){var mt=new Date().getTime(),it=We(),st=new Date().getTime(),oe=st-mt;return{time:oe,value:it}}e.timer=xt;function Dt(We){function mt(){}mt.prototype=We;var it=new mt;function st(){return typeof it.bar}return st(),st(),We}e.toFastProperties=Dt}),$y=ri((e,t)=>{(function(r,i){typeof define=="function"&&define.amd?define([],i):typeof t=="object"&&t.exports?t.exports=i():r.regexpToAst=i()})(typeof self<"u"?self:e,function(){function r(){}r.prototype.saveState=function(){return{idx:this.idx,input:this.input,groupIdx:this.groupIdx}},r.prototype.restoreState=function(g){this.idx=g.idx,this.input=g.input,this.groupIdx=g.groupIdx},r.prototype.pattern=function(g){this.idx=0,this.input=g,this.groupIdx=0,this.consumeChar("/");var v=this.disjunction();this.consumeChar("/");for(var _={type:"Flags",loc:{begin:this.idx,end:g.length},global:!1,ignoreCase:!1,multiLine:!1,unicode:!1,sticky:!1};this.isRegExpFlag();)switch(this.popChar()){case"g":l(_,"global");break;case"i":l(_,"ignoreCase");break;case"m":l(_,"multiLine");break;case"u":l(_,"unicode");break;case"y":l(_,"sticky");break}if(this.idx!==this.input.length)throw Error("Redundant input: "+this.input.substring(this.idx));return{type:"Pattern",flags:_,value:v,loc:this.loc(0)}},r.prototype.disjunction=function(){var g=[],v=this.idx;for(g.push(this.alternative());this.peekChar()==="|";)this.consumeChar("|"),g.push(this.alternative());return{type:"Disjunction",value:g,loc:this.loc(v)}},r.prototype.alternative=function(){for(var g=[],v=this.idx;this.isTerm();)g.push(this.term());return{type:"Alternative",value:g,loc:this.loc(v)}},r.prototype.term=function(){return this.isAssertion()?this.assertion():this.atom()},r.prototype.assertion=function(){var g=this.idx;switch(this.popChar()){case"^":return{type:"StartAnchor",loc:this.loc(g)};case"$":return{type:"EndAnchor",loc:this.loc(g)};case"\\":switch(this.popChar()){case"b":return{type:"WordBoundary",loc:this.loc(g)};case"B":return{type:"NonWordBoundary",loc:this.loc(g)}}throw Error("Invalid Assertion Escape");case"(":this.consumeChar("?");var v;switch(this.popChar()){case"=":v="Lookahead";break;case"!":v="NegativeLookahead";break}c(v);var _=this.disjunction();return this.consumeChar(")"),{type:v,value:_,loc:this.loc(g)}}u()},r.prototype.quantifier=function(g){var v,_=this.idx;switch(this.popChar()){case"*":v={atLeast:0,atMost:1/0};break;case"+":v={atLeast:1,atMost:1/0};break;case"?":v={atLeast:0,atMost:1};break;case"{":var E=this.integerIncludingZero();switch(this.popChar()){case"}":v={atLeast:E,atMost:E};break;case",":var M;this.isDigit()?(M=this.integerIncludingZero(),v={atLeast:E,atMost:M}):v={atLeast:E,atMost:1/0},this.consumeChar("}");break}if(g===!0&&v===void 0)return;c(v);break}if(!(g===!0&&v===void 0))return c(v),this.peekChar(0)==="?"?(this.consumeChar("?"),v.greedy=!1):v.greedy=!0,v.type="Quantifier",v.loc=this.loc(_),v},r.prototype.atom=function(){var g,v=this.idx;switch(this.peekChar()){case".":g=this.dotAll();break;case"\\":g=this.atomEscape();break;case"[":g=this.characterClass();break;case"(":g=this.group();break}return g===void 0&&this.isPatternCharacter()&&(g=this.patternCharacter()),c(g),g.loc=this.loc(v),this.isQuantifier()&&(g.quantifier=this.quantifier()),g},r.prototype.dotAll=function(){return this.consumeChar("."),{type:"Set",complement:!0,value:[a(`
`),a("\r"),a("\u2028"),a("\u2029")]}},r.prototype.atomEscape=function(){switch(this.consumeChar("\\"),this.peekChar()){case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":return this.decimalEscapeAtom();case"d":case"D":case"s":case"S":case"w":case"W":return this.characterClassEscape();case"f":case"n":case"r":case"t":case"v":return this.controlEscapeAtom();case"c":return this.controlLetterEscapeAtom();case"0":return this.nulCharacterAtom();case"x":return this.hexEscapeSequenceAtom();case"u":return this.regExpUnicodeEscapeSequenceAtom();default:return this.identityEscapeAtom()}},r.prototype.decimalEscapeAtom=function(){var g=this.positiveInteger();return{type:"GroupBackReference",value:g}},r.prototype.characterClassEscape=function(){var g,v=!1;switch(this.popChar()){case"d":g=f;break;case"D":g=f,v=!0;break;case"s":g=b;break;case"S":g=b,v=!0;break;case"w":g=y;break;case"W":g=y,v=!0;break}return c(g),{type:"Set",value:g,complement:v}},r.prototype.controlEscapeAtom=function(){var g;switch(this.popChar()){case"f":g=a("\f");break;case"n":g=a(`
`);break;case"r":g=a("\r");break;case"t":g=a("	");break;case"v":g=a("\v");break}return c(g),{type:"Character",value:g}},r.prototype.controlLetterEscapeAtom=function(){this.consumeChar("c");var g=this.popChar();if(/[a-zA-Z]/.test(g)===!1)throw Error("Invalid ");var v=g.toUpperCase().charCodeAt(0)-64;return{type:"Character",value:v}},r.prototype.nulCharacterAtom=function(){return this.consumeChar("0"),{type:"Character",value:a("\0")}},r.prototype.hexEscapeSequenceAtom=function(){return this.consumeChar("x"),this.parseHexDigits(2)},r.prototype.regExpUnicodeEscapeSequenceAtom=function(){return this.consumeChar("u"),this.parseHexDigits(4)},r.prototype.identityEscapeAtom=function(){var g=this.popChar();return{type:"Character",value:a(g)}},r.prototype.classPatternCharacterAtom=function(){switch(this.peekChar()){case`
`:case"\r":case"\u2028":case"\u2029":case"\\":case"]":throw Error("TBD");default:var g=this.popChar();return{type:"Character",value:a(g)}}},r.prototype.characterClass=function(){var g=[],v=!1;for(this.consumeChar("["),this.peekChar(0)==="^"&&(this.consumeChar("^"),v=!0);this.isClassAtom();){var _=this.classAtom(),E=_.type==="Character";if(E&&this.isRangeDash()){this.consumeChar("-");var M=this.classAtom(),P=M.type==="Character";if(P){if(M.value<_.value)throw Error("Range out of order in character class");g.push({from:_.value,to:M.value})}else o(_.value,g),g.push(a("-")),o(M.value,g)}else o(_.value,g)}return this.consumeChar("]"),{type:"Set",complement:v,value:g}},r.prototype.classAtom=function(){switch(this.peekChar()){case"]":case`
`:case"\r":case"\u2028":case"\u2029":throw Error("TBD");case"\\":return this.classEscape();default:return this.classPatternCharacterAtom()}},r.prototype.classEscape=function(){switch(this.consumeChar("\\"),this.peekChar()){case"b":return this.consumeChar("b"),{type:"Character",value:a("\b")};case"d":case"D":case"s":case"S":case"w":case"W":return this.characterClassEscape();case"f":case"n":case"r":case"t":case"v":return this.controlEscapeAtom();case"c":return this.controlLetterEscapeAtom();case"0":return this.nulCharacterAtom();case"x":return this.hexEscapeSequenceAtom();case"u":return this.regExpUnicodeEscapeSequenceAtom();default:return this.identityEscapeAtom()}},r.prototype.group=function(){var g=!0;switch(this.consumeChar("("),this.peekChar(0)){case"?":this.consumeChar("?"),this.consumeChar(":"),g=!1;break;default:this.groupIdx++;break}var v=this.disjunction();this.consumeChar(")");var _={type:"Group",capturing:g,value:v};return g&&(_.idx=this.groupIdx),_},r.prototype.positiveInteger=function(){var g=this.popChar();if(s.test(g)===!1)throw Error("Expecting a positive integer");for(;n.test(this.peekChar(0));)g+=this.popChar();return parseInt(g,10)},r.prototype.integerIncludingZero=function(){var g=this.popChar();if(n.test(g)===!1)throw Error("Expecting an integer");for(;n.test(this.peekChar(0));)g+=this.popChar();return parseInt(g,10)},r.prototype.patternCharacter=function(){var g=this.popChar();switch(g){case`
`:case"\r":case"\u2028":case"\u2029":case"^":case"$":case"\\":case".":case"*":case"+":case"?":case"(":case")":case"[":case"|":throw Error("TBD");default:return{type:"Character",value:a(g)}}},r.prototype.isRegExpFlag=function(){switch(this.peekChar(0)){case"g":case"i":case"m":case"u":case"y":return!0;default:return!1}},r.prototype.isRangeDash=function(){return this.peekChar()==="-"&&this.isClassAtom(1)},r.prototype.isDigit=function(){return n.test(this.peekChar(0))},r.prototype.isClassAtom=function(g){switch(g===void 0&&(g=0),this.peekChar(g)){case"]":case`
`:case"\r":case"\u2028":case"\u2029":return!1;default:return!0}},r.prototype.isTerm=function(){return this.isAtom()||this.isAssertion()},r.prototype.isAtom=function(){if(this.isPatternCharacter())return!0;switch(this.peekChar(0)){case".":case"\\":case"[":case"(":return!0;default:return!1}},r.prototype.isAssertion=function(){switch(this.peekChar(0)){case"^":case"$":return!0;case"\\":switch(this.peekChar(1)){case"b":case"B":return!0;default:return!1}case"(":return this.peekChar(1)==="?"&&(this.peekChar(2)==="="||this.peekChar(2)==="!");default:return!1}},r.prototype.isQuantifier=function(){var g=this.saveState();try{return this.quantifier(!0)!==void 0}catch{return!1}finally{this.restoreState(g)}},r.prototype.isPatternCharacter=function(){switch(this.peekChar()){case"^":case"$":case"\\":case".":case"*":case"+":case"?":case"(":case")":case"[":case"|":case"/":case`
`:case"\r":case"\u2028":case"\u2029":return!1;default:return!0}},r.prototype.parseHexDigits=function(g){for(var v="",_=0;_<g;_++){var E=this.popChar();if(i.test(E)===!1)throw Error("Expecting a HexDecimal digits");v+=E}var M=parseInt(v,16);return{type:"Character",value:M}},r.prototype.peekChar=function(g){return g===void 0&&(g=0),this.input[this.idx+g]},r.prototype.popChar=function(){var g=this.peekChar(0);return this.consumeChar(),g},r.prototype.consumeChar=function(g){if(g!==void 0&&this.input[this.idx]!==g)throw Error("Expected: '"+g+"' but found: '"+this.input[this.idx]+"' at offset: "+this.idx);if(this.idx>=this.input.length)throw Error("Unexpected end of input");this.idx++},r.prototype.loc=function(g){return{begin:g,end:this.idx}};var i=/[0-9a-fA-F]/,n=/[0-9]/,s=/[1-9]/;function a(g){return g.charCodeAt(0)}function o(g,v){g.length!==void 0?g.forEach(function(_){v.push(_)}):v.push(g)}function l(g,v){if(g[v]===!0)throw"duplicate flag "+v;g[v]=!0}function c(g){if(g===void 0)throw Error("Internal Error - Should never get here!")}function u(){throw Error("Internal Error - Should never get here!")}var d,f=[];for(d=a("0");d<=a("9");d++)f.push(d);var y=[a("_")].concat(f);for(d=a("a");d<=a("z");d++)y.push(d);for(d=a("A");d<=a("Z");d++)y.push(d);var b=[a(" "),a("\f"),a(`
`),a("\r"),a("	"),a("\v"),a("	"),a("\xA0"),a("\u1680"),a("\u2000"),a("\u2001"),a("\u2002"),a("\u2003"),a("\u2004"),a("\u2005"),a("\u2006"),a("\u2007"),a("\u2008"),a("\u2009"),a("\u200A"),a("\u2028"),a("\u2029"),a("\u202F"),a("\u205F"),a("\u3000"),a("\uFEFF")];function x(){}return x.prototype.visitChildren=function(g){for(var v in g){var _=g[v];g.hasOwnProperty(v)&&(_.type!==void 0?this.visit(_):Array.isArray(_)&&_.forEach(function(E){this.visit(E)},this))}},x.prototype.visit=function(g){switch(g.type){case"Pattern":this.visitPattern(g);break;case"Flags":this.visitFlags(g);break;case"Disjunction":this.visitDisjunction(g);break;case"Alternative":this.visitAlternative(g);break;case"StartAnchor":this.visitStartAnchor(g);break;case"EndAnchor":this.visitEndAnchor(g);break;case"WordBoundary":this.visitWordBoundary(g);break;case"NonWordBoundary":this.visitNonWordBoundary(g);break;case"Lookahead":this.visitLookahead(g);break;case"NegativeLookahead":this.visitNegativeLookahead(g);break;case"Character":this.visitCharacter(g);break;case"Set":this.visitSet(g);break;case"Group":this.visitGroup(g);break;case"GroupBackReference":this.visitGroupBackReference(g);break;case"Quantifier":this.visitQuantifier(g);break}this.visitChildren(g)},x.prototype.visitPattern=function(g){},x.prototype.visitFlags=function(g){},x.prototype.visitDisjunction=function(g){},x.prototype.visitAlternative=function(g){},x.prototype.visitStartAnchor=function(g){},x.prototype.visitEndAnchor=function(g){},x.prototype.visitWordBoundary=function(g){},x.prototype.visitNonWordBoundary=function(g){},x.prototype.visitLookahead=function(g){},x.prototype.visitNegativeLookahead=function(g){},x.prototype.visitCharacter=function(g){},x.prototype.visitSet=function(g){},x.prototype.visitGroup=function(g){},x.prototype.visitGroupBackReference=function(g){},x.prototype.visitQuantifier=function(g){},{RegExpParser:r,BaseRegExpVisitor:x,VERSION:"0.5.0"}})}),Jy=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.clearRegExpParserCache=e.getRegExpAst=void 0;var t=$y(),r={},i=new t.RegExpParser;function n(a){var o=a.toString();if(r.hasOwnProperty(o))return r[o];var l=i.pattern(o);return r[o]=l,l}e.getRegExpAst=n;function s(){r={}}e.clearRegExpParserCache=s}),Tk=ri(e=>{"use strict";var t=e&&e.__extends||(function(){var x=function(g,v){return x=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(_,E){_.__proto__=E}||function(_,E){for(var M in E)Object.prototype.hasOwnProperty.call(E,M)&&(_[M]=E[M])},x(g,v)};return function(g,v){if(typeof v!="function"&&v!==null)throw new TypeError("Class extends value "+String(v)+" is not a constructor or null");x(g,v);function _(){this.constructor=g}g.prototype=v===null?Object.create(v):(_.prototype=v.prototype,new _)}})();Object.defineProperty(e,"__esModule",{value:!0}),e.canMatchCharCode=e.firstCharOptimizedIndices=e.getOptimizedStartCodesIndices=e.failedOptimizationPrefixMsg=void 0;var r=$y(),i=Ai(),n=Jy(),s=Pw(),a="Complement Sets are not supported for first char optimization";e.failedOptimizationPrefixMsg=`Unable to use "first char" lexer optimizations:
`;function o(x,g){g===void 0&&(g=!1);try{var v=n.getRegExpAst(x),_=l(v.value,{},v.flags.ignoreCase);return _}catch(M){if(M.message===a)g&&i.PRINT_WARNING(""+e.failedOptimizationPrefixMsg+("	Unable to optimize: < "+x.toString()+` >
`)+`	Complement Sets cannot be automatically optimized.
	This will disable the lexer's first char optimizations.
	See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.`);else{var E="";g&&(E=`
	This will disable the lexer's first char optimizations.
	See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.`),i.PRINT_ERROR(e.failedOptimizationPrefixMsg+`
`+("	Failed parsing: < "+x.toString()+` >
`)+("	Using the regexp-to-ast library version: "+r.VERSION+`
`)+"	Please open an issue at: https://github.com/bd82/regexp-to-ast/issues"+E)}}return[]}e.getOptimizedStartCodesIndices=o;function l(x,g,v){switch(x.type){case"Disjunction":for(var _=0;_<x.value.length;_++)l(x.value[_],g,v);break;case"Alternative":for(var E=x.value,_=0;_<E.length;_++){var M=E[_];switch(M.type){case"EndAnchor":case"GroupBackReference":case"Lookahead":case"NegativeLookahead":case"StartAnchor":case"WordBoundary":case"NonWordBoundary":continue}var P=M;switch(P.type){case"Character":c(P.value,g,v);break;case"Set":if(P.complement===!0)throw Error(a);i.forEach(P.value,function(D){if(typeof D=="number")c(D,g,v);else{var I=D;if(v===!0)for(var L=I.from;L<=I.to;L++)c(L,g,v);else{for(var L=I.from;L<=I.to&&L<s.minOptimizationVal;L++)c(L,g,v);if(I.to>=s.minOptimizationVal)for(var Z=I.from>=s.minOptimizationVal?I.from:s.minOptimizationVal,se=I.to,ce=s.charCodeToOptimizedIndex(Z),fe=s.charCodeToOptimizedIndex(se),ze=ce;ze<=fe;ze++)g[ze]=ze}}});break;case"Group":l(P.value,g,v);break;default:throw Error("Non Exhaustive Match")}var k=P.quantifier!==void 0&&P.quantifier.atLeast===0;if(P.type==="Group"&&f(P)===!1||P.type!=="Group"&&k===!1)break}break;default:throw Error("non exhaustive match!")}return i.values(g)}e.firstCharOptimizedIndices=l;function c(x,g,v){var _=s.charCodeToOptimizedIndex(x);g[_]=_,v===!0&&u(x,g)}function u(x,g){var v=String.fromCharCode(x),_=v.toUpperCase();if(_!==v){var E=s.charCodeToOptimizedIndex(_.charCodeAt(0));g[E]=E}else{var M=v.toLowerCase();if(M!==v){var E=s.charCodeToOptimizedIndex(M.charCodeAt(0));g[E]=E}}}function d(x,g){return i.find(x.value,function(v){if(typeof v=="number")return i.contains(g,v);var _=v;return i.find(g,function(E){return _.from<=E&&E<=_.to})!==void 0})}function f(x){return x.quantifier&&x.quantifier.atLeast===0?!0:x.value?i.isArray(x.value)?i.every(x.value,f):f(x.value):!1}var y=(function(x){t(g,x);function g(v){var _=x.call(this)||this;return _.targetCharCodes=v,_.found=!1,_}return g.prototype.visitChildren=function(v){if(this.found!==!0){switch(v.type){case"Lookahead":this.visitLookahead(v);return;case"NegativeLookahead":this.visitNegativeLookahead(v);return}x.prototype.visitChildren.call(this,v)}},g.prototype.visitCharacter=function(v){i.contains(this.targetCharCodes,v.value)&&(this.found=!0)},g.prototype.visitSet=function(v){v.complement?d(v,this.targetCharCodes)===void 0&&(this.found=!0):d(v,this.targetCharCodes)!==void 0&&(this.found=!0)},g})(r.BaseRegExpVisitor);function b(x,g){if(g instanceof RegExp){var v=n.getRegExpAst(g),_=new y(x);return _.visit(v),_.found}else return i.find(g,function(E){return i.contains(x,E.charCodeAt(0))})!==void 0}e.canMatchCharCode=b}),Pw=ri(e=>{"use strict";var t=e&&e.__extends||(function(){var U=function(ie,Ae){return U=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(Ue,Ge){Ue.__proto__=Ge}||function(Ue,Ge){for(var nt in Ge)Object.prototype.hasOwnProperty.call(Ge,nt)&&(Ue[nt]=Ge[nt])},U(ie,Ae)};return function(ie,Ae){if(typeof Ae!="function"&&Ae!==null)throw new TypeError("Class extends value "+String(Ae)+" is not a constructor or null");U(ie,Ae);function Ue(){this.constructor=ie}ie.prototype=Ae===null?Object.create(Ae):(Ue.prototype=Ae.prototype,new Ue)}})();Object.defineProperty(e,"__esModule",{value:!0}),e.charCodeToOptimizedIndex=e.minOptimizationVal=e.buildLineBreakIssueMessage=e.LineTerminatorOptimizedTester=e.isShortPattern=e.isCustomPattern=e.cloneEmptyGroups=e.performWarningRuntimeChecks=e.performRuntimeChecks=e.addStickyFlag=e.addStartOfInput=e.findUnreachablePatterns=e.findModesThatDoNotExist=e.findInvalidGroupType=e.findDuplicatePatterns=e.findUnsupportedFlags=e.findStartOfInputAnchor=e.findEmptyMatchRegExps=e.findEndOfInputAnchor=e.findInvalidPatterns=e.findMissingPatterns=e.validatePatterns=e.analyzeTokenTypes=e.enableSticky=e.disableSticky=e.SUPPORT_STICKY=e.MODES=e.DEFAULT_MODE=void 0;var r=$y(),i=yf(),n=Ai(),s=Tk(),a=Jy(),o="PATTERN";e.DEFAULT_MODE="defaultMode",e.MODES="modes",e.SUPPORT_STICKY=typeof new RegExp("(?:)").sticky=="boolean";function l(){e.SUPPORT_STICKY=!1}e.disableSticky=l;function c(){e.SUPPORT_STICKY=!0}e.enableSticky=c;function u(U,ie){ie=n.defaults(ie,{useSticky:e.SUPPORT_STICKY,debug:!1,safeMode:!1,positionTracking:"full",lineTerminatorCharacters:["\r",`
`],tracer:function(le,pe){return pe()}});var Ae=ie.tracer;Ae("initCharCodeToOptimizedIndexMap",function(){Se()});var Ue;Ae("Reject Lexer.NA",function(){Ue=n.reject(U,function(le){return le[o]===i.Lexer.NA})});var Ge=!1,nt;Ae("Transform Patterns",function(){Ge=!1,nt=n.map(Ue,function(le){var pe=le[o];if(n.isRegExp(pe)){var Le=pe.source;return Le.length===1&&Le!=="^"&&Le!=="$"&&Le!=="."&&!pe.ignoreCase?Le:Le.length===2&&Le[0]==="\\"&&!n.contains(["d","D","s","S","t","r","n","t","0","c","b","B","f","v","w","W"],Le[1])?Le[1]:ie.useSticky?se(pe):Z(pe)}else{if(n.isFunction(pe))return Ge=!0,{exec:pe};if(n.has(pe,"exec"))return Ge=!0,pe;if(typeof pe=="string"){if(pe.length===1)return pe;var He=pe.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),at=new RegExp(He);return ie.useSticky?se(at):Z(at)}else throw Error("non exhaustive match")}})});var Qe,ct,ye,dt,xt;Ae("misc mapping",function(){Qe=n.map(Ue,function(le){return le.tokenTypeIdx}),ct=n.map(Ue,function(le){var pe=le.GROUP;if(pe!==i.Lexer.SKIPPED){if(n.isString(pe))return pe;if(n.isUndefined(pe))return!1;throw Error("non exhaustive match")}}),ye=n.map(Ue,function(le){var pe=le.LONGER_ALT;if(pe){var Le=n.indexOf(Ue,pe);return Le}}),dt=n.map(Ue,function(le){return le.PUSH_MODE}),xt=n.map(Ue,function(le){return n.has(le,"POP_MODE")})});var Dt;Ae("Line Terminator Handling",function(){var le=de(ie.lineTerminatorCharacters);Dt=n.map(Ue,function(pe){return!1}),ie.positionTracking!=="onlyOffset"&&(Dt=n.map(Ue,function(pe){if(n.has(pe,"LINE_BREAKS"))return pe.LINE_BREAKS;if(ue(pe,le)===!1)return s.canMatchCharCode(le,pe.PATTERN)}))});var We,mt,it,st;Ae("Misc Mapping #2",function(){We=n.map(Ue,Fe),mt=n.map(nt,Pe),it=n.reduce(Ue,function(le,pe){var Le=pe.GROUP;return n.isString(Le)&&Le!==i.Lexer.SKIPPED&&(le[Le]=[]),le},{}),st=n.map(nt,function(le,pe){return{pattern:nt[pe],longerAlt:ye[pe],canLineTerminator:Dt[pe],isCustom:We[pe],short:mt[pe],group:ct[pe],push:dt[pe],pop:xt[pe],tokenTypeIdx:Qe[pe],tokenType:Ue[pe]}})});var oe=!0,F=[];return ie.safeMode||Ae("First Char Optimization",function(){F=n.reduce(Ue,function(le,pe,Le){if(typeof pe.PATTERN=="string"){var He=pe.PATTERN.charCodeAt(0),at=Be(He);Ie(le,at,st[Le])}else if(n.isArray(pe.START_CHARS_HINT)){var rt;n.forEach(pe.START_CHARS_HINT,function(Tt){var Mt=typeof Tt=="string"?Tt.charCodeAt(0):Tt,Ut=Be(Mt);rt!==Ut&&(rt=Ut,Ie(le,Ut,st[Le]))})}else if(n.isRegExp(pe.PATTERN))if(pe.PATTERN.unicode)oe=!1,ie.ensureOptimizations&&n.PRINT_ERROR(""+s.failedOptimizationPrefixMsg+("	Unable to analyze < "+pe.PATTERN.toString()+` > pattern.
`)+`	The regexp unicode flag is not currently supported by the regexp-to-ast library.
	This will disable the lexer's first char optimizations.
	For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE`);else{var ht=s.getOptimizedStartCodesIndices(pe.PATTERN,ie.ensureOptimizations);n.isEmpty(ht)&&(oe=!1),n.forEach(ht,function(Tt){Ie(le,Tt,st[Le])})}else ie.ensureOptimizations&&n.PRINT_ERROR(""+s.failedOptimizationPrefixMsg+("	TokenType: <"+pe.name+`> is using a custom token pattern without providing <start_chars_hint> parameter.
`)+`	This will disable the lexer's first char optimizations.
	For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE`),oe=!1;return le},[])}),Ae("ArrayPacking",function(){F=n.packArray(F)}),{emptyGroups:it,patternIdxToConfig:st,charCodeToPatternIdxToConfig:F,hasCustom:Ge,canBeOptimized:oe}}e.analyzeTokenTypes=u;function d(U,ie){var Ae=[],Ue=y(U);Ae=Ae.concat(Ue.errors);var Ge=b(Ue.valid),nt=Ge.valid;return Ae=Ae.concat(Ge.errors),Ae=Ae.concat(f(nt)),Ae=Ae.concat(k(nt)),Ae=Ae.concat(z(nt,ie)),Ae=Ae.concat(D(nt)),Ae}e.validatePatterns=d;function f(U){var ie=[],Ae=n.filter(U,function(Ue){return n.isRegExp(Ue[o])});return ie=ie.concat(g(Ae)),ie=ie.concat(E(Ae)),ie=ie.concat(M(Ae)),ie=ie.concat(P(Ae)),ie=ie.concat(v(Ae)),ie}function y(U){var ie=n.filter(U,function(Ge){return!n.has(Ge,o)}),Ae=n.map(ie,function(Ge){return{message:"Token Type: ->"+Ge.name+"<- missing static 'PATTERN' property",type:i.LexerDefinitionErrorType.MISSING_PATTERN,tokenTypes:[Ge]}}),Ue=n.difference(U,ie);return{errors:Ae,valid:Ue}}e.findMissingPatterns=y;function b(U){var ie=n.filter(U,function(Ge){var nt=Ge[o];return!n.isRegExp(nt)&&!n.isFunction(nt)&&!n.has(nt,"exec")&&!n.isString(nt)}),Ae=n.map(ie,function(Ge){return{message:"Token Type: ->"+Ge.name+"<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",type:i.LexerDefinitionErrorType.INVALID_PATTERN,tokenTypes:[Ge]}}),Ue=n.difference(U,ie);return{errors:Ae,valid:Ue}}e.findInvalidPatterns=b;var x=/[^\\][\$]/;function g(U){var ie=(function(Ge){t(nt,Ge);function nt(){var Qe=Ge!==null&&Ge.apply(this,arguments)||this;return Qe.found=!1,Qe}return nt.prototype.visitEndAnchor=function(Qe){this.found=!0},nt})(r.BaseRegExpVisitor),Ae=n.filter(U,function(Ge){var nt=Ge[o];try{var Qe=a.getRegExpAst(nt),ct=new ie;return ct.visit(Qe),ct.found}catch{return x.test(nt.source)}}),Ue=n.map(Ae,function(Ge){return{message:`Unexpected RegExp Anchor Error:
	Token Type: ->`+Ge.name+`<- static 'PATTERN' cannot contain end of input anchor '$'
	See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS	for details.`,type:i.LexerDefinitionErrorType.EOI_ANCHOR_FOUND,tokenTypes:[Ge]}});return Ue}e.findEndOfInputAnchor=g;function v(U){var ie=n.filter(U,function(Ue){var Ge=Ue[o];return Ge.test("")}),Ae=n.map(ie,function(Ue){return{message:"Token Type: ->"+Ue.name+"<- static 'PATTERN' must not match an empty string",type:i.LexerDefinitionErrorType.EMPTY_MATCH_PATTERN,tokenTypes:[Ue]}});return Ae}e.findEmptyMatchRegExps=v;var _=/[^\\[][\^]|^\^/;function E(U){var ie=(function(Ge){t(nt,Ge);function nt(){var Qe=Ge!==null&&Ge.apply(this,arguments)||this;return Qe.found=!1,Qe}return nt.prototype.visitStartAnchor=function(Qe){this.found=!0},nt})(r.BaseRegExpVisitor),Ae=n.filter(U,function(Ge){var nt=Ge[o];try{var Qe=a.getRegExpAst(nt),ct=new ie;return ct.visit(Qe),ct.found}catch{return _.test(nt.source)}}),Ue=n.map(Ae,function(Ge){return{message:`Unexpected RegExp Anchor Error:
	Token Type: ->`+Ge.name+`<- static 'PATTERN' cannot contain start of input anchor '^'
	See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS	for details.`,type:i.LexerDefinitionErrorType.SOI_ANCHOR_FOUND,tokenTypes:[Ge]}});return Ue}e.findStartOfInputAnchor=E;function M(U){var ie=n.filter(U,function(Ue){var Ge=Ue[o];return Ge instanceof RegExp&&(Ge.multiline||Ge.global)}),Ae=n.map(ie,function(Ue){return{message:"Token Type: ->"+Ue.name+"<- static 'PATTERN' may NOT contain global('g') or multiline('m')",type:i.LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND,tokenTypes:[Ue]}});return Ae}e.findUnsupportedFlags=M;function P(U){var ie=[],Ae=n.map(U,function(nt){return n.reduce(U,function(Qe,ct){return nt.PATTERN.source===ct.PATTERN.source&&!n.contains(ie,ct)&&ct.PATTERN!==i.Lexer.NA&&(ie.push(ct),Qe.push(ct)),Qe},[])});Ae=n.compact(Ae);var Ue=n.filter(Ae,function(nt){return nt.length>1}),Ge=n.map(Ue,function(nt){var Qe=n.map(nt,function(ye){return ye.name}),ct=n.first(nt).PATTERN;return{message:"The same RegExp pattern ->"+ct+"<-"+("has been used in all of the following Token Types: "+Qe.join(", ")+" <-"),type:i.LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND,tokenTypes:nt}});return Ge}e.findDuplicatePatterns=P;function k(U){var ie=n.filter(U,function(Ue){if(!n.has(Ue,"GROUP"))return!1;var Ge=Ue.GROUP;return Ge!==i.Lexer.SKIPPED&&Ge!==i.Lexer.NA&&!n.isString(Ge)}),Ae=n.map(ie,function(Ue){return{message:"Token Type: ->"+Ue.name+"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",type:i.LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND,tokenTypes:[Ue]}});return Ae}e.findInvalidGroupType=k;function z(U,ie){var Ae=n.filter(U,function(Ge){return Ge.PUSH_MODE!==void 0&&!n.contains(ie,Ge.PUSH_MODE)}),Ue=n.map(Ae,function(Ge){var nt="Token Type: ->"+Ge.name+"<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->"+Ge.PUSH_MODE+"<-which does not exist";return{message:nt,type:i.LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST,tokenTypes:[Ge]}});return Ue}e.findModesThatDoNotExist=z;function D(U){var ie=[],Ae=n.reduce(U,function(Ue,Ge,nt){var Qe=Ge.PATTERN;return Qe===i.Lexer.NA||(n.isString(Qe)?Ue.push({str:Qe,idx:nt,tokenType:Ge}):n.isRegExp(Qe)&&L(Qe)&&Ue.push({str:Qe.source,idx:nt,tokenType:Ge})),Ue},[]);return n.forEach(U,function(Ue,Ge){n.forEach(Ae,function(nt){var Qe=nt.str,ct=nt.idx,ye=nt.tokenType;if(Ge<ct&&I(Qe,Ue.PATTERN)){var dt="Token: ->"+ye.name+`<- can never be matched.
`+("Because it appears AFTER the Token Type ->"+Ue.name+"<-")+`in the lexer's definition.
See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;ie.push({message:dt,type:i.LexerDefinitionErrorType.UNREACHABLE_PATTERN,tokenTypes:[Ue,ye]})}})}),ie}e.findUnreachablePatterns=D;function I(U,ie){if(n.isRegExp(ie)){var Ae=ie.exec(U);return Ae!==null&&Ae.index===0}else{if(n.isFunction(ie))return ie(U,0,[],{});if(n.has(ie,"exec"))return ie.exec(U,0,[],{});if(typeof ie=="string")return ie===U;throw Error("non exhaustive match")}}function L(U){var ie=[".","\\","[","]","|","^","$","(",")","?","*","+","{"];return n.find(ie,function(Ae){return U.source.indexOf(Ae)!==-1})===void 0}function Z(U){var ie=U.ignoreCase?"i":"";return new RegExp("^(?:"+U.source+")",ie)}e.addStartOfInput=Z;function se(U){var ie=U.ignoreCase?"iy":"y";return new RegExp(""+U.source,ie)}e.addStickyFlag=se;function ce(U,ie,Ae){var Ue=[];return n.has(U,e.DEFAULT_MODE)||Ue.push({message:"A MultiMode Lexer cannot be initialized without a <"+e.DEFAULT_MODE+`> property in its definition
`,type:i.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE}),n.has(U,e.MODES)||Ue.push({message:"A MultiMode Lexer cannot be initialized without a <"+e.MODES+`> property in its definition
`,type:i.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY}),n.has(U,e.MODES)&&n.has(U,e.DEFAULT_MODE)&&!n.has(U.modes,U.defaultMode)&&Ue.push({message:"A MultiMode Lexer cannot be initialized with a "+e.DEFAULT_MODE+": <"+U.defaultMode+`>which does not exist
`,type:i.LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST}),n.has(U,e.MODES)&&n.forEach(U.modes,function(Ge,nt){n.forEach(Ge,function(Qe,ct){n.isUndefined(Qe)&&Ue.push({message:"A Lexer cannot be initialized using an undefined Token Type. Mode:"+("<"+nt+"> at index: <"+ct+`>
`),type:i.LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED})})}),Ue}e.performRuntimeChecks=ce;function fe(U,ie,Ae){var Ue=[],Ge=!1,nt=n.compact(n.flatten(n.mapValues(U.modes,function(ye){return ye}))),Qe=n.reject(nt,function(ye){return ye[o]===i.Lexer.NA}),ct=de(Ae);return ie&&n.forEach(Qe,function(ye){var dt=ue(ye,ct);if(dt!==!1){var xt=Te(ye,dt),Dt={message:xt,type:dt.issue,tokenType:ye};Ue.push(Dt)}else n.has(ye,"LINE_BREAKS")?ye.LINE_BREAKS===!0&&(Ge=!0):s.canMatchCharCode(ct,ye.PATTERN)&&(Ge=!0)}),ie&&!Ge&&Ue.push({message:`Warning: No LINE_BREAKS Found.
	This Lexer has been defined to track line and column information,
	But none of the Token Types can be identified as matching a line terminator.
	See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS
	for details.`,type:i.LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS}),Ue}e.performWarningRuntimeChecks=fe;function ze(U){var ie={},Ae=n.keys(U);return n.forEach(Ae,function(Ue){var Ge=U[Ue];if(n.isArray(Ge))ie[Ue]=[];else throw Error("non exhaustive match")}),ie}e.cloneEmptyGroups=ze;function Fe(U){var ie=U.PATTERN;if(n.isRegExp(ie))return!1;if(n.isFunction(ie)||n.has(ie,"exec"))return!0;if(n.isString(ie))return!1;throw Error("non exhaustive match")}e.isCustomPattern=Fe;function Pe(U){return n.isString(U)&&U.length===1?U.charCodeAt(0):!1}e.isShortPattern=Pe,e.LineTerminatorOptimizedTester={test:function(U){for(var ie=U.length,Ae=this.lastIndex;Ae<ie;Ae++){var Ue=U.charCodeAt(Ae);if(Ue===10)return this.lastIndex=Ae+1,!0;if(Ue===13)return U.charCodeAt(Ae+1)===10?this.lastIndex=Ae+2:this.lastIndex=Ae+1,!0}return!1},lastIndex:0};function ue(U,ie){if(n.has(U,"LINE_BREAKS"))return!1;if(n.isRegExp(U.PATTERN)){try{s.canMatchCharCode(ie,U.PATTERN)}catch(Ae){return{issue:i.LexerDefinitionErrorType.IDENTIFY_TERMINATOR,errMsg:Ae.message}}return!1}else{if(n.isString(U.PATTERN))return!1;if(Fe(U))return{issue:i.LexerDefinitionErrorType.CUSTOM_LINE_BREAK};throw Error("non exhaustive match")}}function Te(U,ie){if(ie.issue===i.LexerDefinitionErrorType.IDENTIFY_TERMINATOR)return`Warning: unable to identify line terminator usage in pattern.
`+("	The problem is in the <"+U.name+`> Token Type
`)+("	 Root cause: "+ie.errMsg+`.
`)+"	For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR";if(ie.issue===i.LexerDefinitionErrorType.CUSTOM_LINE_BREAK)return`Warning: A Custom Token Pattern should specify the <line_breaks> option.
`+("	The problem is in the <"+U.name+`> Token Type
`)+"	For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK";throw Error("non exhaustive match")}e.buildLineBreakIssueMessage=Te;function de(U){var ie=n.map(U,function(Ae){return n.isString(Ae)&&Ae.length>0?Ae.charCodeAt(0):Ae});return ie}function Ie(U,ie,Ae){U[ie]===void 0?U[ie]=[Ae]:U[ie].push(Ae)}e.minOptimizationVal=256;var Re=[];function Be(U){return U<e.minOptimizationVal?U:Re[U]}e.charCodeToOptimizedIndex=Be;function Se(){if(n.isEmpty(Re)){Re=new Array(65536);for(var U=0;U<65536;U++)Re[U]=U>255?255+~~(U/255):U}}}),pu=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.isTokenType=e.hasExtendingTokensTypesMapProperty=e.hasExtendingTokensTypesProperty=e.hasCategoriesProperty=e.hasShortKeyProperty=e.singleAssignCategoriesToksMap=e.assignCategoriesMapProp=e.assignCategoriesTokensProp=e.assignTokenDefaultProps=e.expandCategories=e.augmentTokenTypes=e.tokenIdxToClass=e.tokenShortNameIdx=e.tokenStructuredMatcherNoCategories=e.tokenStructuredMatcher=void 0;var t=Ai();function r(x,g){var v=x.tokenTypeIdx;return v===g.tokenTypeIdx?!0:g.isParent===!0&&g.categoryMatchesMap[v]===!0}e.tokenStructuredMatcher=r;function i(x,g){return x.tokenTypeIdx===g.tokenTypeIdx}e.tokenStructuredMatcherNoCategories=i,e.tokenShortNameIdx=1,e.tokenIdxToClass={};function n(x){var g=s(x);a(g),l(g),o(g),t.forEach(g,function(v){v.isParent=v.categoryMatches.length>0})}e.augmentTokenTypes=n;function s(x){for(var g=t.cloneArr(x),v=x,_=!0;_;){v=t.compact(t.flatten(t.map(v,function(M){return M.CATEGORIES})));var E=t.difference(v,g);g=g.concat(E),t.isEmpty(E)?_=!1:v=E}return g}e.expandCategories=s;function a(x){t.forEach(x,function(g){u(g)||(e.tokenIdxToClass[e.tokenShortNameIdx]=g,g.tokenTypeIdx=e.tokenShortNameIdx++),d(g)&&!t.isArray(g.CATEGORIES)&&(g.CATEGORIES=[g.CATEGORIES]),d(g)||(g.CATEGORIES=[]),f(g)||(g.categoryMatches=[]),y(g)||(g.categoryMatchesMap={})})}e.assignTokenDefaultProps=a;function o(x){t.forEach(x,function(g){g.categoryMatches=[],t.forEach(g.categoryMatchesMap,function(v,_){g.categoryMatches.push(e.tokenIdxToClass[_].tokenTypeIdx)})})}e.assignCategoriesTokensProp=o;function l(x){t.forEach(x,function(g){c([],g)})}e.assignCategoriesMapProp=l;function c(x,g){t.forEach(x,function(v){g.categoryMatchesMap[v.tokenTypeIdx]=!0}),t.forEach(g.CATEGORIES,function(v){var _=x.concat(g);t.contains(_,v)||c(_,v)})}e.singleAssignCategoriesToksMap=c;function u(x){return t.has(x,"tokenTypeIdx")}e.hasShortKeyProperty=u;function d(x){return t.has(x,"CATEGORIES")}e.hasCategoriesProperty=d;function f(x){return t.has(x,"categoryMatches")}e.hasExtendingTokensTypesProperty=f;function y(x){return t.has(x,"categoryMatchesMap")}e.hasExtendingTokensTypesMapProperty=y;function b(x){return t.has(x,"tokenTypeIdx")}e.isTokenType=b}),Iw=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.defaultLexerErrorProvider=void 0,e.defaultLexerErrorProvider={buildUnableToPopLexerModeMessage:function(t){return"Unable to pop Lexer Mode after encountering Token ->"+t.image+"<- The Mode Stack is empty"},buildUnexpectedCharactersMessage:function(t,r,i,n,s){return"unexpected character: ->"+t.charAt(r)+"<- at offset: "+r+","+(" skipped "+i+" characters.")}}}),yf=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Lexer=e.LexerDefinitionErrorType=void 0;var t=Pw(),r=Ai(),i=pu(),n=Iw(),s=Jy(),a;(function(c){c[c.MISSING_PATTERN=0]="MISSING_PATTERN",c[c.INVALID_PATTERN=1]="INVALID_PATTERN",c[c.EOI_ANCHOR_FOUND=2]="EOI_ANCHOR_FOUND",c[c.UNSUPPORTED_FLAGS_FOUND=3]="UNSUPPORTED_FLAGS_FOUND",c[c.DUPLICATE_PATTERNS_FOUND=4]="DUPLICATE_PATTERNS_FOUND",c[c.INVALID_GROUP_TYPE_FOUND=5]="INVALID_GROUP_TYPE_FOUND",c[c.PUSH_MODE_DOES_NOT_EXIST=6]="PUSH_MODE_DOES_NOT_EXIST",c[c.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE=7]="MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE",c[c.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY=8]="MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY",c[c.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST=9]="MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST",c[c.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED=10]="LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED",c[c.SOI_ANCHOR_FOUND=11]="SOI_ANCHOR_FOUND",c[c.EMPTY_MATCH_PATTERN=12]="EMPTY_MATCH_PATTERN",c[c.NO_LINE_BREAKS_FLAGS=13]="NO_LINE_BREAKS_FLAGS",c[c.UNREACHABLE_PATTERN=14]="UNREACHABLE_PATTERN",c[c.IDENTIFY_TERMINATOR=15]="IDENTIFY_TERMINATOR",c[c.CUSTOM_LINE_BREAK=16]="CUSTOM_LINE_BREAK"})(a=e.LexerDefinitionErrorType||(e.LexerDefinitionErrorType={}));var o={deferDefinitionErrorsHandling:!1,positionTracking:"full",lineTerminatorsPattern:/\n|\r\n?/g,lineTerminatorCharacters:[`
`,"\r"],ensureOptimizations:!1,safeMode:!1,errorMessageProvider:n.defaultLexerErrorProvider,traceInitPerf:!1,skipValidations:!1};Object.freeze(o);var l=(function(){function c(u,d){var f=this;if(d===void 0&&(d=o),this.lexerDefinition=u,this.lexerDefinitionErrors=[],this.lexerDefinitionWarning=[],this.patternIdxToConfig={},this.charCodeToPatternIdxToConfig={},this.modes=[],this.emptyGroups={},this.config=void 0,this.trackStartLines=!0,this.trackEndLines=!0,this.hasCustom=!1,this.canModeBeOptimized={},typeof d=="boolean")throw Error(`The second argument to the Lexer constructor is now an ILexerConfig Object.
a boolean 2nd argument is no longer supported`);this.config=r.merge(o,d);var y=this.config.traceInitPerf;y===!0?(this.traceInitMaxIdent=1/0,this.traceInitPerf=!0):typeof y=="number"&&(this.traceInitMaxIdent=y,this.traceInitPerf=!0),this.traceInitIndent=-1,this.TRACE_INIT("Lexer Constructor",function(){var b,x=!0;f.TRACE_INIT("Lexer Config handling",function(){if(f.config.lineTerminatorsPattern===o.lineTerminatorsPattern)f.config.lineTerminatorsPattern=t.LineTerminatorOptimizedTester;else if(f.config.lineTerminatorCharacters===o.lineTerminatorCharacters)throw Error(`Error: Missing <lineTerminatorCharacters> property on the Lexer config.
	For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS`);if(d.safeMode&&d.ensureOptimizations)throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.');f.trackStartLines=/full|onlyStart/i.test(f.config.positionTracking),f.trackEndLines=/full/i.test(f.config.positionTracking),r.isArray(u)?(b={modes:{}},b.modes[t.DEFAULT_MODE]=r.cloneArr(u),b[t.DEFAULT_MODE]=t.DEFAULT_MODE):(x=!1,b=r.cloneObj(u))}),f.config.skipValidations===!1&&(f.TRACE_INIT("performRuntimeChecks",function(){f.lexerDefinitionErrors=f.lexerDefinitionErrors.concat(t.performRuntimeChecks(b,f.trackStartLines,f.config.lineTerminatorCharacters))}),f.TRACE_INIT("performWarningRuntimeChecks",function(){f.lexerDefinitionWarning=f.lexerDefinitionWarning.concat(t.performWarningRuntimeChecks(b,f.trackStartLines,f.config.lineTerminatorCharacters))})),b.modes=b.modes?b.modes:{},r.forEach(b.modes,function(E,M){b.modes[M]=r.reject(E,function(P){return r.isUndefined(P)})});var g=r.keys(b.modes);if(r.forEach(b.modes,function(E,M){f.TRACE_INIT("Mode: <"+M+"> processing",function(){if(f.modes.push(M),f.config.skipValidations===!1&&f.TRACE_INIT("validatePatterns",function(){f.lexerDefinitionErrors=f.lexerDefinitionErrors.concat(t.validatePatterns(E,g))}),r.isEmpty(f.lexerDefinitionErrors)){i.augmentTokenTypes(E);var P;f.TRACE_INIT("analyzeTokenTypes",function(){P=t.analyzeTokenTypes(E,{lineTerminatorCharacters:f.config.lineTerminatorCharacters,positionTracking:d.positionTracking,ensureOptimizations:d.ensureOptimizations,safeMode:d.safeMode,tracer:f.TRACE_INIT.bind(f)})}),f.patternIdxToConfig[M]=P.patternIdxToConfig,f.charCodeToPatternIdxToConfig[M]=P.charCodeToPatternIdxToConfig,f.emptyGroups=r.merge(f.emptyGroups,P.emptyGroups),f.hasCustom=P.hasCustom||f.hasCustom,f.canModeBeOptimized[M]=P.canBeOptimized}})}),f.defaultMode=b.defaultMode,!r.isEmpty(f.lexerDefinitionErrors)&&!f.config.deferDefinitionErrorsHandling){var v=r.map(f.lexerDefinitionErrors,function(E){return E.message}),_=v.join(`-----------------------
`);throw new Error(`Errors detected in definition of Lexer:
`+_)}r.forEach(f.lexerDefinitionWarning,function(E){r.PRINT_WARNING(E.message)}),f.TRACE_INIT("Choosing sub-methods implementations",function(){if(t.SUPPORT_STICKY?(f.chopInput=r.IDENTITY,f.match=f.matchWithTest):(f.updateLastIndex=r.NOOP,f.match=f.matchWithExec),x&&(f.handleModes=r.NOOP),f.trackStartLines===!1&&(f.computeNewColumn=r.IDENTITY),f.trackEndLines===!1&&(f.updateTokenEndLineColumnLocation=r.NOOP),/full/i.test(f.config.positionTracking))f.createTokenInstance=f.createFullToken;else if(/onlyStart/i.test(f.config.positionTracking))f.createTokenInstance=f.createStartOnlyToken;else if(/onlyOffset/i.test(f.config.positionTracking))f.createTokenInstance=f.createOffsetOnlyToken;else throw Error('Invalid <positionTracking> config option: "'+f.config.positionTracking+'"');f.hasCustom?(f.addToken=f.addTokenUsingPush,f.handlePayload=f.handlePayloadWithCustom):(f.addToken=f.addTokenUsingMemberAccess,f.handlePayload=f.handlePayloadNoCustom)}),f.TRACE_INIT("Failed Optimization Warnings",function(){var E=r.reduce(f.canModeBeOptimized,function(M,P,k){return P===!1&&M.push(k),M},[]);if(d.ensureOptimizations&&!r.isEmpty(E))throw Error("Lexer Modes: < "+E.join(", ")+` > cannot be optimized.
	 Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode.
	 Or inspect the console log for details on how to resolve these issues.`)}),f.TRACE_INIT("clearRegExpParserCache",function(){s.clearRegExpParserCache()}),f.TRACE_INIT("toFastProperties",function(){r.toFastProperties(f)})})}return c.prototype.tokenize=function(u,d){if(d===void 0&&(d=this.defaultMode),!r.isEmpty(this.lexerDefinitionErrors)){var f=r.map(this.lexerDefinitionErrors,function(x){return x.message}),y=f.join(`-----------------------
`);throw new Error(`Unable to Tokenize because Errors detected in definition of Lexer:
`+y)}var b=this.tokenizeInternal(u,d);return b},c.prototype.tokenizeInternal=function(u,d){var f=this,y,b,x,g,v,_,E,M,P,k,z,D,I,L,Z,se=u,ce=se.length,fe=0,ze=0,Fe=this.hasCustom?0:Math.floor(u.length/10),Pe=new Array(Fe),ue=[],Te=this.trackStartLines?1:void 0,de=this.trackStartLines?1:void 0,Ie=t.cloneEmptyGroups(this.emptyGroups),Re=this.trackStartLines,Be=this.config.lineTerminatorsPattern,Se=0,U=[],ie=[],Ae=[],Ue=[];Object.freeze(Ue);var Ge=void 0;function nt(){return U}function Qe(Tt){var Mt=t.charCodeToOptimizedIndex(Tt),Ut=ie[Mt];return Ut===void 0?Ue:Ut}var ct=function(Tt){if(Ae.length===1&&Tt.tokenType.PUSH_MODE===void 0){var Mt=f.config.errorMessageProvider.buildUnableToPopLexerModeMessage(Tt);ue.push({offset:Tt.startOffset,line:Tt.startLine!==void 0?Tt.startLine:void 0,column:Tt.startColumn!==void 0?Tt.startColumn:void 0,length:Tt.image.length,message:Mt})}else{Ae.pop();var Ut=r.last(Ae);U=f.patternIdxToConfig[Ut],ie=f.charCodeToPatternIdxToConfig[Ut],Se=U.length;var Kt=f.canModeBeOptimized[Ut]&&f.config.safeMode===!1;ie&&Kt?Ge=Qe:Ge=nt}};function ye(Tt){Ae.push(Tt),ie=this.charCodeToPatternIdxToConfig[Tt],U=this.patternIdxToConfig[Tt],Se=U.length,Se=U.length;var Mt=this.canModeBeOptimized[Tt]&&this.config.safeMode===!1;ie&&Mt?Ge=Qe:Ge=nt}ye.call(this,d);for(var dt;fe<ce;){v=null;var xt=se.charCodeAt(fe),Dt=Ge(xt),We=Dt.length;for(y=0;y<We;y++){dt=Dt[y];var mt=dt.pattern;_=null;var it=dt.short;if(it!==!1?xt===it&&(v=mt):dt.isCustom===!0?(Z=mt.exec(se,fe,Pe,Ie),Z!==null?(v=Z[0],Z.payload!==void 0&&(_=Z.payload)):v=null):(this.updateLastIndex(mt,fe),v=this.match(mt,u,fe)),v!==null){if(g=dt.longerAlt,g!==void 0){var st=U[g],oe=st.pattern;E=null,st.isCustom===!0?(Z=oe.exec(se,fe,Pe,Ie),Z!==null?(x=Z[0],Z.payload!==void 0&&(E=Z.payload)):x=null):(this.updateLastIndex(oe,fe),x=this.match(oe,u,fe)),x&&x.length>v.length&&(v=x,_=E,dt=st)}break}}if(v!==null){if(M=v.length,P=dt.group,P!==void 0&&(k=dt.tokenTypeIdx,z=this.createTokenInstance(v,fe,k,dt.tokenType,Te,de,M),this.handlePayload(z,_),P===!1?ze=this.addToken(Pe,ze,z):Ie[P].push(z)),u=this.chopInput(u,M),fe=fe+M,de=this.computeNewColumn(de,M),Re===!0&&dt.canLineTerminator===!0){var F=0,le=void 0,pe=void 0;Be.lastIndex=0;do le=Be.test(v),le===!0&&(pe=Be.lastIndex-1,F++);while(le===!0);F!==0&&(Te=Te+F,de=M-pe,this.updateTokenEndLineColumnLocation(z,P,pe,F,Te,de,M))}this.handleModes(dt,ct,ye,z)}else{for(var Le=fe,He=Te,at=de,rt=!1;!rt&&fe<ce;)for(I=se.charCodeAt(fe),u=this.chopInput(u,1),fe++,b=0;b<Se;b++){var ht=U[b],mt=ht.pattern,it=ht.short;if(it!==!1?se.charCodeAt(fe)===it&&(rt=!0):ht.isCustom===!0?rt=mt.exec(se,fe,Pe,Ie)!==null:(this.updateLastIndex(mt,fe),rt=mt.exec(u)!==null),rt===!0)break}D=fe-Le,L=this.config.errorMessageProvider.buildUnexpectedCharactersMessage(se,Le,D,He,at),ue.push({offset:Le,line:He,column:at,length:D,message:L})}}return this.hasCustom||(Pe.length=ze),{tokens:Pe,groups:Ie,errors:ue}},c.prototype.handleModes=function(u,d,f,y){if(u.pop===!0){var b=u.push;d(y),b!==void 0&&f.call(this,b)}else u.push!==void 0&&f.call(this,u.push)},c.prototype.chopInput=function(u,d){return u.substring(d)},c.prototype.updateLastIndex=function(u,d){u.lastIndex=d},c.prototype.updateTokenEndLineColumnLocation=function(u,d,f,y,b,x,g){var v,_;d!==void 0&&(v=f===g-1,_=v?-1:0,y===1&&v===!0||(u.endLine=b+_,u.endColumn=x-1+-_))},c.prototype.computeNewColumn=function(u,d){return u+d},c.prototype.createTokenInstance=function(){for(var u=[],d=0;d<arguments.length;d++)u[d]=arguments[d];return null},c.prototype.createOffsetOnlyToken=function(u,d,f,y){return{image:u,startOffset:d,tokenTypeIdx:f,tokenType:y}},c.prototype.createStartOnlyToken=function(u,d,f,y,b,x){return{image:u,startOffset:d,startLine:b,startColumn:x,tokenTypeIdx:f,tokenType:y}},c.prototype.createFullToken=function(u,d,f,y,b,x,g){return{image:u,startOffset:d,endOffset:d+g-1,startLine:b,endLine:b,startColumn:x,endColumn:x+g-1,tokenTypeIdx:f,tokenType:y}},c.prototype.addToken=function(u,d,f){return 666},c.prototype.addTokenUsingPush=function(u,d,f){return u.push(f),d},c.prototype.addTokenUsingMemberAccess=function(u,d,f){return u[d]=f,d++,d},c.prototype.handlePayload=function(u,d){},c.prototype.handlePayloadNoCustom=function(u,d){},c.prototype.handlePayloadWithCustom=function(u,d){d!==null&&(u.payload=d)},c.prototype.match=function(u,d,f){return null},c.prototype.matchWithTest=function(u,d,f){var y=u.test(d);return y===!0?d.substring(f,u.lastIndex):null},c.prototype.matchWithExec=function(u,d){var f=u.exec(d);return f!==null?f[0]:f},c.prototype.TRACE_INIT=function(u,d){if(this.traceInitPerf===!0){this.traceInitIndent++;var f=new Array(this.traceInitIndent+1).join("	");this.traceInitIndent<this.traceInitMaxIdent&&console.log(f+"--> <"+u+">");var y=r.timer(d),b=y.time,x=y.value,g=b>10?console.warn:console.log;return this.traceInitIndent<this.traceInitMaxIdent&&g(f+"<-- <"+u+"> time: "+b+"ms"),this.traceInitIndent--,x}else return d()},c.SKIPPED="This marks a skipped Token pattern, this means each token identified by it willbe consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace.",c.NA=/NOT_APPLICABLE/,c})();e.Lexer=l}),gl=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.tokenMatcher=e.createTokenInstance=e.EOF=e.createToken=e.hasTokenLabel=e.tokenName=e.tokenLabel=void 0;var t=Ai(),r=yf(),i=pu();function n(M){return a(M)?M.LABEL:M.name}e.tokenLabel=n;function s(M){return M.name}e.tokenName=s;function a(M){return t.isString(M.LABEL)&&M.LABEL!==""}e.hasTokenLabel=a;var o="parent",l="categories",c="label",u="group",d="push_mode",f="pop_mode",y="longer_alt",b="line_breaks",x="start_chars_hint";function g(M){return v(M)}e.createToken=g;function v(M){var P=M.pattern,k={};if(k.name=M.name,t.isUndefined(P)||(k.PATTERN=P),t.has(M,o))throw`The parent property is no longer supported.
See: https://github.com/chevrotain/chevrotain/issues/564#issuecomment-349062346 for details.`;return t.has(M,l)&&(k.CATEGORIES=M[l]),i.augmentTokenTypes([k]),t.has(M,c)&&(k.LABEL=M[c]),t.has(M,u)&&(k.GROUP=M[u]),t.has(M,f)&&(k.POP_MODE=M[f]),t.has(M,d)&&(k.PUSH_MODE=M[d]),t.has(M,y)&&(k.LONGER_ALT=M[y]),t.has(M,b)&&(k.LINE_BREAKS=M[b]),t.has(M,x)&&(k.START_CHARS_HINT=M[x]),k}e.EOF=g({name:"EOF",pattern:r.Lexer.NA}),i.augmentTokenTypes([e.EOF]);function _(M,P,k,z,D,I,L,Z){return{image:P,startOffset:k,endOffset:z,startLine:D,endLine:I,startColumn:L,endColumn:Z,tokenTypeIdx:M.tokenTypeIdx,tokenType:M}}e.createTokenInstance=_;function E(M,P){return i.tokenStructuredMatcher(M,P)}e.tokenMatcher=E}),xs=ri(e=>{"use strict";var t=e&&e.__extends||(function(){var v=function(_,E){return v=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(M,P){M.__proto__=P}||function(M,P){for(var k in P)Object.prototype.hasOwnProperty.call(P,k)&&(M[k]=P[k])},v(_,E)};return function(_,E){if(typeof E!="function"&&E!==null)throw new TypeError("Class extends value "+String(E)+" is not a constructor or null");v(_,E);function M(){this.constructor=_}_.prototype=E===null?Object.create(E):(M.prototype=E.prototype,new M)}})();Object.defineProperty(e,"__esModule",{value:!0}),e.serializeProduction=e.serializeGrammar=e.Terminal=e.Alternation=e.RepetitionWithSeparator=e.Repetition=e.RepetitionMandatoryWithSeparator=e.RepetitionMandatory=e.Option=e.Alternative=e.Rule=e.NonTerminal=e.AbstractProduction=void 0;var r=Ai(),i=gl(),n=(function(){function v(_){this._definition=_}return Object.defineProperty(v.prototype,"definition",{get:function(){return this._definition},set:function(_){this._definition=_},enumerable:!1,configurable:!0}),v.prototype.accept=function(_){_.visit(this),r.forEach(this.definition,function(E){E.accept(_)})},v})();e.AbstractProduction=n;var s=(function(v){t(_,v);function _(E){var M=v.call(this,[])||this;return M.idx=1,r.assign(M,r.pick(E,function(P){return P!==void 0})),M}return Object.defineProperty(_.prototype,"definition",{get:function(){return this.referencedRule!==void 0?this.referencedRule.definition:[]},set:function(E){},enumerable:!1,configurable:!0}),_.prototype.accept=function(E){E.visit(this)},_})(n);e.NonTerminal=s;var a=(function(v){t(_,v);function _(E){var M=v.call(this,E.definition)||this;return M.orgText="",r.assign(M,r.pick(E,function(P){return P!==void 0})),M}return _})(n);e.Rule=a;var o=(function(v){t(_,v);function _(E){var M=v.call(this,E.definition)||this;return M.ignoreAmbiguities=!1,r.assign(M,r.pick(E,function(P){return P!==void 0})),M}return _})(n);e.Alternative=o;var l=(function(v){t(_,v);function _(E){var M=v.call(this,E.definition)||this;return M.idx=1,r.assign(M,r.pick(E,function(P){return P!==void 0})),M}return _})(n);e.Option=l;var c=(function(v){t(_,v);function _(E){var M=v.call(this,E.definition)||this;return M.idx=1,r.assign(M,r.pick(E,function(P){return P!==void 0})),M}return _})(n);e.RepetitionMandatory=c;var u=(function(v){t(_,v);function _(E){var M=v.call(this,E.definition)||this;return M.idx=1,r.assign(M,r.pick(E,function(P){return P!==void 0})),M}return _})(n);e.RepetitionMandatoryWithSeparator=u;var d=(function(v){t(_,v);function _(E){var M=v.call(this,E.definition)||this;return M.idx=1,r.assign(M,r.pick(E,function(P){return P!==void 0})),M}return _})(n);e.Repetition=d;var f=(function(v){t(_,v);function _(E){var M=v.call(this,E.definition)||this;return M.idx=1,r.assign(M,r.pick(E,function(P){return P!==void 0})),M}return _})(n);e.RepetitionWithSeparator=f;var y=(function(v){t(_,v);function _(E){var M=v.call(this,E.definition)||this;return M.idx=1,M.ignoreAmbiguities=!1,M.hasPredicates=!1,r.assign(M,r.pick(E,function(P){return P!==void 0})),M}return Object.defineProperty(_.prototype,"definition",{get:function(){return this._definition},set:function(E){this._definition=E},enumerable:!1,configurable:!0}),_})(n);e.Alternation=y;var b=(function(){function v(_){this.idx=1,r.assign(this,r.pick(_,function(E){return E!==void 0}))}return v.prototype.accept=function(_){_.visit(this)},v})();e.Terminal=b;function x(v){return r.map(v,g)}e.serializeGrammar=x;function g(v){function _(P){return r.map(P,g)}if(v instanceof s)return{type:"NonTerminal",name:v.nonTerminalName,idx:v.idx};if(v instanceof o)return{type:"Alternative",definition:_(v.definition)};if(v instanceof l)return{type:"Option",idx:v.idx,definition:_(v.definition)};if(v instanceof c)return{type:"RepetitionMandatory",idx:v.idx,definition:_(v.definition)};if(v instanceof u)return{type:"RepetitionMandatoryWithSeparator",idx:v.idx,separator:g(new b({terminalType:v.separator})),definition:_(v.definition)};if(v instanceof f)return{type:"RepetitionWithSeparator",idx:v.idx,separator:g(new b({terminalType:v.separator})),definition:_(v.definition)};if(v instanceof d)return{type:"Repetition",idx:v.idx,definition:_(v.definition)};if(v instanceof y)return{type:"Alternation",idx:v.idx,definition:_(v.definition)};if(v instanceof b){var E={type:"Terminal",name:v.terminalType.name,label:i.tokenLabel(v.terminalType),idx:v.idx},M=v.terminalType.PATTERN;return v.terminalType.PATTERN&&(E.pattern=r.isRegExp(M)?M.source:M),E}else{if(v instanceof a)return{type:"Rule",name:v.name,orgText:v.orgText,definition:_(v.definition)};throw Error("non exhaustive match")}}e.serializeProduction=g}),Qy=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.RestWalker=void 0;var t=Ai(),r=xs(),i=(function(){function s(){}return s.prototype.walk=function(a,o){var l=this;o===void 0&&(o=[]),t.forEach(a.definition,function(c,u){var d=t.drop(a.definition,u+1);if(c instanceof r.NonTerminal)l.walkProdRef(c,d,o);else if(c instanceof r.Terminal)l.walkTerminal(c,d,o);else if(c instanceof r.Alternative)l.walkFlat(c,d,o);else if(c instanceof r.Option)l.walkOption(c,d,o);else if(c instanceof r.RepetitionMandatory)l.walkAtLeastOne(c,d,o);else if(c instanceof r.RepetitionMandatoryWithSeparator)l.walkAtLeastOneSep(c,d,o);else if(c instanceof r.RepetitionWithSeparator)l.walkManySep(c,d,o);else if(c instanceof r.Repetition)l.walkMany(c,d,o);else if(c instanceof r.Alternation)l.walkOr(c,d,o);else throw Error("non exhaustive match")})},s.prototype.walkTerminal=function(a,o,l){},s.prototype.walkProdRef=function(a,o,l){},s.prototype.walkFlat=function(a,o,l){var c=o.concat(l);this.walk(a,c)},s.prototype.walkOption=function(a,o,l){var c=o.concat(l);this.walk(a,c)},s.prototype.walkAtLeastOne=function(a,o,l){var c=[new r.Option({definition:a.definition})].concat(o,l);this.walk(a,c)},s.prototype.walkAtLeastOneSep=function(a,o,l){var c=n(a,o,l);this.walk(a,c)},s.prototype.walkMany=function(a,o,l){var c=[new r.Option({definition:a.definition})].concat(o,l);this.walk(a,c)},s.prototype.walkManySep=function(a,o,l){var c=n(a,o,l);this.walk(a,c)},s.prototype.walkOr=function(a,o,l){var c=this,u=o.concat(l);t.forEach(a.definition,function(d){var f=new r.Alternative({definition:[d]});c.walk(f,u)})},s})();e.RestWalker=i;function n(s,a,o){var l=[new r.Option({definition:[new r.Terminal({terminalType:s.separator})].concat(s.definition)})],c=l.concat(a,o);return c}}),fu=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.GAstVisitor=void 0;var t=xs(),r=(function(){function i(){}return i.prototype.visit=function(n){var s=n;switch(s.constructor){case t.NonTerminal:return this.visitNonTerminal(s);case t.Alternative:return this.visitAlternative(s);case t.Option:return this.visitOption(s);case t.RepetitionMandatory:return this.visitRepetitionMandatory(s);case t.RepetitionMandatoryWithSeparator:return this.visitRepetitionMandatoryWithSeparator(s);case t.RepetitionWithSeparator:return this.visitRepetitionWithSeparator(s);case t.Repetition:return this.visitRepetition(s);case t.Alternation:return this.visitAlternation(s);case t.Terminal:return this.visitTerminal(s);case t.Rule:return this.visitRule(s);default:throw Error("non exhaustive match")}},i.prototype.visitNonTerminal=function(n){},i.prototype.visitAlternative=function(n){},i.prototype.visitOption=function(n){},i.prototype.visitRepetition=function(n){},i.prototype.visitRepetitionMandatory=function(n){},i.prototype.visitRepetitionMandatoryWithSeparator=function(n){},i.prototype.visitRepetitionWithSeparator=function(n){},i.prototype.visitAlternation=function(n){},i.prototype.visitTerminal=function(n){},i.prototype.visitRule=function(n){},i})();e.GAstVisitor=r}),vf=ri(e=>{"use strict";var t=e&&e.__extends||(function(){var f=function(y,b){return f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(x,g){x.__proto__=g}||function(x,g){for(var v in g)Object.prototype.hasOwnProperty.call(g,v)&&(x[v]=g[v])},f(y,b)};return function(y,b){if(typeof b!="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");f(y,b);function x(){this.constructor=y}y.prototype=b===null?Object.create(b):(x.prototype=b.prototype,new x)}})();Object.defineProperty(e,"__esModule",{value:!0}),e.collectMethods=e.DslMethodsCollectorVisitor=e.getProductionDslName=e.isBranchingProd=e.isOptionalProd=e.isSequenceProd=void 0;var r=Ai(),i=xs(),n=fu();function s(f){return f instanceof i.Alternative||f instanceof i.Option||f instanceof i.Repetition||f instanceof i.RepetitionMandatory||f instanceof i.RepetitionMandatoryWithSeparator||f instanceof i.RepetitionWithSeparator||f instanceof i.Terminal||f instanceof i.Rule}e.isSequenceProd=s;function a(f,y){y===void 0&&(y=[]);var b=f instanceof i.Option||f instanceof i.Repetition||f instanceof i.RepetitionWithSeparator;return b?!0:f instanceof i.Alternation?r.some(f.definition,function(x){return a(x,y)}):f instanceof i.NonTerminal&&r.contains(y,f)?!1:f instanceof i.AbstractProduction?(f instanceof i.NonTerminal&&y.push(f),r.every(f.definition,function(x){return a(x,y)})):!1}e.isOptionalProd=a;function o(f){return f instanceof i.Alternation}e.isBranchingProd=o;function l(f){if(f instanceof i.NonTerminal)return"SUBRULE";if(f instanceof i.Option)return"OPTION";if(f instanceof i.Alternation)return"OR";if(f instanceof i.RepetitionMandatory)return"AT_LEAST_ONE";if(f instanceof i.RepetitionMandatoryWithSeparator)return"AT_LEAST_ONE_SEP";if(f instanceof i.RepetitionWithSeparator)return"MANY_SEP";if(f instanceof i.Repetition)return"MANY";if(f instanceof i.Terminal)return"CONSUME";throw Error("non exhaustive match")}e.getProductionDslName=l;var c=(function(f){t(y,f);function y(){var b=f!==null&&f.apply(this,arguments)||this;return b.separator="-",b.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]},b}return y.prototype.reset=function(){this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}},y.prototype.visitTerminal=function(b){var x=b.terminalType.name+this.separator+"Terminal";r.has(this.dslMethods,x)||(this.dslMethods[x]=[]),this.dslMethods[x].push(b)},y.prototype.visitNonTerminal=function(b){var x=b.nonTerminalName+this.separator+"Terminal";r.has(this.dslMethods,x)||(this.dslMethods[x]=[]),this.dslMethods[x].push(b)},y.prototype.visitOption=function(b){this.dslMethods.option.push(b)},y.prototype.visitRepetitionWithSeparator=function(b){this.dslMethods.repetitionWithSeparator.push(b)},y.prototype.visitRepetitionMandatory=function(b){this.dslMethods.repetitionMandatory.push(b)},y.prototype.visitRepetitionMandatoryWithSeparator=function(b){this.dslMethods.repetitionMandatoryWithSeparator.push(b)},y.prototype.visitRepetition=function(b){this.dslMethods.repetition.push(b)},y.prototype.visitAlternation=function(b){this.dslMethods.alternation.push(b)},y})(n.GAstVisitor);e.DslMethodsCollectorVisitor=c;var u=new c;function d(f){u.reset(),f.accept(u);var y=u.dslMethods;return u.reset(),y}e.collectMethods=d}),Nw=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.firstForTerminal=e.firstForBranching=e.firstForSequence=e.first=void 0;var t=Ai(),r=xs(),i=vf();function n(l){if(l instanceof r.NonTerminal)return n(l.referencedRule);if(l instanceof r.Terminal)return o(l);if(i.isSequenceProd(l))return s(l);if(i.isBranchingProd(l))return a(l);throw Error("non exhaustive match")}e.first=n;function s(l){for(var c=[],u=l.definition,d=0,f=u.length>d,y,b=!0;f&&b;)y=u[d],b=i.isOptionalProd(y),c=c.concat(n(y)),d=d+1,f=u.length>d;return t.uniq(c)}e.firstForSequence=s;function a(l){var c=t.map(l.definition,function(u){return n(u)});return t.uniq(t.flatten(c))}e.firstForBranching=a;function o(l){return[l.terminalType]}e.firstForTerminal=o}),Lw=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.IN=void 0,e.IN="_~IN~_"}),Ck=ri(e=>{"use strict";var t=e&&e.__extends||(function(){var d=function(f,y){return d=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,x){b.__proto__=x}||function(b,x){for(var g in x)Object.prototype.hasOwnProperty.call(x,g)&&(b[g]=x[g])},d(f,y)};return function(f,y){if(typeof y!="function"&&y!==null)throw new TypeError("Class extends value "+String(y)+" is not a constructor or null");d(f,y);function b(){this.constructor=f}f.prototype=y===null?Object.create(y):(b.prototype=y.prototype,new b)}})();Object.defineProperty(e,"__esModule",{value:!0}),e.buildInProdFollowPrefix=e.buildBetweenProdsFollowPrefix=e.computeAllProdsFollows=e.ResyncFollowsWalker=void 0;var r=Qy(),i=Nw(),n=Ai(),s=Lw(),a=xs(),o=(function(d){t(f,d);function f(y){var b=d.call(this)||this;return b.topProd=y,b.follows={},b}return f.prototype.startWalking=function(){return this.walk(this.topProd),this.follows},f.prototype.walkTerminal=function(y,b,x){},f.prototype.walkProdRef=function(y,b,x){var g=c(y.referencedRule,y.idx)+this.topProd.name,v=b.concat(x),_=new a.Alternative({definition:v}),E=i.first(_);this.follows[g]=E},f})(r.RestWalker);e.ResyncFollowsWalker=o;function l(d){var f={};return n.forEach(d,function(y){var b=new o(y).startWalking();n.assign(f,b)}),f}e.computeAllProdsFollows=l;function c(d,f){return d.name+f+s.IN}e.buildBetweenProdsFollowPrefix=c;function u(d){var f=d.terminalType.name;return f+d.idx+s.IN}e.buildInProdFollowPrefix=u}),xf=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.defaultGrammarValidatorErrorProvider=e.defaultGrammarResolverErrorProvider=e.defaultParserErrorProvider=void 0;var t=gl(),r=Ai(),i=Ai(),n=xs(),s=vf();e.defaultParserErrorProvider={buildMismatchTokenMessage:function(a){var o=a.expected,l=a.actual,c=a.previous,u=a.ruleName,d=t.hasTokenLabel(o),f=d?"--> "+t.tokenLabel(o)+" <--":"token of type --> "+o.name+" <--",y="Expecting "+f+" but found --> '"+l.image+"' <--";return y},buildNotAllInputParsedMessage:function(a){var o=a.firstRedundant,l=a.ruleName;return"Redundant input, expecting EOF but found: "+o.image},buildNoViableAltMessage:function(a){var o=a.expectedPathsPerAlt,l=a.actual,c=a.previous,u=a.customUserDescription,d=a.ruleName,f="Expecting: ",y=i.first(l).image,b=`
but found: '`+y+"'";if(u)return f+u+b;var x=i.reduce(o,function(E,M){return E.concat(M)},[]),g=i.map(x,function(E){return"["+i.map(E,function(M){return t.tokenLabel(M)}).join(", ")+"]"}),v=i.map(g,function(E,M){return"  "+(M+1)+". "+E}),_=`one of these possible Token sequences:
`+v.join(`
`);return f+_+b},buildEarlyExitMessage:function(a){var o=a.expectedIterationPaths,l=a.actual,c=a.customUserDescription,u=a.ruleName,d="Expecting: ",f=i.first(l).image,y=`
but found: '`+f+"'";if(c)return d+c+y;var b=i.map(o,function(g){return"["+i.map(g,function(v){return t.tokenLabel(v)}).join(",")+"]"}),x=`expecting at least one iteration which starts with one of these possible Token sequences::
  `+("<"+b.join(" ,")+">");return d+x+y}},Object.freeze(e.defaultParserErrorProvider),e.defaultGrammarResolverErrorProvider={buildRuleNotFoundError:function(a,o){var l="Invalid grammar, reference to a rule which is not defined: ->"+o.nonTerminalName+`<-
inside top level rule: ->`+a.name+"<-";return l}},e.defaultGrammarValidatorErrorProvider={buildDuplicateFoundError:function(a,o){function l(g){return g instanceof n.Terminal?g.terminalType.name:g instanceof n.NonTerminal?g.nonTerminalName:""}var c=a.name,u=i.first(o),d=u.idx,f=s.getProductionDslName(u),y=l(u),b=d>0,x="->"+f+(b?d:"")+"<- "+(y?"with argument: ->"+y+"<-":"")+`
                  appears more than once (`+o.length+" times) in the top level rule: ->"+c+`<-.
                  For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES
                  `;return x=x.replace(/[ \t]+/g," "),x=x.replace(/\s\s+/g,`
`),x},buildNamespaceConflictError:function(a){var o=`Namespace conflict found in grammar.
`+("The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <"+a.name+`>.
`)+`To resolve this make sure each Terminal and Non-Terminal names are unique
This is easy to accomplish by using the convention that Terminal names start with an uppercase letter
and Non-Terminal names start with a lower case letter.`;return o},buildAlternationPrefixAmbiguityError:function(a){var o=i.map(a.prefixPath,function(u){return t.tokenLabel(u)}).join(", "),l=a.alternation.idx===0?"":a.alternation.idx,c="Ambiguous alternatives: <"+a.ambiguityIndices.join(" ,")+`> due to common lookahead prefix
`+("in <OR"+l+"> inside <"+a.topLevelRule.name+`> Rule,
`)+("<"+o+`> may appears as a prefix path in all these alternatives.
`)+`See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX
For Further details.`;return c},buildAlternationAmbiguityError:function(a){var o=i.map(a.prefixPath,function(u){return t.tokenLabel(u)}).join(", "),l=a.alternation.idx===0?"":a.alternation.idx,c="Ambiguous Alternatives Detected: <"+a.ambiguityIndices.join(" ,")+"> in <OR"+l+">"+(" inside <"+a.topLevelRule.name+`> Rule,
`)+("<"+o+`> may appears as a prefix path in all these alternatives.
`);return c=c+`See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES
For Further details.`,c},buildEmptyRepetitionError:function(a){var o=s.getProductionDslName(a.repetition);a.repetition.idx!==0&&(o+=a.repetition.idx);var l="The repetition <"+o+"> within Rule <"+a.topLevelRule.name+`> can never consume any tokens.
This could lead to an infinite loop.`;return l},buildTokenNameError:function(a){return"deprecated"},buildEmptyAlternationError:function(a){var o="Ambiguous empty alternative: <"+(a.emptyChoiceIdx+1)+">"+(" in <OR"+a.alternation.idx+"> inside <"+a.topLevelRule.name+`> Rule.
`)+"Only the last alternative may be an empty alternative.";return o},buildTooManyAlternativesError:function(a){var o=`An Alternation cannot have more than 256 alternatives:
`+("<OR"+a.alternation.idx+"> inside <"+a.topLevelRule.name+`> Rule.
 has `+(a.alternation.definition.length+1)+" alternatives.");return o},buildLeftRecursionError:function(a){var o=a.topLevelRule.name,l=r.map(a.leftRecursionPath,function(d){return d.name}),c=o+" --> "+l.concat([o]).join(" --> "),u=`Left Recursion found in grammar.
`+("rule: <"+o+`> can be invoked from itself (directly or indirectly)
`)+(`without consuming any Tokens. The grammar path that causes this is:
 `+c+`
`)+` To fix this refactor your grammar to remove the left recursion.
see: https://en.wikipedia.org/wiki/LL_parser#Left_Factoring.`;return u},buildInvalidRuleNameError:function(a){return"deprecated"},buildDuplicateRuleNameError:function(a){var o;a.topLevelRule instanceof n.Rule?o=a.topLevelRule.name:o=a.topLevelRule;var l="Duplicate definition, rule: ->"+o+"<- is already defined in the grammar: ->"+a.grammarName+"<-";return l}}}),Rk=ri(e=>{"use strict";var t=e&&e.__extends||(function(){var o=function(l,c){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(u,d){u.__proto__=d}||function(u,d){for(var f in d)Object.prototype.hasOwnProperty.call(d,f)&&(u[f]=d[f])},o(l,c)};return function(l,c){if(typeof c!="function"&&c!==null)throw new TypeError("Class extends value "+String(c)+" is not a constructor or null");o(l,c);function u(){this.constructor=l}l.prototype=c===null?Object.create(c):(u.prototype=c.prototype,new u)}})();Object.defineProperty(e,"__esModule",{value:!0}),e.GastRefResolverVisitor=e.resolveGrammar=void 0;var r=Ns(),i=Ai(),n=fu();function s(o,l){var c=new a(o,l);return c.resolveRefs(),c.errors}e.resolveGrammar=s;var a=(function(o){t(l,o);function l(c,u){var d=o.call(this)||this;return d.nameToTopRule=c,d.errMsgProvider=u,d.errors=[],d}return l.prototype.resolveRefs=function(){var c=this;i.forEach(i.values(this.nameToTopRule),function(u){c.currTopLevel=u,u.accept(c)})},l.prototype.visitNonTerminal=function(c){var u=this.nameToTopRule[c.nonTerminalName];if(u)c.referencedRule=u;else{var d=this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel,c);this.errors.push({message:d,type:r.ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF,ruleName:this.currTopLevel.name,unresolvedRefName:c.nonTerminalName})}},l})(n.GAstVisitor);e.GastRefResolverVisitor=a}),bf=ri(e=>{"use strict";var t=e&&e.__extends||(function(){var g=function(v,_){return g=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(E,M){E.__proto__=M}||function(E,M){for(var P in M)Object.prototype.hasOwnProperty.call(M,P)&&(E[P]=M[P])},g(v,_)};return function(v,_){if(typeof _!="function"&&_!==null)throw new TypeError("Class extends value "+String(_)+" is not a constructor or null");g(v,_);function E(){this.constructor=v}v.prototype=_===null?Object.create(_):(E.prototype=_.prototype,new E)}})();Object.defineProperty(e,"__esModule",{value:!0}),e.nextPossibleTokensAfter=e.possiblePathsFrom=e.NextTerminalAfterAtLeastOneSepWalker=e.NextTerminalAfterAtLeastOneWalker=e.NextTerminalAfterManySepWalker=e.NextTerminalAfterManyWalker=e.AbstractNextTerminalAfterProductionWalker=e.NextAfterTokenWalker=e.AbstractNextPossibleTokensWalker=void 0;var r=Qy(),i=Ai(),n=Nw(),s=xs(),a=(function(g){t(v,g);function v(_,E){var M=g.call(this)||this;return M.topProd=_,M.path=E,M.possibleTokTypes=[],M.nextProductionName="",M.nextProductionOccurrence=0,M.found=!1,M.isAtEndOfPath=!1,M}return v.prototype.startWalking=function(){if(this.found=!1,this.path.ruleStack[0]!==this.topProd.name)throw Error("The path does not start with the walker's top Rule!");return this.ruleStack=i.cloneArr(this.path.ruleStack).reverse(),this.occurrenceStack=i.cloneArr(this.path.occurrenceStack).reverse(),this.ruleStack.pop(),this.occurrenceStack.pop(),this.updateExpectedNext(),this.walk(this.topProd),this.possibleTokTypes},v.prototype.walk=function(_,E){E===void 0&&(E=[]),this.found||g.prototype.walk.call(this,_,E)},v.prototype.walkProdRef=function(_,E,M){if(_.referencedRule.name===this.nextProductionName&&_.idx===this.nextProductionOccurrence){var P=E.concat(M);this.updateExpectedNext(),this.walk(_.referencedRule,P)}},v.prototype.updateExpectedNext=function(){i.isEmpty(this.ruleStack)?(this.nextProductionName="",this.nextProductionOccurrence=0,this.isAtEndOfPath=!0):(this.nextProductionName=this.ruleStack.pop(),this.nextProductionOccurrence=this.occurrenceStack.pop())},v})(r.RestWalker);e.AbstractNextPossibleTokensWalker=a;var o=(function(g){t(v,g);function v(_,E){var M=g.call(this,_,E)||this;return M.path=E,M.nextTerminalName="",M.nextTerminalOccurrence=0,M.nextTerminalName=M.path.lastTok.name,M.nextTerminalOccurrence=M.path.lastTokOccurrence,M}return v.prototype.walkTerminal=function(_,E,M){if(this.isAtEndOfPath&&_.terminalType.name===this.nextTerminalName&&_.idx===this.nextTerminalOccurrence&&!this.found){var P=E.concat(M),k=new s.Alternative({definition:P});this.possibleTokTypes=n.first(k),this.found=!0}},v})(a);e.NextAfterTokenWalker=o;var l=(function(g){t(v,g);function v(_,E){var M=g.call(this)||this;return M.topRule=_,M.occurrence=E,M.result={token:void 0,occurrence:void 0,isEndOfRule:void 0},M}return v.prototype.startWalking=function(){return this.walk(this.topRule),this.result},v})(r.RestWalker);e.AbstractNextTerminalAfterProductionWalker=l;var c=(function(g){t(v,g);function v(){return g!==null&&g.apply(this,arguments)||this}return v.prototype.walkMany=function(_,E,M){if(_.idx===this.occurrence){var P=i.first(E.concat(M));this.result.isEndOfRule=P===void 0,P instanceof s.Terminal&&(this.result.token=P.terminalType,this.result.occurrence=P.idx)}else g.prototype.walkMany.call(this,_,E,M)},v})(l);e.NextTerminalAfterManyWalker=c;var u=(function(g){t(v,g);function v(){return g!==null&&g.apply(this,arguments)||this}return v.prototype.walkManySep=function(_,E,M){if(_.idx===this.occurrence){var P=i.first(E.concat(M));this.result.isEndOfRule=P===void 0,P instanceof s.Terminal&&(this.result.token=P.terminalType,this.result.occurrence=P.idx)}else g.prototype.walkManySep.call(this,_,E,M)},v})(l);e.NextTerminalAfterManySepWalker=u;var d=(function(g){t(v,g);function v(){return g!==null&&g.apply(this,arguments)||this}return v.prototype.walkAtLeastOne=function(_,E,M){if(_.idx===this.occurrence){var P=i.first(E.concat(M));this.result.isEndOfRule=P===void 0,P instanceof s.Terminal&&(this.result.token=P.terminalType,this.result.occurrence=P.idx)}else g.prototype.walkAtLeastOne.call(this,_,E,M)},v})(l);e.NextTerminalAfterAtLeastOneWalker=d;var f=(function(g){t(v,g);function v(){return g!==null&&g.apply(this,arguments)||this}return v.prototype.walkAtLeastOneSep=function(_,E,M){if(_.idx===this.occurrence){var P=i.first(E.concat(M));this.result.isEndOfRule=P===void 0,P instanceof s.Terminal&&(this.result.token=P.terminalType,this.result.occurrence=P.idx)}else g.prototype.walkAtLeastOneSep.call(this,_,E,M)},v})(l);e.NextTerminalAfterAtLeastOneSepWalker=f;function y(g,v,_){_===void 0&&(_=[]),_=i.cloneArr(_);var E=[],M=0;function P(I){return I.concat(i.drop(g,M+1))}function k(I){var L=y(P(I),v,_);return E.concat(L)}for(;_.length<v&&M<g.length;){var z=g[M];if(z instanceof s.Alternative||z instanceof s.NonTerminal)return k(z.definition);if(z instanceof s.Option)E=k(z.definition);else if(z instanceof s.RepetitionMandatory){var D=z.definition.concat([new s.Repetition({definition:z.definition})]);return k(D)}else if(z instanceof s.RepetitionMandatoryWithSeparator){var D=[new s.Alternative({definition:z.definition}),new s.Repetition({definition:[new s.Terminal({terminalType:z.separator})].concat(z.definition)})];return k(D)}else if(z instanceof s.RepetitionWithSeparator){var D=z.definition.concat([new s.Repetition({definition:[new s.Terminal({terminalType:z.separator})].concat(z.definition)})]);E=k(D)}else if(z instanceof s.Repetition){var D=z.definition.concat([new s.Repetition({definition:z.definition})]);E=k(D)}else{if(z instanceof s.Alternation)return i.forEach(z.definition,function(I){i.isEmpty(I.definition)===!1&&(E=k(I.definition))}),E;if(z instanceof s.Terminal)_.push(z.terminalType);else throw Error("non exhaustive match")}M++}return E.push({partialPath:_,suffixDef:i.drop(g,M)}),E}e.possiblePathsFrom=y;function b(g,v,_,E){var M="EXIT_NONE_TERMINAL",P=[M],k="EXIT_ALTERNATIVE",z=!1,D=v.length,I=D-E-1,L=[],Z=[];for(Z.push({idx:-1,def:g,ruleStack:[],occurrenceStack:[]});!i.isEmpty(Z);){var se=Z.pop();if(se===k){z&&i.last(Z).idx<=I&&Z.pop();continue}var ce=se.def,fe=se.idx,ze=se.ruleStack,Fe=se.occurrenceStack;if(!i.isEmpty(ce)){var Pe=ce[0];if(Pe===M){var ue={idx:fe,def:i.drop(ce),ruleStack:i.dropRight(ze),occurrenceStack:i.dropRight(Fe)};Z.push(ue)}else if(Pe instanceof s.Terminal)if(fe<D-1){var Te=fe+1,de=v[Te];if(_(de,Pe.terminalType)){var ue={idx:Te,def:i.drop(ce),ruleStack:ze,occurrenceStack:Fe};Z.push(ue)}}else if(fe===D-1)L.push({nextTokenType:Pe.terminalType,nextTokenOccurrence:Pe.idx,ruleStack:ze,occurrenceStack:Fe}),z=!0;else throw Error("non exhaustive match");else if(Pe instanceof s.NonTerminal){var Ie=i.cloneArr(ze);Ie.push(Pe.nonTerminalName);var Re=i.cloneArr(Fe);Re.push(Pe.idx);var ue={idx:fe,def:Pe.definition.concat(P,i.drop(ce)),ruleStack:Ie,occurrenceStack:Re};Z.push(ue)}else if(Pe instanceof s.Option){var Be={idx:fe,def:i.drop(ce),ruleStack:ze,occurrenceStack:Fe};Z.push(Be),Z.push(k);var Se={idx:fe,def:Pe.definition.concat(i.drop(ce)),ruleStack:ze,occurrenceStack:Fe};Z.push(Se)}else if(Pe instanceof s.RepetitionMandatory){var U=new s.Repetition({definition:Pe.definition,idx:Pe.idx}),ie=Pe.definition.concat([U],i.drop(ce)),ue={idx:fe,def:ie,ruleStack:ze,occurrenceStack:Fe};Z.push(ue)}else if(Pe instanceof s.RepetitionMandatoryWithSeparator){var Ae=new s.Terminal({terminalType:Pe.separator}),U=new s.Repetition({definition:[Ae].concat(Pe.definition),idx:Pe.idx}),ie=Pe.definition.concat([U],i.drop(ce)),ue={idx:fe,def:ie,ruleStack:ze,occurrenceStack:Fe};Z.push(ue)}else if(Pe instanceof s.RepetitionWithSeparator){var Be={idx:fe,def:i.drop(ce),ruleStack:ze,occurrenceStack:Fe};Z.push(Be),Z.push(k);var Ae=new s.Terminal({terminalType:Pe.separator}),Ue=new s.Repetition({definition:[Ae].concat(Pe.definition),idx:Pe.idx}),ie=Pe.definition.concat([Ue],i.drop(ce)),Se={idx:fe,def:ie,ruleStack:ze,occurrenceStack:Fe};Z.push(Se)}else if(Pe instanceof s.Repetition){var Be={idx:fe,def:i.drop(ce),ruleStack:ze,occurrenceStack:Fe};Z.push(Be),Z.push(k);var Ue=new s.Repetition({definition:Pe.definition,idx:Pe.idx}),ie=Pe.definition.concat([Ue],i.drop(ce)),Se={idx:fe,def:ie,ruleStack:ze,occurrenceStack:Fe};Z.push(Se)}else if(Pe instanceof s.Alternation)for(var Ge=Pe.definition.length-1;Ge>=0;Ge--){var nt=Pe.definition[Ge],Qe={idx:fe,def:nt.definition.concat(i.drop(ce)),ruleStack:ze,occurrenceStack:Fe};Z.push(Qe),Z.push(k)}else if(Pe instanceof s.Alternative)Z.push({idx:fe,def:Pe.definition.concat(i.drop(ce)),ruleStack:ze,occurrenceStack:Fe});else if(Pe instanceof s.Rule)Z.push(x(Pe,fe,ze,Fe));else throw Error("non exhaustive match")}}return L}e.nextPossibleTokensAfter=b;function x(g,v,_,E){var M=i.cloneArr(_);M.push(g.name);var P=i.cloneArr(E);return P.push(1),{idx:v,def:g.definition,ruleStack:M,occurrenceStack:P}}}),wf=ri(e=>{"use strict";var t=e&&e.__extends||(function(){var I=function(L,Z){return I=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(se,ce){se.__proto__=ce}||function(se,ce){for(var fe in ce)Object.prototype.hasOwnProperty.call(ce,fe)&&(se[fe]=ce[fe])},I(L,Z)};return function(L,Z){if(typeof Z!="function"&&Z!==null)throw new TypeError("Class extends value "+String(Z)+" is not a constructor or null");I(L,Z);function se(){this.constructor=L}L.prototype=Z===null?Object.create(Z):(se.prototype=Z.prototype,new se)}})();Object.defineProperty(e,"__esModule",{value:!0}),e.areTokenCategoriesNotUsed=e.isStrictPrefixOfPath=e.containsPath=e.getLookaheadPathsForOptionalProd=e.getLookaheadPathsForOr=e.lookAheadSequenceFromAlternatives=e.buildSingleAlternativeLookaheadFunction=e.buildAlternativesLookAheadFunc=e.buildLookaheadFuncForOptionalProd=e.buildLookaheadFuncForOr=e.getProdType=e.PROD_TYPE=void 0;var r=Ai(),i=bf(),n=Qy(),s=pu(),a=xs(),o=fu(),l;(function(I){I[I.OPTION=0]="OPTION",I[I.REPETITION=1]="REPETITION",I[I.REPETITION_MANDATORY=2]="REPETITION_MANDATORY",I[I.REPETITION_MANDATORY_WITH_SEPARATOR=3]="REPETITION_MANDATORY_WITH_SEPARATOR",I[I.REPETITION_WITH_SEPARATOR=4]="REPETITION_WITH_SEPARATOR",I[I.ALTERNATION=5]="ALTERNATION"})(l=e.PROD_TYPE||(e.PROD_TYPE={}));function c(I){if(I instanceof a.Option)return l.OPTION;if(I instanceof a.Repetition)return l.REPETITION;if(I instanceof a.RepetitionMandatory)return l.REPETITION_MANDATORY;if(I instanceof a.RepetitionMandatoryWithSeparator)return l.REPETITION_MANDATORY_WITH_SEPARATOR;if(I instanceof a.RepetitionWithSeparator)return l.REPETITION_WITH_SEPARATOR;if(I instanceof a.Alternation)return l.ALTERNATION;throw Error("non exhaustive match")}e.getProdType=c;function u(I,L,Z,se,ce,fe){var ze=M(I,L,Z),Fe=D(ze)?s.tokenStructuredMatcherNoCategories:s.tokenStructuredMatcher;return fe(ze,se,Fe,ce)}e.buildLookaheadFuncForOr=u;function d(I,L,Z,se,ce,fe){var ze=P(I,L,ce,Z),Fe=D(ze)?s.tokenStructuredMatcherNoCategories:s.tokenStructuredMatcher;return fe(ze[0],Fe,se)}e.buildLookaheadFuncForOptionalProd=d;function f(I,L,Z,se){var ce=I.length,fe=r.every(I,function(Pe){return r.every(Pe,function(ue){return ue.length===1})});if(L)return function(Pe){for(var ue=r.map(Pe,function(Ue){return Ue.GATE}),Te=0;Te<ce;Te++){var de=I[Te],Ie=de.length,Re=ue[Te];if(!(Re!==void 0&&Re.call(this)===!1))e:for(var Be=0;Be<Ie;Be++){for(var Se=de[Be],U=Se.length,ie=0;ie<U;ie++){var Ae=this.LA(ie+1);if(Z(Ae,Se[ie])===!1)continue e}return Te}}};if(fe&&!se){var ze=r.map(I,function(Pe){return r.flatten(Pe)}),Fe=r.reduce(ze,function(Pe,ue,Te){return r.forEach(ue,function(de){r.has(Pe,de.tokenTypeIdx)||(Pe[de.tokenTypeIdx]=Te),r.forEach(de.categoryMatches,function(Ie){r.has(Pe,Ie)||(Pe[Ie]=Te)})}),Pe},[]);return function(){var Pe=this.LA(1);return Fe[Pe.tokenTypeIdx]}}else return function(){for(var Pe=0;Pe<ce;Pe++){var ue=I[Pe],Te=ue.length;e:for(var de=0;de<Te;de++){for(var Ie=ue[de],Re=Ie.length,Be=0;Be<Re;Be++){var Se=this.LA(Be+1);if(Z(Se,Ie[Be])===!1)continue e}return Pe}}}}e.buildAlternativesLookAheadFunc=f;function y(I,L,Z){var se=r.every(I,function(ue){return ue.length===1}),ce=I.length;if(se&&!Z){var fe=r.flatten(I);if(fe.length===1&&r.isEmpty(fe[0].categoryMatches)){var ze=fe[0],Fe=ze.tokenTypeIdx;return function(){return this.LA(1).tokenTypeIdx===Fe}}else{var Pe=r.reduce(fe,function(ue,Te,de){return ue[Te.tokenTypeIdx]=!0,r.forEach(Te.categoryMatches,function(Ie){ue[Ie]=!0}),ue},[]);return function(){var ue=this.LA(1);return Pe[ue.tokenTypeIdx]===!0}}}else return function(){e:for(var ue=0;ue<ce;ue++){for(var Te=I[ue],de=Te.length,Ie=0;Ie<de;Ie++){var Re=this.LA(Ie+1);if(L(Re,Te[Ie])===!1)continue e}return!0}return!1}}e.buildSingleAlternativeLookaheadFunction=y;var b=(function(I){t(L,I);function L(Z,se,ce){var fe=I.call(this)||this;return fe.topProd=Z,fe.targetOccurrence=se,fe.targetProdType=ce,fe}return L.prototype.startWalking=function(){return this.walk(this.topProd),this.restDef},L.prototype.checkIsTarget=function(Z,se,ce,fe){return Z.idx===this.targetOccurrence&&this.targetProdType===se?(this.restDef=ce.concat(fe),!0):!1},L.prototype.walkOption=function(Z,se,ce){this.checkIsTarget(Z,l.OPTION,se,ce)||I.prototype.walkOption.call(this,Z,se,ce)},L.prototype.walkAtLeastOne=function(Z,se,ce){this.checkIsTarget(Z,l.REPETITION_MANDATORY,se,ce)||I.prototype.walkOption.call(this,Z,se,ce)},L.prototype.walkAtLeastOneSep=function(Z,se,ce){this.checkIsTarget(Z,l.REPETITION_MANDATORY_WITH_SEPARATOR,se,ce)||I.prototype.walkOption.call(this,Z,se,ce)},L.prototype.walkMany=function(Z,se,ce){this.checkIsTarget(Z,l.REPETITION,se,ce)||I.prototype.walkOption.call(this,Z,se,ce)},L.prototype.walkManySep=function(Z,se,ce){this.checkIsTarget(Z,l.REPETITION_WITH_SEPARATOR,se,ce)||I.prototype.walkOption.call(this,Z,se,ce)},L})(n.RestWalker),x=(function(I){t(L,I);function L(Z,se,ce){var fe=I.call(this)||this;return fe.targetOccurrence=Z,fe.targetProdType=se,fe.targetRef=ce,fe.result=[],fe}return L.prototype.checkIsTarget=function(Z,se){Z.idx===this.targetOccurrence&&this.targetProdType===se&&(this.targetRef===void 0||Z===this.targetRef)&&(this.result=Z.definition)},L.prototype.visitOption=function(Z){this.checkIsTarget(Z,l.OPTION)},L.prototype.visitRepetition=function(Z){this.checkIsTarget(Z,l.REPETITION)},L.prototype.visitRepetitionMandatory=function(Z){this.checkIsTarget(Z,l.REPETITION_MANDATORY)},L.prototype.visitRepetitionMandatoryWithSeparator=function(Z){this.checkIsTarget(Z,l.REPETITION_MANDATORY_WITH_SEPARATOR)},L.prototype.visitRepetitionWithSeparator=function(Z){this.checkIsTarget(Z,l.REPETITION_WITH_SEPARATOR)},L.prototype.visitAlternation=function(Z){this.checkIsTarget(Z,l.ALTERNATION)},L})(o.GAstVisitor);function g(I){for(var L=new Array(I),Z=0;Z<I;Z++)L[Z]=[];return L}function v(I){for(var L=[""],Z=0;Z<I.length;Z++){for(var se=I[Z],ce=[],fe=0;fe<L.length;fe++){var ze=L[fe];ce.push(ze+"_"+se.tokenTypeIdx);for(var Fe=0;Fe<se.categoryMatches.length;Fe++){var Pe="_"+se.categoryMatches[Fe];ce.push(ze+Pe)}}L=ce}return L}function _(I,L,Z){for(var se=0;se<I.length;se++)if(se!==Z)for(var ce=I[se],fe=0;fe<L.length;fe++){var ze=L[fe];if(ce[ze]===!0)return!1}return!0}function E(I,L){for(var Z=r.map(I,function(Te){return i.possiblePathsFrom([Te],1)}),se=g(Z.length),ce=r.map(Z,function(Te){var de={};return r.forEach(Te,function(Ie){var Re=v(Ie.partialPath);r.forEach(Re,function(Be){de[Be]=!0})}),de}),fe=Z,ze=1;ze<=L;ze++){var Fe=fe;fe=g(Fe.length);for(var Pe=function(Te){for(var de=Fe[Te],Ie=0;Ie<de.length;Ie++){var Re=de[Ie].partialPath,Be=de[Ie].suffixDef,Se=v(Re),U=_(ce,Se,Te);if(U||r.isEmpty(Be)||Re.length===L){var ie=se[Te];if(k(ie,Re)===!1){ie.push(Re);for(var Ae=0;Ae<Se.length;Ae++){var Ue=Se[Ae];ce[Te][Ue]=!0}}}else{var Ge=i.possiblePathsFrom(Be,ze+1,Re);fe[Te]=fe[Te].concat(Ge),r.forEach(Ge,function(nt){var Qe=v(nt.partialPath);r.forEach(Qe,function(ct){ce[Te][ct]=!0})})}}},ue=0;ue<Fe.length;ue++)Pe(ue)}return se}e.lookAheadSequenceFromAlternatives=E;function M(I,L,Z,se){var ce=new x(I,l.ALTERNATION,se);return L.accept(ce),E(ce.result,Z)}e.getLookaheadPathsForOr=M;function P(I,L,Z,se){var ce=new x(I,Z);L.accept(ce);var fe=ce.result,ze=new b(L,I,Z),Fe=ze.startWalking(),Pe=new a.Alternative({definition:fe}),ue=new a.Alternative({definition:Fe});return E([Pe,ue],se)}e.getLookaheadPathsForOptionalProd=P;function k(I,L){e:for(var Z=0;Z<I.length;Z++){var se=I[Z];if(se.length===L.length){for(var ce=0;ce<se.length;ce++){var fe=L[ce],ze=se[ce],Fe=fe===ze||ze.categoryMatchesMap[fe.tokenTypeIdx]!==void 0;if(Fe===!1)continue e}return!0}}return!1}e.containsPath=k;function z(I,L){return I.length<L.length&&r.every(I,function(Z,se){var ce=L[se];return Z===ce||ce.categoryMatchesMap[Z.tokenTypeIdx]})}e.isStrictPrefixOfPath=z;function D(I){return r.every(I,function(L){return r.every(L,function(Z){return r.every(Z,function(se){return r.isEmpty(se.categoryMatches)})})})}e.areTokenCategoriesNotUsed=D}),kw=ri(e=>{"use strict";var t=e&&e.__extends||(function(){var se=function(ce,fe){return se=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(ze,Fe){ze.__proto__=Fe}||function(ze,Fe){for(var Pe in Fe)Object.prototype.hasOwnProperty.call(Fe,Pe)&&(ze[Pe]=Fe[Pe])},se(ce,fe)};return function(ce,fe){if(typeof fe!="function"&&fe!==null)throw new TypeError("Class extends value "+String(fe)+" is not a constructor or null");se(ce,fe);function ze(){this.constructor=ce}ce.prototype=fe===null?Object.create(fe):(ze.prototype=fe.prototype,new ze)}})();Object.defineProperty(e,"__esModule",{value:!0}),e.checkPrefixAlternativesAmbiguities=e.validateSomeNonEmptyLookaheadPath=e.validateTooManyAlts=e.RepetionCollector=e.validateAmbiguousAlternationAlternatives=e.validateEmptyOrAlternative=e.getFirstNoneTerminal=e.validateNoLeftRecursion=e.validateRuleIsOverridden=e.validateRuleDoesNotAlreadyExist=e.OccurrenceValidationCollector=e.identifyProductionForDuplicates=e.validateGrammar=void 0;var r=Ai(),i=Ai(),n=Ns(),s=vf(),a=wf(),o=bf(),l=xs(),c=fu();function u(se,ce,fe,ze,Fe){var Pe=r.map(se,function(U){return d(U,ze)}),ue=r.map(se,function(U){return v(U,U,ze)}),Te=[],de=[],Ie=[];i.every(ue,i.isEmpty)&&(Te=i.map(se,function(U){return M(U,ze)}),de=i.map(se,function(U){return P(U,ce,ze)}),Ie=D(se,ce,ze));var Re=Z(se,fe,ze),Be=i.map(se,function(U){return z(U,ze)}),Se=i.map(se,function(U){return x(U,se,Fe,ze)});return r.flatten(Pe.concat(Ie,ue,Te,de,Re,Be,Se))}e.validateGrammar=u;function d(se,ce){var fe=new b;se.accept(fe);var ze=fe.allProductions,Fe=r.groupBy(ze,f),Pe=r.pick(Fe,function(Te){return Te.length>1}),ue=r.map(r.values(Pe),function(Te){var de=r.first(Te),Ie=ce.buildDuplicateFoundError(se,Te),Re=s.getProductionDslName(de),Be={message:Ie,type:n.ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS,ruleName:se.name,dslName:Re,occurrence:de.idx},Se=y(de);return Se&&(Be.parameter=Se),Be});return ue}function f(se){return s.getProductionDslName(se)+"_#_"+se.idx+"_#_"+y(se)}e.identifyProductionForDuplicates=f;function y(se){return se instanceof l.Terminal?se.terminalType.name:se instanceof l.NonTerminal?se.nonTerminalName:""}var b=(function(se){t(ce,se);function ce(){var fe=se!==null&&se.apply(this,arguments)||this;return fe.allProductions=[],fe}return ce.prototype.visitNonTerminal=function(fe){this.allProductions.push(fe)},ce.prototype.visitOption=function(fe){this.allProductions.push(fe)},ce.prototype.visitRepetitionWithSeparator=function(fe){this.allProductions.push(fe)},ce.prototype.visitRepetitionMandatory=function(fe){this.allProductions.push(fe)},ce.prototype.visitRepetitionMandatoryWithSeparator=function(fe){this.allProductions.push(fe)},ce.prototype.visitRepetition=function(fe){this.allProductions.push(fe)},ce.prototype.visitAlternation=function(fe){this.allProductions.push(fe)},ce.prototype.visitTerminal=function(fe){this.allProductions.push(fe)},ce})(c.GAstVisitor);e.OccurrenceValidationCollector=b;function x(se,ce,fe,ze){var Fe=[],Pe=i.reduce(ce,function(Te,de){return de.name===se.name?Te+1:Te},0);if(Pe>1){var ue=ze.buildDuplicateRuleNameError({topLevelRule:se,grammarName:fe});Fe.push({message:ue,type:n.ParserDefinitionErrorType.DUPLICATE_RULE_NAME,ruleName:se.name})}return Fe}e.validateRuleDoesNotAlreadyExist=x;function g(se,ce,fe){var ze=[],Fe;return r.contains(ce,se)||(Fe="Invalid rule override, rule: ->"+se+"<- cannot be overridden in the grammar: ->"+fe+"<-as it is not defined in any of the super grammars ",ze.push({message:Fe,type:n.ParserDefinitionErrorType.INVALID_RULE_OVERRIDE,ruleName:se})),ze}e.validateRuleIsOverridden=g;function v(se,ce,fe,ze){ze===void 0&&(ze=[]);var Fe=[],Pe=_(ce.definition);if(r.isEmpty(Pe))return[];var ue=se.name,Te=r.contains(Pe,se);Te&&Fe.push({message:fe.buildLeftRecursionError({topLevelRule:se,leftRecursionPath:ze}),type:n.ParserDefinitionErrorType.LEFT_RECURSION,ruleName:ue});var de=r.difference(Pe,ze.concat([se])),Ie=r.map(de,function(Re){var Be=r.cloneArr(ze);return Be.push(Re),v(se,Re,fe,Be)});return Fe.concat(r.flatten(Ie))}e.validateNoLeftRecursion=v;function _(se){var ce=[];if(r.isEmpty(se))return ce;var fe=r.first(se);if(fe instanceof l.NonTerminal)ce.push(fe.referencedRule);else if(fe instanceof l.Alternative||fe instanceof l.Option||fe instanceof l.RepetitionMandatory||fe instanceof l.RepetitionMandatoryWithSeparator||fe instanceof l.RepetitionWithSeparator||fe instanceof l.Repetition)ce=ce.concat(_(fe.definition));else if(fe instanceof l.Alternation)ce=r.flatten(r.map(fe.definition,function(ue){return _(ue.definition)}));else if(!(fe instanceof l.Terminal))throw Error("non exhaustive match");var ze=s.isOptionalProd(fe),Fe=se.length>1;if(ze&&Fe){var Pe=r.drop(se);return ce.concat(_(Pe))}else return ce}e.getFirstNoneTerminal=_;var E=(function(se){t(ce,se);function ce(){var fe=se!==null&&se.apply(this,arguments)||this;return fe.alternations=[],fe}return ce.prototype.visitAlternation=function(fe){this.alternations.push(fe)},ce})(c.GAstVisitor);function M(se,ce){var fe=new E;se.accept(fe);var ze=fe.alternations,Fe=r.reduce(ze,function(Pe,ue){var Te=r.dropRight(ue.definition),de=r.map(Te,function(Ie,Re){var Be=o.nextPossibleTokensAfter([Ie],[],null,1);return r.isEmpty(Be)?{message:ce.buildEmptyAlternationError({topLevelRule:se,alternation:ue,emptyChoiceIdx:Re}),type:n.ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT,ruleName:se.name,occurrence:ue.idx,alternative:Re+1}:null});return Pe.concat(r.compact(de))},[]);return Fe}e.validateEmptyOrAlternative=M;function P(se,ce,fe){var ze=new E;se.accept(ze);var Fe=ze.alternations;Fe=i.reject(Fe,function(ue){return ue.ignoreAmbiguities===!0});var Pe=r.reduce(Fe,function(ue,Te){var de=Te.idx,Ie=Te.maxLookahead||ce,Re=a.getLookaheadPathsForOr(de,se,Ie,Te),Be=I(Re,Te,se,fe),Se=L(Re,Te,se,fe);return ue.concat(Be,Se)},[]);return Pe}e.validateAmbiguousAlternationAlternatives=P;var k=(function(se){t(ce,se);function ce(){var fe=se!==null&&se.apply(this,arguments)||this;return fe.allProductions=[],fe}return ce.prototype.visitRepetitionWithSeparator=function(fe){this.allProductions.push(fe)},ce.prototype.visitRepetitionMandatory=function(fe){this.allProductions.push(fe)},ce.prototype.visitRepetitionMandatoryWithSeparator=function(fe){this.allProductions.push(fe)},ce.prototype.visitRepetition=function(fe){this.allProductions.push(fe)},ce})(c.GAstVisitor);e.RepetionCollector=k;function z(se,ce){var fe=new E;se.accept(fe);var ze=fe.alternations,Fe=r.reduce(ze,function(Pe,ue){return ue.definition.length>255&&Pe.push({message:ce.buildTooManyAlternativesError({topLevelRule:se,alternation:ue}),type:n.ParserDefinitionErrorType.TOO_MANY_ALTS,ruleName:se.name,occurrence:ue.idx}),Pe},[]);return Fe}e.validateTooManyAlts=z;function D(se,ce,fe){var ze=[];return i.forEach(se,function(Fe){var Pe=new k;Fe.accept(Pe);var ue=Pe.allProductions;i.forEach(ue,function(Te){var de=a.getProdType(Te),Ie=Te.maxLookahead||ce,Re=Te.idx,Be=a.getLookaheadPathsForOptionalProd(Re,Fe,de,Ie),Se=Be[0];if(i.isEmpty(i.flatten(Se))){var U=fe.buildEmptyRepetitionError({topLevelRule:Fe,repetition:Te});ze.push({message:U,type:n.ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD,ruleName:Fe.name})}})}),ze}e.validateSomeNonEmptyLookaheadPath=D;function I(se,ce,fe,ze){var Fe=[],Pe=i.reduce(se,function(Te,de,Ie){return ce.definition[Ie].ignoreAmbiguities===!0||i.forEach(de,function(Re){var Be=[Ie];i.forEach(se,function(Se,U){Ie!==U&&a.containsPath(Se,Re)&&ce.definition[U].ignoreAmbiguities!==!0&&Be.push(U)}),Be.length>1&&!a.containsPath(Fe,Re)&&(Fe.push(Re),Te.push({alts:Be,path:Re}))}),Te},[]),ue=r.map(Pe,function(Te){var de=i.map(Te.alts,function(Re){return Re+1}),Ie=ze.buildAlternationAmbiguityError({topLevelRule:fe,alternation:ce,ambiguityIndices:de,prefixPath:Te.path});return{message:Ie,type:n.ParserDefinitionErrorType.AMBIGUOUS_ALTS,ruleName:fe.name,occurrence:ce.idx,alternatives:[Te.alts]}});return ue}function L(se,ce,fe,ze){var Fe=[],Pe=i.reduce(se,function(ue,Te,de){var Ie=i.map(Te,function(Re){return{idx:de,path:Re}});return ue.concat(Ie)},[]);return i.forEach(Pe,function(ue){var Te=ce.definition[ue.idx];if(Te.ignoreAmbiguities!==!0){var de=ue.idx,Ie=ue.path,Re=i.findAll(Pe,function(Se){return ce.definition[Se.idx].ignoreAmbiguities!==!0&&Se.idx<de&&a.isStrictPrefixOfPath(Se.path,Ie)}),Be=i.map(Re,function(Se){var U=[Se.idx+1,de+1],ie=ce.idx===0?"":ce.idx,Ae=ze.buildAlternationPrefixAmbiguityError({topLevelRule:fe,alternation:ce,ambiguityIndices:U,prefixPath:Se.path});return{message:Ae,type:n.ParserDefinitionErrorType.AMBIGUOUS_PREFIX_ALTS,ruleName:fe.name,occurrence:ie,alternatives:U}});Fe=Fe.concat(Be)}}),Fe}e.checkPrefixAlternativesAmbiguities=L;function Z(se,ce,fe){var ze=[],Fe=i.map(ce,function(Pe){return Pe.name});return i.forEach(se,function(Pe){var ue=Pe.name;if(i.contains(Fe,ue)){var Te=fe.buildNamespaceConflictError(Pe);ze.push({message:Te,type:n.ParserDefinitionErrorType.CONFLICT_TOKENS_RULES_NAMESPACE,ruleName:ue})}}),ze}}),Pk=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.validateGrammar=e.resolveGrammar=void 0;var t=Ai(),r=Rk(),i=kw(),n=xf();function s(o){o=t.defaults(o,{errMsgProvider:n.defaultGrammarResolverErrorProvider});var l={};return t.forEach(o.rules,function(c){l[c.name]=c}),r.resolveGrammar(l,o.errMsgProvider)}e.resolveGrammar=s;function a(o){return o=t.defaults(o,{errMsgProvider:n.defaultGrammarValidatorErrorProvider}),i.validateGrammar(o.rules,o.maxLookahead,o.tokenTypes,o.errMsgProvider,o.grammarName)}e.validateGrammar=a}),mu=ri(e=>{"use strict";var t=e&&e.__extends||(function(){var b=function(x,g){return b=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(v,_){v.__proto__=_}||function(v,_){for(var E in _)Object.prototype.hasOwnProperty.call(_,E)&&(v[E]=_[E])},b(x,g)};return function(x,g){if(typeof g!="function"&&g!==null)throw new TypeError("Class extends value "+String(g)+" is not a constructor or null");b(x,g);function v(){this.constructor=x}x.prototype=g===null?Object.create(g):(v.prototype=g.prototype,new v)}})();Object.defineProperty(e,"__esModule",{value:!0}),e.EarlyExitException=e.NotAllInputParsedException=e.NoViableAltException=e.MismatchedTokenException=e.isRecognitionException=void 0;var r=Ai(),i="MismatchedTokenException",n="NoViableAltException",s="EarlyExitException",a="NotAllInputParsedException",o=[i,n,s,a];Object.freeze(o);function l(b){return r.contains(o,b.name)}e.isRecognitionException=l;var c=(function(b){t(x,b);function x(g,v){var _=this.constructor,E=b.call(this,g)||this;return E.token=v,E.resyncedTokens=[],Object.setPrototypeOf(E,_.prototype),Error.captureStackTrace&&Error.captureStackTrace(E,E.constructor),E}return x})(Error),u=(function(b){t(x,b);function x(g,v,_){var E=b.call(this,g,v)||this;return E.previousToken=_,E.name=i,E}return x})(c);e.MismatchedTokenException=u;var d=(function(b){t(x,b);function x(g,v,_){var E=b.call(this,g,v)||this;return E.previousToken=_,E.name=n,E}return x})(c);e.NoViableAltException=d;var f=(function(b){t(x,b);function x(g,v){var _=b.call(this,g,v)||this;return _.name=a,_}return x})(c);e.NotAllInputParsedException=f;var y=(function(b){t(x,b);function x(g,v,_){var E=b.call(this,g,v)||this;return E.previousToken=_,E.name=s,E}return x})(c);e.EarlyExitException=y}),Ow=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.attemptInRepetitionRecovery=e.Recoverable=e.InRuleRecoveryException=e.IN_RULE_RECOVERY_EXCEPTION=e.EOF_FOLLOW_KEY=void 0;var t=gl(),r=Ai(),i=mu(),n=Lw(),s=Ns();e.EOF_FOLLOW_KEY={},e.IN_RULE_RECOVERY_EXCEPTION="InRuleRecoveryException";function a(c){this.name=e.IN_RULE_RECOVERY_EXCEPTION,this.message=c}e.InRuleRecoveryException=a,a.prototype=Error.prototype;var o=(function(){function c(){}return c.prototype.initRecoverable=function(u){this.firstAfterRepMap={},this.resyncFollows={},this.recoveryEnabled=r.has(u,"recoveryEnabled")?u.recoveryEnabled:s.DEFAULT_PARSER_CONFIG.recoveryEnabled,this.recoveryEnabled&&(this.attemptInRepetitionRecovery=l)},c.prototype.getTokenToInsert=function(u){var d=t.createTokenInstance(u,"",NaN,NaN,NaN,NaN,NaN,NaN);return d.isInsertedInRecovery=!0,d},c.prototype.canTokenTypeBeInsertedInRecovery=function(u){return!0},c.prototype.tryInRepetitionRecovery=function(u,d,f,y){for(var b=this,x=this.findReSyncTokenType(),g=this.exportLexerState(),v=[],_=!1,E=this.LA(1),M=this.LA(1),P=function(){var k=b.LA(0),z=b.errorMessageProvider.buildMismatchTokenMessage({expected:y,actual:E,previous:k,ruleName:b.getCurrRuleFullName()}),D=new i.MismatchedTokenException(z,E,b.LA(0));D.resyncedTokens=r.dropRight(v),b.SAVE_ERROR(D)};!_;)if(this.tokenMatcher(M,y)){P();return}else if(f.call(this)){P(),u.apply(this,d);return}else this.tokenMatcher(M,x)?_=!0:(M=this.SKIP_TOKEN(),this.addToResyncTokens(M,v));this.importLexerState(g)},c.prototype.shouldInRepetitionRecoveryBeTried=function(u,d,f){return!(f===!1||u===void 0||d===void 0||this.tokenMatcher(this.LA(1),u)||this.isBackTracking()||this.canPerformInRuleRecovery(u,this.getFollowsForInRuleRecovery(u,d)))},c.prototype.getFollowsForInRuleRecovery=function(u,d){var f=this.getCurrentGrammarPath(u,d),y=this.getNextPossibleTokenTypes(f);return y},c.prototype.tryInRuleRecovery=function(u,d){if(this.canRecoverWithSingleTokenInsertion(u,d)){var f=this.getTokenToInsert(u);return f}if(this.canRecoverWithSingleTokenDeletion(u)){var y=this.SKIP_TOKEN();return this.consumeToken(),y}throw new a("sad sad panda")},c.prototype.canPerformInRuleRecovery=function(u,d){return this.canRecoverWithSingleTokenInsertion(u,d)||this.canRecoverWithSingleTokenDeletion(u)},c.prototype.canRecoverWithSingleTokenInsertion=function(u,d){var f=this;if(!this.canTokenTypeBeInsertedInRecovery(u)||r.isEmpty(d))return!1;var y=this.LA(1),b=r.find(d,function(x){return f.tokenMatcher(y,x)})!==void 0;return b},c.prototype.canRecoverWithSingleTokenDeletion=function(u){var d=this.tokenMatcher(this.LA(2),u);return d},c.prototype.isInCurrentRuleReSyncSet=function(u){var d=this.getCurrFollowKey(),f=this.getFollowSetFromFollowKey(d);return r.contains(f,u)},c.prototype.findReSyncTokenType=function(){for(var u=this.flattenFollowSet(),d=this.LA(1),f=2;;){var y=d.tokenType;if(r.contains(u,y))return y;d=this.LA(f),f++}},c.prototype.getCurrFollowKey=function(){if(this.RULE_STACK.length===1)return e.EOF_FOLLOW_KEY;var u=this.getLastExplicitRuleShortName(),d=this.getLastExplicitRuleOccurrenceIndex(),f=this.getPreviousExplicitRuleShortName();return{ruleName:this.shortRuleNameToFullName(u),idxInCallingRule:d,inRule:this.shortRuleNameToFullName(f)}},c.prototype.buildFullFollowKeyStack=function(){var u=this,d=this.RULE_STACK,f=this.RULE_OCCURRENCE_STACK;return r.map(d,function(y,b){return b===0?e.EOF_FOLLOW_KEY:{ruleName:u.shortRuleNameToFullName(y),idxInCallingRule:f[b],inRule:u.shortRuleNameToFullName(d[b-1])}})},c.prototype.flattenFollowSet=function(){var u=this,d=r.map(this.buildFullFollowKeyStack(),function(f){return u.getFollowSetFromFollowKey(f)});return r.flatten(d)},c.prototype.getFollowSetFromFollowKey=function(u){if(u===e.EOF_FOLLOW_KEY)return[t.EOF];var d=u.ruleName+u.idxInCallingRule+n.IN+u.inRule;return this.resyncFollows[d]},c.prototype.addToResyncTokens=function(u,d){return this.tokenMatcher(u,t.EOF)||d.push(u),d},c.prototype.reSyncTo=function(u){for(var d=[],f=this.LA(1);this.tokenMatcher(f,u)===!1;)f=this.SKIP_TOKEN(),this.addToResyncTokens(f,d);return r.dropRight(d)},c.prototype.attemptInRepetitionRecovery=function(u,d,f,y,b,x,g){},c.prototype.getCurrentGrammarPath=function(u,d){var f=this.getHumanReadableRuleStack(),y=r.cloneArr(this.RULE_OCCURRENCE_STACK),b={ruleStack:f,occurrenceStack:y,lastTok:u,lastTokOccurrence:d};return b},c.prototype.getHumanReadableRuleStack=function(){var u=this;return r.map(this.RULE_STACK,function(d){return u.shortRuleNameToFullName(d)})},c})();e.Recoverable=o;function l(c,u,d,f,y,b,x){var g=this.getKeyForAutomaticLookahead(f,y),v=this.firstAfterRepMap[g];if(v===void 0){var _=this.getCurrRuleFullName(),E=this.getGAstProductions()[_],M=new b(E,y);v=M.startWalking(),this.firstAfterRepMap[g]=v}var P=v.token,k=v.occurrence,z=v.isEndOfRule;this.RULE_STACK.length===1&&z&&P===void 0&&(P=t.EOF,k=1),this.shouldInRepetitionRecoveryBeTried(P,k,x)&&this.tryInRepetitionRecovery(c,u,d,P)}e.attemptInRepetitionRecovery=l}),e0=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.getKeyForAutomaticLookahead=e.AT_LEAST_ONE_SEP_IDX=e.MANY_SEP_IDX=e.AT_LEAST_ONE_IDX=e.MANY_IDX=e.OPTION_IDX=e.OR_IDX=e.BITS_FOR_ALT_IDX=e.BITS_FOR_RULE_IDX=e.BITS_FOR_OCCURRENCE_IDX=e.BITS_FOR_METHOD_TYPE=void 0,e.BITS_FOR_METHOD_TYPE=4,e.BITS_FOR_OCCURRENCE_IDX=8,e.BITS_FOR_RULE_IDX=12,e.BITS_FOR_ALT_IDX=8,e.OR_IDX=1<<e.BITS_FOR_OCCURRENCE_IDX,e.OPTION_IDX=2<<e.BITS_FOR_OCCURRENCE_IDX,e.MANY_IDX=3<<e.BITS_FOR_OCCURRENCE_IDX,e.AT_LEAST_ONE_IDX=4<<e.BITS_FOR_OCCURRENCE_IDX,e.MANY_SEP_IDX=5<<e.BITS_FOR_OCCURRENCE_IDX,e.AT_LEAST_ONE_SEP_IDX=6<<e.BITS_FOR_OCCURRENCE_IDX;function t(i,n,s){return s|n|i}e.getKeyForAutomaticLookahead=t;var r=32-e.BITS_FOR_ALT_IDX}),Ik=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.LooksAhead=void 0;var t=wf(),r=Ai(),i=Ns(),n=e0(),s=vf(),a=(function(){function o(){}return o.prototype.initLooksAhead=function(l){this.dynamicTokensEnabled=r.has(l,"dynamicTokensEnabled")?l.dynamicTokensEnabled:i.DEFAULT_PARSER_CONFIG.dynamicTokensEnabled,this.maxLookahead=r.has(l,"maxLookahead")?l.maxLookahead:i.DEFAULT_PARSER_CONFIG.maxLookahead,this.lookAheadFuncsCache=r.isES2015MapSupported()?new Map:[],r.isES2015MapSupported()?(this.getLaFuncFromCache=this.getLaFuncFromMap,this.setLaFuncCache=this.setLaFuncCacheUsingMap):(this.getLaFuncFromCache=this.getLaFuncFromObj,this.setLaFuncCache=this.setLaFuncUsingObj)},o.prototype.preComputeLookaheadFunctions=function(l){var c=this;r.forEach(l,function(u){c.TRACE_INIT(u.name+" Rule Lookahead",function(){var d=s.collectMethods(u),f=d.alternation,y=d.repetition,b=d.option,x=d.repetitionMandatory,g=d.repetitionMandatoryWithSeparator,v=d.repetitionWithSeparator;r.forEach(f,function(_){var E=_.idx===0?"":_.idx;c.TRACE_INIT(""+s.getProductionDslName(_)+E,function(){var M=t.buildLookaheadFuncForOr(_.idx,u,_.maxLookahead||c.maxLookahead,_.hasPredicates,c.dynamicTokensEnabled,c.lookAheadBuilderForAlternatives),P=n.getKeyForAutomaticLookahead(c.fullRuleNameToShort[u.name],n.OR_IDX,_.idx);c.setLaFuncCache(P,M)})}),r.forEach(y,function(_){c.computeLookaheadFunc(u,_.idx,n.MANY_IDX,t.PROD_TYPE.REPETITION,_.maxLookahead,s.getProductionDslName(_))}),r.forEach(b,function(_){c.computeLookaheadFunc(u,_.idx,n.OPTION_IDX,t.PROD_TYPE.OPTION,_.maxLookahead,s.getProductionDslName(_))}),r.forEach(x,function(_){c.computeLookaheadFunc(u,_.idx,n.AT_LEAST_ONE_IDX,t.PROD_TYPE.REPETITION_MANDATORY,_.maxLookahead,s.getProductionDslName(_))}),r.forEach(g,function(_){c.computeLookaheadFunc(u,_.idx,n.AT_LEAST_ONE_SEP_IDX,t.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR,_.maxLookahead,s.getProductionDslName(_))}),r.forEach(v,function(_){c.computeLookaheadFunc(u,_.idx,n.MANY_SEP_IDX,t.PROD_TYPE.REPETITION_WITH_SEPARATOR,_.maxLookahead,s.getProductionDslName(_))})})})},o.prototype.computeLookaheadFunc=function(l,c,u,d,f,y){var b=this;this.TRACE_INIT(""+y+(c===0?"":c),function(){var x=t.buildLookaheadFuncForOptionalProd(c,l,f||b.maxLookahead,b.dynamicTokensEnabled,d,b.lookAheadBuilderForOptional),g=n.getKeyForAutomaticLookahead(b.fullRuleNameToShort[l.name],u,c);b.setLaFuncCache(g,x)})},o.prototype.lookAheadBuilderForOptional=function(l,c,u){return t.buildSingleAlternativeLookaheadFunction(l,c,u)},o.prototype.lookAheadBuilderForAlternatives=function(l,c,u,d){return t.buildAlternativesLookAheadFunc(l,c,u,d)},o.prototype.getKeyForAutomaticLookahead=function(l,c){var u=this.getLastExplicitRuleShortName();return n.getKeyForAutomaticLookahead(u,l,c)},o.prototype.getLaFuncFromCache=function(l){},o.prototype.getLaFuncFromMap=function(l){return this.lookAheadFuncsCache.get(l)},o.prototype.getLaFuncFromObj=function(l){return this.lookAheadFuncsCache[l]},o.prototype.setLaFuncCache=function(l,c){},o.prototype.setLaFuncCacheUsingMap=function(l,c){this.lookAheadFuncsCache.set(l,c)},o.prototype.setLaFuncUsingObj=function(l,c){this.lookAheadFuncsCache[l]=c},o})();e.LooksAhead=a}),Nk=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.addNoneTerminalToCst=e.addTerminalToCst=e.setNodeLocationFull=e.setNodeLocationOnlyOffset=void 0;function t(s,a){isNaN(s.startOffset)===!0?(s.startOffset=a.startOffset,s.endOffset=a.endOffset):s.endOffset<a.endOffset&&(s.endOffset=a.endOffset)}e.setNodeLocationOnlyOffset=t;function r(s,a){isNaN(s.startOffset)===!0?(s.startOffset=a.startOffset,s.startColumn=a.startColumn,s.startLine=a.startLine,s.endOffset=a.endOffset,s.endColumn=a.endColumn,s.endLine=a.endLine):s.endOffset<a.endOffset&&(s.endOffset=a.endOffset,s.endColumn=a.endColumn,s.endLine=a.endLine)}e.setNodeLocationFull=r;function i(s,a,o){s.children[o]===void 0?s.children[o]=[a]:s.children[o].push(a)}e.addTerminalToCst=i;function n(s,a,o){s.children[a]===void 0?s.children[a]=[o]:s.children[a].push(o)}e.addNoneTerminalToCst=n}),Dw=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.defineNameProp=e.functionName=e.classNameFromInstance=void 0;var t=Ai();function r(a){return n(a.constructor)}e.classNameFromInstance=r;var i="name";function n(a){var o=a.name;return o||"anonymous"}e.functionName=n;function s(a,o){var l=Object.getOwnPropertyDescriptor(a,i);return t.isUndefined(l)||l.configurable?(Object.defineProperty(a,i,{enumerable:!1,configurable:!0,writable:!1,value:o}),!0):!1}e.defineNameProp=s}),Lk=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.validateRedundantMethods=e.validateMissingCstMethods=e.validateVisitor=e.CstVisitorDefinitionError=e.createBaseVisitorConstructorWithDefaults=e.createBaseSemanticVisitorConstructor=e.defaultVisit=void 0;var t=Ai(),r=Dw();function i(d,f){for(var y=t.keys(d),b=y.length,x=0;x<b;x++)for(var g=y[x],v=d[g],_=v.length,E=0;E<_;E++){var M=v[E];M.tokenTypeIdx===void 0&&this[M.name](M.children,f)}}e.defaultVisit=i;function n(d,f){var y=function(){};r.defineNameProp(y,d+"BaseSemantics");var b={visit:function(x,g){if(t.isArray(x)&&(x=x[0]),!t.isUndefined(x))return this[x.name](x.children,g)},validateVisitor:function(){var x=o(this,f);if(!t.isEmpty(x)){var g=t.map(x,function(v){return v.msg});throw Error("Errors Detected in CST Visitor <"+r.functionName(this.constructor)+`>:
	`+(""+g.join(`

`).replace(/\n/g,`
	`)))}}};return y.prototype=b,y.prototype.constructor=y,y._RULE_NAMES=f,y}e.createBaseSemanticVisitorConstructor=n;function s(d,f,y){var b=function(){};r.defineNameProp(b,d+"BaseSemanticsWithDefaults");var x=Object.create(y.prototype);return t.forEach(f,function(g){x[g]=i}),b.prototype=x,b.prototype.constructor=b,b}e.createBaseVisitorConstructorWithDefaults=s;var a;(function(d){d[d.REDUNDANT_METHOD=0]="REDUNDANT_METHOD",d[d.MISSING_METHOD=1]="MISSING_METHOD"})(a=e.CstVisitorDefinitionError||(e.CstVisitorDefinitionError={}));function o(d,f){var y=l(d,f),b=u(d,f);return y.concat(b)}e.validateVisitor=o;function l(d,f){var y=t.map(f,function(b){if(!t.isFunction(d[b]))return{msg:"Missing visitor method: <"+b+"> on "+r.functionName(d.constructor)+" CST Visitor.",type:a.MISSING_METHOD,methodName:b}});return t.compact(y)}e.validateMissingCstMethods=l;var c=["constructor","visit","validateVisitor"];function u(d,f){var y=[];for(var b in d)t.isFunction(d[b])&&!t.contains(c,b)&&!t.contains(f,b)&&y.push({msg:"Redundant visitor method: <"+b+"> on "+r.functionName(d.constructor)+` CST Visitor
There is no Grammar Rule corresponding to this method's name.
`,type:a.REDUNDANT_METHOD,methodName:b});return y}e.validateRedundantMethods=u}),kk=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.TreeBuilder=void 0;var t=Nk(),r=Ai(),i=Lk(),n=Ns(),s=(function(){function a(){}return a.prototype.initTreeBuilder=function(o){if(this.CST_STACK=[],this.outputCst=o.outputCst,this.nodeLocationTracking=r.has(o,"nodeLocationTracking")?o.nodeLocationTracking:n.DEFAULT_PARSER_CONFIG.nodeLocationTracking,!this.outputCst)this.cstInvocationStateUpdate=r.NOOP,this.cstFinallyStateUpdate=r.NOOP,this.cstPostTerminal=r.NOOP,this.cstPostNonTerminal=r.NOOP,this.cstPostRule=r.NOOP;else if(/full/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=t.setNodeLocationFull,this.setNodeLocationFromNode=t.setNodeLocationFull,this.cstPostRule=r.NOOP,this.setInitialNodeLocation=this.setInitialNodeLocationFullRecovery):(this.setNodeLocationFromToken=r.NOOP,this.setNodeLocationFromNode=r.NOOP,this.cstPostRule=this.cstPostRuleFull,this.setInitialNodeLocation=this.setInitialNodeLocationFullRegular);else if(/onlyOffset/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=t.setNodeLocationOnlyOffset,this.setNodeLocationFromNode=t.setNodeLocationOnlyOffset,this.cstPostRule=r.NOOP,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRecovery):(this.setNodeLocationFromToken=r.NOOP,this.setNodeLocationFromNode=r.NOOP,this.cstPostRule=this.cstPostRuleOnlyOffset,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRegular);else if(/none/i.test(this.nodeLocationTracking))this.setNodeLocationFromToken=r.NOOP,this.setNodeLocationFromNode=r.NOOP,this.cstPostRule=r.NOOP,this.setInitialNodeLocation=r.NOOP;else throw Error('Invalid <nodeLocationTracking> config option: "'+o.nodeLocationTracking+'"')},a.prototype.setInitialNodeLocationOnlyOffsetRecovery=function(o){o.location={startOffset:NaN,endOffset:NaN}},a.prototype.setInitialNodeLocationOnlyOffsetRegular=function(o){o.location={startOffset:this.LA(1).startOffset,endOffset:NaN}},a.prototype.setInitialNodeLocationFullRecovery=function(o){o.location={startOffset:NaN,startLine:NaN,startColumn:NaN,endOffset:NaN,endLine:NaN,endColumn:NaN}},a.prototype.setInitialNodeLocationFullRegular=function(o){var l=this.LA(1);o.location={startOffset:l.startOffset,startLine:l.startLine,startColumn:l.startColumn,endOffset:NaN,endLine:NaN,endColumn:NaN}},a.prototype.cstInvocationStateUpdate=function(o,l){var c={name:o,children:{}};this.setInitialNodeLocation(c),this.CST_STACK.push(c)},a.prototype.cstFinallyStateUpdate=function(){this.CST_STACK.pop()},a.prototype.cstPostRuleFull=function(o){var l=this.LA(0),c=o.location;c.startOffset<=l.startOffset?(c.endOffset=l.endOffset,c.endLine=l.endLine,c.endColumn=l.endColumn):(c.startOffset=NaN,c.startLine=NaN,c.startColumn=NaN)},a.prototype.cstPostRuleOnlyOffset=function(o){var l=this.LA(0),c=o.location;c.startOffset<=l.startOffset?c.endOffset=l.endOffset:c.startOffset=NaN},a.prototype.cstPostTerminal=function(o,l){var c=this.CST_STACK[this.CST_STACK.length-1];t.addTerminalToCst(c,l,o),this.setNodeLocationFromToken(c.location,l)},a.prototype.cstPostNonTerminal=function(o,l){var c=this.CST_STACK[this.CST_STACK.length-1];t.addNoneTerminalToCst(c,l,o),this.setNodeLocationFromNode(c.location,o.location)},a.prototype.getBaseCstVisitorConstructor=function(){if(r.isUndefined(this.baseCstVisitorConstructor)){var o=i.createBaseSemanticVisitorConstructor(this.className,r.keys(this.gastProductionsCache));return this.baseCstVisitorConstructor=o,o}return this.baseCstVisitorConstructor},a.prototype.getBaseCstVisitorConstructorWithDefaults=function(){if(r.isUndefined(this.baseCstVisitorWithDefaultsConstructor)){var o=i.createBaseVisitorConstructorWithDefaults(this.className,r.keys(this.gastProductionsCache),this.getBaseCstVisitorConstructor());return this.baseCstVisitorWithDefaultsConstructor=o,o}return this.baseCstVisitorWithDefaultsConstructor},a.prototype.getLastExplicitRuleShortName=function(){var o=this.RULE_STACK;return o[o.length-1]},a.prototype.getPreviousExplicitRuleShortName=function(){var o=this.RULE_STACK;return o[o.length-2]},a.prototype.getLastExplicitRuleOccurrenceIndex=function(){var o=this.RULE_OCCURRENCE_STACK;return o[o.length-1]},a})();e.TreeBuilder=s}),Ok=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.LexerAdapter=void 0;var t=Ns(),r=(function(){function i(){}return i.prototype.initLexerAdapter=function(){this.tokVector=[],this.tokVectorLength=0,this.currIdx=-1},Object.defineProperty(i.prototype,"input",{get:function(){return this.tokVector},set:function(n){if(this.selfAnalysisDone!==!0)throw Error("Missing <performSelfAnalysis> invocation at the end of the Parser's constructor.");this.reset(),this.tokVector=n,this.tokVectorLength=n.length},enumerable:!1,configurable:!0}),i.prototype.SKIP_TOKEN=function(){return this.currIdx<=this.tokVector.length-2?(this.consumeToken(),this.LA(1)):t.END_OF_FILE},i.prototype.LA=function(n){var s=this.currIdx+n;return s<0||this.tokVectorLength<=s?t.END_OF_FILE:this.tokVector[s]},i.prototype.consumeToken=function(){this.currIdx++},i.prototype.exportLexerState=function(){return this.currIdx},i.prototype.importLexerState=function(n){this.currIdx=n},i.prototype.resetLexerState=function(){this.currIdx=-1},i.prototype.moveToTerminatedState=function(){this.currIdx=this.tokVector.length-1},i.prototype.getLexerPosition=function(){return this.exportLexerState()},i})();e.LexerAdapter=r}),Dk=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.RecognizerApi=void 0;var t=Ai(),r=mu(),i=Ns(),n=xf(),s=kw(),a=xs(),o=(function(){function l(){}return l.prototype.ACTION=function(c){return c.call(this)},l.prototype.consume=function(c,u,d){return this.consumeInternal(u,c,d)},l.prototype.subrule=function(c,u,d){return this.subruleInternal(u,c,d)},l.prototype.option=function(c,u){return this.optionInternal(u,c)},l.prototype.or=function(c,u){return this.orInternal(u,c)},l.prototype.many=function(c,u){return this.manyInternal(c,u)},l.prototype.atLeastOne=function(c,u){return this.atLeastOneInternal(c,u)},l.prototype.CONSUME=function(c,u){return this.consumeInternal(c,0,u)},l.prototype.CONSUME1=function(c,u){return this.consumeInternal(c,1,u)},l.prototype.CONSUME2=function(c,u){return this.consumeInternal(c,2,u)},l.prototype.CONSUME3=function(c,u){return this.consumeInternal(c,3,u)},l.prototype.CONSUME4=function(c,u){return this.consumeInternal(c,4,u)},l.prototype.CONSUME5=function(c,u){return this.consumeInternal(c,5,u)},l.prototype.CONSUME6=function(c,u){return this.consumeInternal(c,6,u)},l.prototype.CONSUME7=function(c,u){return this.consumeInternal(c,7,u)},l.prototype.CONSUME8=function(c,u){return this.consumeInternal(c,8,u)},l.prototype.CONSUME9=function(c,u){return this.consumeInternal(c,9,u)},l.prototype.SUBRULE=function(c,u){return this.subruleInternal(c,0,u)},l.prototype.SUBRULE1=function(c,u){return this.subruleInternal(c,1,u)},l.prototype.SUBRULE2=function(c,u){return this.subruleInternal(c,2,u)},l.prototype.SUBRULE3=function(c,u){return this.subruleInternal(c,3,u)},l.prototype.SUBRULE4=function(c,u){return this.subruleInternal(c,4,u)},l.prototype.SUBRULE5=function(c,u){return this.subruleInternal(c,5,u)},l.prototype.SUBRULE6=function(c,u){return this.subruleInternal(c,6,u)},l.prototype.SUBRULE7=function(c,u){return this.subruleInternal(c,7,u)},l.prototype.SUBRULE8=function(c,u){return this.subruleInternal(c,8,u)},l.prototype.SUBRULE9=function(c,u){return this.subruleInternal(c,9,u)},l.prototype.OPTION=function(c){return this.optionInternal(c,0)},l.prototype.OPTION1=function(c){return this.optionInternal(c,1)},l.prototype.OPTION2=function(c){return this.optionInternal(c,2)},l.prototype.OPTION3=function(c){return this.optionInternal(c,3)},l.prototype.OPTION4=function(c){return this.optionInternal(c,4)},l.prototype.OPTION5=function(c){return this.optionInternal(c,5)},l.prototype.OPTION6=function(c){return this.optionInternal(c,6)},l.prototype.OPTION7=function(c){return this.optionInternal(c,7)},l.prototype.OPTION8=function(c){return this.optionInternal(c,8)},l.prototype.OPTION9=function(c){return this.optionInternal(c,9)},l.prototype.OR=function(c){return this.orInternal(c,0)},l.prototype.OR1=function(c){return this.orInternal(c,1)},l.prototype.OR2=function(c){return this.orInternal(c,2)},l.prototype.OR3=function(c){return this.orInternal(c,3)},l.prototype.OR4=function(c){return this.orInternal(c,4)},l.prototype.OR5=function(c){return this.orInternal(c,5)},l.prototype.OR6=function(c){return this.orInternal(c,6)},l.prototype.OR7=function(c){return this.orInternal(c,7)},l.prototype.OR8=function(c){return this.orInternal(c,8)},l.prototype.OR9=function(c){return this.orInternal(c,9)},l.prototype.MANY=function(c){this.manyInternal(0,c)},l.prototype.MANY1=function(c){this.manyInternal(1,c)},l.prototype.MANY2=function(c){this.manyInternal(2,c)},l.prototype.MANY3=function(c){this.manyInternal(3,c)},l.prototype.MANY4=function(c){this.manyInternal(4,c)},l.prototype.MANY5=function(c){this.manyInternal(5,c)},l.prototype.MANY6=function(c){this.manyInternal(6,c)},l.prototype.MANY7=function(c){this.manyInternal(7,c)},l.prototype.MANY8=function(c){this.manyInternal(8,c)},l.prototype.MANY9=function(c){this.manyInternal(9,c)},l.prototype.MANY_SEP=function(c){this.manySepFirstInternal(0,c)},l.prototype.MANY_SEP1=function(c){this.manySepFirstInternal(1,c)},l.prototype.MANY_SEP2=function(c){this.manySepFirstInternal(2,c)},l.prototype.MANY_SEP3=function(c){this.manySepFirstInternal(3,c)},l.prototype.MANY_SEP4=function(c){this.manySepFirstInternal(4,c)},l.prototype.MANY_SEP5=function(c){this.manySepFirstInternal(5,c)},l.prototype.MANY_SEP6=function(c){this.manySepFirstInternal(6,c)},l.prototype.MANY_SEP7=function(c){this.manySepFirstInternal(7,c)},l.prototype.MANY_SEP8=function(c){this.manySepFirstInternal(8,c)},l.prototype.MANY_SEP9=function(c){this.manySepFirstInternal(9,c)},l.prototype.AT_LEAST_ONE=function(c){this.atLeastOneInternal(0,c)},l.prototype.AT_LEAST_ONE1=function(c){return this.atLeastOneInternal(1,c)},l.prototype.AT_LEAST_ONE2=function(c){this.atLeastOneInternal(2,c)},l.prototype.AT_LEAST_ONE3=function(c){this.atLeastOneInternal(3,c)},l.prototype.AT_LEAST_ONE4=function(c){this.atLeastOneInternal(4,c)},l.prototype.AT_LEAST_ONE5=function(c){this.atLeastOneInternal(5,c)},l.prototype.AT_LEAST_ONE6=function(c){this.atLeastOneInternal(6,c)},l.prototype.AT_LEAST_ONE7=function(c){this.atLeastOneInternal(7,c)},l.prototype.AT_LEAST_ONE8=function(c){this.atLeastOneInternal(8,c)},l.prototype.AT_LEAST_ONE9=function(c){this.atLeastOneInternal(9,c)},l.prototype.AT_LEAST_ONE_SEP=function(c){this.atLeastOneSepFirstInternal(0,c)},l.prototype.AT_LEAST_ONE_SEP1=function(c){this.atLeastOneSepFirstInternal(1,c)},l.prototype.AT_LEAST_ONE_SEP2=function(c){this.atLeastOneSepFirstInternal(2,c)},l.prototype.AT_LEAST_ONE_SEP3=function(c){this.atLeastOneSepFirstInternal(3,c)},l.prototype.AT_LEAST_ONE_SEP4=function(c){this.atLeastOneSepFirstInternal(4,c)},l.prototype.AT_LEAST_ONE_SEP5=function(c){this.atLeastOneSepFirstInternal(5,c)},l.prototype.AT_LEAST_ONE_SEP6=function(c){this.atLeastOneSepFirstInternal(6,c)},l.prototype.AT_LEAST_ONE_SEP7=function(c){this.atLeastOneSepFirstInternal(7,c)},l.prototype.AT_LEAST_ONE_SEP8=function(c){this.atLeastOneSepFirstInternal(8,c)},l.prototype.AT_LEAST_ONE_SEP9=function(c){this.atLeastOneSepFirstInternal(9,c)},l.prototype.RULE=function(c,u,d){if(d===void 0&&(d=i.DEFAULT_RULE_CONFIG),t.contains(this.definedRulesNames,c)){var f=n.defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({topLevelRule:c,grammarName:this.className}),y={message:f,type:i.ParserDefinitionErrorType.DUPLICATE_RULE_NAME,ruleName:c};this.definitionErrors.push(y)}this.definedRulesNames.push(c);var b=this.defineRule(c,u,d);return this[c]=b,b},l.prototype.OVERRIDE_RULE=function(c,u,d){d===void 0&&(d=i.DEFAULT_RULE_CONFIG);var f=[];f=f.concat(s.validateRuleIsOverridden(c,this.definedRulesNames,this.className)),this.definitionErrors=this.definitionErrors.concat(f);var y=this.defineRule(c,u,d);return this[c]=y,y},l.prototype.BACKTRACK=function(c,u){return function(){this.isBackTrackingStack.push(1);var d=this.saveRecogState();try{return c.apply(this,u),!0}catch(f){if(r.isRecognitionException(f))return!1;throw f}finally{this.reloadRecogState(d),this.isBackTrackingStack.pop()}}},l.prototype.getGAstProductions=function(){return this.gastProductionsCache},l.prototype.getSerializedGastProductions=function(){return a.serializeGrammar(t.values(this.gastProductionsCache))},l})();e.RecognizerApi=o}),Uk=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.RecognizerEngine=void 0;var t=Ai(),r=e0(),i=mu(),n=wf(),s=bf(),a=Ns(),o=Ow(),l=gl(),c=pu(),u=Dw(),d=(function(){function f(){}return f.prototype.initRecognizerEngine=function(y,b){if(this.className=u.classNameFromInstance(this),this.shortRuleNameToFull={},this.fullRuleNameToShort={},this.ruleShortNameIdx=256,this.tokenMatcher=c.tokenStructuredMatcherNoCategories,this.definedRulesNames=[],this.tokensMap={},this.isBackTrackingStack=[],this.RULE_STACK=[],this.RULE_OCCURRENCE_STACK=[],this.gastProductionsCache={},t.has(b,"serializedGrammar"))throw Error(`The Parser's configuration can no longer contain a <serializedGrammar> property.
	See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0
	For Further details.`);if(t.isArray(y)){if(t.isEmpty(y))throw Error(`A Token Vocabulary cannot be empty.
	Note that the first argument for the parser constructor
	is no longer a Token vector (since v4.0).`);if(typeof y[0].startOffset=="number")throw Error(`The Parser constructor no longer accepts a token vector as the first argument.
	See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0
	For Further details.`)}if(t.isArray(y))this.tokensMap=t.reduce(y,function(_,E){return _[E.name]=E,_},{});else if(t.has(y,"modes")&&t.every(t.flatten(t.values(y.modes)),c.isTokenType)){var x=t.flatten(t.values(y.modes)),g=t.uniq(x);this.tokensMap=t.reduce(g,function(_,E){return _[E.name]=E,_},{})}else if(t.isObject(y))this.tokensMap=t.cloneObj(y);else throw new Error("<tokensDictionary> argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition");this.tokensMap.EOF=l.EOF;var v=t.every(t.values(y),function(_){return t.isEmpty(_.categoryMatches)});this.tokenMatcher=v?c.tokenStructuredMatcherNoCategories:c.tokenStructuredMatcher,c.augmentTokenTypes(t.values(this.tokensMap))},f.prototype.defineRule=function(y,b,x){if(this.selfAnalysisDone)throw Error("Grammar rule <"+y+`> may not be defined after the 'performSelfAnalysis' method has been called'
Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`);var g=t.has(x,"resyncEnabled")?x.resyncEnabled:a.DEFAULT_RULE_CONFIG.resyncEnabled,v=t.has(x,"recoveryValueFunc")?x.recoveryValueFunc:a.DEFAULT_RULE_CONFIG.recoveryValueFunc,_=this.ruleShortNameIdx<<r.BITS_FOR_METHOD_TYPE+r.BITS_FOR_OCCURRENCE_IDX;this.ruleShortNameIdx++,this.shortRuleNameToFull[_]=y,this.fullRuleNameToShort[y]=_;function E(k){try{if(this.outputCst===!0){b.apply(this,k);var z=this.CST_STACK[this.CST_STACK.length-1];return this.cstPostRule(z),z}else return b.apply(this,k)}catch(D){return this.invokeRuleCatch(D,g,v)}finally{this.ruleFinallyStateUpdate()}}var M=function(k,z){return k===void 0&&(k=0),this.ruleInvocationStateUpdate(_,y,k),E.call(this,z)},P="ruleName";return M[P]=y,M.originalGrammarAction=b,M},f.prototype.invokeRuleCatch=function(y,b,x){var g=this.RULE_STACK.length===1,v=b&&!this.isBackTracking()&&this.recoveryEnabled;if(i.isRecognitionException(y)){var _=y;if(v){var E=this.findReSyncTokenType();if(this.isInCurrentRuleReSyncSet(E))if(_.resyncedTokens=this.reSyncTo(E),this.outputCst){var M=this.CST_STACK[this.CST_STACK.length-1];return M.recoveredNode=!0,M}else return x();else{if(this.outputCst){var M=this.CST_STACK[this.CST_STACK.length-1];M.recoveredNode=!0,_.partialCstResult=M}throw _}}else{if(g)return this.moveToTerminatedState(),x();throw _}}else throw y},f.prototype.optionInternal=function(y,b){var x=this.getKeyForAutomaticLookahead(r.OPTION_IDX,b);return this.optionInternalLogic(y,b,x)},f.prototype.optionInternalLogic=function(y,b,x){var g=this,v=this.getLaFuncFromCache(x),_,E;if(y.DEF!==void 0){if(_=y.DEF,E=y.GATE,E!==void 0){var M=v;v=function(){return E.call(g)&&M.call(g)}}}else _=y;if(v.call(this)===!0)return _.call(this)},f.prototype.atLeastOneInternal=function(y,b){var x=this.getKeyForAutomaticLookahead(r.AT_LEAST_ONE_IDX,y);return this.atLeastOneInternalLogic(y,b,x)},f.prototype.atLeastOneInternalLogic=function(y,b,x){var g=this,v=this.getLaFuncFromCache(x),_,E;if(b.DEF!==void 0){if(_=b.DEF,E=b.GATE,E!==void 0){var M=v;v=function(){return E.call(g)&&M.call(g)}}}else _=b;if(v.call(this)===!0)for(var P=this.doSingleRepetition(_);v.call(this)===!0&&P===!0;)P=this.doSingleRepetition(_);else throw this.raiseEarlyExitException(y,n.PROD_TYPE.REPETITION_MANDATORY,b.ERR_MSG);this.attemptInRepetitionRecovery(this.atLeastOneInternal,[y,b],v,r.AT_LEAST_ONE_IDX,y,s.NextTerminalAfterAtLeastOneWalker)},f.prototype.atLeastOneSepFirstInternal=function(y,b){var x=this.getKeyForAutomaticLookahead(r.AT_LEAST_ONE_SEP_IDX,y);this.atLeastOneSepFirstInternalLogic(y,b,x)},f.prototype.atLeastOneSepFirstInternalLogic=function(y,b,x){var g=this,v=b.DEF,_=b.SEP,E=this.getLaFuncFromCache(x);if(E.call(this)===!0){v.call(this);for(var M=function(){return g.tokenMatcher(g.LA(1),_)};this.tokenMatcher(this.LA(1),_)===!0;)this.CONSUME(_),v.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[y,_,M,v,s.NextTerminalAfterAtLeastOneSepWalker],M,r.AT_LEAST_ONE_SEP_IDX,y,s.NextTerminalAfterAtLeastOneSepWalker)}else throw this.raiseEarlyExitException(y,n.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR,b.ERR_MSG)},f.prototype.manyInternal=function(y,b){var x=this.getKeyForAutomaticLookahead(r.MANY_IDX,y);return this.manyInternalLogic(y,b,x)},f.prototype.manyInternalLogic=function(y,b,x){var g=this,v=this.getLaFuncFromCache(x),_,E;if(b.DEF!==void 0){if(_=b.DEF,E=b.GATE,E!==void 0){var M=v;v=function(){return E.call(g)&&M.call(g)}}}else _=b;for(var P=!0;v.call(this)===!0&&P===!0;)P=this.doSingleRepetition(_);this.attemptInRepetitionRecovery(this.manyInternal,[y,b],v,r.MANY_IDX,y,s.NextTerminalAfterManyWalker,P)},f.prototype.manySepFirstInternal=function(y,b){var x=this.getKeyForAutomaticLookahead(r.MANY_SEP_IDX,y);this.manySepFirstInternalLogic(y,b,x)},f.prototype.manySepFirstInternalLogic=function(y,b,x){var g=this,v=b.DEF,_=b.SEP,E=this.getLaFuncFromCache(x);if(E.call(this)===!0){v.call(this);for(var M=function(){return g.tokenMatcher(g.LA(1),_)};this.tokenMatcher(this.LA(1),_)===!0;)this.CONSUME(_),v.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[y,_,M,v,s.NextTerminalAfterManySepWalker],M,r.MANY_SEP_IDX,y,s.NextTerminalAfterManySepWalker)}},f.prototype.repetitionSepSecondInternal=function(y,b,x,g,v){for(;x();)this.CONSUME(b),g.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[y,b,x,g,v],x,r.AT_LEAST_ONE_SEP_IDX,y,v)},f.prototype.doSingleRepetition=function(y){var b=this.getLexerPosition();y.call(this);var x=this.getLexerPosition();return x>b},f.prototype.orInternal=function(y,b){var x=this.getKeyForAutomaticLookahead(r.OR_IDX,b),g=t.isArray(y)?y:y.DEF,v=this.getLaFuncFromCache(x),_=v.call(this,g);if(_!==void 0){var E=g[_];return E.ALT.call(this)}this.raiseNoAltException(b,y.ERR_MSG)},f.prototype.ruleFinallyStateUpdate=function(){if(this.RULE_STACK.pop(),this.RULE_OCCURRENCE_STACK.pop(),this.cstFinallyStateUpdate(),this.RULE_STACK.length===0&&this.isAtEndOfInput()===!1){var y=this.LA(1),b=this.errorMessageProvider.buildNotAllInputParsedMessage({firstRedundant:y,ruleName:this.getCurrRuleFullName()});this.SAVE_ERROR(new i.NotAllInputParsedException(b,y))}},f.prototype.subruleInternal=function(y,b,x){var g;try{var v=x!==void 0?x.ARGS:void 0;return g=y.call(this,b,v),this.cstPostNonTerminal(g,x!==void 0&&x.LABEL!==void 0?x.LABEL:y.ruleName),g}catch(_){this.subruleInternalError(_,x,y.ruleName)}},f.prototype.subruleInternalError=function(y,b,x){throw i.isRecognitionException(y)&&y.partialCstResult!==void 0&&(this.cstPostNonTerminal(y.partialCstResult,b!==void 0&&b.LABEL!==void 0?b.LABEL:x),delete y.partialCstResult),y},f.prototype.consumeInternal=function(y,b,x){var g;try{var v=this.LA(1);this.tokenMatcher(v,y)===!0?(this.consumeToken(),g=v):this.consumeInternalError(y,v,x)}catch(_){g=this.consumeInternalRecovery(y,b,_)}return this.cstPostTerminal(x!==void 0&&x.LABEL!==void 0?x.LABEL:y.name,g),g},f.prototype.consumeInternalError=function(y,b,x){var g,v=this.LA(0);throw x!==void 0&&x.ERR_MSG?g=x.ERR_MSG:g=this.errorMessageProvider.buildMismatchTokenMessage({expected:y,actual:b,previous:v,ruleName:this.getCurrRuleFullName()}),this.SAVE_ERROR(new i.MismatchedTokenException(g,b,v))},f.prototype.consumeInternalRecovery=function(y,b,x){if(this.recoveryEnabled&&x.name==="MismatchedTokenException"&&!this.isBackTracking()){var g=this.getFollowsForInRuleRecovery(y,b);try{return this.tryInRuleRecovery(y,g)}catch(v){throw v.name===o.IN_RULE_RECOVERY_EXCEPTION?x:v}}else throw x},f.prototype.saveRecogState=function(){var y=this.errors,b=t.cloneArr(this.RULE_STACK);return{errors:y,lexerState:this.exportLexerState(),RULE_STACK:b,CST_STACK:this.CST_STACK}},f.prototype.reloadRecogState=function(y){this.errors=y.errors,this.importLexerState(y.lexerState),this.RULE_STACK=y.RULE_STACK},f.prototype.ruleInvocationStateUpdate=function(y,b,x){this.RULE_OCCURRENCE_STACK.push(x),this.RULE_STACK.push(y),this.cstInvocationStateUpdate(b,y)},f.prototype.isBackTracking=function(){return this.isBackTrackingStack.length!==0},f.prototype.getCurrRuleFullName=function(){var y=this.getLastExplicitRuleShortName();return this.shortRuleNameToFull[y]},f.prototype.shortRuleNameToFullName=function(y){return this.shortRuleNameToFull[y]},f.prototype.isAtEndOfInput=function(){return this.tokenMatcher(this.LA(1),l.EOF)},f.prototype.reset=function(){this.resetLexerState(),this.isBackTrackingStack=[],this.errors=[],this.RULE_STACK=[],this.CST_STACK=[],this.RULE_OCCURRENCE_STACK=[]},f})();e.RecognizerEngine=d}),Fk=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ErrorHandler=void 0;var t=mu(),r=Ai(),i=wf(),n=Ns(),s=(function(){function a(){}return a.prototype.initErrorHandler=function(o){this._errors=[],this.errorMessageProvider=r.has(o,"errorMessageProvider")?o.errorMessageProvider:n.DEFAULT_PARSER_CONFIG.errorMessageProvider},a.prototype.SAVE_ERROR=function(o){if(t.isRecognitionException(o))return o.context={ruleStack:this.getHumanReadableRuleStack(),ruleOccurrenceStack:r.cloneArr(this.RULE_OCCURRENCE_STACK)},this._errors.push(o),o;throw Error("Trying to save an Error which is not a RecognitionException")},Object.defineProperty(a.prototype,"errors",{get:function(){return r.cloneArr(this._errors)},set:function(o){this._errors=o},enumerable:!1,configurable:!0}),a.prototype.raiseEarlyExitException=function(o,l,c){for(var u=this.getCurrRuleFullName(),d=this.getGAstProductions()[u],f=i.getLookaheadPathsForOptionalProd(o,d,l,this.maxLookahead),y=f[0],b=[],x=1;x<=this.maxLookahead;x++)b.push(this.LA(x));var g=this.errorMessageProvider.buildEarlyExitMessage({expectedIterationPaths:y,actual:b,previous:this.LA(0),customUserDescription:c,ruleName:u});throw this.SAVE_ERROR(new t.EarlyExitException(g,this.LA(1),this.LA(0)))},a.prototype.raiseNoAltException=function(o,l){for(var c=this.getCurrRuleFullName(),u=this.getGAstProductions()[c],d=i.getLookaheadPathsForOr(o,u,this.maxLookahead),f=[],y=1;y<=this.maxLookahead;y++)f.push(this.LA(y));var b=this.LA(0),x=this.errorMessageProvider.buildNoViableAltMessage({expectedPathsPerAlt:d,actual:f,previous:b,customUserDescription:l,ruleName:this.getCurrRuleFullName()});throw this.SAVE_ERROR(new t.NoViableAltException(x,this.LA(1),b))},a})();e.ErrorHandler=s}),zk=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ContentAssist=void 0;var t=bf(),r=Ai(),i=(function(){function n(){}return n.prototype.initContentAssist=function(){},n.prototype.computeContentAssist=function(s,a){var o=this.gastProductionsCache[s];if(r.isUndefined(o))throw Error("Rule ->"+s+"<- does not exist in this grammar.");return t.nextPossibleTokensAfter([o],a,this.tokenMatcher,this.maxLookahead)},n.prototype.getNextPossibleTokenTypes=function(s){var a=r.first(s.ruleStack),o=this.getGAstProductions(),l=o[a],c=new t.NextAfterTokenWalker(l,s).startWalking();return c},n})();e.ContentAssist=i}),Bk=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.GastRecorder=void 0;var t=Ai(),r=xs(),i=yf(),n=pu(),s=gl(),a=Ns(),o=e0(),l={description:"This Object indicates the Parser is during Recording Phase"};Object.freeze(l);var c=!0,u=Math.pow(2,o.BITS_FOR_OCCURRENCE_IDX)-1,d=s.createToken({name:"RECORDING_PHASE_TOKEN",pattern:i.Lexer.NA});n.augmentTokenTypes([d]);var f=s.createTokenInstance(d,`This IToken indicates the Parser is in Recording Phase
	See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,-1,-1,-1,-1,-1,-1);Object.freeze(f);var y={name:`This CSTNode indicates the Parser is in Recording Phase
	See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,children:{}},b=(function(){function E(){}return E.prototype.initGastRecorder=function(M){this.recordingProdStack=[],this.RECORDING_PHASE=!1},E.prototype.enableRecording=function(){var M=this;this.RECORDING_PHASE=!0,this.TRACE_INIT("Enable Recording",function(){for(var P=function(z){var D=z>0?z:"";M["CONSUME"+D]=function(I,L){return this.consumeInternalRecord(I,z,L)},M["SUBRULE"+D]=function(I,L){return this.subruleInternalRecord(I,z,L)},M["OPTION"+D]=function(I){return this.optionInternalRecord(I,z)},M["OR"+D]=function(I){return this.orInternalRecord(I,z)},M["MANY"+D]=function(I){this.manyInternalRecord(z,I)},M["MANY_SEP"+D]=function(I){this.manySepFirstInternalRecord(z,I)},M["AT_LEAST_ONE"+D]=function(I){this.atLeastOneInternalRecord(z,I)},M["AT_LEAST_ONE_SEP"+D]=function(I){this.atLeastOneSepFirstInternalRecord(z,I)}},k=0;k<10;k++)P(k);M.consume=function(z,D,I){return this.consumeInternalRecord(D,z,I)},M.subrule=function(z,D,I){return this.subruleInternalRecord(D,z,I)},M.option=function(z,D){return this.optionInternalRecord(D,z)},M.or=function(z,D){return this.orInternalRecord(D,z)},M.many=function(z,D){this.manyInternalRecord(z,D)},M.atLeastOne=function(z,D){this.atLeastOneInternalRecord(z,D)},M.ACTION=M.ACTION_RECORD,M.BACKTRACK=M.BACKTRACK_RECORD,M.LA=M.LA_RECORD})},E.prototype.disableRecording=function(){var M=this;this.RECORDING_PHASE=!1,this.TRACE_INIT("Deleting Recording methods",function(){for(var P=0;P<10;P++){var k=P>0?P:"";delete M["CONSUME"+k],delete M["SUBRULE"+k],delete M["OPTION"+k],delete M["OR"+k],delete M["MANY"+k],delete M["MANY_SEP"+k],delete M["AT_LEAST_ONE"+k],delete M["AT_LEAST_ONE_SEP"+k]}delete M.consume,delete M.subrule,delete M.option,delete M.or,delete M.many,delete M.atLeastOne,delete M.ACTION,delete M.BACKTRACK,delete M.LA})},E.prototype.ACTION_RECORD=function(M){},E.prototype.BACKTRACK_RECORD=function(M,P){return function(){return!0}},E.prototype.LA_RECORD=function(M){return a.END_OF_FILE},E.prototype.topLevelRuleRecord=function(M,P){try{var k=new r.Rule({definition:[],name:M});return k.name=M,this.recordingProdStack.push(k),P.call(this),this.recordingProdStack.pop(),k}catch(z){if(z.KNOWN_RECORDER_ERROR!==!0)try{z.message=z.message+`
	 This error was thrown during the "grammar recording phase" For more info see:
	https://chevrotain.io/docs/guide/internals.html#grammar-recording`}catch{throw z}throw z}},E.prototype.optionInternalRecord=function(M,P){return x.call(this,r.Option,M,P)},E.prototype.atLeastOneInternalRecord=function(M,P){x.call(this,r.RepetitionMandatory,P,M)},E.prototype.atLeastOneSepFirstInternalRecord=function(M,P){x.call(this,r.RepetitionMandatoryWithSeparator,P,M,c)},E.prototype.manyInternalRecord=function(M,P){x.call(this,r.Repetition,P,M)},E.prototype.manySepFirstInternalRecord=function(M,P){x.call(this,r.RepetitionWithSeparator,P,M,c)},E.prototype.orInternalRecord=function(M,P){return g.call(this,M,P)},E.prototype.subruleInternalRecord=function(M,P,k){if(_(P),!M||t.has(M,"ruleName")===!1){var z=new Error("<SUBRULE"+v(P)+"> argument is invalid"+(" expecting a Parser method reference but got: <"+JSON.stringify(M)+">")+(`
 inside top level rule: <`+this.recordingProdStack[0].name+">"));throw z.KNOWN_RECORDER_ERROR=!0,z}var D=t.peek(this.recordingProdStack),I=M.ruleName,L=new r.NonTerminal({idx:P,nonTerminalName:I,referencedRule:void 0});return D.definition.push(L),this.outputCst?y:l},E.prototype.consumeInternalRecord=function(M,P,k){if(_(P),!n.hasShortKeyProperty(M)){var z=new Error("<CONSUME"+v(P)+"> argument is invalid"+(" expecting a TokenType reference but got: <"+JSON.stringify(M)+">")+(`
 inside top level rule: <`+this.recordingProdStack[0].name+">"));throw z.KNOWN_RECORDER_ERROR=!0,z}var D=t.peek(this.recordingProdStack),I=new r.Terminal({idx:P,terminalType:M});return D.definition.push(I),f},E})();e.GastRecorder=b;function x(E,M,P,k){k===void 0&&(k=!1),_(P);var z=t.peek(this.recordingProdStack),D=t.isFunction(M)?M:M.DEF,I=new E({definition:[],idx:P});return k&&(I.separator=M.SEP),t.has(M,"MAX_LOOKAHEAD")&&(I.maxLookahead=M.MAX_LOOKAHEAD),this.recordingProdStack.push(I),D.call(this),z.definition.push(I),this.recordingProdStack.pop(),l}function g(E,M){var P=this;_(M);var k=t.peek(this.recordingProdStack),z=t.isArray(E)===!1,D=z===!1?E:E.DEF,I=new r.Alternation({definition:[],idx:M,ignoreAmbiguities:z&&E.IGNORE_AMBIGUITIES===!0});t.has(E,"MAX_LOOKAHEAD")&&(I.maxLookahead=E.MAX_LOOKAHEAD);var L=t.some(D,function(Z){return t.isFunction(Z.GATE)});return I.hasPredicates=L,k.definition.push(I),t.forEach(D,function(Z){var se=new r.Alternative({definition:[]});I.definition.push(se),t.has(Z,"IGNORE_AMBIGUITIES")?se.ignoreAmbiguities=Z.IGNORE_AMBIGUITIES:t.has(Z,"GATE")&&(se.ignoreAmbiguities=!0),P.recordingProdStack.push(se),Z.ALT.call(P),P.recordingProdStack.pop()}),l}function v(E){return E===0?"":""+E}function _(E){if(E<0||E>u){var M=new Error("Invalid DSL Method idx value: <"+E+`>
	`+("Idx value must be a none negative value smaller than "+(u+1)));throw M.KNOWN_RECORDER_ERROR=!0,M}}}),jk=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.PerformanceTracer=void 0;var t=Ai(),r=Ns(),i=(function(){function n(){}return n.prototype.initPerformanceTracer=function(s){if(t.has(s,"traceInitPerf")){var a=s.traceInitPerf,o=typeof a=="number";this.traceInitMaxIdent=o?a:1/0,this.traceInitPerf=o?a>0:a}else this.traceInitMaxIdent=0,this.traceInitPerf=r.DEFAULT_PARSER_CONFIG.traceInitPerf;this.traceInitIndent=-1},n.prototype.TRACE_INIT=function(s,a){if(this.traceInitPerf===!0){this.traceInitIndent++;var o=new Array(this.traceInitIndent+1).join("	");this.traceInitIndent<this.traceInitMaxIdent&&console.log(o+"--> <"+s+">");var l=t.timer(a),c=l.time,u=l.value,d=c>10?console.warn:console.log;return this.traceInitIndent<this.traceInitMaxIdent&&d(o+"<-- <"+s+"> time: "+c+"ms"),this.traceInitIndent--,u}else return a()},n})();e.PerformanceTracer=i}),Vk=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.applyMixins=void 0;function t(r,i){i.forEach(function(n){var s=n.prototype;Object.getOwnPropertyNames(s).forEach(function(a){if(a!=="constructor"){var o=Object.getOwnPropertyDescriptor(s,a);o&&(o.get||o.set)?Object.defineProperty(r.prototype,a,o):r.prototype[a]=n.prototype[a]}})})}e.applyMixins=t}),Ns=ri(e=>{"use strict";var t=e&&e.__extends||(function(){var z=function(D,I){return z=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(L,Z){L.__proto__=Z}||function(L,Z){for(var se in Z)Object.prototype.hasOwnProperty.call(Z,se)&&(L[se]=Z[se])},z(D,I)};return function(D,I){if(typeof I!="function"&&I!==null)throw new TypeError("Class extends value "+String(I)+" is not a constructor or null");z(D,I);function L(){this.constructor=D}D.prototype=I===null?Object.create(I):(L.prototype=I.prototype,new L)}})();Object.defineProperty(e,"__esModule",{value:!0}),e.EmbeddedActionsParser=e.CstParser=e.Parser=e.EMPTY_ALT=e.ParserDefinitionErrorType=e.DEFAULT_RULE_CONFIG=e.DEFAULT_PARSER_CONFIG=e.END_OF_FILE=void 0;var r=Ai(),i=Ck(),n=gl(),s=xf(),a=Pk(),o=Ow(),l=Ik(),c=kk(),u=Ok(),d=Dk(),f=Uk(),y=Fk(),b=zk(),x=Bk(),g=jk(),v=Vk();e.END_OF_FILE=n.createTokenInstance(n.EOF,"",NaN,NaN,NaN,NaN,NaN,NaN),Object.freeze(e.END_OF_FILE),e.DEFAULT_PARSER_CONFIG=Object.freeze({recoveryEnabled:!1,maxLookahead:3,dynamicTokensEnabled:!1,outputCst:!0,errorMessageProvider:s.defaultParserErrorProvider,nodeLocationTracking:"none",traceInitPerf:!1,skipValidations:!1}),e.DEFAULT_RULE_CONFIG=Object.freeze({recoveryValueFunc:function(){},resyncEnabled:!0});var _;(function(z){z[z.INVALID_RULE_NAME=0]="INVALID_RULE_NAME",z[z.DUPLICATE_RULE_NAME=1]="DUPLICATE_RULE_NAME",z[z.INVALID_RULE_OVERRIDE=2]="INVALID_RULE_OVERRIDE",z[z.DUPLICATE_PRODUCTIONS=3]="DUPLICATE_PRODUCTIONS",z[z.UNRESOLVED_SUBRULE_REF=4]="UNRESOLVED_SUBRULE_REF",z[z.LEFT_RECURSION=5]="LEFT_RECURSION",z[z.NONE_LAST_EMPTY_ALT=6]="NONE_LAST_EMPTY_ALT",z[z.AMBIGUOUS_ALTS=7]="AMBIGUOUS_ALTS",z[z.CONFLICT_TOKENS_RULES_NAMESPACE=8]="CONFLICT_TOKENS_RULES_NAMESPACE",z[z.INVALID_TOKEN_NAME=9]="INVALID_TOKEN_NAME",z[z.NO_NON_EMPTY_LOOKAHEAD=10]="NO_NON_EMPTY_LOOKAHEAD",z[z.AMBIGUOUS_PREFIX_ALTS=11]="AMBIGUOUS_PREFIX_ALTS",z[z.TOO_MANY_ALTS=12]="TOO_MANY_ALTS"})(_=e.ParserDefinitionErrorType||(e.ParserDefinitionErrorType={}));function E(z){return z===void 0&&(z=void 0),function(){return z}}e.EMPTY_ALT=E;var M=(function(){function z(D,I){this.definitionErrors=[],this.selfAnalysisDone=!1;var L=this;if(L.initErrorHandler(I),L.initLexerAdapter(),L.initLooksAhead(I),L.initRecognizerEngine(D,I),L.initRecoverable(I),L.initTreeBuilder(I),L.initContentAssist(),L.initGastRecorder(I),L.initPerformanceTracer(I),r.has(I,"ignoredIssues"))throw new Error(`The <ignoredIssues> IParserConfig property has been deprecated.
	Please use the <IGNORE_AMBIGUITIES> flag on the relevant DSL method instead.
	See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES
	For further details.`);this.skipValidations=r.has(I,"skipValidations")?I.skipValidations:e.DEFAULT_PARSER_CONFIG.skipValidations}return z.performSelfAnalysis=function(D){throw Error("The **static** `performSelfAnalysis` method has been deprecated.	\nUse the **instance** method with the same name instead.")},z.prototype.performSelfAnalysis=function(){var D=this;this.TRACE_INIT("performSelfAnalysis",function(){var I;D.selfAnalysisDone=!0;var L=D.className;D.TRACE_INIT("toFastProps",function(){r.toFastProperties(D)}),D.TRACE_INIT("Grammar Recording",function(){try{D.enableRecording(),r.forEach(D.definedRulesNames,function(se){var ce=D[se],fe=ce.originalGrammarAction,ze=void 0;D.TRACE_INIT(se+" Rule",function(){ze=D.topLevelRuleRecord(se,fe)}),D.gastProductionsCache[se]=ze})}finally{D.disableRecording()}});var Z=[];if(D.TRACE_INIT("Grammar Resolving",function(){Z=a.resolveGrammar({rules:r.values(D.gastProductionsCache)}),D.definitionErrors=D.definitionErrors.concat(Z)}),D.TRACE_INIT("Grammar Validations",function(){if(r.isEmpty(Z)&&D.skipValidations===!1){var se=a.validateGrammar({rules:r.values(D.gastProductionsCache),maxLookahead:D.maxLookahead,tokenTypes:r.values(D.tokensMap),errMsgProvider:s.defaultGrammarValidatorErrorProvider,grammarName:L});D.definitionErrors=D.definitionErrors.concat(se)}}),r.isEmpty(D.definitionErrors)&&(D.recoveryEnabled&&D.TRACE_INIT("computeAllProdsFollows",function(){var se=i.computeAllProdsFollows(r.values(D.gastProductionsCache));D.resyncFollows=se}),D.TRACE_INIT("ComputeLookaheadFunctions",function(){D.preComputeLookaheadFunctions(r.values(D.gastProductionsCache))})),!z.DEFER_DEFINITION_ERRORS_HANDLING&&!r.isEmpty(D.definitionErrors))throw I=r.map(D.definitionErrors,function(se){return se.message}),new Error(`Parser Definition Errors detected:
 `+I.join(`
-------------------------------
`))})},z.DEFER_DEFINITION_ERRORS_HANDLING=!1,z})();e.Parser=M,v.applyMixins(M,[o.Recoverable,l.LooksAhead,c.TreeBuilder,u.LexerAdapter,f.RecognizerEngine,d.RecognizerApi,y.ErrorHandler,b.ContentAssist,x.GastRecorder,g.PerformanceTracer]);var P=(function(z){t(D,z);function D(I,L){L===void 0&&(L=e.DEFAULT_PARSER_CONFIG);var Z=this,se=r.cloneObj(L);return se.outputCst=!0,Z=z.call(this,I,se)||this,Z}return D})(M);e.CstParser=P;var k=(function(z){t(D,z);function D(I,L){L===void 0&&(L=e.DEFAULT_PARSER_CONFIG);var Z=this,se=r.cloneObj(L);return se.outputCst=!1,Z=z.call(this,I,se)||this,Z}return D})(M);e.EmbeddedActionsParser=k}),Hk=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createSyntaxDiagramsCode=void 0;var t=Rw();function r(i,n){var s=n===void 0?{}:n,a=s.resourceBase,o=a===void 0?"https://unpkg.com/chevrotain@"+t.VERSION+"/diagrams/":a,l=s.css,c=l===void 0?"https://unpkg.com/chevrotain@"+t.VERSION+"/diagrams/diagrams.css":l,u=`
<!-- This is a generated file -->
<!DOCTYPE html>
<meta charset="utf-8">
<style>
  body {
    background-color: hsl(30, 20%, 95%)
  }
</style>

`,d=`
<link rel='stylesheet' href='`+c+`'>
`,f=`
<script src='`+o+`vendor/railroad-diagrams.js'><\/script>
<script src='`+o+`src/diagrams_builder.js'><\/script>
<script src='`+o+`src/diagrams_behavior.js'><\/script>
<script src='`+o+`src/main.js'><\/script>
`,y=`
<div id="diagrams" align="center"></div>
`,b=`
<script>
    window.serializedGrammar = `+JSON.stringify(i,null,"  ")+`;
<\/script>
`,x=`
<script>
    var diagramsDiv = document.getElementById("diagrams");
    main.drawDiagramsFromSerializedGrammar(serializedGrammar, diagramsDiv);
<\/script>
`;return u+d+f+y+b+x}e.createSyntaxDiagramsCode=r}),Gk=ri(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Parser=e.createSyntaxDiagramsCode=e.clearCache=e.GAstVisitor=e.serializeProduction=e.serializeGrammar=e.Terminal=e.Rule=e.RepetitionWithSeparator=e.RepetitionMandatoryWithSeparator=e.RepetitionMandatory=e.Repetition=e.Option=e.NonTerminal=e.Alternative=e.Alternation=e.defaultLexerErrorProvider=e.NoViableAltException=e.NotAllInputParsedException=e.MismatchedTokenException=e.isRecognitionException=e.EarlyExitException=e.defaultParserErrorProvider=e.tokenName=e.tokenMatcher=e.tokenLabel=e.EOF=e.createTokenInstance=e.createToken=e.LexerDefinitionErrorType=e.Lexer=e.EMPTY_ALT=e.ParserDefinitionErrorType=e.EmbeddedActionsParser=e.CstParser=e.VERSION=void 0;var t=Rw();Object.defineProperty(e,"VERSION",{enumerable:!0,get:function(){return t.VERSION}});var r=Ns();Object.defineProperty(e,"CstParser",{enumerable:!0,get:function(){return r.CstParser}}),Object.defineProperty(e,"EmbeddedActionsParser",{enumerable:!0,get:function(){return r.EmbeddedActionsParser}}),Object.defineProperty(e,"ParserDefinitionErrorType",{enumerable:!0,get:function(){return r.ParserDefinitionErrorType}}),Object.defineProperty(e,"EMPTY_ALT",{enumerable:!0,get:function(){return r.EMPTY_ALT}});var i=yf();Object.defineProperty(e,"Lexer",{enumerable:!0,get:function(){return i.Lexer}}),Object.defineProperty(e,"LexerDefinitionErrorType",{enumerable:!0,get:function(){return i.LexerDefinitionErrorType}});var n=gl();Object.defineProperty(e,"createToken",{enumerable:!0,get:function(){return n.createToken}}),Object.defineProperty(e,"createTokenInstance",{enumerable:!0,get:function(){return n.createTokenInstance}}),Object.defineProperty(e,"EOF",{enumerable:!0,get:function(){return n.EOF}}),Object.defineProperty(e,"tokenLabel",{enumerable:!0,get:function(){return n.tokenLabel}}),Object.defineProperty(e,"tokenMatcher",{enumerable:!0,get:function(){return n.tokenMatcher}}),Object.defineProperty(e,"tokenName",{enumerable:!0,get:function(){return n.tokenName}});var s=xf();Object.defineProperty(e,"defaultParserErrorProvider",{enumerable:!0,get:function(){return s.defaultParserErrorProvider}});var a=mu();Object.defineProperty(e,"EarlyExitException",{enumerable:!0,get:function(){return a.EarlyExitException}}),Object.defineProperty(e,"isRecognitionException",{enumerable:!0,get:function(){return a.isRecognitionException}}),Object.defineProperty(e,"MismatchedTokenException",{enumerable:!0,get:function(){return a.MismatchedTokenException}}),Object.defineProperty(e,"NotAllInputParsedException",{enumerable:!0,get:function(){return a.NotAllInputParsedException}}),Object.defineProperty(e,"NoViableAltException",{enumerable:!0,get:function(){return a.NoViableAltException}});var o=Iw();Object.defineProperty(e,"defaultLexerErrorProvider",{enumerable:!0,get:function(){return o.defaultLexerErrorProvider}});var l=xs();Object.defineProperty(e,"Alternation",{enumerable:!0,get:function(){return l.Alternation}}),Object.defineProperty(e,"Alternative",{enumerable:!0,get:function(){return l.Alternative}}),Object.defineProperty(e,"NonTerminal",{enumerable:!0,get:function(){return l.NonTerminal}}),Object.defineProperty(e,"Option",{enumerable:!0,get:function(){return l.Option}}),Object.defineProperty(e,"Repetition",{enumerable:!0,get:function(){return l.Repetition}}),Object.defineProperty(e,"RepetitionMandatory",{enumerable:!0,get:function(){return l.RepetitionMandatory}}),Object.defineProperty(e,"RepetitionMandatoryWithSeparator",{enumerable:!0,get:function(){return l.RepetitionMandatoryWithSeparator}}),Object.defineProperty(e,"RepetitionWithSeparator",{enumerable:!0,get:function(){return l.RepetitionWithSeparator}}),Object.defineProperty(e,"Rule",{enumerable:!0,get:function(){return l.Rule}}),Object.defineProperty(e,"Terminal",{enumerable:!0,get:function(){return l.Terminal}});var c=xs();Object.defineProperty(e,"serializeGrammar",{enumerable:!0,get:function(){return c.serializeGrammar}}),Object.defineProperty(e,"serializeProduction",{enumerable:!0,get:function(){return c.serializeProduction}});var u=fu();Object.defineProperty(e,"GAstVisitor",{enumerable:!0,get:function(){return u.GAstVisitor}});function d(){console.warn(`The clearCache function was 'soft' removed from the Chevrotain API.
	 It performs no action other than printing this message.
	 Please avoid using it as it will be completely removed in the future`)}e.clearCache=d;var f=Hk();Object.defineProperty(e,"createSyntaxDiagramsCode",{enumerable:!0,get:function(){return f.createSyntaxDiagramsCode}});var y=(function(){function b(){throw new Error(`The Parser class has been deprecated, use CstParser or EmbeddedActionsParser instead.
See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_7-0-0`)}return b})();e.Parser=y}),gu=Gk(),Wk=class extends mn{constructor(e){super(e)}load(e,t,r,i){let n=this,s=n.path===""?Va.extractUrlBase(e):n.path,a=new Ps(n.manager);a.setPath(n.path),a.setRequestHeader(n.requestHeader),a.setWithCredentials(n.withCredentials),a.load(e,function(o){try{t(n.parse(o,s))}catch(l){i?i(l):console.error(l),n.manager.itemError(e)}},r,i)}parse(e,t){let r={};function i(oe){let F=n(),le=new Xk(F.tokens),pe=new qk(F.tokenVocabulary),Le=s(pe.getBaseCstVisitorConstructor()),He=le.lex(oe);pe.input=He.tokens;let at=pe.vrml();if(pe.errors.length>0)throw console.error(pe.errors),Error("THREE.VRMLLoader: Parsing errors detected.");return Le.visit(at)}function n(){let oe=gu.createToken,F=oe({name:"RouteIdentifier",pattern:/[^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*[\.][^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d][^\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]*/}),le=oe({name:"Identifier",pattern:/[^\x30-\x39\0-\x20\x22\x27\x23\x2b\x2c\x2d\x2e\x5b\x5d\x5c\x7b\x7d]([^\0-\x20\x22\x27\x23\x2b\x2c\x2e\x5b\x5d\x5c\x7b\x7d])*/,longer_alt:F}),pe=["Anchor","Billboard","Collision","Group","Transform","Inline","LOD","Switch","AudioClip","DirectionalLight","PointLight","Script","Shape","Sound","SpotLight","WorldInfo","CylinderSensor","PlaneSensor","ProximitySensor","SphereSensor","TimeSensor","TouchSensor","VisibilitySensor","Box","Cone","Cylinder","ElevationGrid","Extrusion","IndexedFaceSet","IndexedLineSet","PointSet","Sphere","Color","Coordinate","Normal","TextureCoordinate","Appearance","FontStyle","ImageTexture","Material","MovieTexture","PixelTexture","TextureTransform","ColorInterpolator","CoordinateInterpolator","NormalInterpolator","OrientationInterpolator","PositionInterpolator","ScalarInterpolator","Background","Fog","NavigationInfo","Viewpoint","Text"],Le=oe({name:"Version",pattern:/#VRML.*/,longer_alt:le}),He=oe({name:"NodeName",pattern:new RegExp(pe.join("|")),longer_alt:le}),at=oe({name:"DEF",pattern:/DEF/,longer_alt:le}),rt=oe({name:"USE",pattern:/USE/,longer_alt:le}),ht=oe({name:"ROUTE",pattern:/ROUTE/,longer_alt:le}),Tt=oe({name:"TO",pattern:/TO/,longer_alt:le}),Mt=oe({name:"StringLiteral",pattern:/"(?:[^\\"\n\r]|\\[bfnrtv"\\/]|\\u[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F])*"/}),Ut=oe({name:"HexLiteral",pattern:/0[xX][0-9a-fA-F]+/}),Kt=oe({name:"NumberLiteral",pattern:/[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/}),fr=oe({name:"TrueLiteral",pattern:/TRUE/}),er=oe({name:"FalseLiteral",pattern:/FALSE/}),Zt=oe({name:"NullLiteral",pattern:/NULL/}),Gt=oe({name:"LSquare",pattern:/\[/}),Er=oe({name:"RSquare",pattern:/]/}),ut=oe({name:"LCurly",pattern:/{/}),zt=oe({name:"RCurly",pattern:/}/}),It=oe({name:"Comment",pattern:/#.*/,group:gu.Lexer.SKIPPED}),Ct=[oe({name:"WhiteSpace",pattern:/[ ,\s]/,group:gu.Lexer.SKIPPED}),He,at,rt,ht,Tt,fr,er,Zt,Le,le,F,Mt,Ut,Kt,Gt,Er,ut,zt,It],rr={};for(let $t=0,xr=Ct.length;$t<xr;$t++){let cr=Ct[$t];rr[cr.name]=cr}return{tokens:Ct,tokenVocabulary:rr}}function s(oe){class F extends oe{constructor(){super(),this.validateVisitor()}vrml(Le){let He={version:this.visit(Le.version),nodes:[],routes:[]};for(let at=0,rt=Le.node.length;at<rt;at++){let ht=Le.node[at];He.nodes.push(this.visit(ht))}if(Le.route)for(let at=0,rt=Le.route.length;at<rt;at++){let ht=Le.route[at];He.routes.push(this.visit(ht))}return He}version(Le){return Le.Version[0].image}node(Le){let He={name:Le.NodeName[0].image,fields:[]};if(Le.field)for(let at=0,rt=Le.field.length;at<rt;at++){let ht=Le.field[at];He.fields.push(this.visit(ht))}return Le.def&&(He.DEF=this.visit(Le.def[0])),He}field(Le){let He={name:Le.Identifier[0].image,type:null,values:null},at;return Le.singleFieldValue&&(at=this.visit(Le.singleFieldValue[0])),Le.multiFieldValue&&(at=this.visit(Le.multiFieldValue[0])),He.type=at.type,He.values=at.values,He}def(Le){return(Le.Identifier||Le.NodeName)[0].image}use(Le){return{USE:(Le.Identifier||Le.NodeName)[0].image}}singleFieldValue(Le){return le(this,Le)}multiFieldValue(Le){return le(this,Le)}route(Le){return{FROM:Le.RouteIdentifier[0].image,TO:Le.RouteIdentifier[1].image}}}function le(pe,Le){let He={type:null,values:[]};if(Le.node){He.type="node";for(let at=0,rt=Le.node.length;at<rt;at++){let ht=Le.node[at];He.values.push(pe.visit(ht))}}if(Le.use){He.type="use";for(let at=0,rt=Le.use.length;at<rt;at++){let ht=Le.use[at];He.values.push(pe.visit(ht))}}if(Le.StringLiteral){He.type="string";for(let at=0,rt=Le.StringLiteral.length;at<rt;at++){let ht=Le.StringLiteral[at];He.values.push(ht.image.replace(/'|"/g,""))}}if(Le.NumberLiteral){He.type="number";for(let at=0,rt=Le.NumberLiteral.length;at<rt;at++){let ht=Le.NumberLiteral[at];He.values.push(parseFloat(ht.image))}}if(Le.HexLiteral){He.type="hex";for(let at=0,rt=Le.HexLiteral.length;at<rt;at++){let ht=Le.HexLiteral[at];He.values.push(ht.image)}}if(Le.TrueLiteral){He.type="boolean";for(let at=0,rt=Le.TrueLiteral.length;at<rt;at++)Le.TrueLiteral[at].image==="TRUE"&&He.values.push(!0)}if(Le.FalseLiteral){He.type="boolean";for(let at=0,rt=Le.FalseLiteral.length;at<rt;at++)Le.FalseLiteral[at].image==="FALSE"&&He.values.push(!1)}return Le.NullLiteral&&(He.type="null",Le.NullLiteral.forEach(function(){He.values.push(null)})),He}return new F}function a(oe){let F=oe.nodes,le=new Yo;for(let pe=0,Le=F.length;pe<Le;pe++){let He=F[pe];o(He)}for(let pe=0,Le=F.length;pe<Le;pe++){let He=F[pe],at=l(He);at instanceof mi&&le.add(at),He.name==="WorldInfo"&&(le.userData.worldInfo=at)}return le}function o(oe){oe.DEF&&(r[oe.DEF]=oe);let F=oe.fields;for(let le=0,pe=F.length;le<pe;le++){let Le=F[le];if(Le.type==="node"){let He=Le.values;for(let at=0,rt=He.length;at<rt;at++)o(He[at])}}}function l(oe){return oe.USE?ze(oe.USE):(oe.build!==void 0||(oe.build=c(oe)),oe.build)}function c(oe){let F=oe.name,le;switch(F){case"Anchor":case"Group":case"Transform":case"Collision":le=u(oe);break;case"Background":le=d(oe);break;case"Shape":le=f(oe);break;case"Appearance":le=y(oe);break;case"Material":le=b(oe);break;case"ImageTexture":le=_(oe);break;case"PixelTexture":le=v(oe);break;case"TextureTransform":le=E(oe);break;case"IndexedFaceSet":le=k(oe);break;case"IndexedLineSet":le=z(oe);break;case"PointSet":le=D(oe);break;case"Box":le=I(oe);break;case"Cone":le=L(oe);break;case"Cylinder":le=Z(oe);break;case"Sphere":le=se(oe);break;case"ElevationGrid":le=ce(oe);break;case"Extrusion":le=fe(oe);break;case"Color":case"Coordinate":case"Normal":case"TextureCoordinate":le=M(oe);break;case"WorldInfo":le=P(oe);break;case"Billboard":case"Inline":case"LOD":case"Switch":case"AudioClip":case"DirectionalLight":case"PointLight":case"Script":case"Sound":case"SpotLight":case"CylinderSensor":case"PlaneSensor":case"ProximitySensor":case"SphereSensor":case"TimeSensor":case"TouchSensor":case"VisibilitySensor":case"Text":case"FontStyle":case"MovieTexture":case"ColorInterpolator":case"CoordinateInterpolator":case"NormalInterpolator":case"OrientationInterpolator":case"PositionInterpolator":case"ScalarInterpolator":case"Fog":case"NavigationInfo":case"Viewpoint":break;default:console.warn("THREE.VRMLLoader: Unknown node:",F);break}return le!==void 0&&oe.DEF!==void 0&&le.hasOwnProperty("name")===!0&&(le.name=oe.DEF),le}function u(oe){let F=new Wi,le=oe.fields;for(let pe=0,Le=le.length;pe<Le;pe++){let He=le[pe],at=He.name,rt=He.values;switch(at){case"bboxCenter":break;case"bboxSize":break;case"center":break;case"children":Fe(rt,F);break;case"description":break;case"collide":break;case"parameter":break;case"rotation":let ht=new je(rt[0],rt[1],rt[2]).normalize(),Tt=rt[3];F.quaternion.setFromAxisAngle(ht,Tt);break;case"scale":F.scale.set(rt[0],rt[1],rt[2]);break;case"scaleOrientation":break;case"translation":F.position.set(rt[0],rt[1],rt[2]);break;case"proxy":break;case"url":break;default:console.warn("THREE.VRMLLoader: Unknown field:",at);break}}return F}function d(oe){let F=new Wi,le,pe,Le,He,at=oe.fields;for(let ht=0,Tt=at.length;ht<Tt;ht++){let Mt=at[ht],Ut=Mt.name,Kt=Mt.values;switch(Ut){case"groundAngle":le=Kt;break;case"groundColor":pe=Kt;break;case"backUrl":break;case"bottomUrl":break;case"frontUrl":break;case"leftUrl":break;case"rightUrl":break;case"topUrl":break;case"skyAngle":Le=Kt;break;case"skyColor":He=Kt;break;default:console.warn("THREE.VRMLLoader: Unknown field:",Ut);break}}let rt=1e4;if(He){let ht=new po(rt,32,16),Tt=new en({fog:!1,side:tt,depthWrite:!1,depthTest:!1});He.length>3?(mt(ht,rt,Le,Dt(He),!0),Tt.vertexColors=!0):Tt.color.setRGB(He[0],He[1],He[2],xi);let Mt=new qr(ht,Tt);F.add(Mt)}if(pe&&pe.length>0){let ht=new po(rt,32,16,0,2*Math.PI,.5*Math.PI,1.5*Math.PI),Tt=new en({fog:!1,side:tt,vertexColors:!0,depthWrite:!1,depthTest:!1});mt(ht,rt,le,Dt(pe),!1);let Mt=new qr(ht,Tt);F.add(Mt)}return F.renderOrder=-1/0,F}function f(oe){let F=oe.fields,le=new en({name:mn.DEFAULT_MATERIAL_NAME,color:0}),pe;for(let He=0,at=F.length;He<at;He++){let rt=F[He],ht=rt.name,Tt=rt.values;switch(ht){case"appearance":Tt[0]!==null&&(le=l(Tt[0]));break;case"geometry":Tt[0]!==null&&(pe=l(Tt[0]));break;default:console.warn("THREE.VRMLLoader: Unknown field:",ht);break}}let Le;if(pe&&pe.attributes.position){let He=pe._type;if(He==="points"){let at=new $h({name:mn.DEFAULT_MATERIAL_NAME,color:16777215,opacity:le.opacity,transparent:le.transparent});pe.attributes.color!==void 0?at.vertexColors=!0:le.isMeshPhongMaterial&&at.color.copy(le.emissive),Le=new Dp(pe,at)}else if(He==="line"){let at=new tn({name:mn.DEFAULT_MATERIAL_NAME,color:16777215,opacity:le.opacity,transparent:le.transparent});pe.attributes.color!==void 0?at.vertexColors=!0:le.isMeshPhongMaterial&&at.color.copy(le.emissive),Le=new Fn(pe,at)}else pe._solid!==void 0&&(le.side=pe._solid?Ce:Ze),pe.attributes.color!==void 0&&(le.vertexColors=!0),Le=new qr(pe,le)}else Le=new mi,Le.visible=!1;return Le}function y(oe){let F=new oy,le,pe=oe.fields;for(let Le=0,He=pe.length;Le<He;Le++){let at=pe[Le],rt=at.name,ht=at.values;switch(rt){case"material":if(ht[0]!==null){let Mt=l(ht[0]);Mt.diffuseColor&&F.color.copy(Mt.diffuseColor),Mt.emissiveColor&&F.emissive.copy(Mt.emissiveColor),Mt.shininess&&(F.shininess=Mt.shininess),Mt.specularColor&&F.specular.copy(Mt.specularColor),Mt.transparency&&(F.opacity=1-Mt.transparency),Mt.transparency>0&&(F.transparent=!0)}else F=new en({name:mn.DEFAULT_MATERIAL_NAME,color:0});break;case"texture":let Tt=ht[0];Tt!==null&&(Tt.name==="ImageTexture"||Tt.name==="PixelTexture")&&(F.map=l(Tt));break;case"textureTransform":ht[0]!==null&&(le=l(ht[0]));break;default:console.warn("THREE.VRMLLoader: Unknown field:",rt);break}}if(F.map){if(F.map.__type){switch(F.map.__type){case Js.INTENSITY_ALPHA:F.opacity=1;break;case Js.RGB:F.color.set(16777215);break;case Js.RGBA:F.color.set(16777215),F.opacity=1;break;default:}delete F.map.__type}le&&(F.map.center.copy(le.center),F.map.rotation=le.rotation,F.map.repeat.copy(le.scale),F.map.offset.copy(le.translation))}return F}function b(oe){let F={},le=oe.fields;for(let pe=0,Le=le.length;pe<Le;pe++){let He=le[pe],at=He.name,rt=He.values;switch(at){case"ambientIntensity":break;case"diffuseColor":F.diffuseColor=new or().setRGB(rt[0],rt[1],rt[2],xi);break;case"emissiveColor":F.emissiveColor=new or().setRGB(rt[0],rt[1],rt[2],xi);break;case"shininess":F.shininess=rt[0];break;case"specularColor":F.specularColor=new or().setRGB(rt[0],rt[1],rt[2],xi);break;case"transparency":F.transparency=rt[0];break;default:console.warn("THREE.VRMLLoader: Unknown field:",at);break}}return F}function x(oe,F,le){let pe;switch(F){case Js.INTENSITY:pe=parseInt(oe),le.r=pe,le.g=pe,le.b=pe,le.a=1;break;case Js.INTENSITY_ALPHA:pe=parseInt("0x"+oe.substring(2,4)),le.r=pe,le.g=pe,le.b=pe,le.a=parseInt("0x"+oe.substring(4,6));break;case Js.RGB:le.r=parseInt("0x"+oe.substring(2,4)),le.g=parseInt("0x"+oe.substring(4,6)),le.b=parseInt("0x"+oe.substring(6,8)),le.a=1;break;case Js.RGBA:le.r=parseInt("0x"+oe.substring(2,4)),le.g=parseInt("0x"+oe.substring(4,6)),le.b=parseInt("0x"+oe.substring(6,8)),le.a=parseInt("0x"+oe.substring(8,10));break;default:}}function g(oe){let F;switch(oe){case 1:F=Js.INTENSITY;break;case 2:F=Js.INTENSITY_ALPHA;break;case 3:F=Js.RGB;break;case 4:F=Js.RGBA;break;default:}return F}function v(oe){let F,le=Wr,pe=Wr,Le=oe.fields;for(let He=0,at=Le.length;He<at;He++){let rt=Le[He],ht=rt.name,Tt=rt.values;switch(ht){case"image":let Mt=Tt[0],Ut=Tt[1],Kt=Tt[2],fr=g(Kt),er=new Uint8Array(4*Mt*Ut),Zt={r:0,g:0,b:0,a:0};for(let Gt=3,Er=0,ut=Tt.length;Gt<ut;Gt++,Er++){x(Tt[Gt],fr,Zt);let zt=Er*4;er[zt+0]=Zt.r,er[zt+1]=Zt.g,er[zt+2]=Zt.b,er[zt+3]=Zt.a}F=new ys(er,Mt,Ut),F.colorSpace=xi,F.needsUpdate=!0,F.__type=fr;break;case"repeatS":Tt[0]===!1&&(le=ei);break;case"repeatT":Tt[0]===!1&&(pe=ei);break;default:console.warn("THREE.VRMLLoader: Unknown field:",ht);break}}return F&&(F.wrapS=le,F.wrapT=pe),F}function _(oe){let F,le=Wr,pe=Wr,Le=oe.fields;for(let He=0,at=Le.length;He<at;He++){let rt=Le[He],ht=rt.name,Tt=rt.values;switch(ht){case"url":let Mt=Tt[0];Mt&&(F=it.load(Mt));break;case"repeatS":Tt[0]===!1&&(le=ei);break;case"repeatT":Tt[0]===!1&&(pe=ei);break;default:console.warn("THREE.VRMLLoader: Unknown field:",ht);break}}return F&&(F.wrapS=le,F.wrapT=pe,F.colorSpace=xi),F}function E(oe){let F={center:new Ft,rotation:new Ft,scale:new Ft,translation:new Ft},le=oe.fields;for(let pe=0,Le=le.length;pe<Le;pe++){let He=le[pe],at=He.name,rt=He.values;switch(at){case"center":F.center.set(rt[0],rt[1]);break;case"rotation":F.rotation=rt[0];break;case"scale":F.scale.set(rt[0],rt[1]);break;case"translation":F.translation.set(rt[0],rt[1]);break;default:console.warn("THREE.VRMLLoader: Unknown field:",at);break}}return F}function M(oe){return oe.fields[0].values}function P(oe){let F={},le=oe.fields;for(let pe=0,Le=le.length;pe<Le;pe++){let He=le[pe],at=He.name,rt=He.values;switch(at){case"title":F.title=rt[0];break;case"info":F.info=rt;break;default:console.warn("THREE.VRMLLoader: Unknown field:",at);break}}return F}function k(oe){let F,le,pe,Le,He=!0,at=!0,rt=0,ht,Tt,Mt,Ut,Kt=!0,fr=!0,er=oe.fields;for(let Ct=0,rr=er.length;Ct<rr;Ct++){let $t=er[Ct],xr=$t.name,cr=$t.values;switch(xr){case"color":let yr=cr[0];yr!==null&&(F=l(yr));break;case"coord":let ir=cr[0];ir!==null&&(le=l(ir));break;case"normal":let _r=cr[0];_r!==null&&(pe=l(_r));break;case"texCoord":let Vt=cr[0];Vt!==null&&(Le=l(Vt));break;case"ccw":He=cr[0];break;case"colorIndex":ht=cr;break;case"colorPerVertex":Kt=cr[0];break;case"convex":break;case"coordIndex":Tt=cr;break;case"creaseAngle":rt=cr[0];break;case"normalIndex":Mt=cr;break;case"normalPerVertex":fr=cr[0];break;case"solid":at=cr[0];break;case"texCoordIndex":Ut=cr;break;default:console.warn("THREE.VRMLLoader: Unknown field:",xr);break}}if(Tt===void 0)return console.warn("THREE.VRMLLoader: Missing coordIndex."),new Hr;let Zt=Pe(Tt,He),Gt,Er,ut;if(F){if(Kt===!0)if(ht&&ht.length>0){let Ct=Pe(ht,He);Gt=Ue(Zt,Ct,F,3)}else Gt=Qe(Zt,new hr(F,3));else if(ht&&ht.length>0){let Ct=Te(F,ht),rr=ue(Ct,Tt);Gt=Ge(Zt,rr)}else{let Ct=ue(F,Tt);Gt=Ge(Zt,Ct)}We(Gt)}if(pe)if(fr===!0)if(Mt&&Mt.length>0){let Ct=Pe(Mt,He);Er=Ue(Zt,Ct,pe,3)}else Er=Qe(Zt,new hr(pe,3));else if(Mt&&Mt.length>0){let Ct=Te(pe,Mt),rr=ue(Ct,Tt);Er=Ge(Zt,rr)}else{let Ct=ue(pe,Tt);Er=Ge(Zt,Ct)}else Er=dt(Zt,le,rt);if(Le)if(Ut&&Ut.length>0){let Ct=Pe(Ut,He);ut=Ue(Zt,Ct,Le,2)}else ut=Qe(Zt,new hr(Le,2));let zt=new Hr,It=Qe(Zt,new hr(le,3));return zt.setAttribute("position",It),zt.setAttribute("normal",Er),Gt&&zt.setAttribute("color",Gt),ut&&zt.setAttribute("uv",ut),zt._solid=at,zt._type="mesh",zt}function z(oe){let F,le,pe,Le,He=!0,at=oe.fields;for(let Ut=0,Kt=at.length;Ut<Kt;Ut++){let fr=at[Ut],er=fr.name,Zt=fr.values;switch(er){case"color":let Gt=Zt[0];Gt!==null&&(F=l(Gt));break;case"coord":let Er=Zt[0];Er!==null&&(le=l(Er));break;case"colorIndex":pe=Zt;break;case"colorPerVertex":He=Zt[0];break;case"coordIndex":Le=Zt;break;default:console.warn("THREE.VRMLLoader: Unknown field:",er);break}}let rt,ht=de(Le);if(F){if(He===!0)if(pe.length>0){let Ut=de(pe);rt=Ue(ht,Ut,F,3)}else rt=Qe(ht,new hr(F,3));else if(pe.length>0){let Ut=Te(F,pe),Kt=Ie(Ut,Le);rt=nt(ht,Kt)}else{let Ut=Ie(F,Le);rt=nt(ht,Ut)}We(rt)}let Tt=new Hr,Mt=Qe(ht,new hr(le,3));return Tt.setAttribute("position",Mt),rt&&Tt.setAttribute("color",rt),Tt._type="line",Tt}function D(oe){let F,le,pe=oe.fields;for(let He=0,at=pe.length;He<at;He++){let rt=pe[He],ht=rt.name,Tt=rt.values;switch(ht){case"color":let Mt=Tt[0];Mt!==null&&(F=l(Mt));break;case"coord":let Ut=Tt[0];Ut!==null&&(le=l(Ut));break;default:console.warn("THREE.VRMLLoader: Unknown field:",ht);break}}let Le=new Hr;if(Le.setAttribute("position",new hr(le,3)),F){let He=new hr(F,3);We(He),Le.setAttribute("color",He)}return Le._type="points",Le}function I(oe){let F=new je(2,2,2),le=oe.fields;for(let pe=0,Le=le.length;pe<Le;pe++){let He=le[pe],at=He.name,rt=He.values;switch(at){case"size":F.x=rt[0],F.y=rt[1],F.z=rt[2];break;default:console.warn("THREE.VRMLLoader: Unknown field:",at);break}}return new Da(F.x,F.y,F.z)}function L(oe){let F=1,le=2,pe=!1,Le=oe.fields;for(let He=0,at=Le.length;He<at;He++){let rt=Le[He],ht=rt.name,Tt=rt.values;switch(ht){case"bottom":pe=!Tt[0];break;case"bottomRadius":F=Tt[0];break;case"height":le=Tt[0];break;case"side":break;default:console.warn("THREE.VRMLLoader: Unknown field:",ht);break}}return new ty(F,le,16,1,pe)}function Z(oe){let F=1,le=2,pe=oe.fields;for(let Le=0,He=pe.length;Le<He;Le++){let at=pe[Le],rt=at.name,ht=at.values;switch(rt){case"bottom":break;case"radius":F=ht[0];break;case"height":le=ht[0];break;case"side":break;case"top":break;default:console.warn("THREE.VRMLLoader: Unknown field:",rt);break}}return new eu(F,F,le,16,1)}function se(oe){let F=1,le=oe.fields;for(let pe=0,Le=le.length;pe<Le;pe++){let He=le[pe],at=He.name,rt=He.values;switch(at){case"radius":F=rt[0];break;default:console.warn("THREE.VRMLLoader: Unknown field:",at);break}}return new po(F,16,16)}function ce(oe){let F,le,pe,Le,He=!0,at=!0,rt=!0,ht=!0,Tt=0,Mt=2,Ut=2,Kt=1,fr=1,er=oe.fields;for(let cr=0,yr=er.length;cr<yr;cr++){let ir=er[cr],_r=ir.name,Vt=ir.values;switch(_r){case"color":let pi=Vt[0];pi!==null&&(F=l(pi));break;case"normal":let nn=Vt[0];nn!==null&&(le=l(nn));break;case"texCoord":let $i=Vt[0];$i!==null&&(pe=l($i));break;case"height":Le=Vt;break;case"ccw":ht=Vt[0];break;case"colorPerVertex":He=Vt[0];break;case"creaseAngle":Tt=Vt[0];break;case"normalPerVertex":at=Vt[0];break;case"solid":rt=Vt[0];break;case"xDimension":Mt=Vt[0];break;case"xSpacing":Kt=Vt[0];break;case"zDimension":Ut=Vt[0];break;case"zSpacing":fr=Vt[0];break;default:console.warn("THREE.VRMLLoader: Unknown field:",_r);break}}let Zt=[],Gt=[],Er=[],ut=[];for(let cr=0;cr<Ut;cr++)for(let yr=0;yr<Mt;yr++){let ir=cr*Mt+yr,_r=Kt*cr,Vt=Le[ir],pi=fr*yr;if(Zt.push(_r,Vt,pi),F&&He===!0){let nn=F[ir*3+0],$i=F[ir*3+1],fa=F[ir*3+2];Er.push(nn,$i,fa)}if(le&&at===!0){let nn=le[ir*3+0],$i=le[ir*3+1],fa=le[ir*3+2];Gt.push(nn,$i,fa)}if(pe){let nn=pe[ir*2+0],$i=pe[ir*2+1];ut.push(nn,$i)}else ut.push(cr/(Mt-1),yr/(Ut-1))}let zt=[];for(let cr=0;cr<Mt-1;cr++)for(let yr=0;yr<Ut-1;yr++){let ir=cr+yr*Mt,_r=cr+(yr+1)*Mt,Vt=cr+1+(yr+1)*Mt,pi=cr+1+yr*Mt;ht===!0?(zt.push(ir,Vt,_r),zt.push(Vt,ir,pi)):(zt.push(ir,_r,Vt),zt.push(Vt,pi,ir))}let It=Qe(zt,new hr(Zt,3)),Ct=Qe(zt,new hr(ut,2)),rr,$t;if(F){if(He===!1){for(let cr=0;cr<Mt-1;cr++)for(let yr=0;yr<Ut-1;yr++){let ir=cr+yr*(Mt-1),_r=F[ir*3+0],Vt=F[ir*3+1],pi=F[ir*3+2];Er.push(_r,Vt,pi),Er.push(_r,Vt,pi),Er.push(_r,Vt,pi),Er.push(_r,Vt,pi),Er.push(_r,Vt,pi),Er.push(_r,Vt,pi)}rr=new hr(Er,3)}else rr=Qe(zt,new hr(Er,3));We(rr)}if(le)if(at===!1){for(let cr=0;cr<Mt-1;cr++)for(let yr=0;yr<Ut-1;yr++){let ir=cr+yr*(Mt-1),_r=le[ir*3+0],Vt=le[ir*3+1],pi=le[ir*3+2];Gt.push(_r,Vt,pi),Gt.push(_r,Vt,pi),Gt.push(_r,Vt,pi),Gt.push(_r,Vt,pi),Gt.push(_r,Vt,pi),Gt.push(_r,Vt,pi)}$t=new hr(Gt,3)}else $t=Qe(zt,new hr(Gt,3));else $t=dt(zt,Zt,Tt);let xr=new Hr;return xr.setAttribute("position",It),xr.setAttribute("normal",$t),xr.setAttribute("uv",Ct),rr&&xr.setAttribute("color",rr),xr._solid=rt,xr._type="mesh",xr}function fe(oe){let F=[1,1,1,-1,-1,-1,-1,1,1,1],le=[0,0,0,0,1,0],pe,Le,He=!0,at=!0,rt=0,ht=!0,Tt=!0,Mt=oe.fields;for(let xr=0,cr=Mt.length;xr<cr;xr++){let yr=Mt[xr],ir=yr.name,_r=yr.values;switch(ir){case"beginCap":He=_r[0];break;case"ccw":at=_r[0];break;case"convex":break;case"creaseAngle":rt=_r[0];break;case"crossSection":F=_r;break;case"endCap":ht=_r[0];break;case"orientation":Le=_r;break;case"scale":pe=_r;break;case"solid":Tt=_r[0];break;case"spine":le=_r;break;default:console.warn("THREE.VRMLLoader: Unknown field:",ir);break}}let Ut=F[0]===F[F.length-2]&&F[1]===F[F.length-1],Kt=[],fr=new je,er=new je,Zt=new je,Gt=new je,Er=new pn;for(let xr=0,cr=0,yr=0,ir=le.length;xr<ir;xr+=3,cr+=2,yr+=4){fr.fromArray(le,xr),er.x=pe?pe[cr+0]:1,er.y=1,er.z=pe?pe[cr+1]:1,Zt.x=Le?Le[yr+0]:0,Zt.y=Le?Le[yr+1]:0,Zt.z=Le?Le[yr+2]:1;let _r=Le?Le[yr+3]:0;for(let Vt=0,pi=F.length;Vt<pi;Vt+=2)Gt.x=F[Vt+0],Gt.y=0,Gt.z=F[Vt+1],Gt.multiply(er),Er.setFromAxisAngle(Zt,_r),Gt.applyQuaternion(Er),Gt.add(fr),Kt.push(Gt.x,Gt.y,Gt.z)}let ut=[],zt=le.length/3,It=F.length/2;for(let xr=0;xr<zt-1;xr++)for(let cr=0;cr<It-1;cr++){let yr=cr+xr*It,ir=cr+1+xr*It,_r=cr+(xr+1)*It,Vt=cr+1+(xr+1)*It;cr===It-2&&Ut===!0&&(ir=xr*It,Vt=(xr+1)*It),at===!0?(ut.push(yr,ir,_r),ut.push(_r,ir,Vt)):(ut.push(yr,_r,ir),ut.push(_r,Vt,ir))}if(He===!0||ht===!0){let xr=[];for(let ir=0,_r=F.length;ir<_r;ir+=2)xr.push(new Ft(F[ir],F[ir+1]));let cr=za.triangulateShape(xr,[]),yr=[];for(let ir=0,_r=cr.length;ir<_r;ir++){let Vt=cr[ir];yr.push(Vt[0],Vt[1],Vt[2])}if(He===!0)for(let ir=0,_r=yr.length;ir<_r;ir+=3)at===!0?ut.push(yr[ir+0],yr[ir+1],yr[ir+2]):ut.push(yr[ir+0],yr[ir+2],yr[ir+1]);if(ht===!0){let ir=It*(zt-1);for(let _r=0,Vt=yr.length;_r<Vt;_r+=3)at===!0?ut.push(ir+yr[_r+0],ir+yr[_r+2],ir+yr[_r+1]):ut.push(ir+yr[_r+0],ir+yr[_r+1],ir+yr[_r+2])}}let Ct=Qe(ut,new hr(Kt,3)),rr=dt(ut,Kt,rt),$t=new Hr;return $t.setAttribute("position",Ct),$t.setAttribute("normal",rr),$t._solid=Tt,$t._type="mesh",$t}function ze(oe){let F=r[oe],le=l(F);return le.isObject3D||le.isMaterial?le.clone():le}function Fe(oe,F){for(let le=0,pe=oe.length;le<pe;le++){let Le=l(oe[le]);Le instanceof mi&&F.add(Le)}}function Pe(oe,F){let le=[],pe=0;for(let Le=0,He=oe.length;Le<He;Le++){let at=oe[pe],rt=oe[Le+(F?1:2)],ht=oe[Le+(F?2:1)];le.push(at,rt,ht),(oe[Le+3]===-1||Le+3>=He)&&(Le+=3,pe=Le+1)}return le}function ue(oe,F){let le=[],pe=0;for(let Le=0,He=F.length;Le<He;Le++){let at=pe*3,rt=oe[at],ht=oe[at+1],Tt=oe[at+2];le.push(rt,ht,Tt),(F[Le+3]===-1||Le+3>=He)&&(Le+=3,pe++)}return le}function Te(oe,F){let le=[];for(let pe=0,Le=F.length;pe<Le;pe++){let He=F[pe]*3,at=oe[He],rt=oe[He+1],ht=oe[He+2];le.push(at,rt,ht)}return le}function de(oe){let F=[];for(let le=0,pe=oe.length;le<pe;le++){let Le=oe[le],He=oe[le+1];F.push(Le,He),(oe[le+2]===-1||le+2>=pe)&&(le+=2)}return F}function Ie(oe,F){let le=[],pe=0;for(let Le=0,He=F.length;Le<He;Le++){let at=pe*3,rt=oe[at],ht=oe[at+1],Tt=oe[at+2];le.push(rt,ht,Tt),(F[Le+2]===-1||Le+2>=He)&&(Le+=2,pe++)}return le}let Re=new je,Be=new je,Se=new je,U=new Ft,ie=new Ft,Ae=new Ft;function Ue(oe,F,le,pe){let Le=[];for(let He=0,at=oe.length;He<at;He+=3){let rt=F[He],ht=F[He+1],Tt=F[He+2];pe===2?(U.fromArray(le,rt*pe),ie.fromArray(le,ht*pe),Ae.fromArray(le,Tt*pe),Le.push(U.x,U.y),Le.push(ie.x,ie.y),Le.push(Ae.x,Ae.y)):(Re.fromArray(le,rt*pe),Be.fromArray(le,ht*pe),Se.fromArray(le,Tt*pe),Le.push(Re.x,Re.y,Re.z),Le.push(Be.x,Be.y,Be.z),Le.push(Se.x,Se.y,Se.z))}return new hr(Le,pe)}function Ge(oe,F){let le=[];for(let pe=0,Le=0,He=oe.length;pe<He;pe+=3,Le++)Re.fromArray(F,Le*3),le.push(Re.x,Re.y,Re.z),le.push(Re.x,Re.y,Re.z),le.push(Re.x,Re.y,Re.z);return new hr(le,3)}function nt(oe,F){let le=[];for(let pe=0,Le=0,He=oe.length;pe<He;pe+=2,Le++)Re.fromArray(F,Le*3),le.push(Re.x,Re.y,Re.z),le.push(Re.x,Re.y,Re.z);return new hr(le,3)}function Qe(oe,F){let le=F.array,pe=F.itemSize,Le=new le.constructor(oe.length*pe),He=0,at=0;for(let rt=0,ht=oe.length;rt<ht;rt++){He=oe[rt]*pe;for(let Tt=0;Tt<pe;Tt++)Le[at++]=le[He++]}return new hr(Le,pe)}let ct=new je,ye=new je;function dt(oe,F,le){let pe=[],Le={};for(let at=0,rt=oe.length;at<rt;at+=3){let ht=oe[at],Tt=oe[at+1],Mt=oe[at+2],Ut=new Kk(ht,Tt,Mt);Re.fromArray(F,ht*3),Be.fromArray(F,Tt*3),Se.fromArray(F,Mt*3),ye.subVectors(Se,Be),ct.subVectors(Re,Be),ye.cross(ct),ye.normalize(),Ut.normal.copy(ye),Le[ht]===void 0&&(Le[ht]=[]),Le[Tt]===void 0&&(Le[Tt]=[]),Le[Mt]===void 0&&(Le[Mt]=[]),Le[ht].push(Ut.normal),Le[Tt].push(Ut.normal),Le[Mt].push(Ut.normal),pe.push(Ut)}let He=[];for(let at=0,rt=pe.length;at<rt;at++){let ht=pe[at],Tt=xt(Le[ht.a],ht.normal,le),Mt=xt(Le[ht.b],ht.normal,le),Ut=xt(Le[ht.c],ht.normal,le);Re.fromArray(F,ht.a*3),Be.fromArray(F,ht.b*3),Se.fromArray(F,ht.c*3),He.push(Tt.x,Tt.y,Tt.z),He.push(Mt.x,Mt.y,Mt.z),He.push(Ut.x,Ut.y,Ut.z)}return new hr(He,3)}function xt(oe,F,le){let pe=new je;if(le===0)pe.copy(F);else for(let Le=0,He=oe.length;Le<He;Le++)oe[Le].angleTo(F)<le&&pe.add(oe[Le]);return pe.normalize()}function Dt(oe){let F=[];for(let le=0,pe=oe.length;le<pe;le+=3)F.push(new or(oe[le],oe[le+1],oe[le+2]));return F}function We(oe){let F=new or;for(let le=0;le<oe.count;le++)F.fromBufferAttribute(oe,le),li.toWorkingColorSpace(F,xi),oe.setXYZ(le,F.r,F.g,F.b)}function mt(oe,F,le,pe,Le){let He=[],at=Le===!0?0:Math.PI;for(let Kt=0,fr=pe.length;Kt<fr;Kt++){let er=Kt===0?0:le[Kt-1];er=Le===!0?er:at-er;let Zt=new je;Zt.setFromSphericalCoords(F,er,0),He.push(Zt)}let rt=oe.index,ht=oe.attributes.position,Tt=new ui(new Float32Array(oe.attributes.position.count*3),3),Mt=new je,Ut=new or;for(let Kt=0;Kt<rt.count;Kt++){let fr=rt.getX(Kt);Mt.fromBufferAttribute(ht,fr);let er,Zt,Gt=1;for(let zt=1;zt<He.length;zt++){er=zt-1,Zt=zt;let It=He[er],Ct=He[Zt];if(Le===!0){if(Mt.y<=It.y&&Mt.y>Ct.y){Gt=Math.abs(It.y-Mt.y)/Math.abs(It.y-Ct.y);break}}else if(Mt.y>=It.y&&Mt.y<Ct.y){Gt=Math.abs(It.y-Mt.y)/Math.abs(It.y-Ct.y);break}}let Er=pe[er],ut=pe[Zt];Ut.copy(Er).lerp(ut,Gt),li.toWorkingColorSpace(Ut,xi),Tt.setXYZ(fr,Ut.r,Ut.g,Ut.b)}oe.setAttribute("color",Tt)}let it=new gy(this.manager);if(it.setPath(this.resourcePath||t).setCrossOrigin(this.crossOrigin),e.indexOf("#VRML V2.0")===-1)throw Error("THREE.VRMLLexer: Version of VRML asset not supported.");let st=i(e);return a(st)}},Xk=class{constructor(e){this.lexer=new gu.Lexer(e)}lex(e){let t=this.lexer.tokenize(e);if(t.errors.length>0)throw console.error(t.errors),Error("THREE.VRMLLexer: Lexing errors detected.");return t}},Yk=gu.CstParser,qk=class extends Yk{constructor(e){super(e);let t=this,r=e.Version,i=e.LCurly,n=e.RCurly,s=e.LSquare,a=e.RSquare,o=e.Identifier,l=e.RouteIdentifier,c=e.StringLiteral,u=e.HexLiteral,d=e.NumberLiteral,f=e.TrueLiteral,y=e.FalseLiteral,b=e.NullLiteral,x=e.DEF,g=e.USE,v=e.ROUTE,_=e.TO,E=e.NodeName;t.RULE("vrml",function(){t.SUBRULE(t.version),t.AT_LEAST_ONE(function(){t.SUBRULE(t.node)}),t.MANY(function(){t.SUBRULE(t.route)})}),t.RULE("version",function(){t.CONSUME(r)}),t.RULE("node",function(){t.OPTION(function(){t.SUBRULE(t.def)}),t.CONSUME(E),t.CONSUME(i),t.MANY(function(){t.SUBRULE(t.field)}),t.CONSUME(n)}),t.RULE("field",function(){t.CONSUME(o),t.OR2([{ALT:function(){t.SUBRULE(t.singleFieldValue)}},{ALT:function(){t.SUBRULE(t.multiFieldValue)}}])}),t.RULE("def",function(){t.CONSUME(x),t.OR([{ALT:function(){t.CONSUME(o)}},{ALT:function(){t.CONSUME(E)}}])}),t.RULE("use",function(){t.CONSUME(g),t.OR([{ALT:function(){t.CONSUME(o)}},{ALT:function(){t.CONSUME(E)}}])}),t.RULE("singleFieldValue",function(){t.AT_LEAST_ONE(function(){t.OR([{ALT:function(){t.SUBRULE(t.node)}},{ALT:function(){t.SUBRULE(t.use)}},{ALT:function(){t.CONSUME(c)}},{ALT:function(){t.CONSUME(u)}},{ALT:function(){t.CONSUME(d)}},{ALT:function(){t.CONSUME(f)}},{ALT:function(){t.CONSUME(y)}},{ALT:function(){t.CONSUME(b)}}])})}),t.RULE("multiFieldValue",function(){t.CONSUME(s),t.MANY(function(){t.OR([{ALT:function(){t.SUBRULE(t.node)}},{ALT:function(){t.SUBRULE(t.use)}},{ALT:function(){t.CONSUME(c)}},{ALT:function(){t.CONSUME(u)}},{ALT:function(){t.CONSUME(d)}},{ALT:function(){t.CONSUME(b)}}])}),t.CONSUME(a)}),t.RULE("route",function(){t.CONSUME(v),t.CONSUME(l),t.CONSUME(_),t.CONSUME2(l)}),this.performSelfAnalysis()}},Kk=class{constructor(e,t,r){this.a=e,this.b=t,this.c=r,this.normal=new je}},Js={INTENSITY:1,INTENSITY_ALPHA:2,RGB:3,RGBA:4},Zk=class extends Yo{constructor(){super();let e=new Da;e.deleteAttribute("uv");let t=new is({side:tt}),r=new is,i=new Zp(16777215,900,28,2);i.position.set(.418,16.199,.3),this.add(i);let n=new qr(e,t);n.position.set(-.757,13.219,.717),n.scale.set(31.713,28.305,28.591),this.add(n);let s=new qr(e,r);s.position.set(-10.906,2.009,1.846),s.rotation.set(0,-.195,0),s.scale.set(2.328,7.905,4.651),this.add(s);let a=new qr(e,r);a.position.set(-5.607,-.754,-.758),a.rotation.set(0,.994,0),a.scale.set(1.97,1.534,3.955),this.add(a);let o=new qr(e,r);o.position.set(6.167,.857,7.803),o.rotation.set(0,.561,0),o.scale.set(3.927,6.285,3.687),this.add(o);let l=new qr(e,r);l.position.set(-2.017,.018,6.124),l.rotation.set(0,.333,0),l.scale.set(2.002,4.566,2.064),this.add(l);let c=new qr(e,r);c.position.set(2.291,-.756,-2.621),c.rotation.set(0,-.286,0),c.scale.set(1.546,1.552,1.496),this.add(c);let u=new qr(e,r);u.position.set(-2.193,-.369,-5.547),u.rotation.set(0,.516,0),u.scale.set(3.875,3.487,2.986),this.add(u);let d=new qr(e,Tc(50));d.position.set(-16.116,14.37,8.208),d.scale.set(.1,2.428,2.739),this.add(d);let f=new qr(e,Tc(50));f.position.set(-16.109,18.021,-8.207),f.scale.set(.1,2.425,2.751),this.add(f);let y=new qr(e,Tc(17));y.position.set(14.904,12.198,-1.832),y.scale.set(.15,4.265,6.331),this.add(y);let b=new qr(e,Tc(43));b.position.set(-.462,8.89,14.52),b.scale.set(4.38,5.441,.088),this.add(b);let x=new qr(e,Tc(20));x.position.set(3.235,11.486,-12.541),x.scale.set(2.5,2,.1),this.add(x);let g=new qr(e,Tc(100));g.position.set(0,20,0),g.scale.set(1,.1,1),this.add(g)}dispose(){let e=new Set;this.traverse(t=>{t.isMesh&&(e.add(t.geometry),e.add(t.material))});for(let t of e)t.dispose()}};function Tc(e){let t=new en;return t.color.setScalar(e),t}var yu=new je;function Ls(e,t,r,i,n,s){let a=2*Math.PI*n/4,o=Math.max(s-2*n,0),l=Math.PI/4;yu.copy(t),yu[i]=0,yu.normalize();let c=.5*a/(a+o),u=1-yu.angleTo(e)/l;return Math.sign(yu[r])===1?u*c:o/(a+o)+c+c*(1-u)}var $k=class extends Da{constructor(e=1,t=1,r=1,i=2,n=.1){if(i=i*2+1,n=Math.min(e/2,t/2,r/2,n),super(1,1,1,i,i,i),i===1)return;let s=this.toNonIndexed();this.index=null,this.attributes.position=s.attributes.position,this.attributes.normal=s.attributes.normal,this.attributes.uv=s.attributes.uv;let a=new je,o=new je,l=new je(e,t,r).divideScalar(2).subScalar(n),c=this.attributes.position.array,u=this.attributes.normal.array,d=this.attributes.uv.array,f=c.length/6,y=new je,b=.5/i;for(let x=0,g=0;x<c.length;x+=3,g+=2)switch(a.fromArray(c,x),o.copy(a),o.x-=Math.sign(o.x)*b,o.y-=Math.sign(o.y)*b,o.z-=Math.sign(o.z)*b,o.normalize(),c[x+0]=l.x*Math.sign(a.x)+o.x*n,c[x+1]=l.y*Math.sign(a.y)+o.y*n,c[x+2]=l.z*Math.sign(a.z)+o.z*n,u[x+0]=o.x,u[x+1]=o.y,u[x+2]=o.z,Math.floor(x/f)){case 0:y.set(1,0,0),d[g+0]=Ls(y,o,"z","y",n,r),d[g+1]=1-Ls(y,o,"y","z",n,t);break;case 1:y.set(-1,0,0),d[g+0]=1-Ls(y,o,"z","y",n,r),d[g+1]=1-Ls(y,o,"y","z",n,t);break;case 2:y.set(0,1,0),d[g+0]=1-Ls(y,o,"x","z",n,e),d[g+1]=Ls(y,o,"z","x",n,r);break;case 3:y.set(0,-1,0),d[g+0]=1-Ls(y,o,"x","z",n,e),d[g+1]=1-Ls(y,o,"z","x",n,r);break;case 4:y.set(0,0,1),d[g+0]=1-Ls(y,o,"x","y",n,e),d[g+1]=1-Ls(y,o,"y","x",n,t);break;case 5:y.set(0,0,-1),d[g+0]=Ls(y,o,"x","y",n,e),d[g+1]=1-Ls(y,o,"y","x",n,t);break}}},_f={name:"CopyShader",uniforms:{tDiffuse:{value:null},opacity:{value:1}},vertexShader:`

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

		}`,fragmentShader:`

		uniform float opacity;

		uniform sampler2D tDiffuse;

		varying vec2 vUv;

		void main() {

			vec4 texel = texture2D( tDiffuse, vUv );
			gl_FragColor = opacity * texel;


		}`},yl=class{constructor(){this.isPass=!0,this.enabled=!0,this.needsSwap=!0,this.clear=!1,this.renderToScreen=!1}setSize(){}render(){console.error("THREE.Pass: .render() must be implemented in derived pass.")}dispose(){}},Jk=new wc(-1,1,1,-1,0,1),Qk=class extends Hr{constructor(){super(),this.setAttribute("position",new hr([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new hr([0,2,0,0,2,0],2))}},e3=new Qk,Ef=class{constructor(e){this._mesh=new qr(e3,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,Jk)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}},t3=class extends yl{constructor(e,t){super(),this.textureID=t!==void 0?t:"tDiffuse",e instanceof ln?(this.uniforms=e.uniforms,this.material=e):e&&(this.uniforms=Rs.clone(e.uniforms),this.material=new ln({name:e.name!==void 0?e.name:"unspecified",defines:Object.assign({},e.defines),uniforms:this.uniforms,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader})),this.fsQuad=new Ef(this.material)}render(e,t,r){this.uniforms[this.textureID]&&(this.uniforms[this.textureID].value=r.texture),this.fsQuad.material=this.material,this.renderToScreen?(e.setRenderTarget(null),this.fsQuad.render(e)):(e.setRenderTarget(t),this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),this.fsQuad.render(e))}dispose(){this.material.dispose(),this.fsQuad.dispose()}},Uw=class extends yl{constructor(e,t){super(),this.scene=e,this.camera=t,this.clear=!0,this.needsSwap=!1,this.inverse=!1}render(e,t,r){let i=e.getContext(),n=e.state;n.buffers.color.setMask(!1),n.buffers.depth.setMask(!1),n.buffers.color.setLocked(!0),n.buffers.depth.setLocked(!0);let s,a;this.inverse?(s=0,a=1):(s=1,a=0),n.buffers.stencil.setTest(!0),n.buffers.stencil.setOp(i.REPLACE,i.REPLACE,i.REPLACE),n.buffers.stencil.setFunc(i.ALWAYS,s,4294967295),n.buffers.stencil.setClear(a),n.buffers.stencil.setLocked(!0),e.setRenderTarget(r),this.clear&&e.clear(),e.render(this.scene,this.camera),e.setRenderTarget(t),this.clear&&e.clear(),e.render(this.scene,this.camera),n.buffers.color.setLocked(!1),n.buffers.depth.setLocked(!1),n.buffers.color.setMask(!0),n.buffers.depth.setMask(!0),n.buffers.stencil.setLocked(!1),n.buffers.stencil.setFunc(i.EQUAL,1,4294967295),n.buffers.stencil.setOp(i.KEEP,i.KEEP,i.KEEP),n.buffers.stencil.setLocked(!0)}},r3=class extends yl{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}},i3=class{constructor(e,t){if(this.renderer=e,this._pixelRatio=e.getPixelRatio(),t===void 0){let r=e.getSize(new Ft);this._width=r.width,this._height=r.height,t=new In(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:Ts}),t.texture.name="EffectComposer.rt1"}else this._width=t.width,this._height=t.height;this.renderTarget1=t,this.renderTarget2=t.clone(),this.renderTarget2.texture.name="EffectComposer.rt2",this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2,this.renderToScreen=!0,this.passes=[],this.copyPass=new t3(_f),this.copyPass.material.blending=Ye,this.clock=new Ey}swapBuffers(){let e=this.readBuffer;this.readBuffer=this.writeBuffer,this.writeBuffer=e}addPass(e){this.passes.push(e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}insertPass(e,t){this.passes.splice(t,0,e),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}removePass(e){let t=this.passes.indexOf(e);t!==-1&&this.passes.splice(t,1)}isLastEnabledPass(e){for(let t=e+1;t<this.passes.length;t++)if(this.passes[t].enabled)return!1;return!0}render(e){e===void 0&&(e=this.clock.getDelta());let t=this.renderer.getRenderTarget(),r=!1;for(let i=0,n=this.passes.length;i<n;i++){let s=this.passes[i];if(s.enabled!==!1){if(s.renderToScreen=this.renderToScreen&&this.isLastEnabledPass(i),s.render(this.renderer,this.writeBuffer,this.readBuffer,e,r),s.needsSwap){if(r){let a=this.renderer.getContext(),o=this.renderer.state.buffers.stencil;o.setFunc(a.NOTEQUAL,1,4294967295),this.copyPass.render(this.renderer,this.writeBuffer,this.readBuffer,e),o.setFunc(a.EQUAL,1,4294967295)}this.swapBuffers()}Uw!==void 0&&(s instanceof Uw?r=!0:s instanceof r3&&(r=!1))}}this.renderer.setRenderTarget(t)}reset(e){if(e===void 0){let t=this.renderer.getSize(new Ft);this._pixelRatio=this.renderer.getPixelRatio(),this._width=t.width,this._height=t.height,e=this.renderTarget1.clone(),e.setSize(this._width*this._pixelRatio,this._height*this._pixelRatio)}this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.renderTarget1=e,this.renderTarget2=e.clone(),this.writeBuffer=this.renderTarget1,this.readBuffer=this.renderTarget2}setSize(e,t){this._width=e,this._height=t;let r=this._width*this._pixelRatio,i=this._height*this._pixelRatio;this.renderTarget1.setSize(r,i),this.renderTarget2.setSize(r,i);for(let n=0;n<this.passes.length;n++)this.passes[n].setSize(r,i)}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget1.dispose(),this.renderTarget2.dispose(),this.copyPass.dispose()}},n3=class extends yl{constructor(e,t,r=null,i=null,n=null){super(),this.scene=e,this.camera=t,this.overrideMaterial=r,this.clearColor=i,this.clearAlpha=n,this.clear=!0,this.clearDepth=!1,this.needsSwap=!1,this._oldClearColor=new or}render(e,t,r){let i=e.autoClear;e.autoClear=!1;let n,s;this.overrideMaterial!==null&&(s=this.scene.overrideMaterial,this.scene.overrideMaterial=this.overrideMaterial),this.clearColor!==null&&(e.getClearColor(this._oldClearColor),e.setClearColor(this.clearColor,e.getClearAlpha())),this.clearAlpha!==null&&(n=e.getClearAlpha(),e.setClearAlpha(this.clearAlpha)),this.clearDepth==!0&&e.clearDepth(),e.setRenderTarget(this.renderToScreen?null:r),this.clear===!0&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),e.render(this.scene,this.camera),this.clearColor!==null&&e.setClearColor(this._oldClearColor),this.clearAlpha!==null&&e.setClearAlpha(n),this.overrideMaterial!==null&&(this.scene.overrideMaterial=s),e.autoClear=i}},Sf={name:"GTAOShader",defines:{PERSPECTIVE_CAMERA:1,SAMPLES:16,NORMAL_VECTOR_TYPE:1,DEPTH_SWIZZLING:"x",SCREEN_SPACE_RADIUS:0,SCREEN_SPACE_RADIUS_SCALE:100,SCENE_CLIP_BOX:0},uniforms:{tNormal:{value:null},tDepth:{value:null},tNoise:{value:null},resolution:{value:new Ft},cameraNear:{value:null},cameraFar:{value:null},cameraProjectionMatrix:{value:new Ir},cameraProjectionMatrixInverse:{value:new Ir},cameraWorldMatrix:{value:new Ir},radius:{value:.25},distanceExponent:{value:1},thickness:{value:1},distanceFallOff:{value:1},scale:{value:1},sceneBoxMin:{value:new je(-1,-1,-1)},sceneBoxMax:{value:new je(1,1,1)}},vertexShader:`

		varying vec2 vUv;

		void main() {
			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
		}`,fragmentShader:`
		varying vec2 vUv;
		uniform highp sampler2D tNormal;
		uniform highp sampler2D tDepth;
		uniform sampler2D tNoise;
		uniform vec2 resolution;
		uniform float cameraNear;
		uniform float cameraFar;
		uniform mat4 cameraProjectionMatrix;
		uniform mat4 cameraProjectionMatrixInverse;		
		uniform mat4 cameraWorldMatrix;
		uniform float radius;
		uniform float distanceExponent;
		uniform float thickness;
		uniform float distanceFallOff;
		uniform float scale;
		#if SCENE_CLIP_BOX == 1
			uniform vec3 sceneBoxMin;
			uniform vec3 sceneBoxMax;
		#endif
		
		#include <common>
		#include <packing>

		#ifndef FRAGMENT_OUTPUT
		#define FRAGMENT_OUTPUT vec4(vec3(ao), 1.)
		#endif

		vec3 getViewPosition(const in vec2 screenPosition, const in float depth) {
			vec4 clipSpacePosition = vec4(vec3(screenPosition, depth) * 2.0 - 1.0, 1.0);
			vec4 viewSpacePosition = cameraProjectionMatrixInverse * clipSpacePosition;
			return viewSpacePosition.xyz / viewSpacePosition.w;
		}

		float getDepth(const vec2 uv) {  
			return textureLod(tDepth, uv.xy, 0.0).DEPTH_SWIZZLING;
		}

		float fetchDepth(const ivec2 uv) {   
			return texelFetch(tDepth, uv.xy, 0).DEPTH_SWIZZLING;
		}

		float getViewZ(const in float depth) {
			#if PERSPECTIVE_CAMERA == 1
				return perspectiveDepthToViewZ(depth, cameraNear, cameraFar);
			#else
				return orthographicDepthToViewZ(depth, cameraNear, cameraFar);
			#endif
		}

		vec3 computeNormalFromDepth(const vec2 uv) {
			vec2 size = vec2(textureSize(tDepth, 0));
			ivec2 p = ivec2(uv * size);
			float c0 = fetchDepth(p);
			float l2 = fetchDepth(p - ivec2(2, 0));
			float l1 = fetchDepth(p - ivec2(1, 0));
			float r1 = fetchDepth(p + ivec2(1, 0));
			float r2 = fetchDepth(p + ivec2(2, 0));
			float b2 = fetchDepth(p - ivec2(0, 2));
			float b1 = fetchDepth(p - ivec2(0, 1));
			float t1 = fetchDepth(p + ivec2(0, 1));
			float t2 = fetchDepth(p + ivec2(0, 2));
			float dl = abs((2.0 * l1 - l2) - c0);
			float dr = abs((2.0 * r1 - r2) - c0);
			float db = abs((2.0 * b1 - b2) - c0);
			float dt = abs((2.0 * t1 - t2) - c0);
			vec3 ce = getViewPosition(uv, c0).xyz;
			vec3 dpdx = (dl < dr) ? ce - getViewPosition((uv - vec2(1.0 / size.x, 0.0)), l1).xyz : -ce + getViewPosition((uv + vec2(1.0 / size.x, 0.0)), r1).xyz;
			vec3 dpdy = (db < dt) ? ce - getViewPosition((uv - vec2(0.0, 1.0 / size.y)), b1).xyz : -ce + getViewPosition((uv + vec2(0.0, 1.0 / size.y)), t1).xyz;
			return normalize(cross(dpdx, dpdy));
		}

		vec3 getViewNormal(const vec2 uv) {
			#if NORMAL_VECTOR_TYPE == 2
				return normalize(textureLod(tNormal, uv, 0.).rgb);
			#elif NORMAL_VECTOR_TYPE == 1
				return unpackRGBToNormal(textureLod(tNormal, uv, 0.).rgb);
			#else
				return computeNormalFromDepth(uv);
			#endif
		}

		vec3 getSceneUvAndDepth(vec3 sampleViewPos) {
			vec4 sampleClipPos = cameraProjectionMatrix * vec4(sampleViewPos, 1.);
			vec2 sampleUv = sampleClipPos.xy / sampleClipPos.w * 0.5 + 0.5;
			float sampleSceneDepth = getDepth(sampleUv);
			return vec3(sampleUv, sampleSceneDepth);
		}
		
		void main() {
			float depth = getDepth(vUv.xy);
			if (depth >= 1.0) {
				discard;
				return;
			}
			vec3 viewPos = getViewPosition(vUv, depth);
			vec3 viewNormal = getViewNormal(vUv);

			float radiusToUse = radius;
			float distanceFalloffToUse = thickness;
			#if SCREEN_SPACE_RADIUS == 1
				float radiusScale = getViewPosition(vec2(0.5 + float(SCREEN_SPACE_RADIUS_SCALE) / resolution.x, 0.0), depth).x;
				radiusToUse *= radiusScale;
				distanceFalloffToUse *= radiusScale;
			#endif

			#if SCENE_CLIP_BOX == 1
				vec3 worldPos = (cameraWorldMatrix * vec4(viewPos, 1.0)).xyz;
				float boxDistance = length(max(vec3(0.0), max(sceneBoxMin - worldPos, worldPos - sceneBoxMax)));
				if (boxDistance > radiusToUse) {
					discard;
					return;
				}
			#endif
			
			vec2 noiseResolution = vec2(textureSize(tNoise, 0));
			vec2 noiseUv = vUv * resolution / noiseResolution;
			vec4 noiseTexel = textureLod(tNoise, noiseUv, 0.0);
			vec3 randomVec = noiseTexel.xyz * 2.0 - 1.0;
			vec3 tangent = normalize(vec3(randomVec.xy, 0.));
			vec3 bitangent = vec3(-tangent.y, tangent.x, 0.);
			mat3 kernelMatrix = mat3(tangent, bitangent, vec3(0., 0., 1.));

			const int DIRECTIONS = SAMPLES < 30 ? 3 : 5;
			const int STEPS = (SAMPLES + DIRECTIONS - 1) / DIRECTIONS;
			float ao = 0.0;
			for (int i = 0; i < DIRECTIONS; ++i) {
				
				float angle = float(i) / float(DIRECTIONS) * PI;
				vec4 sampleDir = vec4(cos(angle), sin(angle), 0., 0.5 + 0.5 * noiseTexel.w); 
				sampleDir.xyz = normalize(kernelMatrix * sampleDir.xyz);

				vec3 viewDir = normalize(-viewPos.xyz);
				vec3 sliceBitangent = normalize(cross(sampleDir.xyz, viewDir));
				vec3 sliceTangent = cross(sliceBitangent, viewDir);
				vec3 normalInSlice = normalize(viewNormal - sliceBitangent * dot(viewNormal, sliceBitangent));
				
				vec3 tangentToNormalInSlice = cross(normalInSlice, sliceBitangent);
				vec2 cosHorizons = vec2(dot(viewDir, tangentToNormalInSlice), dot(viewDir, -tangentToNormalInSlice));
				
				for (int j = 0; j < STEPS; ++j) {
					vec3 sampleViewOffset = sampleDir.xyz * radiusToUse * sampleDir.w * pow(float(j + 1) / float(STEPS), distanceExponent);	

					vec3 sampleSceneUvDepth = getSceneUvAndDepth(viewPos + sampleViewOffset);
					vec3 sampleSceneViewPos = getViewPosition(sampleSceneUvDepth.xy, sampleSceneUvDepth.z);
					vec3 viewDelta = sampleSceneViewPos - viewPos;
					if (abs(viewDelta.z) < thickness) {
						float sampleCosHorizon = dot(viewDir, normalize(viewDelta));
						cosHorizons.x += max(0., (sampleCosHorizon - cosHorizons.x) * mix(1., 2. / float(j + 2), distanceFallOff));
					}		

					sampleSceneUvDepth = getSceneUvAndDepth(viewPos - sampleViewOffset);
					sampleSceneViewPos = getViewPosition(sampleSceneUvDepth.xy, sampleSceneUvDepth.z);
					viewDelta = sampleSceneViewPos - viewPos;
					if (abs(viewDelta.z) < thickness) {
						float sampleCosHorizon = dot(viewDir, normalize(viewDelta));
						cosHorizons.y += max(0., (sampleCosHorizon - cosHorizons.y) * mix(1., 2. / float(j + 2), distanceFallOff));
					}
				}

				vec2 sinHorizons = sqrt(1. - cosHorizons * cosHorizons);
				float nx = dot(normalInSlice, sliceTangent);
				float ny = dot(normalInSlice, viewDir);
				float nxb = 1. / 2. * (acos(cosHorizons.y) - acos(cosHorizons.x) + sinHorizons.x * cosHorizons.x - sinHorizons.y * cosHorizons.y);
				float nyb = 1. / 2. * (2. - cosHorizons.x * cosHorizons.x - cosHorizons.y * cosHorizons.y);
				float occlusion = nx * nxb + ny * nyb;
				ao += occlusion;
			}

			ao = clamp(ao / float(DIRECTIONS), 0., 1.);		
		#if SCENE_CLIP_BOX == 1
			ao = mix(ao, 1., smoothstep(0., radiusToUse, boxDistance));
		#endif
			ao = pow(ao, scale);

			gl_FragColor = FRAGMENT_OUTPUT;
		}`},Mf={name:"GTAODepthShader",defines:{PERSPECTIVE_CAMERA:1},uniforms:{tDepth:{value:null},cameraNear:{value:null},cameraFar:{value:null}},vertexShader:`
		varying vec2 vUv;

		void main() {
			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
		}`,fragmentShader:`
		uniform sampler2D tDepth;
		uniform float cameraNear;
		uniform float cameraFar;
		varying vec2 vUv;

		#include <packing>

		float getLinearDepth( const in vec2 screenPosition ) {
			#if PERSPECTIVE_CAMERA == 1
				float fragCoordZ = texture2D( tDepth, screenPosition ).x;
				float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );
				return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
			#else
				return texture2D( tDepth, screenPosition ).x;
			#endif
		}

		void main() {
			float depth = getLinearDepth( vUv );
			gl_FragColor = vec4( vec3( 1.0 - depth ), 1.0 );

		}`},t0={name:"GTAOBlendShader",uniforms:{tDiffuse:{value:null},intensity:{value:1}},vertexShader:`
		varying vec2 vUv;

		void main() {
			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
		}`,fragmentShader:`
		uniform float intensity;
		uniform sampler2D tDiffuse;
		varying vec2 vUv;

		void main() {
			vec4 texel = texture2D( tDiffuse, vUv );
			gl_FragColor = vec4(mix(vec3(1.), texel.rgb, intensity), texel.a);
		}`};function s3(e=5){let t=Math.floor(e)%2===0?Math.floor(e)+1:Math.floor(e),r=a3(t),i=r.length,n=new Uint8Array(i*4);for(let a=0;a<i;++a){let o=r[a],l=2*Math.PI*o/i,c=new je(Math.cos(l),Math.sin(l),0).normalize();n[a*4]=(c.x*.5+.5)*255,n[a*4+1]=(c.y*.5+.5)*255,n[a*4+2]=127,n[a*4+3]=255}let s=new ys(n,t,t);return s.wrapS=Wr,s.wrapT=Wr,s.needsUpdate=!0,s}function a3(e){let t=Math.floor(e)%2===0?Math.floor(e)+1:Math.floor(e),r=t*t,i=Array(r).fill(0),n=Math.floor(t/2),s=t-1;for(let a=1;a<=r;){if(n===-1&&s===t?(s=t-2,n=0):(s===t&&(s=0),n<0&&(n=t-1)),i[n*t+s]!==0){s-=2,n++;continue}else i[n*t+s]=a++;s++,n--}return i}var Af={name:"PoissonDenoiseShader",defines:{SAMPLES:16,SAMPLE_VECTORS:Fw(16,2,1),NORMAL_VECTOR_TYPE:1,DEPTH_VALUE_SOURCE:0},uniforms:{tDiffuse:{value:null},tNormal:{value:null},tDepth:{value:null},tNoise:{value:null},resolution:{value:new Ft},cameraProjectionMatrixInverse:{value:new Ir},lumaPhi:{value:5},depthPhi:{value:5},normalPhi:{value:5},radius:{value:4},index:{value:0}},vertexShader:`

		varying vec2 vUv;

		void main() {
			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
		}`,fragmentShader:`

		varying vec2 vUv;

		uniform sampler2D tDiffuse;
		uniform sampler2D tNormal;
		uniform sampler2D tDepth;
		uniform sampler2D tNoise;
		uniform vec2 resolution;
		uniform mat4 cameraProjectionMatrixInverse;
		uniform float lumaPhi;
		uniform float depthPhi;
		uniform float normalPhi;
		uniform float radius;
		uniform int index;
		
		#include <common>
		#include <packing>

		#ifndef SAMPLE_LUMINANCE
		#define SAMPLE_LUMINANCE dot(vec3(0.2125, 0.7154, 0.0721), a)
		#endif

		#ifndef FRAGMENT_OUTPUT
		#define FRAGMENT_OUTPUT vec4(denoised, 1.)
		#endif

		float getLuminance(const in vec3 a) {
			return SAMPLE_LUMINANCE;
		}

		const vec3 poissonDisk[SAMPLES] = SAMPLE_VECTORS;

		vec3 getViewPosition(const in vec2 screenPosition, const in float depth) {
			vec4 clipSpacePosition = vec4(vec3(screenPosition, depth) * 2.0 - 1.0, 1.0);
			vec4 viewSpacePosition = cameraProjectionMatrixInverse * clipSpacePosition;
			return viewSpacePosition.xyz / viewSpacePosition.w;
		}
		
		float getDepth(const vec2 uv) {
		#if DEPTH_VALUE_SOURCE == 1    
			return textureLod(tDepth, uv.xy, 0.0).a;
		#else
			return textureLod(tDepth, uv.xy, 0.0).r;
		#endif
		}

		float fetchDepth(const ivec2 uv) {
			#if DEPTH_VALUE_SOURCE == 1    
				return texelFetch(tDepth, uv.xy, 0).a;
			#else
				return texelFetch(tDepth, uv.xy, 0).r;
			#endif
		}

		vec3 computeNormalFromDepth(const vec2 uv) {
			vec2 size = vec2(textureSize(tDepth, 0));
			ivec2 p = ivec2(uv * size);
			float c0 = fetchDepth(p);
			float l2 = fetchDepth(p - ivec2(2, 0));
			float l1 = fetchDepth(p - ivec2(1, 0));
			float r1 = fetchDepth(p + ivec2(1, 0));
			float r2 = fetchDepth(p + ivec2(2, 0));
			float b2 = fetchDepth(p - ivec2(0, 2));
			float b1 = fetchDepth(p - ivec2(0, 1));
			float t1 = fetchDepth(p + ivec2(0, 1));
			float t2 = fetchDepth(p + ivec2(0, 2));
			float dl = abs((2.0 * l1 - l2) - c0);
			float dr = abs((2.0 * r1 - r2) - c0);
			float db = abs((2.0 * b1 - b2) - c0);
			float dt = abs((2.0 * t1 - t2) - c0);
			vec3 ce = getViewPosition(uv, c0).xyz;
			vec3 dpdx = (dl < dr) ?  ce - getViewPosition((uv - vec2(1.0 / size.x, 0.0)), l1).xyz
									: -ce + getViewPosition((uv + vec2(1.0 / size.x, 0.0)), r1).xyz;
			vec3 dpdy = (db < dt) ?  ce - getViewPosition((uv - vec2(0.0, 1.0 / size.y)), b1).xyz
									: -ce + getViewPosition((uv + vec2(0.0, 1.0 / size.y)), t1).xyz;
			return normalize(cross(dpdx, dpdy));
		}

		vec3 getViewNormal(const vec2 uv) {
		#if NORMAL_VECTOR_TYPE == 2
			return normalize(textureLod(tNormal, uv, 0.).rgb);
		#elif NORMAL_VECTOR_TYPE == 1
			return unpackRGBToNormal(textureLod(tNormal, uv, 0.).rgb);
		#else
			return computeNormalFromDepth(uv);
		#endif
		}

		void denoiseSample(in vec3 center, in vec3 viewNormal, in vec3 viewPos, in vec2 sampleUv, inout vec3 denoised, inout float totalWeight) {
			vec4 sampleTexel = textureLod(tDiffuse, sampleUv, 0.0);
			float sampleDepth = getDepth(sampleUv);
			vec3 sampleNormal = getViewNormal(sampleUv);
			vec3 neighborColor = sampleTexel.rgb;
			vec3 viewPosSample = getViewPosition(sampleUv, sampleDepth);
			
			float normalDiff = dot(viewNormal, sampleNormal);
			float normalSimilarity = pow(max(normalDiff, 0.), normalPhi);
			float lumaDiff = abs(getLuminance(neighborColor) - getLuminance(center));
			float lumaSimilarity = max(1.0 - lumaDiff / lumaPhi, 0.0);
			float depthDiff = abs(dot(viewPos - viewPosSample, viewNormal));
			float depthSimilarity = max(1. - depthDiff / depthPhi, 0.);
			float w = lumaSimilarity * depthSimilarity * normalSimilarity;
		
			denoised += w * neighborColor;
			totalWeight += w;
		}
		
		void main() {
			float depth = getDepth(vUv.xy);	
			vec3 viewNormal = getViewNormal(vUv);	
			if (depth == 1. || dot(viewNormal, viewNormal) == 0.) {
				discard;
				return;
			}
			vec4 texel = textureLod(tDiffuse, vUv, 0.0);
			vec3 center = texel.rgb;
			vec3 viewPos = getViewPosition(vUv, depth);

			vec2 noiseResolution = vec2(textureSize(tNoise, 0));
			vec2 noiseUv = vUv * resolution / noiseResolution;
			vec4 noiseTexel = textureLod(tNoise, noiseUv, 0.0);
      		vec2 noiseVec = vec2(sin(noiseTexel[index % 4] * 2. * PI), cos(noiseTexel[index % 4] * 2. * PI));
    		mat2 rotationMatrix = mat2(noiseVec.x, -noiseVec.y, noiseVec.x, noiseVec.y);
		
			float totalWeight = 1.0;
			vec3 denoised = texel.rgb;
			for (int i = 0; i < SAMPLES; i++) {
				vec3 sampleDir = poissonDisk[i];
				vec2 offset = rotationMatrix * (sampleDir.xy * (1. + sampleDir.z * (radius - 1.)) / resolution);
				vec2 sampleUv = vUv + offset;
				denoiseSample(center, viewNormal, viewPos, sampleUv, denoised, totalWeight);
			}
		
			if (totalWeight > 0.) { 
				denoised /= totalWeight;
			}
			gl_FragColor = FRAGMENT_OUTPUT;
		}`};function Fw(e,t,r){let i=o3(e,t,r),n="vec3[SAMPLES](";for(let s=0;s<e;s++){let a=i[s];n+=`vec3(${a.x}, ${a.y}, ${a.z})${s<e-1?",":")"}`}return n}function o3(e,t,r){let i=[];for(let n=0;n<e;n++){let s=2*Math.PI*t*n/e,a=Math.pow(n/(e-1),r);i.push(new je(Math.cos(s),Math.sin(s),a))}return i}var l3=class{constructor(e=Math){this.grad3=[[1,1,0],[-1,1,0],[1,-1,0],[-1,-1,0],[1,0,1],[-1,0,1],[1,0,-1],[-1,0,-1],[0,1,1],[0,-1,1],[0,1,-1],[0,-1,-1]],this.grad4=[[0,1,1,1],[0,1,1,-1],[0,1,-1,1],[0,1,-1,-1],[0,-1,1,1],[0,-1,1,-1],[0,-1,-1,1],[0,-1,-1,-1],[1,0,1,1],[1,0,1,-1],[1,0,-1,1],[1,0,-1,-1],[-1,0,1,1],[-1,0,1,-1],[-1,0,-1,1],[-1,0,-1,-1],[1,1,0,1],[1,1,0,-1],[1,-1,0,1],[1,-1,0,-1],[-1,1,0,1],[-1,1,0,-1],[-1,-1,0,1],[-1,-1,0,-1],[1,1,1,0],[1,1,-1,0],[1,-1,1,0],[1,-1,-1,0],[-1,1,1,0],[-1,1,-1,0],[-1,-1,1,0],[-1,-1,-1,0]],this.p=[];for(let t=0;t<256;t++)this.p[t]=Math.floor(e.random()*256);this.perm=[];for(let t=0;t<512;t++)this.perm[t]=this.p[t&255];this.simplex=[[0,1,2,3],[0,1,3,2],[0,0,0,0],[0,2,3,1],[0,0,0,0],[0,0,0,0],[0,0,0,0],[1,2,3,0],[0,2,1,3],[0,0,0,0],[0,3,1,2],[0,3,2,1],[0,0,0,0],[0,0,0,0],[0,0,0,0],[1,3,2,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[1,2,0,3],[0,0,0,0],[1,3,0,2],[0,0,0,0],[0,0,0,0],[0,0,0,0],[2,3,0,1],[2,3,1,0],[1,0,2,3],[1,0,3,2],[0,0,0,0],[0,0,0,0],[0,0,0,0],[2,0,3,1],[0,0,0,0],[2,1,3,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[2,0,1,3],[0,0,0,0],[0,0,0,0],[0,0,0,0],[3,0,1,2],[3,0,2,1],[0,0,0,0],[3,1,2,0],[2,1,0,3],[0,0,0,0],[0,0,0,0],[0,0,0,0],[3,1,0,2],[0,0,0,0],[3,2,0,1],[3,2,1,0]]}dot(e,t,r){return e[0]*t+e[1]*r}dot3(e,t,r,i){return e[0]*t+e[1]*r+e[2]*i}dot4(e,t,r,i,n){return e[0]*t+e[1]*r+e[2]*i+e[3]*n}noise(e,t){let r,i,n,s=.5*(Math.sqrt(3)-1),a=(e+t)*s,o=Math.floor(e+a),l=Math.floor(t+a),c=(3-Math.sqrt(3))/6,u=(o+l)*c,d=o-u,f=l-u,y=e-d,b=t-f,x,g;y>b?(x=1,g=0):(x=0,g=1);let v=y-x+c,_=b-g+c,E=y-1+2*c,M=b-1+2*c,P=o&255,k=l&255,z=this.perm[P+this.perm[k]]%12,D=this.perm[P+x+this.perm[k+g]]%12,I=this.perm[P+1+this.perm[k+1]]%12,L=.5-y*y-b*b;L<0?r=0:(L*=L,r=L*L*this.dot(this.grad3[z],y,b));let Z=.5-v*v-_*_;Z<0?i=0:(Z*=Z,i=Z*Z*this.dot(this.grad3[D],v,_));let se=.5-E*E-M*M;return se<0?n=0:(se*=se,n=se*se*this.dot(this.grad3[I],E,M)),70*(r+i+n)}noise3d(e,t,r){let i,n,s,a,o=(e+t+r)*.3333333333333333,l=Math.floor(e+o),c=Math.floor(t+o),u=Math.floor(r+o),d=1/6,f=(l+c+u)*d,y=l-f,b=c-f,x=u-f,g=e-y,v=t-b,_=r-x,E,M,P,k,z,D;g>=v?v>=_?(E=1,M=0,P=0,k=1,z=1,D=0):g>=_?(E=1,M=0,P=0,k=1,z=0,D=1):(E=0,M=0,P=1,k=1,z=0,D=1):v<_?(E=0,M=0,P=1,k=0,z=1,D=1):g<_?(E=0,M=1,P=0,k=0,z=1,D=1):(E=0,M=1,P=0,k=1,z=1,D=0);let I=g-E+d,L=v-M+d,Z=_-P+d,se=g-k+2*d,ce=v-z+2*d,fe=_-D+2*d,ze=g-1+3*d,Fe=v-1+3*d,Pe=_-1+3*d,ue=l&255,Te=c&255,de=u&255,Ie=this.perm[ue+this.perm[Te+this.perm[de]]]%12,Re=this.perm[ue+E+this.perm[Te+M+this.perm[de+P]]]%12,Be=this.perm[ue+k+this.perm[Te+z+this.perm[de+D]]]%12,Se=this.perm[ue+1+this.perm[Te+1+this.perm[de+1]]]%12,U=.6-g*g-v*v-_*_;U<0?i=0:(U*=U,i=U*U*this.dot3(this.grad3[Ie],g,v,_));let ie=.6-I*I-L*L-Z*Z;ie<0?n=0:(ie*=ie,n=ie*ie*this.dot3(this.grad3[Re],I,L,Z));let Ae=.6-se*se-ce*ce-fe*fe;Ae<0?s=0:(Ae*=Ae,s=Ae*Ae*this.dot3(this.grad3[Be],se,ce,fe));let Ue=.6-ze*ze-Fe*Fe-Pe*Pe;return Ue<0?a=0:(Ue*=Ue,a=Ue*Ue*this.dot3(this.grad3[Se],ze,Fe,Pe)),32*(i+n+s+a)}noise4d(e,t,r,i){let n=this.grad4,s=this.simplex,a=this.perm,o=(Math.sqrt(5)-1)/4,l=(5-Math.sqrt(5))/20,c,u,d,f,y,b=(e+t+r+i)*o,x=Math.floor(e+b),g=Math.floor(t+b),v=Math.floor(r+b),_=Math.floor(i+b),E=(x+g+v+_)*l,M=x-E,P=g-E,k=v-E,z=_-E,D=e-M,I=t-P,L=r-k,Z=i-z,se=D>I?32:0,ce=D>L?16:0,fe=I>L?8:0,ze=D>Z?4:0,Fe=I>Z?2:0,Pe=L>Z?1:0,ue=se+ce+fe+ze+Fe+Pe,Te=s[ue][0]>=3?1:0,de=s[ue][1]>=3?1:0,Ie=s[ue][2]>=3?1:0,Re=s[ue][3]>=3?1:0,Be=s[ue][0]>=2?1:0,Se=s[ue][1]>=2?1:0,U=s[ue][2]>=2?1:0,ie=s[ue][3]>=2?1:0,Ae=s[ue][0]>=1?1:0,Ue=s[ue][1]>=1?1:0,Ge=s[ue][2]>=1?1:0,nt=s[ue][3]>=1?1:0,Qe=D-Te+l,ct=I-de+l,ye=L-Ie+l,dt=Z-Re+l,xt=D-Be+2*l,Dt=I-Se+2*l,We=L-U+2*l,mt=Z-ie+2*l,it=D-Ae+3*l,st=I-Ue+3*l,oe=L-Ge+3*l,F=Z-nt+3*l,le=D-1+4*l,pe=I-1+4*l,Le=L-1+4*l,He=Z-1+4*l,at=x&255,rt=g&255,ht=v&255,Tt=_&255,Mt=a[at+a[rt+a[ht+a[Tt]]]]%32,Ut=a[at+Te+a[rt+de+a[ht+Ie+a[Tt+Re]]]]%32,Kt=a[at+Be+a[rt+Se+a[ht+U+a[Tt+ie]]]]%32,fr=a[at+Ae+a[rt+Ue+a[ht+Ge+a[Tt+nt]]]]%32,er=a[at+1+a[rt+1+a[ht+1+a[Tt+1]]]]%32,Zt=.6-D*D-I*I-L*L-Z*Z;Zt<0?c=0:(Zt*=Zt,c=Zt*Zt*this.dot4(n[Mt],D,I,L,Z));let Gt=.6-Qe*Qe-ct*ct-ye*ye-dt*dt;Gt<0?u=0:(Gt*=Gt,u=Gt*Gt*this.dot4(n[Ut],Qe,ct,ye,dt));let Er=.6-xt*xt-Dt*Dt-We*We-mt*mt;Er<0?d=0:(Er*=Er,d=Er*Er*this.dot4(n[Kt],xt,Dt,We,mt));let ut=.6-it*it-st*st-oe*oe-F*F;ut<0?f=0:(ut*=ut,f=ut*ut*this.dot4(n[fr],it,st,oe,F));let zt=.6-le*le-pe*pe-Le*Le-He*He;return zt<0?y=0:(zt*=zt,y=zt*zt*this.dot4(n[er],le,pe,Le,He)),27*(c+u+d+f+y)}},r0=class No extends yl{constructor(t,r,i,n,s,a,o){super(),this.width=i!==void 0?i:512,this.height=n!==void 0?n:512,this.clear=!0,this.camera=r,this.scene=t,this.output=0,this._renderGBuffer=!0,this._visibilityCache=new Map,this.blendIntensity=1,this.pdRings=2,this.pdRadiusExponent=2,this.pdSamples=16,this.gtaoNoiseTexture=s3(),this.pdNoiseTexture=this.generateNoise(),this.gtaoRenderTarget=new In(this.width,this.height,{type:Ts}),this.pdRenderTarget=this.gtaoRenderTarget.clone(),this.gtaoMaterial=new ln({defines:Object.assign({},Sf.defines),uniforms:Rs.clone(Sf.uniforms),vertexShader:Sf.vertexShader,fragmentShader:Sf.fragmentShader,blending:Ye,depthTest:!1,depthWrite:!1}),this.gtaoMaterial.defines.PERSPECTIVE_CAMERA=this.camera.isPerspectiveCamera?1:0,this.gtaoMaterial.uniforms.tNoise.value=this.gtaoNoiseTexture,this.gtaoMaterial.uniforms.resolution.value.set(this.width,this.height),this.gtaoMaterial.uniforms.cameraNear.value=this.camera.near,this.gtaoMaterial.uniforms.cameraFar.value=this.camera.far,this.normalMaterial=new ly,this.normalMaterial.blending=Ye,this.pdMaterial=new ln({defines:Object.assign({},Af.defines),uniforms:Rs.clone(Af.uniforms),vertexShader:Af.vertexShader,fragmentShader:Af.fragmentShader,depthTest:!1,depthWrite:!1}),this.pdMaterial.uniforms.tDiffuse.value=this.gtaoRenderTarget.texture,this.pdMaterial.uniforms.tNoise.value=this.pdNoiseTexture,this.pdMaterial.uniforms.resolution.value.set(this.width,this.height),this.pdMaterial.uniforms.lumaPhi.value=10,this.pdMaterial.uniforms.depthPhi.value=2,this.pdMaterial.uniforms.normalPhi.value=3,this.pdMaterial.uniforms.radius.value=8,this.depthRenderMaterial=new ln({defines:Object.assign({},Mf.defines),uniforms:Rs.clone(Mf.uniforms),vertexShader:Mf.vertexShader,fragmentShader:Mf.fragmentShader,blending:Ye}),this.depthRenderMaterial.uniforms.cameraNear.value=this.camera.near,this.depthRenderMaterial.uniforms.cameraFar.value=this.camera.far,this.copyMaterial=new ln({uniforms:Rs.clone(_f.uniforms),vertexShader:_f.vertexShader,fragmentShader:_f.fragmentShader,transparent:!0,depthTest:!1,depthWrite:!1,blendSrc:Gr,blendDst:At,blendEquation:gt,blendSrcAlpha:Yt,blendDstAlpha:At,blendEquationAlpha:gt}),this.blendMaterial=new ln({uniforms:Rs.clone(t0.uniforms),vertexShader:t0.vertexShader,fragmentShader:t0.fragmentShader,transparent:!0,depthTest:!1,depthWrite:!1,blending:Et,blendSrc:Gr,blendDst:At,blendEquation:gt,blendSrcAlpha:Yt,blendDstAlpha:At,blendEquationAlpha:gt}),this.fsQuad=new Ef(null),this.originalClearColor=new or,this.setGBuffer(s?s.depthTexture:void 0,s?s.normalTexture:void 0),a!==void 0&&this.updateGtaoMaterial(a),o!==void 0&&this.updatePdMaterial(o)}dispose(){this.gtaoNoiseTexture.dispose(),this.pdNoiseTexture.dispose(),this.normalRenderTarget.dispose(),this.gtaoRenderTarget.dispose(),this.pdRenderTarget.dispose(),this.normalMaterial.dispose(),this.pdMaterial.dispose(),this.copyMaterial.dispose(),this.depthRenderMaterial.dispose(),this.fsQuad.dispose()}get gtaoMap(){return this.pdRenderTarget.texture}setGBuffer(t,r){t!==void 0?(this.depthTexture=t,this.normalTexture=r,this._renderGBuffer=!1):(this.depthTexture=new zp,this.depthTexture.format=no,this.depthTexture.type=io,this.normalRenderTarget=new In(this.width,this.height,{minFilter:oi,magFilter:oi,type:Ts,depthTexture:this.depthTexture}),this.normalTexture=this.normalRenderTarget.texture,this._renderGBuffer=!0);let i=this.normalTexture?1:0,n=this.depthTexture===this.normalTexture?"w":"x";this.gtaoMaterial.defines.NORMAL_VECTOR_TYPE=i,this.gtaoMaterial.defines.DEPTH_SWIZZLING=n,this.gtaoMaterial.uniforms.tNormal.value=this.normalTexture,this.gtaoMaterial.uniforms.tDepth.value=this.depthTexture,this.pdMaterial.defines.NORMAL_VECTOR_TYPE=i,this.pdMaterial.defines.DEPTH_SWIZZLING=n,this.pdMaterial.uniforms.tNormal.value=this.normalTexture,this.pdMaterial.uniforms.tDepth.value=this.depthTexture,this.depthRenderMaterial.uniforms.tDepth.value=this.normalRenderTarget.depthTexture}setSceneClipBox(t){t?(this.gtaoMaterial.needsUpdate=this.gtaoMaterial.defines.SCENE_CLIP_BOX!==1,this.gtaoMaterial.defines.SCENE_CLIP_BOX=1,this.gtaoMaterial.uniforms.sceneBoxMin.value.copy(t.min),this.gtaoMaterial.uniforms.sceneBoxMax.value.copy(t.max)):(this.gtaoMaterial.needsUpdate=this.gtaoMaterial.defines.SCENE_CLIP_BOX===0,this.gtaoMaterial.defines.SCENE_CLIP_BOX=0)}updateGtaoMaterial(t){t.radius!==void 0&&(this.gtaoMaterial.uniforms.radius.value=t.radius),t.distanceExponent!==void 0&&(this.gtaoMaterial.uniforms.distanceExponent.value=t.distanceExponent),t.thickness!==void 0&&(this.gtaoMaterial.uniforms.thickness.value=t.thickness),t.distanceFallOff!==void 0&&(this.gtaoMaterial.uniforms.distanceFallOff.value=t.distanceFallOff,this.gtaoMaterial.needsUpdate=!0),t.scale!==void 0&&(this.gtaoMaterial.uniforms.scale.value=t.scale),t.samples!==void 0&&t.samples!==this.gtaoMaterial.defines.SAMPLES&&(this.gtaoMaterial.defines.SAMPLES=t.samples,this.gtaoMaterial.needsUpdate=!0),t.screenSpaceRadius!==void 0&&(t.screenSpaceRadius?1:0)!==this.gtaoMaterial.defines.SCREEN_SPACE_RADIUS&&(this.gtaoMaterial.defines.SCREEN_SPACE_RADIUS=t.screenSpaceRadius?1:0,this.gtaoMaterial.needsUpdate=!0)}updatePdMaterial(t){let r=!1;t.lumaPhi!==void 0&&(this.pdMaterial.uniforms.lumaPhi.value=t.lumaPhi),t.depthPhi!==void 0&&(this.pdMaterial.uniforms.depthPhi.value=t.depthPhi),t.normalPhi!==void 0&&(this.pdMaterial.uniforms.normalPhi.value=t.normalPhi),t.radius!==void 0&&t.radius!==this.radius&&(this.pdMaterial.uniforms.radius.value=t.radius),t.radiusExponent!==void 0&&t.radiusExponent!==this.pdRadiusExponent&&(this.pdRadiusExponent=t.radiusExponent,r=!0),t.rings!==void 0&&t.rings!==this.pdRings&&(this.pdRings=t.rings,r=!0),t.samples!==void 0&&t.samples!==this.pdSamples&&(this.pdSamples=t.samples,r=!0),r&&(this.pdMaterial.defines.SAMPLES=this.pdSamples,this.pdMaterial.defines.SAMPLE_VECTORS=Fw(this.pdSamples,this.pdRings,this.pdRadiusExponent),this.pdMaterial.needsUpdate=!0)}render(t,r,i){switch(this._renderGBuffer&&(this.overrideVisibility(),this.renderOverride(t,this.normalMaterial,this.normalRenderTarget,7829503,1),this.restoreVisibility()),this.gtaoMaterial.uniforms.cameraNear.value=this.camera.near,this.gtaoMaterial.uniforms.cameraFar.value=this.camera.far,this.gtaoMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix),this.gtaoMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse),this.gtaoMaterial.uniforms.cameraWorldMatrix.value.copy(this.camera.matrixWorld),this.renderPass(t,this.gtaoMaterial,this.gtaoRenderTarget,16777215,1),this.pdMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse),this.renderPass(t,this.pdMaterial,this.pdRenderTarget,16777215,1),this.output){case No.OUTPUT.Off:break;case No.OUTPUT.Diffuse:this.copyMaterial.uniforms.tDiffuse.value=i.texture,this.copyMaterial.blending=Ye,this.renderPass(t,this.copyMaterial,this.renderToScreen?null:r);break;case No.OUTPUT.AO:this.copyMaterial.uniforms.tDiffuse.value=this.gtaoRenderTarget.texture,this.copyMaterial.blending=Ye,this.renderPass(t,this.copyMaterial,this.renderToScreen?null:r);break;case No.OUTPUT.Denoise:this.copyMaterial.uniforms.tDiffuse.value=this.pdRenderTarget.texture,this.copyMaterial.blending=Ye,this.renderPass(t,this.copyMaterial,this.renderToScreen?null:r);break;case No.OUTPUT.Depth:this.depthRenderMaterial.uniforms.cameraNear.value=this.camera.near,this.depthRenderMaterial.uniforms.cameraFar.value=this.camera.far,this.renderPass(t,this.depthRenderMaterial,this.renderToScreen?null:r);break;case No.OUTPUT.Normal:this.copyMaterial.uniforms.tDiffuse.value=this.normalRenderTarget.texture,this.copyMaterial.blending=Ye,this.renderPass(t,this.copyMaterial,this.renderToScreen?null:r);break;case No.OUTPUT.Default:this.copyMaterial.uniforms.tDiffuse.value=i.texture,this.copyMaterial.blending=Ye,this.renderPass(t,this.copyMaterial,this.renderToScreen?null:r),this.blendMaterial.uniforms.intensity.value=this.blendIntensity,this.blendMaterial.uniforms.tDiffuse.value=this.pdRenderTarget.texture,this.renderPass(t,this.blendMaterial,this.renderToScreen?null:r);break;default:console.warn("THREE.GTAOPass: Unknown output type.")}}renderPass(t,r,i,n,s){t.getClearColor(this.originalClearColor);let a=t.getClearAlpha(),o=t.autoClear;t.setRenderTarget(i),t.autoClear=!1,n!=null&&(t.setClearColor(n),t.setClearAlpha(s||0),t.clear()),this.fsQuad.material=r,this.fsQuad.render(t),t.autoClear=o,t.setClearColor(this.originalClearColor),t.setClearAlpha(a)}renderOverride(t,r,i,n,s){t.getClearColor(this.originalClearColor);let a=t.getClearAlpha(),o=t.autoClear;t.setRenderTarget(i),t.autoClear=!1,n=r.clearColor||n,s=r.clearAlpha||s,n!=null&&(t.setClearColor(n),t.setClearAlpha(s||0),t.clear()),this.scene.overrideMaterial=r,t.render(this.scene,this.camera),this.scene.overrideMaterial=null,t.autoClear=o,t.setClearColor(this.originalClearColor),t.setClearAlpha(a)}setSize(t,r){this.width=t,this.height=r,this.gtaoRenderTarget.setSize(t,r),this.normalRenderTarget.setSize(t,r),this.pdRenderTarget.setSize(t,r),this.gtaoMaterial.uniforms.resolution.value.set(t,r),this.gtaoMaterial.uniforms.cameraProjectionMatrix.value.copy(this.camera.projectionMatrix),this.gtaoMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse),this.pdMaterial.uniforms.resolution.value.set(t,r),this.pdMaterial.uniforms.cameraProjectionMatrixInverse.value.copy(this.camera.projectionMatrixInverse)}overrideVisibility(){let t=this.scene,r=this._visibilityCache;t.traverse(function(i){r.set(i,i.visible),(i.isPoints||i.isLine)&&(i.visible=!1)})}restoreVisibility(){let t=this.scene,r=this._visibilityCache;t.traverse(function(i){let n=r.get(i);i.visible=n}),r.clear()}generateNoise(t=64){let r=new l3,i=t*t*4,n=new Uint8Array(i);for(let a=0;a<t;a++)for(let o=0;o<t;o++){let l=a,c=o;n[(a*t+o)*4]=(r.noise(l,c)*.5+.5)*255,n[(a*t+o)*4+1]=(r.noise(l+t,c)*.5+.5)*255,n[(a*t+o)*4+2]=(r.noise(l,c+t)*.5+.5)*255,n[(a*t+o)*4+3]=(r.noise(l+t,c+t)*.5+.5)*255}let s=new ys(n,t,t,Ln,Ji);return s.wrapS=Wr,s.wrapT=Wr,s.needsUpdate=!0,s}};r0.OUTPUT={Off:-1,Default:0,Diffuse:1,Depth:2,Normal:3,AO:4,Denoise:5};var c3={name:"OutputShader",uniforms:{tDiffuse:{value:null},toneMappingExposure:{value:1}},vertexShader:`
		precision highp float;

		uniform mat4 modelViewMatrix;
		uniform mat4 projectionMatrix;

		attribute vec3 position;
		attribute vec2 uv;

		varying vec2 vUv;

		void main() {

			vUv = uv;
			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

		}`,fragmentShader:`
	
		precision highp float;

		uniform sampler2D tDiffuse;

		#include <tonemapping_pars_fragment>
		#include <colorspace_pars_fragment>

		varying vec2 vUv;

		void main() {

			gl_FragColor = texture2D( tDiffuse, vUv );

			// tone mapping

			#ifdef LINEAR_TONE_MAPPING

				gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb );

			#elif defined( REINHARD_TONE_MAPPING )

				gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb );

			#elif defined( CINEON_TONE_MAPPING )

				gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb );

			#elif defined( ACES_FILMIC_TONE_MAPPING )

				gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb );

			#elif defined( AGX_TONE_MAPPING )

				gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb );

			#elif defined( NEUTRAL_TONE_MAPPING )

				gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb );

			#endif

			// color space

			#ifdef SRGB_TRANSFER

				gl_FragColor = sRGBTransferOETF( gl_FragColor );

			#endif

		}`},h3=class extends yl{constructor(){super();let e=c3;this.uniforms=Rs.clone(e.uniforms),this.material=new ay({name:e.name,uniforms:this.uniforms,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader}),this.fsQuad=new Ef(this.material),this._outputColorSpace=null,this._toneMapping=null}render(e,t,r){this.uniforms.tDiffuse.value=r.texture,this.uniforms.toneMappingExposure.value=e.toneMappingExposure,(this._outputColorSpace!==e.outputColorSpace||this._toneMapping!==e.toneMapping)&&(this._outputColorSpace=e.outputColorSpace,this._toneMapping=e.toneMapping,this.material.defines={},li.getTransfer(this._outputColorSpace)===Ii&&(this.material.defines.SRGB_TRANSFER=""),this._toneMapping===Si?this.material.defines.LINEAR_TONE_MAPPING="":this._toneMapping===Vr?this.material.defines.REINHARD_TONE_MAPPING="":this._toneMapping===Yr?this.material.defines.CINEON_TONE_MAPPING="":this._toneMapping===Cr?this.material.defines.ACES_FILMIC_TONE_MAPPING="":this._toneMapping===Ur?this.material.defines.AGX_TONE_MAPPING="":this._toneMapping===ni&&(this.material.defines.NEUTRAL_TONE_MAPPING=""),this.material.needsUpdate=!0),this.renderToScreen===!0?(e.setRenderTarget(null),this.fsQuad.render(e)):(e.setRenderTarget(t),this.clear&&e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil),this.fsQuad.render(e))}dispose(){this.material.dispose(),this.fsQuad.dispose()}},Tf={name:"SMAAEdgesShader",defines:{SMAA_THRESHOLD:"0.1"},uniforms:{tDiffuse:{value:null},resolution:{value:new Ft(1/1024,1/512)}},vertexShader:`

		uniform vec2 resolution;

		varying vec2 vUv;
		varying vec4 vOffset[ 3 ];

		void SMAAEdgeDetectionVS( vec2 texcoord ) {
			vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0,  1.0 ); // WebGL port note: Changed sign in W component
			vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4(  1.0, 0.0, 0.0, -1.0 ); // WebGL port note: Changed sign in W component
			vOffset[ 2 ] = texcoord.xyxy + resolution.xyxy * vec4( -2.0, 0.0, 0.0,  2.0 ); // WebGL port note: Changed sign in W component
		}

		void main() {

			vUv = uv;

			SMAAEdgeDetectionVS( vUv );

			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

		}`,fragmentShader:`

		uniform sampler2D tDiffuse;

		varying vec2 vUv;
		varying vec4 vOffset[ 3 ];

		vec4 SMAAColorEdgeDetectionPS( vec2 texcoord, vec4 offset[3], sampler2D colorTex ) {
			vec2 threshold = vec2( SMAA_THRESHOLD, SMAA_THRESHOLD );

			// Calculate color deltas:
			vec4 delta;
			vec3 C = texture2D( colorTex, texcoord ).rgb;

			vec3 Cleft = texture2D( colorTex, offset[0].xy ).rgb;
			vec3 t = abs( C - Cleft );
			delta.x = max( max( t.r, t.g ), t.b );

			vec3 Ctop = texture2D( colorTex, offset[0].zw ).rgb;
			t = abs( C - Ctop );
			delta.y = max( max( t.r, t.g ), t.b );

			// We do the usual threshold:
			vec2 edges = step( threshold, delta.xy );

			// Then discard if there is no edge:
			if ( dot( edges, vec2( 1.0, 1.0 ) ) == 0.0 )
				discard;

			// Calculate right and bottom deltas:
			vec3 Cright = texture2D( colorTex, offset[1].xy ).rgb;
			t = abs( C - Cright );
			delta.z = max( max( t.r, t.g ), t.b );

			vec3 Cbottom  = texture2D( colorTex, offset[1].zw ).rgb;
			t = abs( C - Cbottom );
			delta.w = max( max( t.r, t.g ), t.b );

			// Calculate the maximum delta in the direct neighborhood:
			float maxDelta = max( max( max( delta.x, delta.y ), delta.z ), delta.w );

			// Calculate left-left and top-top deltas:
			vec3 Cleftleft  = texture2D( colorTex, offset[2].xy ).rgb;
			t = abs( C - Cleftleft );
			delta.z = max( max( t.r, t.g ), t.b );

			vec3 Ctoptop = texture2D( colorTex, offset[2].zw ).rgb;
			t = abs( C - Ctoptop );
			delta.w = max( max( t.r, t.g ), t.b );

			// Calculate the final maximum delta:
			maxDelta = max( max( maxDelta, delta.z ), delta.w );

			// Local contrast adaptation in action:
			edges.xy *= step( 0.5 * maxDelta, delta.xy );

			return vec4( edges, 0.0, 0.0 );
		}

		void main() {

			gl_FragColor = SMAAColorEdgeDetectionPS( vUv, vOffset, tDiffuse );

		}`},Cf={name:"SMAAWeightsShader",defines:{SMAA_MAX_SEARCH_STEPS:"8",SMAA_AREATEX_MAX_DISTANCE:"16",SMAA_AREATEX_PIXEL_SIZE:"( 1.0 / vec2( 160.0, 560.0 ) )",SMAA_AREATEX_SUBTEX_SIZE:"( 1.0 / 7.0 )"},uniforms:{tDiffuse:{value:null},tArea:{value:null},tSearch:{value:null},resolution:{value:new Ft(1/1024,1/512)}},vertexShader:`

		uniform vec2 resolution;

		varying vec2 vUv;
		varying vec4 vOffset[ 3 ];
		varying vec2 vPixcoord;

		void SMAABlendingWeightCalculationVS( vec2 texcoord ) {
			vPixcoord = texcoord / resolution;

			// We will use these offsets for the searches later on (see @PSEUDO_GATHER4):
			vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -0.25, 0.125, 1.25, 0.125 ); // WebGL port note: Changed sign in Y and W components
			vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( -0.125, 0.25, -0.125, -1.25 ); // WebGL port note: Changed sign in Y and W components

			// And these for the searches, they indicate the ends of the loops:
			vOffset[ 2 ] = vec4( vOffset[ 0 ].xz, vOffset[ 1 ].yw ) + vec4( -2.0, 2.0, -2.0, 2.0 ) * resolution.xxyy * float( SMAA_MAX_SEARCH_STEPS );

		}

		void main() {

			vUv = uv;

			SMAABlendingWeightCalculationVS( vUv );

			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

		}`,fragmentShader:`

		#define SMAASampleLevelZeroOffset( tex, coord, offset ) texture2D( tex, coord + float( offset ) * resolution, 0.0 )

		uniform sampler2D tDiffuse;
		uniform sampler2D tArea;
		uniform sampler2D tSearch;
		uniform vec2 resolution;

		varying vec2 vUv;
		varying vec4 vOffset[3];
		varying vec2 vPixcoord;

		#if __VERSION__ == 100
		vec2 round( vec2 x ) {
			return sign( x ) * floor( abs( x ) + 0.5 );
		}
		#endif

		float SMAASearchLength( sampler2D searchTex, vec2 e, float bias, float scale ) {
			// Not required if searchTex accesses are set to point:
			// float2 SEARCH_TEX_PIXEL_SIZE = 1.0 / float2(66.0, 33.0);
			// e = float2(bias, 0.0) + 0.5 * SEARCH_TEX_PIXEL_SIZE +
			//     e * float2(scale, 1.0) * float2(64.0, 32.0) * SEARCH_TEX_PIXEL_SIZE;
			e.r = bias + e.r * scale;
			return 255.0 * texture2D( searchTex, e, 0.0 ).r;
		}

		float SMAASearchXLeft( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {
			/**
				* @PSEUDO_GATHER4
				* This texcoord has been offset by (-0.25, -0.125) in the vertex shader to
				* sample between edge, thus fetching four edges in a row.
				* Sampling with different offsets in each direction allows to disambiguate
				* which edges are active from the four fetched ones.
				*/
			vec2 e = vec2( 0.0, 1.0 );

			for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for
				e = texture2D( edgesTex, texcoord, 0.0 ).rg;
				texcoord -= vec2( 2.0, 0.0 ) * resolution;
				if ( ! ( texcoord.x > end && e.g > 0.8281 && e.r == 0.0 ) ) break;
			}

			// We correct the previous (-0.25, -0.125) offset we applied:
			texcoord.x += 0.25 * resolution.x;

			// The searches are bias by 1, so adjust the coords accordingly:
			texcoord.x += resolution.x;

			// Disambiguate the length added by the last step:
			texcoord.x += 2.0 * resolution.x; // Undo last step
			texcoord.x -= resolution.x * SMAASearchLength(searchTex, e, 0.0, 0.5);

			return texcoord.x;
		}

		float SMAASearchXRight( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {
			vec2 e = vec2( 0.0, 1.0 );

			for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for
				e = texture2D( edgesTex, texcoord, 0.0 ).rg;
				texcoord += vec2( 2.0, 0.0 ) * resolution;
				if ( ! ( texcoord.x < end && e.g > 0.8281 && e.r == 0.0 ) ) break;
			}

			texcoord.x -= 0.25 * resolution.x;
			texcoord.x -= resolution.x;
			texcoord.x -= 2.0 * resolution.x;
			texcoord.x += resolution.x * SMAASearchLength( searchTex, e, 0.5, 0.5 );

			return texcoord.x;
		}

		float SMAASearchYUp( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {
			vec2 e = vec2( 1.0, 0.0 );

			for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for
				e = texture2D( edgesTex, texcoord, 0.0 ).rg;
				texcoord += vec2( 0.0, 2.0 ) * resolution; // WebGL port note: Changed sign
				if ( ! ( texcoord.y > end && e.r > 0.8281 && e.g == 0.0 ) ) break;
			}

			texcoord.y -= 0.25 * resolution.y; // WebGL port note: Changed sign
			texcoord.y -= resolution.y; // WebGL port note: Changed sign
			texcoord.y -= 2.0 * resolution.y; // WebGL port note: Changed sign
			texcoord.y += resolution.y * SMAASearchLength( searchTex, e.gr, 0.0, 0.5 ); // WebGL port note: Changed sign

			return texcoord.y;
		}

		float SMAASearchYDown( sampler2D edgesTex, sampler2D searchTex, vec2 texcoord, float end ) {
			vec2 e = vec2( 1.0, 0.0 );

			for ( int i = 0; i < SMAA_MAX_SEARCH_STEPS; i ++ ) { // WebGL port note: Changed while to for
				e = texture2D( edgesTex, texcoord, 0.0 ).rg;
				texcoord -= vec2( 0.0, 2.0 ) * resolution; // WebGL port note: Changed sign
				if ( ! ( texcoord.y < end && e.r > 0.8281 && e.g == 0.0 ) ) break;
			}

			texcoord.y += 0.25 * resolution.y; // WebGL port note: Changed sign
			texcoord.y += resolution.y; // WebGL port note: Changed sign
			texcoord.y += 2.0 * resolution.y; // WebGL port note: Changed sign
			texcoord.y -= resolution.y * SMAASearchLength( searchTex, e.gr, 0.5, 0.5 ); // WebGL port note: Changed sign

			return texcoord.y;
		}

		vec2 SMAAArea( sampler2D areaTex, vec2 dist, float e1, float e2, float offset ) {
			// Rounding prevents precision errors of bilinear filtering:
			vec2 texcoord = float( SMAA_AREATEX_MAX_DISTANCE ) * round( 4.0 * vec2( e1, e2 ) ) + dist;

			// We do a scale and bias for mapping to texel space:
			texcoord = SMAA_AREATEX_PIXEL_SIZE * texcoord + ( 0.5 * SMAA_AREATEX_PIXEL_SIZE );

			// Move to proper place, according to the subpixel offset:
			texcoord.y += SMAA_AREATEX_SUBTEX_SIZE * offset;

			return texture2D( areaTex, texcoord, 0.0 ).rg;
		}

		vec4 SMAABlendingWeightCalculationPS( vec2 texcoord, vec2 pixcoord, vec4 offset[ 3 ], sampler2D edgesTex, sampler2D areaTex, sampler2D searchTex, ivec4 subsampleIndices ) {
			vec4 weights = vec4( 0.0, 0.0, 0.0, 0.0 );

			vec2 e = texture2D( edgesTex, texcoord ).rg;

			if ( e.g > 0.0 ) { // Edge at north
				vec2 d;

				// Find the distance to the left:
				vec2 coords;
				coords.x = SMAASearchXLeft( edgesTex, searchTex, offset[ 0 ].xy, offset[ 2 ].x );
				coords.y = offset[ 1 ].y; // offset[1].y = texcoord.y - 0.25 * resolution.y (@CROSSING_OFFSET)
				d.x = coords.x;

				// Now fetch the left crossing edges, two at a time using bilinear
				// filtering. Sampling at -0.25 (see @CROSSING_OFFSET) enables to
				// discern what value each edge has:
				float e1 = texture2D( edgesTex, coords, 0.0 ).r;

				// Find the distance to the right:
				coords.x = SMAASearchXRight( edgesTex, searchTex, offset[ 0 ].zw, offset[ 2 ].y );
				d.y = coords.x;

				// We want the distances to be in pixel units (doing this here allow to
				// better interleave arithmetic and memory accesses):
				d = d / resolution.x - pixcoord.x;

				// SMAAArea below needs a sqrt, as the areas texture is compressed
				// quadratically:
				vec2 sqrt_d = sqrt( abs( d ) );

				// Fetch the right crossing edges:
				coords.y -= 1.0 * resolution.y; // WebGL port note: Added
				float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 1, 0 ) ).r;

				// Ok, we know how this pattern looks like, now it is time for getting
				// the actual area:
				weights.rg = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.y ) );
			}

			if ( e.r > 0.0 ) { // Edge at west
				vec2 d;

				// Find the distance to the top:
				vec2 coords;

				coords.y = SMAASearchYUp( edgesTex, searchTex, offset[ 1 ].xy, offset[ 2 ].z );
				coords.x = offset[ 0 ].x; // offset[1].x = texcoord.x - 0.25 * resolution.x;
				d.x = coords.y;

				// Fetch the top crossing edges:
				float e1 = texture2D( edgesTex, coords, 0.0 ).g;

				// Find the distance to the bottom:
				coords.y = SMAASearchYDown( edgesTex, searchTex, offset[ 1 ].zw, offset[ 2 ].w );
				d.y = coords.y;

				// We want the distances to be in pixel units:
				d = d / resolution.y - pixcoord.y;

				// SMAAArea below needs a sqrt, as the areas texture is compressed
				// quadratically:
				vec2 sqrt_d = sqrt( abs( d ) );

				// Fetch the bottom crossing edges:
				coords.y -= 1.0 * resolution.y; // WebGL port note: Added
				float e2 = SMAASampleLevelZeroOffset( edgesTex, coords, ivec2( 0, 1 ) ).g;

				// Get the area for this direction:
				weights.ba = SMAAArea( areaTex, sqrt_d, e1, e2, float( subsampleIndices.x ) );
			}

			return weights;
		}

		void main() {

			gl_FragColor = SMAABlendingWeightCalculationPS( vUv, vPixcoord, vOffset, tDiffuse, tArea, tSearch, ivec4( 0.0 ) );

		}`},i0={name:"SMAABlendShader",uniforms:{tDiffuse:{value:null},tColor:{value:null},resolution:{value:new Ft(1/1024,1/512)}},vertexShader:`

		uniform vec2 resolution;

		varying vec2 vUv;
		varying vec4 vOffset[ 2 ];

		void SMAANeighborhoodBlendingVS( vec2 texcoord ) {
			vOffset[ 0 ] = texcoord.xyxy + resolution.xyxy * vec4( -1.0, 0.0, 0.0, 1.0 ); // WebGL port note: Changed sign in W component
			vOffset[ 1 ] = texcoord.xyxy + resolution.xyxy * vec4( 1.0, 0.0, 0.0, -1.0 ); // WebGL port note: Changed sign in W component
		}

		void main() {

			vUv = uv;

			SMAANeighborhoodBlendingVS( vUv );

			gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

		}`,fragmentShader:`

		uniform sampler2D tDiffuse;
		uniform sampler2D tColor;
		uniform vec2 resolution;

		varying vec2 vUv;
		varying vec4 vOffset[ 2 ];

		vec4 SMAANeighborhoodBlendingPS( vec2 texcoord, vec4 offset[ 2 ], sampler2D colorTex, sampler2D blendTex ) {
			// Fetch the blending weights for current pixel:
			vec4 a;
			a.xz = texture2D( blendTex, texcoord ).xz;
			a.y = texture2D( blendTex, offset[ 1 ].zw ).g;
			a.w = texture2D( blendTex, offset[ 1 ].xy ).a;

			// Is there any blending weight with a value greater than 0.0?
			if ( dot(a, vec4( 1.0, 1.0, 1.0, 1.0 )) < 1e-5 ) {
				return texture2D( colorTex, texcoord, 0.0 );
			} else {
				// Up to 4 lines can be crossing a pixel (one through each edge). We
				// favor blending by choosing the line with the maximum weight for each
				// direction:
				vec2 offset;
				offset.x = a.a > a.b ? a.a : -a.b; // left vs. right
				offset.y = a.g > a.r ? -a.g : a.r; // top vs. bottom // WebGL port note: Changed signs

				// Then we go in the direction that has the maximum weight:
				if ( abs( offset.x ) > abs( offset.y )) { // horizontal vs. vertical
					offset.y = 0.0;
				} else {
					offset.x = 0.0;
				}

				// Fetch the opposite color and lerp by hand:
				vec4 C = texture2D( colorTex, texcoord, 0.0 );
				texcoord += sign( offset ) * resolution;
				vec4 Cop = texture2D( colorTex, texcoord, 0.0 );
				float s = abs( offset.x ) > abs( offset.y ) ? abs( offset.x ) : abs( offset.y );

				// WebGL port note: Added gamma correction
				C.xyz = pow(C.xyz, vec3(2.2));
				Cop.xyz = pow(Cop.xyz, vec3(2.2));
				vec4 mixed = mix(C, Cop, s);
				mixed.xyz = pow(mixed.xyz, vec3(1.0 / 2.2));

				return mixed;
			}
		}

		void main() {

			gl_FragColor = SMAANeighborhoodBlendingPS( vUv, vOffset, tColor, tDiffuse );

		}`},u3=class extends yl{constructor(e,t){super(),this.edgesRT=new In(e,t,{depthBuffer:!1,type:Ts}),this.edgesRT.texture.name="SMAAPass.edges",this.weightsRT=new In(e,t,{depthBuffer:!1,type:Ts}),this.weightsRT.texture.name="SMAAPass.weights";let r=this,i=new Image;i.src=this.getAreaTexture(),i.onload=function(){r.areaTexture.needsUpdate=!0},this.areaTexture=new Qi,this.areaTexture.name="SMAAPass.area",this.areaTexture.image=i,this.areaTexture.minFilter=Pi,this.areaTexture.generateMipmaps=!1,this.areaTexture.flipY=!1;let n=new Image;n.src=this.getSearchTexture(),n.onload=function(){r.searchTexture.needsUpdate=!0},this.searchTexture=new Qi,this.searchTexture.name="SMAAPass.search",this.searchTexture.image=n,this.searchTexture.magFilter=oi,this.searchTexture.minFilter=oi,this.searchTexture.generateMipmaps=!1,this.searchTexture.flipY=!1,this.uniformsEdges=Rs.clone(Tf.uniforms),this.uniformsEdges.resolution.value.set(1/e,1/t),this.materialEdges=new ln({defines:Object.assign({},Tf.defines),uniforms:this.uniformsEdges,vertexShader:Tf.vertexShader,fragmentShader:Tf.fragmentShader}),this.uniformsWeights=Rs.clone(Cf.uniforms),this.uniformsWeights.resolution.value.set(1/e,1/t),this.uniformsWeights.tDiffuse.value=this.edgesRT.texture,this.uniformsWeights.tArea.value=this.areaTexture,this.uniformsWeights.tSearch.value=this.searchTexture,this.materialWeights=new ln({defines:Object.assign({},Cf.defines),uniforms:this.uniformsWeights,vertexShader:Cf.vertexShader,fragmentShader:Cf.fragmentShader}),this.uniformsBlend=Rs.clone(i0.uniforms),this.uniformsBlend.resolution.value.set(1/e,1/t),this.uniformsBlend.tDiffuse.value=this.weightsRT.texture,this.materialBlend=new ln({uniforms:this.uniformsBlend,vertexShader:i0.vertexShader,fragmentShader:i0.fragmentShader}),this.fsQuad=new Ef(null)}render(e,t,r){this.uniformsEdges.tDiffuse.value=r.texture,this.fsQuad.material=this.materialEdges,e.setRenderTarget(this.edgesRT),this.clear&&e.clear(),this.fsQuad.render(e),this.fsQuad.material=this.materialWeights,e.setRenderTarget(this.weightsRT),this.clear&&e.clear(),this.fsQuad.render(e),this.uniformsBlend.tColor.value=r.texture,this.fsQuad.material=this.materialBlend,this.renderToScreen?(e.setRenderTarget(null),this.fsQuad.render(e)):(e.setRenderTarget(t),this.clear&&e.clear(),this.fsQuad.render(e))}setSize(e,t){this.edgesRT.setSize(e,t),this.weightsRT.setSize(e,t),this.materialEdges.uniforms.resolution.value.set(1/e,1/t),this.materialWeights.uniforms.resolution.value.set(1/e,1/t),this.materialBlend.uniforms.resolution.value.set(1/e,1/t)}getAreaTexture(){return"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAKAAAAIwCAIAAACOVPcQAACBeklEQVR42u39W4xlWXrnh/3WWvuciIzMrKxrV8/0rWbY0+SQFKcb4owIkSIFCjY9AC1BT/LYBozRi+EX+cV+8IMsYAaCwRcBwjzMiw2jAWtgwC8WR5Q8mDFHZLNHTarZGrLJJllt1W2qKrsumZWZcTvn7L3W54e1vrXX3vuciLPPORFR1XE2EomorB0nVuz//r71re/y/1eMvb4Cb3N11xV/PP/2v4UBAwJG/7H8urx6/25/Gf8O5hypMQ0EEEQwAqLfoN/Z+97f/SW+/NvcgQk4sGBJK6H7N4PFVL+K+e0N11yNfkKvwUdwdlUAXPHHL38oa15f/i/46Ih6SuMSPmLAYAwyRKn7dfMGH97jaMFBYCJUgotIC2YAdu+LyW9vvubxAP8kAL8H/koAuOKP3+q6+xGnd5kdYCeECnGIJViwGJMAkQKfDvB3WZxjLKGh8VSCCzhwEWBpMc5/kBbjawT4HnwJfhr+pPBIu7uu+OOTo9vsmtQcniMBGkKFd4jDWMSCRUpLjJYNJkM+IRzQ+PQvIeAMTrBS2LEiaiR9b/5PuT6Ap/AcfAFO4Y3dA3DFH7/VS+M8k4baEAQfMI4QfbVDDGIRg7GKaIY52qAjTAgTvGBAPGIIghOCYAUrGFNgzA7Q3QhgCwfwAnwe5vDejgG44o/fbm1C5ZlYQvQDARPAIQGxCWBM+wWl37ZQESb4gImexGMDouhGLx1Cst0Saa4b4AqO4Hk4gxo+3DHAV/nx27p3JziPM2pVgoiia5MdEzCGULprIN7gEEeQ5IQxEBBBQnxhsDb5auGmAAYcHMA9eAAz8PBol8/xij9+C4Djlim4gJjWcwZBhCBgMIIYxGAVIkH3ZtcBuLdtRFMWsPGoY9rN+HoBji9VBYdwD2ZQg4cnO7OSq/z4rU5KKdwVbFAjNojCQzTlCLPFSxtamwh2jMUcEgg2Wm/6XgErIBhBckQtGN3CzbVacERgCnfgLswhnvqf7QyAq/z4rRZm1YglYE3affGITaZsdIe2FmMIpnOCap25I6jt2kCwCW0D1uAD9sZctNGXcQIHCkINDQgc78aCr+zjtw3BU/ijdpw3zhCwcaONwBvdeS2YZKkJNJsMPf2JKEvC28RXxxI0ASJyzQCjCEQrO4Q7sFArEzjZhaFc4cdv+/JFdKULM4px0DfUBI2hIsy06BqLhGTQEVdbfAIZXYMPesq6VoCHICzUyjwInO4Y411//LYLs6TDa9wvg2CC2rElgAnpTBziThxaL22MYhzfkghz6GAs2VHbbdM91VZu1MEEpupMMwKyVTb5ij9+u4VJG/5EgEMMmFF01cFai3isRbKbzb+YaU/MQbAm2XSMoUPAmvZzbuKYRIFApbtlrfFuUGd6vq2hXNnH78ZLh/iFhsQG3T4D1ib7k5CC6vY0DCbtrohgLEIClXiGtl10zc0CnEGIhhatLBva7NP58Tvw0qE8yWhARLQ8h4+AhQSP+I4F5xoU+VilGRJs6wnS7ruti/4KvAY/CfdgqjsMy4pf8fodQO8/gnuX3f/3xi3om1/h7THr+co3x93PP9+FBUfbNUjcjEmhcrkT+8K7ml7V10Jo05mpIEFy1NmCJWx9SIKKt+EjAL4Ez8EBVOB6havuT/rByPvHXK+9zUcfcbb254+9fydJknYnRr1oGfdaiAgpxu1Rx/Rek8KISftx3L+DfsLWAANn8Hvw0/AFeAGO9DFV3c6D+CcWbL8Dj9e7f+T1k8AZv/d7+PXWM/Z+VvdCrIvuAKO09RpEEQJM0Ci6+B4xhTWr4cZNOvhktabw0ta0rSJmqz3Yw5/AKXwenod7cAhTmBSPKf6JBdvH8IP17h95pXqw50/+BFnj88fev4NchyaK47OPhhtI8RFSvAfDSNh0Ck0p2gLxGkib5NJj/JWCr90EWQJvwBzO4AHcgztwAFN1evHPUVGwfXON+0debT1YeGON9Yy9/63X+OguiwmhIhQhD7l4sMqlG3D86Suc3qWZ4rWjI1X7u0Ytw6x3rIMeIOPDprfe2XzNgyj6PahhBjO4C3e6puDgXrdg+/5l948vF3bqwZetZ+z9Rx9zdIY5pInPK4Nk0t+l52xdK2B45Qd87nM8fsD5EfUhIcJcERw4RdqqH7Yde5V7m1vhNmtedkz6EDzUMF/2jJYWbC+4fzzA/Y+/8PPH3j9dcBAPIRP8JLXd5BpAu03aziOL3VVHZzz3CXWDPWd+SH2AnxIqQoTZpo9Ckc6HIrFbAbzNmlcg8Ag8NFDDAhbJvTBZXbC94P7t68EXfv6o+21gUtPETU7bbkLxvNKRFG2+KXzvtObonPP4rBvsgmaKj404DlshFole1Glfh02fE7bYR7dZ82oTewIBGn1Md6CG6YUF26X376oevOLzx95vhUmgblI6LBZwTCDY7vMq0op5WVXgsObOXJ+1x3qaBl9j1FeLxbhU9w1F+Wiba6s1X/TBz1LnUfuYDi4r2C69f1f14BWfP+p+W2GFKuC9phcELMYRRLur9DEZTUdEH+iEqWdaM7X4WOoPGI+ZYD2+wcQ+y+ioHUZ9dTDbArzxmi/bJI9BND0Ynd6lBdve/butBw8+f/T9D3ABa3AG8W3VPX4hBin+bj8dMMmSpp5pg7fJ6xrBFE2WQQEWnV8Qg3FbAWzYfM1rREEnmvkN2o1+acG2d/9u68GDzx91v3mAjb1zkpqT21OipPKO0b9TO5W0nTdOmAQm0TObts3aBKgwARtoPDiCT0gHgwnbArzxmtcLc08HgF1asN0C4Ms/fvD5I+7PhfqyXE/b7RbbrGyRQRT9ARZcwAUmgdoz0ehJ9Fn7QAhUjhDAQSw0bV3T3WbNa59jzmiP6GsWbGXDX2ytjy8+f9T97fiBPq9YeLdBmyuizZHaqXITnXiMUEEVcJ7K4j3BFPurtB4bixW8wTpweL8DC95szWMOqucFYGsWbGU7p3TxxxefP+r+oTVktxY0v5hbq3KiOKYnY8ddJVSBxuMMVffNbxwIOERShst73HZ78DZrHpmJmH3K6sGz0fe3UUj0eyRrSCGTTc+rjVNoGzNSv05srAxUBh8IhqChiQgVNIIBH3AVPnrsnXQZbLTm8ammv8eVXn/vWpaTem5IXRlt+U/LA21zhSb9cye6jcOfCnOwhIAYXAMVTUNV0QhVha9xjgA27ODJbLbmitt3tRN80lqG6N/khgot4ZVlOyO4WNg3OIMzhIZQpUEHieg2im6F91hB3I2tubql6BYNN9Hj5S7G0G2tahslBWKDnOiIvuAEDzakDQKDNFQT6gbn8E2y4BBubM230YIpBnDbMa+y3dx0n1S0BtuG62lCCXwcY0F72T1VRR3t2ONcsmDjbmzNt9RFs2LO2hQNyb022JisaI8rAWuw4HI3FuAIhZdOGIcdjLJvvObqlpqvWTJnnQbyi/1M9O8UxWhBs//H42I0q1Yb/XPGONzcmm+ri172mHKvZBpHkJaNJz6v9jxqiklDj3U4CA2ugpAaYMWqNXsdXbmJNd9egCnJEsphXNM+MnK3m0FCJ5S1kmJpa3DgPVbnQnPGWIDspW9ozbcO4K/9LkfaQO2KHuqlfFXSbdNzcEcwoqNEFE9zcIXu9/6n/ym/BC/C3aJLzEKPuYVlbFnfhZ8kcWxV3dbv4bKl28566wD+8C53aw49lTABp9PWbsB+knfc/Li3eVizf5vv/xmvnPKg5ihwKEwlrcHqucuVcVOxEv8aH37E3ZqpZypUulrHEtIWKUr+txHg+ojZDGlwnqmkGlzcVi1dLiNSJiHjfbRNOPwKpx9TVdTn3K05DBx4psIk4Ei8aCkJahRgffk4YnEXe07T4H2RR1u27E6wfQsBDofUgjFUFnwC2AiVtA+05J2zpiDK2Oa0c5fmAecN1iJzmpqFZxqYBCYhFTCsUNEmUnIcZ6aEA5rQVhEywG6w7HSW02XfOoBlQmjwulOFQAg66SvJblrTEX1YtJ3uG15T/BH1OfOQeuR8g/c0gdpT5fx2SKbs9EfHTKdM8A1GaJRHLVIwhcGyydZsbifAFVKl5EMKNU2Hryo+06BeTgqnxzYjThVySDikbtJPieco75lYfKAJOMEZBTjoITuWHXXZVhcUDIS2hpiXHV9Ku4u44bN5OYLDOkJo8w+xJSMbhBRHEdEs9JZUCkQrPMAvaHyLkxgkEHxiNkx/x2YB0mGsQ8EUWj/stW5YLhtS5SMu+/YBbNPDCkGTUybN8krRLBGPlZkVOA0j+a1+rkyQKWGaPHPLZOkJhioQYnVZ2hS3zVxMtgC46KuRwbJNd9nV2PHgb36F194ecf/Yeu2vAFe5nm/bRBFrnY4BauE8ERmZRFUn0k8hbftiVYSKMEme2dJCJSCGYAlNqh87bXOPdUkGy24P6d1ll21MBqqx48Fvv8ZHH8HZFY7j/uAq1xMJUFqCSUlJPmNbIiNsmwuMs/q9CMtsZsFO6SprzCS1Z7QL8xCQClEelpjTduDMsmWD8S1PT152BtvmIGvUeDA/yRn83u/x0/4qxoPHjx+PXY9pqX9bgMvh/Nz9kpP4pOe1/fYf3axUiMdHLlPpZCNjgtNFAhcHEDxTumNONhHrBduW+vOyY++70WWnPXj98eA4kOt/mj/5E05l9+O4o8ePx67HFqyC+qSSnyselqjZGaVK2TadbFLPWAQ4NBhHqDCCV7OTpo34AlSSylPtIdd2AJZlyzYQrDJ5lcWGNceD80CunPLGGzsfD+7wRb95NevJI5docQ3tgCyr5bGnyaPRlmwNsFELViOOx9loebGNq2moDOKpHLVP5al2cymWHbkfzGXL7kfRl44H9wZy33tvt+PB/Xnf93e+nh5ZlU18wCiRUa9m7kib9LYuOk+hudQNbxwm0AQqbfloimaB2lM5fChex+ylMwuTbfmXQtmWlenZljbdXTLuOxjI/fDDHY4Hjx8/Hrse0zXfPFxbUN1kKqSCCSk50m0Ajtx3ub9XHBKHXESb8iO6E+qGytF4nO0OG3SXzbJlhxBnKtKyl0NwybjvYCD30aMdjgePHz8eu56SVTBbgxJMliQ3Oauwg0QHxXE2Ez/EIReLdQj42Gzb4CLS0YJD9xUx7bsi0vJi5mUbW1QzL0h0PFk17rtiIPfJk52MB48fPx67npJJwyrBa2RCCQRTbGZSPCxTPOiND4G2pYyOQ4h4jINIJh5wFU1NFZt+IsZ59LSnDqBjZ2awbOku+yInunLcd8VA7rNnOxkPHj9+PGY9B0MWJJNozOJmlglvDMXDEozdhQWbgs/U6oBanGzLrdSNNnZFjOkmbi5bNt1lX7JLLhn3vXAg9/h4y/Hg8ePHI9dzQMEkWCgdRfYykYKnkP7D4rIujsujaKPBsB54vE2TS00ccvFY/Tth7JXeq1hz+qgVy04sAJawTsvOknHfCwdyT062HA8eP348Zj0vdoXF4pilKa2BROed+9fyw9rWRXeTFXESMOanvDZfJuJaSXouQdMdDJZtekZcLLvEeK04d8m474UDuaenW44Hjx8/Xns9YYqZpszGWB3AN/4VHw+k7WSFtJ3Qicuqb/NlVmgXWsxh570xg2UwxUw3WfO6B5nOuO8aA7lnZxuPB48fPx6znm1i4bsfcbaptF3zNT78eFPtwi1OaCNOqp1x3zUGcs/PN++AGD1+fMXrSVm2baTtPhPahbPhA71wIHd2bXzRa69nG+3CraTtPivahV/55tXWg8fyRY/9AdsY8VbSdp8V7cKrrgdfM//z6ILQFtJ2nxHtwmuoB4/kf74+gLeRtvvMaBdeSz34+vifx0YG20jbfTa0C6+tHrwe//NmOG0L8EbSdp8R7cLrrQe/996O+ai3ujQOskpTNULa7jOjXXj99eCd8lHvoFiwsbTdZ0a78PrrwTvlo966pLuRtB2fFe3Cm6oHP9kNH/W2FryxtN1nTLvwRurBO+Kj3pWXHidtx2dFu/Bm68Fb81HvykuPlrb7LGkX3mw9eGs+6h1Y8MbSdjegXcguQLjmevDpTQLMxtJ2N6NdyBZu9AbrwVvwUW+LbteULUpCdqm0HTelXbhNPe8G68Gb8lFvVfYfSNuxvrTdTWoXbozAzdaDZzfkorOj1oxVxlIMlpSIlpLrt8D4hrQL17z+c3h6hU/wv4Q/utps4+bm+6P/hIcf0JwQ5oQGPBL0eKPTYEXTW+eL/2DKn73J9BTXYANG57hz1cEMviVf/4tf5b/6C5pTQkMIWoAq7hTpOJjtAM4pxKu5vg5vXeUrtI09/Mo/5H+4z+Mp5xULh7cEm2QbRP2tFIKR7WM3fPf/jZ3SWCqLM2l4NxID5zB72HQXv3jj/8mLR5xXNA5v8EbFQEz7PpRfl1+MB/hlAN65qgDn3wTgH13hK7T59bmP+NIx1SHHU84nLOITt3iVz8mNO+lPrjGAnBFqmioNn1mTyk1ta47R6d4MrX7tjrnjYUpdUbv2rVr6YpVfsGG58AG8Ah9eyUN8CX4WfgV+G8LVWPDGb+Zd4cU584CtqSbMKxauxTg+dyn/LkVgA+IR8KHtejeFKRtTmLLpxN6mYVLjYxwXf5x2VofiZcp/lwKk4wGOpYDnoIZPdg/AAbwMfx0+ge9dgZvYjuqKe4HnGnykYo5TvJbG0Vj12JagRhwKa44H95ShkZa5RyLGGdfYvG7aw1TsF6iapPAS29mNS3NmsTQZCmgTzFwgL3upCTgtBTRwvGMAKrgLn4evwin8+afJRcff+8izUGUM63GOOuAs3tJkw7J4kyoNreqrpO6cYLQeFUd7TTpr5YOTLc9RUUogUOVJQ1GYJaFLAW0oTmKyYS46ZooP4S4EON3xQ5zC8/CX4CnM4c1PE8ApexpoYuzqlP3d4S3OJP8ZDK7cKWNaTlqmgDiiHwl1YsE41w1zT4iRTm3DBqxvOUsbMKKDa/EHxagtnta072ejc3DOIh5ojvh8l3tk1JF/AV6FU6jh3U8HwEazLgdCLYSQ+MYiAI2ltomkzttUb0gGHdSUUgsIYjTzLG3mObX4FBRaYtpDVNZrih9TgTeYOBxsEnN1gOCTM8Bsw/ieMc75w9kuAT6A+/AiHGvN/+Gn4KRkiuzpNNDYhDGFndWRpE6SVfm8U5bxnSgVV2jrg6JCKmneqey8VMFgq2+AM/i4L4RUbfSi27lNXZ7R7W9RTcq/q9fk4Xw3AMQd4I5ifAZz8FcVtm9SAom/dyN4lczJQW/kC42ZrHgcCoIf1oVMKkVItmMBi9cOeNHGLqOZk+QqQmrbc5YmYgxELUUN35z2iohstgfLIFmcMV7s4CFmI74L9+EFmGsi+tGnAOD4Yk9gIpo01Y4cA43BWGygMdr4YZekG3OBIUXXNukvJS8tqa06e+lSDCtnqqMFu6hWHXCF+WaYt64m9QBmNxi7Ioy7D+fa1yHw+FMAcPt7SysFLtoG4PXAk7JOA3aAxBRqUiAdU9Yp5lK3HLSRFtOim0sa8euEt08xvKjYjzeJ2GU7YawexrnKI9tmobInjFXCewpwriY9+RR4aaezFhMhGCppKwom0ChrgFlKzyPKkGlTW1YQrE9HJqu8hKGgMc6hVi5QRq0PZxNfrYNgE64utmRv6KKHRpxf6VDUaOvNP5jCEx5q185My/7RKz69UQu2im5k4/eownpxZxNLwiZ1AZTO2ZjWjkU9uaB2HFn6Q3u0JcsSx/qV9hTEApRzeBLDJQXxYmTnq7bdLa3+uqFrxLJ5w1TehnNHx5ECvCh2g2c3hHH5YsfdaSKddztfjQ6imKFGSyFwlLzxEGPp6r5IevVjk1AMx3wMqi1NxDVjLBiPs9tbsCkIY5we5/ML22zrCScFxnNtzsr9Wcc3CnD+pYO+4VXXiDE0oc/vQQ/fDK3oPESJMYXNmJa/DuloJZkcTpcYE8lIH8Dz8DJMiynNC86Mb2lNaaqP/+L7f2fcE/yP7/Lde8xfgSOdMxvOixZf/9p3+M4hT1+F+zApxg9XfUvYjc8qX2lfOOpK2gNRtB4flpFu9FTKCp2XJRgXnX6olp1zyYjTKJSkGmLE2NjUr1bxFM4AeAAHBUFIeSLqXR+NvH/M9fOnfHzOD2vCSyQJKzfgsCh+yi/Mmc35F2fUrw7miW33W9hBD1vpuUojFphIyvg7aTeoymDkIkeW3XLHmguMzbIAJejN6B5MDrhipE2y6SoFRO/AK/AcHHZHNIfiWrEe/C6cr3f/yOvrQKB+zMM55/GQdLDsR+ifr5Fiuu+/y+M78LzOE5dsNuXC3PYvYWd8NXvphLSkJIasrlD2/HOqQ+RjcRdjKTGWYhhVUm4yxlyiGPuMsZR7sMCHUBeTuNWA7if+ifXgc/hovftHXs/DV+Fvwe+f8shzMiMcweFgBly3//vwJfg5AN4450fn1Hd1Rm1aBLu22Dy3y3H2+OqMemkbGZ4jozcDjJf6596xOLpC0eMTHbKnxLxH27uZ/bMTGs2jOaMOY4m87CfQwF0dw53oa1k80JRuz/XgS+8fX3N9Af4qPIMfzKgCp4H5TDGe9GGeFPzSsZz80SlPTxXjgwJmC45njzgt2vbQ4b4OAdUK4/vWhO8d8v6EE8fMUsfakXbPpFJeLs2ubM/qdm/la3WP91uWhxXHjoWhyRUq2iJ/+5mA73zwIIo+LoZ/SgvIRjAd1IMvvn98PfgOvAJfhhm8scAKVWDuaRaK8aQ9f7vuPDH6Bj47ZXau7rqYJ66mTDwEDU6lLbCjCK0qTXyl5mnDoeNRxanj3FJbaksTk0faXxHxLrssgPkWB9LnA/MFleXcJozzjwsUvUG0X/QCve51qkMDXp9mtcyOy3rwBfdvVJK7D6/ACSzg3RoruIq5UDeESfEmVclDxnniU82vxMLtceD0hGZWzBNPMM/jSPne2OVatiTKUpY5vY7gc0LdUAWeWM5tH+O2I66AOWw9xT2BuyRVLGdoDHUsVRXOo/c+ZdRXvFfnxWyIV4upFLCl9eAL7h8Zv0QH8Ry8pA2cHzQpGesctVA37ZtklBTgHjyvdSeKY/RZw/kJMk0Y25cSNRWSigQtlULPTw+kzuJPeYEkXjQRpoGZobYsLF79pyd1dMRHInbgFTZqNLhDqiIsTNpoex2WLcy0/X6rHcdMMQvFSd5dWA++4P7xv89deACnmr36uGlL69bRCL6BSZsS6c0TU2TKK5gtWCzgAOOwQcurqk9j8whvziZSMLcq5hbuwBEsYjopUBkqw1yYBGpLA97SRElEmx5MCInBY5vgLk94iKqSWmhIGmkJ4Bi9m4L645J68LyY4wsFYBfUg5feP/6gWWm58IEmKQM89hq7KsZNaKtP5TxxrUZZVkNmMJtjbKrGxLNEbHPJxhqy7lAmbC32ZqeF6lTaknRWcYaFpfLUBh/rwaQycCCJmW15Kstv6jRHyJFry2C1ahkkIW0LO75s61+owxK1y3XqweX9m5YLM2DPFeOjn/iiqCKJ+yKXF8t5Yl/kNsqaSCryxPq5xWTFIaP8KSW0RYxqupaUf0RcTNSSdJZGcKYdYA6kdtrtmyBckfKXwqk0pHpUHlwWaffjNRBYFPUDWa8e3Lt/o0R0CdisKDM89cX0pvRHEfM8ca4t0s2Xx4kgo91MPQJ/0c9MQYq0co8MBh7bz1fio0UUHLR4aAIOvOmoYO6kwlEVODSSTliWtOtH6sPkrtctF9ZtJ9GIerBskvhdVS5cFNv9s1BU0AbdUgdK4FG+dRnjFmDTzniRMdZO1QhzMK355vigbdkpz9P6qjUGE5J2qAcXmwJ20cZUiAD0z+pGMx6xkzJkmEf40Hr4qZfVg2XzF9YOyoV5BjzVkUJngKf8lgNYwKECEHrCNDrWZzMlflS3yBhr/InyoUgBc/lKT4pxVrrC6g1YwcceK3BmNxZcAtz3j5EIpqguh9H6wc011YN75cKDLpFDxuwkrPQmUwW4KTbj9mZTwBwLq4aQMUZbHm1rylJ46dzR0dua2n3RYCWZsiHROeywyJGR7mXKlpryyCiouY56sFkBWEnkEB/raeh/Sw4162KeuAxMQpEkzy5alMY5wamMsWKKrtW2WpEWNnReZWONKWjrdsKZarpFjqCslq773PLmEhM448Pc3+FKr1+94vv/rfw4tEcu+lKTBe4kZSdijBrykwv9vbCMPcLQTygBjzVckSLPRVGslqdunwJ4oegtFOYb4SwxNgWLCmD7T9kVjTv5YDgpo0XBmN34Z/rEHp0sgyz7lngsrm4lvMm2Mr1zNOJYJ5cuxuQxwMGJq/TP5emlb8fsQBZviK4t8hFL+zbhtlpwaRSxQRWfeETjuauPsdGxsBVdO7nmP4xvzSoT29pRl7kGqz+k26B3Oy0YNV+SXbbQas1ctC/GarskRdFpKczVAF1ZXnLcpaMuzVe6lZ2g/1ndcvOVgRG3sdUAY1bKD6achijMPdMxV4muKVorSpiDHituH7rSTs7n/4y5DhRXo4FVBN4vO/zbAcxhENzGbHCzU/98Mcx5e7a31kWjw9FCe/zNeYyQjZsWb1uc7U33pN4Mji6hCLhivqfa9Ss6xLg031AgfesA/l99m9fgvnaF9JoE6bYKmkGNK3aPbHB96w3+DnxFm4hs0drLsk7U8kf/N/CvwQNtllna0rjq61sH8L80HAuvwH1tvBy2ChqWSCaYTaGN19sTvlfzFD6n+iKTbvtayfrfe9ueWh6GJFoxLdr7V72a5ZpvHcCPDzma0wTO4EgbLyedxstO81n57LYBOBzyfsOhUKsW1J1BB5vr/tz8RyqOFylQP9Tvst2JALsC5lsH8PyQ40DV4ANzYa4dedNiKNR1s+x2wwbR7q4/4cTxqEk4LWDebfisuo36JXLiWFjOtLrlNWh3K1rRS4xvHcDNlFnNmWBBAl5SWaL3oPOfnvbr5pdjVnEaeBJSYjuLEkyLLsWhKccadmOphZkOPgVdalj2QpSmfOsADhMWE2ZBu4+EEJI4wKTAuCoC4xwQbWXBltpxbjkXJtKxxabo9e7tyhlgb6gNlSbUpMh+l/FaqzVwewGu8BW1Zx7pTpQDJUjb8tsUTW6+GDXbMn3mLbXlXJiGdggxFAoUrtPS3wE4Nk02UZG2OOzlk7fRs7i95QCLo3E0jtrjnM7SR3uS1p4qtS2nJ5OwtQVHgOvArLBFijZUV9QtSl8dAY5d0E0hM0w3HS2DpIeB6m/A1+HfhJcGUq4sOxH+x3f5+VO+Ds9rYNI7zPXOYWPrtf8bYMx6fuOAX5jzNR0PdsuON+X1f7EERxMJJoU6GkTEWBvVolVlb5lh3tKCg6Wx1IbaMDdJ+9sUCc5KC46hKGCk3IVOS4TCqdBNfUs7Kd4iXf2RjnT/LLysJy3XDcHLh/vde3x8DoGvwgsa67vBk91G5Pe/HbOe7xwym0NXbtiuuDkGO2IJDh9oQvJ4cY4vdoqLDuoH9Zl2F/ofsekn8lkuhIlhQcffUtSjytFyp++p6NiE7Rqx/lodgKVoceEp/CP4FfjrquZaTtj2AvH5K/ywpn7M34K/SsoYDAdIN448I1/0/wveW289T1/lX5xBzc8N5IaHr0XMOQdHsIkDuJFifj20pBm5jzwUv9e2FhwRsvhAbalCIuIw3bhJihY3p6nTFFIZgiSYjfTf3aXuOjmeGn4bPoGvwl+CFzTRczBIuHBEeImHc37/lGfwZR0cXzVDOvaKfNHvwe+suZ771K/y/XcBlsoN996JpBhoE2toYxOznNEOS5TJc6Id5GEXLjrWo+LEWGNpPDU4WAwsIRROu+1vM+0oW37z/MBN9kqHnSArwPfgFJ7Cq/Ai3Ie7g7ncmI09v8sjzw9mzOAEXoIHxURueaAce5V80f/DOuuZwHM8vsMb5wBzOFWM7wymTXPAEvm4vcFpZ2ut0VZRjkiP2MlmLd6DIpbGSiHOjdnUHN90hRYmhTnmvhzp1iKDNj+b7t5hi79lWGwQ+HN9RsfFMy0FXbEwhfuczKgCbyxYwBmcFhhvo/7a44v+i3XWcwDP86PzpGQYdWh7csP5dBvZ1jNzdxC8pBGuxqSW5vw40nBpj5JhMwvOzN0RWqERHMr4Lv1kWX84xLR830G3j6yqZ1a8UstTlW+qJPOZ+sZ7xZPKTJLhiNOAFd6tk+jrTH31ncLOxid8+nzRb128HhUcru/y0Wn6iT254YPC6FtVSIMoW2sk727AhvTtrWKZTvgsmckfXYZWeNRXx/3YQ2OUxLDrbHtN11IwrgXT6c8dATDwLniYwxzO4RzuQqTKSC5gAofMZ1QBK3zQ4JWobFbcvJm87FK+6JXrKahLn54m3p+McXzzYtP8VF/QpJuh1OwieElEoI1pRxPS09FBrkq2tWCU59+HdhNtTIqKm8EBrw2RTOEDpG3IKo2Y7mFdLm3ZeVjYwVw11o/oznceMve4CgMfNym/utA/d/ILMR7gpXzRy9eDsgLcgbs8O2Va1L0zzIdwGGemTBuwROHeoMShkUc7P+ISY3KH5ZZeWqO8mFTxQYeXTNuzvvK5FGPdQfuu00DwYFY9dyhctEt+OJDdnucfpmyhzUJzfsJjr29l8S0bXBfwRS9ZT26tmMIdZucch5ZboMz3Nio3nIOsYHCGoDT4kUA9MiXEp9Xsui1S8th/kbWIrMBxDGLodWUQIWcvnXy+9M23xPiSMOiRPqM+YMXkUN3gXFrZJwXGzUaMpJfyRS9ZT0lPe8TpScuRlbMHeUmlaKDoNuy62iWNTWNFYjoxFzuJs8oR+RhRx7O4SVNSXpa0ZJQ0K1LAHDQ+D9IepkMXpcsq5EVCvClBUIzDhDoyKwDw1Lc59GbTeORivugw1IcuaEOaGWdNm+Ps5fQ7/tm0DjMegq3yM3vb5j12qUId5UZD2oxDSEWOZMSqFl/W+5oynWDa/aI04tJRQ2eTXusg86SQVu/nwSYwpW6wLjlqIzwLuxGIvoAvul0PS+ZNz0/akp/pniO/8JDnGyaCkzbhl6YcqmK/69prxPqtpx2+Km9al9sjL+rwMgHw4jE/C8/HQ3m1vBuL1fldbzd8mOueVJ92syqdEY4KJjSCde3mcRw2TA6szxedn+zwhZMps0XrqEsiUjnC1hw0TELC2Ek7uAAdzcheXv1BYLagspxpzSAoZZUsIzIq35MnFQ9DOrlNB30jq3L4pkhccKUAA8/ocvN1Rzx9QyOtERs4CVsJRK/DF71kPYrxYsGsm6RMh4cps5g1DOmM54Ly1ii0Hd3Y/BMk8VWFgBVmhqrkJCPBHAolwZaWzLR9Vb7bcWdX9NyUYE+uB2BKfuaeBUcjDljbYVY4DdtsVWvzRZdWnyUzDpjNl1Du3aloAjVJTNDpcIOVVhrHFF66lLfJL1zJr9PQ2nFJSBaKoDe+sAvLufZVHVzYh7W0h/c6AAZ+7Tvj6q9j68G/cTCS/3n1vLKHZwNi+P+pS0WkZNMBMUl+LDLuiE4omZy71r3UFMwNJV+VJ/GC5ixVUkBStsT4gGKh0Gm4Oy3qvq7Lbmq24nPdDuDR9deR11XzP4vFu3TYzfnIyiSVmgizUYGqkIXNdKTY9pgb9D2Ix5t0+NHkVzCdU03suWkkVZAoCONCn0T35gAeW38de43mf97sMOpSvj4aa1KYUm58USI7Wxxes03bAZdRzk6UtbzMaCQ6IxO0dy7X+XsjoD16hpsBeGz9dfzHj+R/Hp8nCxZRqkEDTaCKCSywjiaoMJ1TITE9eg7Jqnq8HL6gDwiZb0u0V0Rr/rmvqjxKuaLCX7ZWXTvAY+uvm3z8CP7nzVpngqrJpZKwWnCUjIviYVlirlGOzPLI3SMVyp/elvBUjjDkNhrtufFFErQ8pmdSlbK16toBHlt/HV8uHMX/vEGALkV3RJREiSlopxwdMXOZPLZ+ix+kAHpMKIk8UtE1ygtquttwxNhphrIZ1IBzjGF3IIGxGcBj6q8bHJBG8T9vdsoWrTFEuebEZuVxhhClH6P5Zo89OG9fwHNjtNQTpD0TG9PJLEYqvEY6Rlxy+ZZGfL0Aj62/bnQCXp//eeM4KzfQVJbgMQbUjlMFIm6TpcfWlZje7NBSV6IsEVmumWIbjiloUzQX9OzYdo8L1wjw2PrrpimONfmfNyzKklrgnEkSzT5QWYQW40YShyzqsRmMXbvVxKtGuYyMKaU1ugenLDm5Ily4iT14fP11Mx+xJv+zZ3MvnfdFqxU3a1W/FTB4m3Qfsyc1XUcdVhDeUDZXSFHHLQj/Y5jtC7ZqM0CXGwB4bP11i3LhOvzPGygYtiUBiwQV/4wFO0majijGsafHyRLu0yG6q35cL1rOpVxr2s5cM2jJYMCdc10Aj6q/blRpWJ//+dmm5psMl0KA2+AFRx9jMe2WbC4jQxnikd4DU8TwUjRVacgdlhmr3bpddzuJ9zXqr2xnxJfzP29RexdtjDVZqzkqa6PyvcojGrfkXiJ8SEtml/nYskicv0ivlxbqjemwUjMw5evdg8fUX9nOiC/lf94Q2i7MURk9nW1MSj5j8eAyV6y5CN2S6qbnw3vdA1Iwq+XOSCl663udN3IzLnrt+us25cI1+Z83SXQUldqQq0b5XOT17bGpLd6ssN1VMPf8c+jG8L3NeCnMdF+Ra3fRa9dft39/LuZ/3vwHoHrqGmQFafmiQw6eyzMxS05K4bL9uA+SKUQzCnSDkqOGokXyJvbgJ/BHI+qvY69//4rl20NsmK2ou2dTsyIALv/91/8n3P2Aao71WFGi8KKv1fRC5+J67Q/507/E/SOshqN5TsmYIjVt+kcjAx98iz/4SaojbIV1rexE7/C29HcYD/DX4a0rBOF5VTu7omsb11L/AWcVlcVZHSsqGuXLLp9ha8I//w3Mv+T4Ew7nTBsmgapoCrNFObIcN4pf/Ob/mrvHTGqqgAupL8qWjWPS9m/31jAe4DjA+4+uCoQoT/zOzlrNd3qd4SdphFxsUvYwGWbTWtISc3wNOWH+kHBMfc6kpmpwPgHWwqaSUG2ZWWheYOGQGaHB+eQ/kn6b3pOgLV+ODSn94wDvr8Bvb70/LLuiPPEr8OGVWfDmr45PZyccEmsVXZGe1pRNX9SU5+AVQkNTIVPCHF/jGmyDC9j4R9LfWcQvfiETmgMMUCMN1uNCakkweZsowdYobiMSlnKA93u7NzTXlSfe+SVbfnPQXmg9LpYAQxpwEtONyEyaueWM4FPjjyjG3uOaFmBTWDNgBXGEiQpsaWhnAqIijB07Dlsy3fUGeP989xbWkyf+FF2SNEtT1E0f4DYYVlxFlbaSMPIRMk/3iMU5pME2SIWJvjckciebkQuIRRyhUvkHg/iUljG5kzVog5hV7vIlCuBrmlhvgPfNHQM8lCf+FEGsYbMIBC0qC9a0uuy2wLXVbLBaP5kjHokCRxapkQyzI4QEcwgYHRZBp+XEFTqXFuNVzMtjXLJgX4gAid24Hjwc4N3dtVSe+NNiwTrzH4WVUOlDobUqr1FuAgYllc8pmzoVrELRHSIW8ViPxNy4xwjBpyR55I6J220qQTZYR4guvUICJiSpr9gFFle4RcF/OMB7BRiX8sSfhpNSO3lvEZCQfLUVTKT78Ek1LRLhWN+yLyTnp8qWUZ46b6vxdRGXfHVqx3eI75YaLa4iNNiK4NOW7wPW6lhbSOF9/M9qw8e/aoB3d156qTzxp8pXx5BKAsYSTOIIiPkp68GmTq7sZtvyzBQaRLNxIZ+paozHWoLFeExIhRBrWitHCAHrCF7/thhD8JhYz84wg93QRV88wLuLY8zF8sQ36qF1J455bOlgnELfshKVxYOXKVuKx0jaj22sczTQqPqtV/XDgpswmGTWWMSDw3ssyUunLLrVPGjYRsH5ggHeHSWiV8kT33ycFSfMgkoOK8apCye0J6VW6GOYvffgU9RWsukEi2kUV2nl4dOYUzRik9p7bcA4ggdJ53LxKcEe17B1R8eqAd7dOepV8sTXf5lhejoL85hUdhDdknPtKHFhljOT+bdq0hxbm35p2nc8+Ja1Iw+tJykgp0EWuAAZYwMVwac5KzYMslhvgHdHRrxKnvhTYcfKsxTxtTETkjHO7rr3zjoV25lAQHrqpV7bTiy2aXMmUhTBnKS91jhtR3GEoF0oLnWhWNnYgtcc4N0FxlcgT7yz3TgNIKkscx9jtV1ZKpWW+Ub1tc1eOv5ucdgpx+FJy9pgbLE7xDyXb/f+hLHVGeitHOi6A7ybo3sF8sS7w7cgdk0nJaOn3hLj3uyD0Zp5pazFIUXUpuTTU18d1EPkDoX8SkmWTnVIozEdbTcZjoqxhNHf1JrSS/AcvHjZ/SMHhL/7i5z+POsTUh/8BvNfYMTA8n+yU/MlTZxSJDRStqvEuLQKWwDctMTQogUDyQRoTQG5Kc6oQRE1yV1jCA7ri7jdZyK0sYTRjCR0Hnnd+y7nHxNgTULqw+8wj0mQKxpYvhjm9uSUxg+TTy7s2GtLUGcywhXSKZN275GsqlclX90J6bRI1aouxmgL7Q0Nen5ziM80SqMIo8cSOo+8XplT/5DHNWsSUr/6lLN/QQ3rDyzLruEW5enpf7KqZoShEduuSFOV7DLX7Ye+GmXb6/hnNNqKsVXuMDFpb9Y9eH3C6NGEzuOuI3gpMH/I6e+zDiH1fXi15t3vA1czsLws0TGEtmPEJdiiFPwlwKbgLHAFk4P6ZyPdymYYHGE0dutsChQBl2JcBFlrEkY/N5bQeXQ18gjunuMfMfsBlxJSx3niO485fwO4fGD5T/+3fPQqkneWVdwnw/3bMPkW9Wbqg+iC765Zk+xcT98ibKZc2EdgHcLoF8cSOo/Oc8fS+OyEULF4g4sJqXVcmfMfsc7A8v1/yfGXmL9I6Fn5pRwZhsPv0TxFNlAfZCvG+Oohi82UC5f/2IsJo0cTOm9YrDoKhFPEUr/LBYTUNht9zelHXDqwfPCIw4owp3mOcIQcLttWXFe3VZ/j5H3cIc0G6oPbCR+6Y2xF2EC5cGUm6wKC5tGEzhsWqw5hNidUiKX5gFWE1GXh4/Qplw4sVzOmx9QxU78g3EF6wnZlEN4FzJ1QPSLEZz1KfXC7vd8ssGdIbNUYpVx4UapyFUHzJoTOo1McSkeNn1M5MDQfs4qQuhhX5vQZFw8suwWTcyYTgioISk2YdmkhehG4PkE7w51inyAGGaU+uCXADabGzJR1fn3lwkty0asIo8cROm9Vy1g0yDxxtPvHDAmpu+PKnM8Ix1wwsGw91YJqhteaWgjYBmmQiebmSpwKKzE19hx7jkzSWOm66oPbzZ8Yj6kxVSpYjVAuvLzYMCRo3oTQecOOjjgi3NQ4l9K5/hOGhNTdcWVOTrlgYNkEXINbpCkBRyqhp+LdRB3g0OU6rMfW2HPCFFMV9nSp+uB2woepdbLBuJQyaw/ZFysXrlXwHxI0b0LovEkiOpXGA1Ijagf+KUNC6rKNa9bQnLFqYNkEnMc1uJrg2u64ELPBHpkgWbmwKpJoDhMwNbbGzAp7Yg31wS2T5rGtzit59PrKhesWG550CZpHEzpv2NGRaxlNjbMqpmEIzygJqQfjypycs2pg2cS2RY9r8HUqkqdEgKTWtWTKoRvOBPDYBltja2SO0RGjy9UHtxwRjA11ujbKF+ti5cIR9eCnxUg6owidtyoU5tK4NLji5Q3HCtiyF2IqLGYsHViOXTXOYxucDqG0HyttqYAKqYo3KTY1ekyDXRAm2AWh9JmsVh/ccg9WJ2E8YjG201sPq5ULxxX8n3XLXuMInbft2mk80rRGjCGctJ8/GFdmEQ9Ug4FlE1ll1Y7jtiraqm5Fe04VV8lvSVBL8hiPrfFVd8+7QH3Qbu2ipTVi8cvSGivc9cj8yvH11YMHdNSERtuOslM97feYFOPKzGcsI4zW0YGAbTAOaxCnxdfiYUmVWslxiIblCeAYr9VYR1gM7GmoPrilunSxxeT3DN/2eBQ9H11+nk1adn6VK71+5+Jfct4/el10/7KBZfNryUunWSCPxPECk1rdOv1WVSrQmpC+Tl46YD3ikQYcpunSQgzVB2VHFhxHVGKDgMEY5GLlQnP7FMDzw7IacAWnO6sBr12u+XanW2AO0wQ8pknnFhsL7KYIqhkEPmEXFkwaN5KQphbkUmG72wgw7WSm9RiL9QT925hkjiVIIhphFS9HKI6/8QAjlpXqg9W2C0apyaVDwKQwrwLY3j6ADR13ZyUNByQXHQu6RY09Hu6zMqXRaNZGS/KEJs0cJEe9VH1QdvBSJv9h09eiRmy0V2uJcqHcShcdvbSNg5fxkenkVprXM9rDVnX24/y9MVtncvbKY706anNl3ASll9a43UiacVquXGhvq4s2FP62NGKfQLIQYu9q1WmdMfmUrDGt8eDS0cXozH/fjmUH6Jruvm50hBDSaEU/2Ru2LEN/dl006TSc/g7tfJERxGMsgDUEr104pfWH9lQaN+M4KWQjwZbVc2rZVNHsyHal23wZtIs2JJqtIc/WLXXRFCpJkfE9jvWlfFbsNQ9pP5ZBS0zKh4R0aMFj1IjTcTnvi0Zz2rt7NdvQb2mgbju1plsH8MmbnEk7KbK0b+wC2iy3aX3szW8xeZvDwET6hWZYwqTXSSG+wMETKum0Dq/q+x62gt2ua2ppAo309TRk9TPazfV3qL9H8z7uhGqGqxNVg/FKx0HBl9OVUORn8Q8Jx9gFttGQUDr3tzcXX9xGgN0EpzN9mdZ3GATtPhL+CjxFDmkeEU6x56kqZRusLzALXVqkCN7zMEcqwjmywDQ6OhyUe0Xao1Qpyncrg6wKp9XfWDsaZplElvQ/b3sdweeghorwBDlHzgk1JmMc/wiERICVy2VJFdMjFuLQSp3S0W3+sngt2njwNgLssFGVQdJ0tu0KH4ky1LW4yrbkuaA6Iy9oz/qEMMXMMDWyIHhsAyFZc2peV9hc7kiKvfULxCl9iddfRK1f8kk9qvbdOoBtOg7ZkOZ5MsGrSHsokgLXUp9y88smniwWyuFSIRVmjplga3yD8Uij5QS1ZiM4U3Qw5QlSm2bXjFe6jzzBFtpg+/YBbLAWG7OPynNjlCw65fukGNdkJRf7yM1fOxVzbxOJVocFoYIaGwH22mIQkrvu1E2nGuebxIgW9U9TSiukPGU+Lt++c3DJPKhyhEEbXCQLUpae2exiKy6tMPe9mDRBFCEMTWrtwxN8qvuGnt6MoihKWS5NSyBhbH8StXoAz8PLOrRgLtOT/+4vcu+7vDLnqNvztOq7fmd8sMmY9Xzn1zj8Dq8+XVdu2Nv0IIySgEdQo3xVHps3Q5i3fLFsV4aiqzAiBhbgMDEd1uh8qZZ+lwhjkgokkOIv4xNJmyncdfUUzgB4oFMBtiu71Xumpz/P+cfUP+SlwFExwWW62r7b+LSPxqxn/gvMZ5z9C16t15UbNlq+jbGJtco7p8wbYlL4alSyfWdeuu0j7JA3JFNuVAwtst7F7FhWBbPFNKIUORndWtLraFLmMu7KFVDDOzqkeaiN33YAW/r76wR4XDN/yN1z7hejPau06EddkS/6XThfcz1fI/4K736fO48vlxt2PXJYFaeUkFS8U15XE3428xdtn2kc8GQlf1vkIaNRRnOMvLTWrZbElEHeLWi1o0dlKPAh1MVgbbVquPJ5+Cr8LU5/H/+I2QlHIU2ClXM9G8v7Rr7oc/hozfUUgsPnb3D+I+7WF8kNO92GY0SNvuxiE+2Bt8prVJTkzE64sfOstxuwfxUUoyk8VjcTlsqe2qITSFoSj6Epd4KsT6BZOWmtgE3hBfir8IzZDwgV4ZTZvD8VvPHERo8v+vL1DASHTz/i9OlKueHDjK5Rnx/JB1Vb1ioXdBra16dmt7dgik10yA/FwJSVY6XjA3oy4SqM2frqDPPSRMex9qs3XQtoWxMj7/Er8GWYsXgjaVz4OYumP2+9kbxvny/6kvWsEBw+fcb5bInc8APdhpOSs01tEqIkoiZjbAqKMruLbJYddHuHFRIyJcbdEdbl2sVLaySygunutBg96Y2/JjKRCdyHV+AEFtTvIpbKIXOamknYSiB6KV/0JetZITgcjjk5ZdaskBtWO86UF0ap6ozGXJk2WNiRUlCPFir66lzdm/SLSuK7EUdPz8f1z29Skq6F1fXg8+5UVR6bszncP4Tn4KUkkdJ8UFCY1zR1i8RmL/qQL3rlei4THG7OODlnKko4oI01kd3CaM08Ia18kC3GNoVaO9iDh+hWxSyTXFABXoau7Q6q9OxYg/OVEMw6jdbtSrJ9cBcewGmaZmg+bvkUnUUaGr+ZfnMH45Ivevl61hMcXsxYLFTu1hTm2zViCp7u0o5l+2PSUh9bDj6FgYypufBDhqK2+oXkiuHFHR3zfj+9PtA8oR0xnqX8qn+sx3bFODSbbF0X8EUvWQ8jBIcjo5bRmLOljDNtcqNtOe756h3l0VhKa9hDd2l1eqmsnh0MNMT/Cqnx6BInumhLT8luljzQ53RiJeA/0dxe5NK0o2fA1+GLXr6eNQWHNUOJssQaTRlGpLHKL9fD+IrQzTOMZS9fNQD4AnRNVxvTdjC+fJdcDDWQcyB00B0t9BDwTxXgaAfzDZ/DBXzRnfWMFRwuNqocOmX6OKNkY63h5n/fFcB28McVHqnXZVI27K0i4rDLNE9lDKV/rT+udVbD8dFFu2GGZ8mOt0kAXcoX3ZkIWVtw+MNf5NjR2FbivROHmhV1/pj2egv/fMGIOWTIWrV3Av8N9imV9IWml36H6cUjqEWNv9aNc+veb2sH46PRaHSuMBxvtW+twxctq0z+QsHhux8Q7rCY4Ct8lqsx7c6Sy0dl5T89rIeEuZKoVctIk1hNpfavER6yyH1Vvm3MbsUHy4ab4hWr/OZPcsRBphnaV65/ZcdYPNNwsjN/djlf9NqCw9U5ExCPcdhKxUgLSmfROpLp4WSUr8ojdwbncbvCf+a/YzRaEc6QOvXcGO256TXc5Lab9POvB+AWY7PigWYjzhifbovuunzRawsO24ZqQQAqguBtmpmPB7ysXJfyDDaV/aPGillgz1MdQg4u5MYaEtBNNHFjkRlSpd65lp4hd2AVPTfbV7FGpyIOfmNc/XVsPfg7vzaS/3nkvLL593ANLvMuRMGpQIhiF7kUEW9QDpAUbTWYBcbp4WpacHHY1aacqQyjGZS9HI3yCBT9kUZJhVOD+zUDvEH9ddR11fzPcTDQ5TlgB0KwqdXSavk9BC0pKp0WmcuowSw07VXmXC5guzSa4p0UvRw2lbDiYUx0ExJJRzWzi6Gm8cnEkfXXsdcG/M/jAJa0+bmCgdmQ9CYlNlSYZOKixmRsgiFxkrmW4l3KdFKv1DM8tk6WxPYJZhUUzcd8Kdtgrw/gkfXXDT7+avmfVak32qhtkg6NVdUS5wgkru1YzIkSduTW1FDwVWV3JQVJVuieTc0y4iDpFwc7/BvSalvKdQM8sv662cevz/+8sQVnjVAT0W2wLllw1JiMhJRxgDjCjLQsOzSFSgZqx7lAW1JW0e03yAD3asC+GD3NbQhbe+mN5GXH1F83KDOM4n/e5JIuH4NpdQARrFPBVptUNcjj4cVMcFSRTE2NpR1LEYbYMmfWpXgP9KejaPsLUhuvLCsVXznAG9dfx9SR1ud/3hZdCLHb1GMdPqRJgqDmm76mHbvOXDtiO2QPUcKo/TWkQ0i2JFXpBoo7vij1i1Lp3ADAo+qvG3V0rM//vFnnTE4hxd5Ka/Cor5YEdsLVJyKtDgVoHgtW11pWSjolPNMnrlrVj9Fv2Qn60twMwKPqr+N/wvr8z5tZcDsDrv06tkqyzESM85Ycv6XBWA2birlNCXrI6VbD2lx2L0vQO0QVTVVLH4SE67fgsfVXv8n7sz7/85Z7cMtbE6f088wSaR4kCkCm10s6pKbJhfqiUNGLq+0gLWC6eUAZFPnLjwqtKd8EwGvWX59t7iPW4X/eAN1svgRVSY990YZg06BD1ohLMtyFTI4pKTJsS9xREq9EOaPWiO2gpms7397x6nQJkbh+Fz2q/rqRROX6/M8bJrqlVW4l6JEptKeUFuMYUbtCQ7CIttpGc6MY93x1r1vgAnRXvY5cvwWPqb9uWQm+lP95QxdNMeWhOq1x0Db55C7GcUv2ZUuN6n8iKzsvOxibC//Yfs9Na8r2Rlz02vXXDT57FP/zJi66/EJSmsJKa8QxnoqW3VLQ+jZVUtJwJ8PNX1NQCwfNgdhhHD9on7PdRdrdGPF28rJr1F+3LBdeyv+8yYfLoMYet1vX4upNAjVvwOUWnlNXJXlkzk5Il6kqeoiL0C07qno+/CYBXq/+utlnsz7/Mzvy0tmI4zm4ag23PRN3t/CWryoUVJGm+5+K8RJ0V8Hc88/XHUX/HfiAq7t+BH+x6v8t438enWmdJwFA6ZINriLGKv/95f8lT9/FnyA1NMVEvQyaXuu+gz36f/DD73E4pwqpLcvm/o0Vle78n//+L/NPvoefp1pTJye6e4A/D082FERa5/opeH9zpvh13cNm19/4v/LDe5xMWTi8I0Ta0qKlK27AS/v3/r+/x/2GO9K2c7kVMonDpq7//jc5PKCxeNPpFVzaRr01wF8C4Pu76hXuX18H4LduTr79guuFD3n5BHfI+ZRFhY8w29TYhbbLi/bvBdqKE4fUgg1pBKnV3FEaCWOWyA+m3WpORZr/j+9TKJtW8yBTF2/ZEODI9/QavHkVdGFp/Pjn4Q+u5hXapsP5sOH+OXXA1LiKuqJxiMNbhTkbdJTCy4llEt6NnqRT4dhg1V3nbdrm6dYMecA1yTOL4PWTE9L5VzPFlLBCvlG58AhehnN4uHsAYinyJ+AZ/NkVvELbfOBUuOO5syBIEtiqHU1k9XeISX5bsimrkUUhnGDxourN8SgUsCZVtKyGbyGzHXdjOhsAvOAswSRyIBddRdEZWP6GZhNK/yjwew9ehBo+3jEADu7Ay2n8mDc+TS7awUHg0OMzR0LABhqLD4hJEh/BEGyBdGlSJoXYXtr+3HS4ijzVpgi0paWXtdruGTknXBz+11qT1Q2inxaTzQCO46P3lfLpyS4fou2PH/PupwZgCxNhGlj4IvUuWEsTkqMWm6i4xCSMc9N1RDQoCVcuGItJ/MRWefais+3synowi/dESgJjkilnWnBTGvRWmaw8oR15257t7CHmCf8HOn7cwI8+NQBXMBEmAa8PMRemrNCEhLGEhDQKcGZWS319BX9PFBEwGTbRBhLbDcaV3drFcDqk5kCTd2JF1Wp0HraqBx8U0wwBTnbpCadwBA/gTH/CDrcCs93LV8E0YlmmcyQRQnjBa8JESmGUfIjK/7fkaDJpmD2QptFNVJU1bbtIAjjWQizepOKptRjbzR9Kag6xZmMLLjHOtcLT3Tx9o/0EcTT1XN3E45u24AiwEypDJXihKjQxjLprEwcmRKclaDNZCVqr/V8mYWyFADbusiY5hvgFoU2vio49RgJLn5OsReRFN6tabeetiiy0V7KFHT3HyZLx491u95sn4K1QQSPKM9hNT0wMVvAWbzDSVdrKw4zRjZMyJIHkfq1VAVCDl/bUhNKlGq0zGr05+YAceXVPCttVk0oqjVwMPt+BBefx4yPtGVkUsqY3CHDPiCM5ngupUwCdbkpd8kbPrCWHhkmtIKLEetF2499eS1jZlIPGYnlcPXeM2KD9vLS0bW3ktYNqUllpKLn5ZrsxlIzxvDu5eHxzGLctkZLEY4PgSOg2IUVVcUONzUDBEpRaMoXNmUc0tFZrTZquiLyKxrSm3DvIW9Fil+AkhXu5PhEPx9mUNwqypDvZWdKlhIJQY7vn2OsnmBeOWnYZ0m1iwbbw1U60by5om47iHRV6fOgzjMf/DAZrlP40Z7syxpLK0lJ0gqaAK1c2KQKu7tabTXkLFz0sCftuwX++MyNeNn68k5Buq23YQhUh0SNTJa1ioQ0p4nUG2y0XilF1JqODqdImloPS4Bp111DEWT0jJjVv95uX9BBV7eB3bUWcu0acSVM23YZdd8R8UbQUxJ9wdu3oMuhdt929ME+mh6JXJ8di2RxbTi6TbrDquqV4aUKR2iwT6aZbyOwEXN3DUsWr8Hn4EhwNyHuXHh7/pdaUjtR7vnDh/d8c9xD/s5f501eQ1+CuDiCvGhk1AN/4Tf74RfxPwD3toLarR0zNtsnPzmS64KIRk861dMWCU8ArasG9T9H0ZBpsDGnjtAOM2+/LuIb2iIUGXNgl5ZmKD/Tw8TlaAuihaFP5yrw18v4x1898zIdP+DDAX1bM3GAMvPgRP/cJn3zCW013nrhHkrITyvYuwOUkcHuKlRSW5C6rzIdY4ppnF7J8aAJbQepgbJYBjCY9usGXDKQxq7RZfh9eg5d1UHMVATRaD/4BHK93/1iAgYZ/+jqPn8Dn4UExmWrpa3+ZOK6MvM3bjwfzxNWA2dhs8+51XHSPJiaAhGSpWevEs5xHLXcEGFXYiCONySH3fPWq93JIsBiSWvWyc3CAN+EcXoT7rCSANloPPoa31rt/5PUA/gp8Q/jDD3hyrjzlR8VkanfOvB1XPubt17vzxAfdSVbD1pzAnfgyF3ycadOTOTXhpEUoLC1HZyNGW3dtmjeXgr2r56JNmRwdNNWaQVBddd6rh4MhviEB9EFRD/7RGvePvCbwAL4Mx/D6M541hHO4D3e7g6PafdcZVw689z7NGTwo5om7A8sPhccT6qKcl9NJl9aM/9kX+e59Hh1yPqGuCCZxuITcsmNaJ5F7d0q6J3H48TO1/+M57085q2icdu2U+W36Ldllz9Agiv4YGljoEN908EzvDOrBF98/vtJwCC/BF2AG75xxEmjmMIcjxbjoaxqOK3/4hPOZzhMPBpYPG44CM0dTVm1LjLtUWWVz1Bcf8tEx0zs8O2A2YVHRxKYOiy/aOVoAaMu0i7ubu43njjmd4ibMHU1sIDHaQNKrZND/FZYdk54oCXetjq7E7IVl9eAL7t+oHnwXXtLx44czzoRFHBztYVwtH1d+NOMkupZ5MTM+gUmq90X+Bh9zjRlmaQ+m7YMqUL/veemcecAtOJ0yq1JnVlN27di2E0+Klp1tAJ4KRw1eMI7aJjsO3R8kPSI3fUFXnIOfdQe86sIIVtWDL7h//Ok6vj8vwDk08NEcI8zz7OhBy+WwalzZeZ4+0XniRfst9pAJqQHDGLzVQ2pheZnnv1OWhwO43/AgcvAEXEVVpa4db9sGvNK8wjaENHkfFQ4Ci5i7dqnQlPoLQrHXZDvO3BIXZbJOBrOaEbML6sFL798I4FhKihjHMsPjBUZYCMFr6nvaArxqXPn4lCa+cHfSa2cP27g3Z3ziYTRrcbQNGLQmGF3F3cBdzzzX7AILx0IB9rbwn9kx2G1FW3Inic+ZLIsVvKR8Zwfj0l1fkqo8LWY1M3IX14OX3r9RKTIO+d9XzAI8qRPGPn/4NC2n6o4rN8XJ82TOIvuVA8zLKUHRFgBCetlDZlqR1gLKjS39xoE7Bt8UvA6BxuEDjU3tFsEijgA+615tmZkXKqiEENrh41iLDDZNq4pKTWR3LZfnos81LOuNa15cD956vLMsJd1rqYp51gDUQqMYm2XsxnUhD2jg1DM7SeuJxxgrmpfISSXVIJIS5qJJSvJPEQ49DQTVIbYWJ9QWa/E2+c/oPK1drmC7WSfJRNKBO5Yjvcp7Gc3dmmI/Xh1kDTEuiSnWqQf37h+fTMhGnDf6dsS8SQfQWlqqwXXGlc/PEZ/SC5mtzIV0nAshlQdM/LvUtYutrEZ/Y+EAFtq1k28zQhOwLr1AIeANzhF8t9qzTdZf2qRKO6MWE9ohBYwibbOmrFtNmg3mcS+tB28xv2uKd/agYCvOP+GkSc+0lr7RXzyufL7QbkUpjLjEWFLqOIkAGu2B0tNlO9Eau2W1qcOUvVRgKzypKIQZ5KI3q0MLzqTNRYqiZOqmtqloIRlmkBHVpHmRYV6/HixbO6UC47KOFJnoMrVyr7wYz+SlW6GUaghYbY1I6kkxA2W1fSJokUdSh2LQ1GAimRGm0MT+uu57H5l7QgOWxERpO9moLRPgTtquWCfFlGlIjQaRly9odmzMOWY+IBO5tB4sW/0+VWGUh32qYk79EidWKrjWuiLpiVNGFWFRJVktyeXWmbgBBzVl8anPuXyNJlBJOlKLTgAbi/EYHVHxWiDaVR06GnHQNpJcWcK2jJtiCfG2sEHLzuI66sGrMK47nPIInPnu799935aOK2cvmvubrE38ZzZjrELCmXM2hM7UcpXD2oC3+ECVp7xtIuxptJ0jUr3sBmBS47TVxlvJ1Sqb/E0uLdvLj0lLr29ypdd/eMX3f6lrxGlKwKQxEGvw0qHbkbwrF3uHKwVENbIV2wZ13kNEF6zD+x24aLNMfDTCbDPnEikZFyTNttxWBXDaBuM8KtI2rmaMdUY7cXcUPstqTGvBGSrFWIpNMfbdea990bvAOC1YX0qbc6smDS1mPxSJoW4fwEXvjMmhlijDRq6qale6aJEuFGoppYDoBELQzLBuh/mZNx7jkinv0EtnUp50lO9hbNK57lZaMAWuWR5Yo9/kYwcYI0t4gWM47Umnl3YmpeBPqSyNp3K7s2DSAS/39KRuEN2bS4xvowV3dFRMx/VFcp2Yp8w2nTO9hCXtHG1kF1L4KlrJr2wKfyq77R7MKpFKzWlY9UkhYxyHWW6nBWPaudvEAl3CGcNpSXPZ6R9BbBtIl6cHL3gIBi+42CYXqCx1gfGWe7Ap0h3luyXdt1MKy4YUT9xSF01G16YEdWsouW9mgDHd3veyA97H+Ya47ZmEbqMY72oPztCGvK0onL44AvgC49saZKkWRz4veWljE1FHjbRJaWv6ZKKtl875h4CziFCZhG5rx7tefsl0aRT1bMHZjm8dwL/6u7wCRysaQblQoG5yAQN5zpatMNY/+yf8z+GLcH/Qn0iX2W2oEfXP4GvwQHuIL9AYGnaO3zqAX6946nkgqZNnUhx43DIdQtMFeOPrgy/y3Yd85HlJWwjLFkU3kFwq28xPnuPhMWeS+tDLV9Otllq7pQCf3uXJDN9wFDiUTgefHaiYbdfi3b3u8+iY6TnzhgehI1LTe8lcd7s1wJSzKbahCRxKKztTLXstGAiu3a6rPuQs5pk9TWAan5f0BZmGf7Ylxzzk/A7PAs4QPPPAHeFQ2hbFHszlgZuKZsJcUmbDC40sEU403cEjczstOEypa+YxevL4QBC8oRYqWdK6b7sK25tfE+oDZgtOQ2Jg8T41HGcBE6fTWHn4JtHcu9S7uYgU5KSCkl/mcnq+5/YBXOEr6lCUCwOTOM1taOI8mSxx1NsCXBEmLKbMAg5MkwbLmpBaFOPrNSlO2HnLiEqW3tHEwd8AeiQLmn+2gxjC3k6AxREqvKcJbTEzlpLiw4rNZK6oJdidbMMGX9FULKr0AkW+2qDEPBNNm5QAt2Ik2nftNWHetubosHLo2nG4vQA7GkcVCgVCgaDixHqo9UUn1A6OshapaNR/LPRYFV8siT1cCtJE0k/3WtaNSuUZYKPnsVIW0xXWnMUxq5+En4Kvw/MqQmVXnAXj9Z+9zM98zM/Agy7F/qqj2Nh67b8HjFnPP3iBn/tkpdzwEJX/whIcQUXOaikeliCRGUk7tiwF0rItwMEhjkZ309hikFoRAmLTpEXWuHS6y+am/KB/fM50aLEhGnSMwkpxzOov4H0AvgovwJ1iGzDLtJn/9BU+fAINfwUe6FHSLhu83viV/+/HrOePX+STT2B9uWGbrMHHLldRBlhS/CJQmcRxJFqZica01XixAZsYiH1uolZxLrR/SgxVIJjkpQP4PE9sE59LKLr7kltSBogS5tyszzH8Fvw8/AS8rNOg0xUS9fIaHwb+6et8Q/gyvKRjf5OusOzGx8evA/BP4IP11uN/grca5O0lcsPLJ5YjwI4QkJBOHa0WdMZYGxPbh2W2nR9v3WxEWqgp/G3+6VZbRLSAAZ3BhdhAaUL33VUSw9yjEsvbaQ9u4A/gGXwZXoEHOuU1GSj2chf+Mo+f8IcfcAxfIKVmyunRbYQVnoevwgfw3TXXcw++xNuP4fhyueEUNttEduRVaDttddoP0eSxLe2LENk6itYxlrxBNBYrNNKSQmeaLcm9c8UsaB5WyO6675yyQIAWSDpBVoA/gxmcwEvwoDv0m58UE7gHn+fJOa8/Ywan8EKRfjsopF83eCglX/Sfr7OeaRoQfvt1CGvIDccH5BCvw1sWIzRGC/66t0VTcLZQZtm6PlAasbOJ9iwWtUo7biktTSIPxnR24jxP1ZKaqq+2RcXM9OrBAm/AAs7hDJ5bNmGb+KIfwCs8a3jnjBrOFeMjHSCdbKr+2uOLfnOd9eiA8Hvvwwq54VbP2OqwkB48Ytc4YEOiH2vTXqodabfWEOzso4qxdbqD5L6tbtNPECqbhnA708DZH4QOJUXqScmUlks7Ot6FBuZw3n2mEbaUX7kDzxHOOQk8nKWMzAzu6ZZ8sOFw4RK+6PcuXo9tB4SbMz58ApfKDXf3szjNIIbGpD5TKTRxGkEMLjLl+K3wlWXBsCUxIDU+jbOiysESqAy1MGUJpXgwbTWzNOVEziIXZrJ+VIztl1PUBxTSo0dwn2bOmfDRPD3TRTGlfbCJvO9KvuhL1hMHhB9wPuPRLGHcdOWG2xc0U+5bQtAJT0nRTewXL1pgk2+rZAdeWmz3jxAqfNQQdzTlbF8uJ5ecEIWvTkevAHpwz7w78QujlD/Lr491bD8/1vhM2yrUQRrWXNQY4fGilfctMWYjL72UL/qS9eiA8EmN88nbNdour+PBbbAjOjIa4iBhfFg6rxeKdEGcL6p3EWR1Qq2Qkhs2DrnkRnmN9tG2EAqmgPw6hoL7Oza7B+3SCrR9tRftko+Lsf2F/mkTndN2LmzuMcKTuj/mX2+4Va3ki16+nnJY+S7MefpkidxwnV+4wkXH8TKnX0tsYzYp29DOOoSW1nf7nTh2akYiWmcJOuTidSaqESrTYpwjJJNVGQr+rLI7WsqerHW6Kp/oM2pKuV7T1QY9gjqlZp41/WfKpl56FV/0kvXQFRyeQ83xaTu5E8p5dNP3dUF34ihyI3GSpeCsywSh22ZJdWto9winhqifb7VRvgktxp13vyjrS0EjvrRfZ62uyqddSWaWYlwTPAtJZ2oZ3j/Sgi/mi+6vpzesfAcWNA0n8xVyw90GVFGuZjTXEQy+6GfLGLMLL523f5E0OmxVjDoOuRiH91RKU+vtoCtH7TgmvBLvtFXWLW15H9GTdVw8ow4IlRLeHECN9ym1e9K0I+Cbnhgv4Yu+aD2HaQJ80XDqOzSGAV4+4yCqBxrsJAX6ZTIoX36QnvzhhzzMfFW2dZVLOJfo0zbce5OvwXMFaZ81mOnlTVXpDZsQNuoYWveketKb5+6JOOsgX+NTm7H49fUTlx+WLuWL7qxnOFh4BxpmJx0p2gDzA/BUARuS6phR+pUsY7MMboAHx5xNsSVfVZcYSwqCKrqon7zM+8ecCkeS4nm3rINuaWvVNnMRI1IRpxTqx8PZUZ0Br/UEduo3B3hNvmgZfs9gQPj8vIOxd2kndir3awvJ6BLvoUuOfFWNYB0LR1OQJoUySKb9IlOBx74q1+ADC2G6rOdmFdJcD8BkfualA+BdjOOzP9uUhGUEX/TwhZsUduwRr8wNuXKurCixLBgpQI0mDbJr9dIqUuV+92ngkJZ7xduCk2yZKbfWrH1VBiTg9VdzsgRjW3CVXCvAwDd+c1z9dWw9+B+8MJL/eY15ZQ/HqvTwVdsZn5WQsgRRnMaWaecu3jFvMBEmgg+FJFZsnSl0zjB9OqPYaBD7qmoVyImFvzi41usesV0julaAR9dfR15Xzv9sEruRDyk1nb+QaLU67T885GTls6YgcY+UiMa25M/pwGrbCfzkvR3e0jjtuaFtnwuagHTSb5y7boBH119HXhvwP487jJLsLJ4XnUkHX5sLbS61dpiAXRoZSCrFJ+EjpeU3puVfitngYNo6PJrAigKktmwjyQdZpfq30mmtulaAx9Zfx15Xzv+cyeuiBFUs9zq8Kq+XB9a4PVvph3GV4E3y8HENJrN55H1X2p8VyqSKwVusJDKzXOZzplWdzBUFK9e+B4+uv468xvI/b5xtSAkBHQaPvtqWzllVvEOxPbuiE6+j2pvjcKsbvI7txnRErgfH7LdXqjq0IokKzga14GzQ23SSbCQvO6r+Or7SMIr/efOkkqSdMnj9mBx2DRsiY29Uj6+qK9ZrssCKaptR6HKURdwUYeUWA2kPzVKQO8ku2nU3Anhs/XWkBx3F/7wJtCTTTIKftthue1ty9xvNYLY/zo5KSbIuKbXpbEdSyeRyYdAIwKY2neyoc3+k1XUaufYga3T9daMUx/r8z1s10ITknIO0kuoMt+TB8jK0lpayqqjsJ2qtXAYwBU932zinimgmd6mTRDnQfr88q36NAI+tv24E8Pr8zxtasBqx0+xHH9HhlrwsxxNUfKOHQaZBITNf0uccj8GXiVmXAuPEAKSdN/4GLHhs/XWj92dN/uetNuBMnVR+XWDc25JLjo5Mg5IZIq226tmCsip2zZliL213YrTlL2hcFjpCduyim3M7/eB16q/blQsv5X/esDRbtJeabLIosWy3ycavwLhtxdWzbMmHiBTiVjJo6lCLjXZsi7p9PEPnsq6X6wd4bP11i0rD5fzPm/0A6brrIsllenZs0lCJlU4abakR59enZKrKe3BZihbTxlyZ2zl1+g0wvgmA166/bhwDrcn/7Ddz0eWZuJvfSESug6NzZsox3Z04FIxz0mUjMwVOOVTq1CQ0AhdbBGVdjG/CgsfUX7esJl3K/7ytWHRv683praW/8iDOCqWLLhpljDY1ZpzK75QiaZoOTpLKl60auHS/97oBXrv+umU9+FL+5+NtLFgjqVLCdbmj7pY5zPCPLOHNCwXGOcLquOhi8CmCWvbcuO73XmMUPab+ug3A6/A/78Bwe0bcS2+tgHn4J5pyS2WbOck0F51Vq3LcjhLvZ67p1ABbaL2H67bg78BfjKi/jr3+T/ABV3ilLmNXTI2SpvxWBtt6/Z//D0z/FXaGbSBgylzlsEGp+5//xrd4/ae4d8DUUjlslfIYS3t06HZpvfQtvv0N7AHWqtjP2pW08QD/FLy//da38vo8PNlKHf5y37Dxdfe/oj4kVIgFq3koLReSR76W/bx//n9k8jonZxzWTANVwEniDsg87sOSd/z7//PvMp3jQiptGVWFX2caezzAXwfgtzYUvbr0iozs32c3Uge7varH+CNE6cvEYmzbPZ9hMaYDdjK4V2iecf6EcEbdUDVUARda2KzO/JtCuDbNQB/iTeL0EG1JSO1jbXS+nLxtPMDPw1fh5+EPrgSEKE/8Gry5A73ui87AmxwdatyMEBCPNOCSKUeRZ2P6Myb5MRvgCHmA9ywsMifU+AYXcB6Xa5GibUC5TSyerxyh0j6QgLVpdyhfArRTTLqQjwe4HOD9s92D4Ap54odXAPBWLAwB02igG5Kkc+piN4lvODIFGAZgT+EO4Si1s7fjSR7vcQETUkRm9O+MXyo9OYhfe4xt9STQ2pcZRLayCV90b4D3jR0DYAfyxJ+eywg2IL7NTMXna7S/RpQ63JhWEM8U41ZyQGjwsVS0QBrEKLu8xwZsbi4wLcCT+OGidPIOCe1PiSc9Qt+go+vYqB7cG+B9d8cAD+WJPz0Am2gxXgU9IneOqDpAAXOsOltVuMzpdakJXrdPCzXiNVUpCeOos5cxnpQT39G+XVLhs1osQVvJKPZyNq8HDwd4d7pNDuWJPxVX7MSzqUDU6gfadKiNlUFTzLeFHHDlzO4kpa7aiKhBPGKwOqxsBAmYkOIpipyXcQSPlRTf+Tii0U3EJGaZsDER2qoB3h2hu0qe+NNwUooYU8y5mILbJe6OuX+2FTKy7bieTDAemaQyQ0CPthljSWO+xmFDIYiESjM5xKd6Ik5lvLq5GrQ3aCMLvmCA9wowLuWJb9xF59hVVP6O0CrBi3ZjZSNOvRy+I6klNVRJYRBaEzdN+imiUXQ8iVF8fsp+W4JXw7WISW7fDh7lptWkCwZ4d7QTXyBPfJMYK7SijjFppGnlIVJBJBYj7eUwtiP1IBXGI1XCsjNpbjENVpSAJ2hq2LTywEly3hUYazt31J8w2+aiLx3g3fohXixPfOMYm6zCGs9LVo9MoW3MCJE7R5u/WsOIjrqBoHUO0bJE9vxBpbhsd3+Nb4/vtPCZ4oZYCitNeYuC/8UDvDvy0qvkiW/cgqNqRyzqSZa/s0mqNGjtKOoTm14zZpUauiQgVfqtQiZjq7Q27JNaSK5ExRcrGCXO1FJYh6jR6CFqK7bZdQZ4t8g0rSlPfP1RdBtqaa9diqtzJkQ9duSryi2brQXbxDwbRUpFMBHjRj8+Nt7GDKgvph9okW7LX47gu0SpGnnFQ1S1lYldOsC7hYteR574ZuKs7Ei1lBsfdz7IZoxzzCVmmVqaSySzQbBVAWDek+N4jh9E/4VqZrJjPwiv9BC1XcvOWgO8275CVyBPvAtTVlDJfZkaZGU7NpqBogAj/xEHkeAuJihWYCxGN6e8+9JtSegFXF1TrhhLGP1fak3pebgPz192/8gB4d/6WT7+GdYnpH7hH/DJzzFiYPn/vjW0SgNpTNuPIZoAEZv8tlGw4+RLxy+ZjnKa5NdFoC7UaW0aduoYse6+bXg1DLg6UfRYwmhGEjqPvF75U558SANrElK/+MdpXvmqBpaXOa/MTZaa1DOcSiLaw9j0NNNst3c+63c7EKTpkvKHzu6bPbP0RkuHAVcbRY8ijP46MIbQeeT1mhA+5PV/inyDdQipf8LTvMXbwvoDy7IruDNVZKTfV4CTSRUYdybUCnGU7KUTDxLgCknqUm5aAW6/1p6eMsOYsphLzsHrE0Y/P5bQedx1F/4yPHnMB3/IOoTU9+BL8PhtjuFKBpZXnYNJxTuv+2XqolKR2UQgHhS5novuxVySJhBNRF3SoKK1XZbbXjVwWNyOjlqWJjrWJIy+P5bQedyldNScP+HZ61xKSK3jyrz+NiHG1hcOLL/+P+PDF2gOkekKGiNWKgJ+8Z/x8Iv4DdQHzcpZyF4v19I27w9/yPGDFQvmEpKtqv/TLiWMfn4sofMm9eAH8Ao0zzh7h4sJqYtxZd5/D7hkYPneDzl5idlzNHcIB0jVlQ+8ULzw/nc5/ojzl2juE0apD7LRnJxe04dMz2iOCFNtGFpTuXA5AhcTRo8mdN4kz30nVjEC4YTZQy4gpC7GlTlrePKhGsKKgeXpCYeO0MAd/GH7yKQUlXPLOasOH3FnSphjHuDvEu4gB8g66oNbtr6eMbFIA4fIBJkgayoXriw2XEDQPJrQeROAlY6aeYOcMf+IVYTU3XFlZufMHinGywaW3YLpObVBAsbjF4QJMsVUSayjk4voPsHJOQfPWDhCgDnmDl6XIRerD24HsGtw86RMHOLvVSHrKBdeVE26gKB5NKHzaIwLOmrqBWJYZDLhASG16c0Tn+CdRhWDgWXnqRZUTnPIHuMJTfLVpkoYy5CzylHVTGZMTwkGAo2HBlkQplrJX6U+uF1wZz2uwS1SQ12IqWaPuO4baZaEFBdukksJmkcTOm+YJSvoqPFzxFA/YUhIvWxcmSdPWTWwbAKVp6rxTtPFUZfKIwpzm4IoMfaYQLWgmlG5FME2gdBgm+J7J+rtS/XBbaVLsR7bpPQnpMFlo2doWaVceHk9+MkyguZNCJ1He+kuHTWyQAzNM5YSUg/GlTk9ZunAsg1qELVOhUSAK0LABIJHLKbqaEbHZLL1VA3VgqoiOKXYiS+HRyaEKgsfIqX64HYWbLRXy/qWoylIV9gudL1OWBNgBgTNmxA6b4txDT4gi3Ri7xFSLxtXpmmYnzAcWDZgY8d503LFogz5sbonDgkKcxGsWsE1OI+rcQtlgBBCSOKD1mtqYpIU8cTvBmAT0yZe+zUzeY92fYjTtGipXLhuR0ePoHk0ofNWBX+lo8Z7pAZDk8mEw5L7dVyZZoE/pTewbI6SNbiAL5xeygW4xPRuLCGbhcO4RIeTMFYHEJkYyEO9HmJfXMDEj/LaH781wHHZEtqSQ/69UnGpzH7LKIAZEDSPJnTesJTUa+rwTepI9dLJEawYV+ZkRn9g+QirD8vF8Mq0jFQ29js6kCS3E1+jZIhgPNanHdHFqFvPJLHqFwQqbIA4jhDxcNsOCCQLDomaL/dr5lyJaJU6FxPFjO3JOh3kVMcROo8u+C+jo05GjMF3P3/FuDLn5x2M04xXULPwaS6hBYki+MrMdZJSgPHlcB7nCR5bJ9Kr5ACUn9jk5kivdd8tk95SOGrtqu9lr2IhK65ZtEl7ZKrp7DrqwZfRUSN1el7+7NJxZbywOC8neNKTch5vsTEMNsoCCqHBCqIPRjIPkm0BjvFODGtto99rCl+d3wmHkW0FPdpZtC7MMcVtGFQjJLX5bdQ2+x9ypdc313uj8xlsrfuLgWXz1cRhZvJYX0iNVBRcVcmCXZs6aEf3RQF2WI/TcCbKmGU3IOoDJGDdDub0+hYckt6PlGu2BcxmhbTdj/klhccLGJMcqRjMJP1jW2ETqLSWJ/29MAoORluJ+6LPffBZbi5gqi5h6catQpmOT7/OFf5UorRpLzCqcMltBLhwd1are3kztrSzXO0LUbXRQcdLh/RdSZ+swRm819REDrtqzC4es6Gw4JCKlSnjYVpo0xeq33PrADbFLL3RuCmObVmPN+24kfa+AojDuM4umKe2QwCf6EN906HwjujaitDs5o0s1y+k3lgbT2W2i7FJdnwbLXhJUBq/9liTctSmFC/0OqUinb0QddTWamtjbHRFuWJJ6NpqZ8vO3fZJ37Db+2GkaPYLGHs7XTTdiFQJ68SkVJFVmY6McR5UycflNCsccHFaV9FNbR4NttLxw4pQ7wJd066Z0ohVbzihaxHVExd/ay04oxUKWt+AsdiQ9OUyZ2krzN19IZIwafSTFgIBnMV73ADj7V/K8u1MaY2sJp2HWm0f41tqwajEvdHWOJs510MaAqN4aoSiPCXtN2KSi46dUxHdaMquar82O1x5jqhDGvqmoE9LfxcY3zqA7/x3HA67r9ZG4O6Cuxu12/+TP+eLP+I+HErqDDCDVmBDO4larujNe7x8om2rMug0MX0rL1+IWwdwfR+p1TNTyNmVJ85ljWzbWuGv8/C7HD/izjkHNZNYlhZcUOKVzKFUxsxxN/kax+8zPWPSFKw80rJr9Tizyj3o1gEsdwgWGoxPezDdZ1TSENE1dLdNvuKL+I84nxKesZgxXVA1VA1OcL49dFlpFV5yJMhzyCmNQ+a4BqusPJ2bB+xo8V9u3x48VVIEPS/mc3DvAbXyoYr6VgDfh5do5hhHOCXMqBZUPhWYbWZECwVJljLgMUWOCB4MUuMaxGNUQDVI50TQ+S3kFgIcu2qKkNSHVoM0SHsgoZxP2d5HH8B9woOk4x5bPkKtAHucZsdykjxuIpbUrSILgrT8G7G5oCW+K0990o7E3T6AdW4TilH5kDjds+H64kS0mz24grtwlzDHBJqI8YJQExotPvoC4JBq0lEjjQkyBZ8oH2LnRsQ4Hu1QsgDTJbO8fQDnllitkxuVskoiKbRF9VwzMDvxHAdwB7mD9yCplhHFEyUWHx3WtwCbSMMTCUCcEmSGlg4gTXkHpZXWQ7kpznK3EmCHiXInqndkQjunG5kxTKEeGye7jWz9cyMR2mGiFQ15ENRBTbCp+Gh86vAyASdgmJq2MC6hoADQ3GosP0QHbnMHjyBQvQqfhy/BUbeHd5WY/G/9LK/8Ka8Jd7UFeNWEZvzPb458Dn8DGLOe3/wGL/4xP+HXlRt+M1PE2iLhR8t+lfgxsuh7AfO2AOf+owWhSZRYQbd622hbpKWKuU+XuvNzP0OseRDa+mObgDHJUSc/pKx31QdKffQ5OIJpt8GWjlgTwMc/w5MPCR/yl1XC2a2Yut54SvOtMev55Of45BOat9aWG27p2ZVORRvnEk1hqWMVUmqa7S2YtvlIpspuF1pt0syuZS2NV14mUidCSfzQzg+KqvIYCMljIx2YK2AO34fX4GWdu5xcIAb8MzTw+j/lyWM+Dw/gjs4GD6ehNgA48kX/AI7XXM/XAN4WHr+9ntywqoCakCqmKP0rmQrJJEErG2Upg1JObr01lKQy4jskWalKYfJ/EDLMpjNSHFEUAde2fltaDgmrNaWQ9+AAb8I5vKjz3L1n1LriB/BXkG/wwR9y/oRX4LlioHA4LzP2inzRx/DWmutRweFjeP3tNeSGlaE1Fde0OS11yOpmbIp2u/jF1n2RRZviJM0yBT3IZl2HWImKjQOxIyeU325b/qWyU9Moj1o07tS0G7qJDoGHg5m8yeCxMoEH8GU45tnrNM84D2l297DQ9t1YP7jki/7RmutRweEA77/HWXOh3HCxkRgldDQkAjNTMl2Iloc1qN5JfJeeTlyTRzxURTdn1Ixv2uKjs12AbdEWlBtmVdk2k7FFwj07PCZ9XAwW3dG+8xKzNFr4EnwBZpy9Qzhh3jDXebBpYcpuo4fQ44u+fD1dweEnHzI7v0xuuOALRUV8rXpFyfSTQYkhd7IHm07jpyhlkCmI0ALYqPTpUxXS+z4jgDj1Pflvmz5ecuItpIBxyTHpSTGWd9g1ApfD/bvwUhL4nT1EzqgX7cxfCcNmb3mPL/qi9SwTHJ49oj5ZLjccbTG3pRmlYi6JCG0mQrAt1+i2UXTZ2dv9IlQpN5naMYtviaXlTrFpoMsl3bOAFEa8sqPj2WCMrx3Yjx99qFwO59Aw/wgx+HlqNz8oZvA3exRDvuhL1jMQHPaOJ0+XyA3fp1OfM3qObEVdhxjvynxNMXQV4+GJyvOEFqeQBaIbbO7i63rpxCltdZShPFxkjM2FPVkn3TG+Rp9pO3l2RzFegGfxGDHIAh8SteR0C4HopXzRF61nheDw6TFN05Ebvq8M3VKKpGjjO6r7nhudTEGMtYM92HTDaR1FDMXJ1eThsbKfywyoWwrzRSXkc51flG3vIid62h29bIcFbTGhfV+faaB+ohj7dPN0C2e2lC96+XouFByen9AsunLDJZ9z7NExiUc0OuoYW6UZkIyx2YUR2z6/TiRjyKMx5GbbjLHvHuf7YmtKghf34LJfx63Yg8vrvN2zC7lY0x0tvKezo4HmGYDU+Gab6dFL+KI761lDcNifcjLrrr9LWZJctG1FfU1uwhoQE22ObjdfkSzY63CbU5hzs21WeTddH2BaL11Gi7lVdlxP1nkxqhnKhVY6knS3EPgVGg1JpN5cP/hivujOelhXcPj8HC/LyI6MkteVjlolBdMmF3a3DbsuAYhL44dxzthWSN065xxUd55Lmf0wRbOYOqH09/o9WbO2VtFdaMb4qBgtFJoT1SqoN8wPXMoXLb3p1PUEhxfnnLzGzBI0Ku7FxrKsNJj/8bn/H8fPIVOd3rfrklUB/DOeO+nkghgSPzrlPxluCMtOnDL4Yml6dK1r3vsgMxgtPOrMFUZbEUbTdIzii5beq72G4PD0DKnwjmBULUVFmy8t+k7fZ3pKc0Q4UC6jpVRqS9Umv8bxw35flZVOU1X7qkjnhZlsMbk24qQ6Hz7QcuL6sDC0iHHki96Uh2UdvmgZnjIvExy2TeJdMDZNSbdZyAHe/Yd1xsQhHiKzjh7GxQ4yqMPaywPkjMamvqrYpmO7Knad+ZQC5msCuAPWUoxrxVhrGv7a+KLXFhyONdTMrZ7ke23qiO40ZJUyzgYyX5XyL0mV7NiUzEs9mjtbMN0dERqwyAJpigad0B3/zRV7s4PIfXSu6YV/MK7+OrYe/JvfGMn/PHJe2fyUdtnFrKRNpXV0Y2559aWPt/G4BlvjTMtXlVIWCnNyA3YQBDmYIodFz41PvXPSa6rq9lWZawZ4dP115HXV/M/tnFkkrBOdzg6aP4pID+MZnTJ1SuuB6iZlyiox4HT2y3YBtkUKWooacBQUDTpjwaDt5poBHl1/HXltwP887lKKXxNUEyPqpGTyA699UqY/lt9yGdlUKra0fFWS+36iylVWrAyd7Uw0CZM0z7xKTOduznLIjG2Hx8cDPLb+OvK6Bv7n1DYci4CxUuRxrjBc0bb4vD3rN5Zz36ntLb83eVJIB8LiIzCmn6SMPjlX+yNlTjvIGjs+QzHPf60Aj62/jrzG8j9vYMFtm1VoRWCJdmw7z9N0t+c8cxZpPeK4aTRicS25QhrVtUp7U578chk4q04Wx4YoQSjFryUlpcQ1AbxZ/XVMknIU//OGl7Q6z9Zpxi0+3yFhSkjUDpnCIUhLWVX23KQ+L9vKvFKI0ZWFQgkDLvBoylrHNVmaw10zwCPrr5tlodfnf94EWnQ0lFRWy8pW9LbkLsyUVDc2NSTHGDtnD1uMtchjbCeb1mpxFP0YbcClhzdLu6lfO8Bj6q+bdT2sz/+8SZCV7VIxtt0DUn9L7r4cLYWDSXnseEpOGFuty0qbOVlS7NNzs5FOGJUqQpl2Q64/yBpZf90sxbE+//PGdZ02HSipCbmD6NItmQ4Lk5XUrGpDMkhbMm2ZVheNYV+VbUWTcv99+2NyX1VoafSuC+AN6q9bFIMv5X/eagNWXZxEa9JjlMwNWb00akGUkSoepp1/yRuuqHGbUn3UdBSTxBU6SEVklzWRUkPndVvw2PrrpjvxOvzPmwHc0hpmq82npi7GRro8dXp0KXnUQmhZbRL7NEVp1uuZmO45vuzKsHrktS3GLWXODVjw+vXXLYx4Hf7njRPd0i3aoAGX6W29GnaV5YdyDj9TFkakje7GHYzDoObfddHtOSpoi2SmzJHrB3hM/XUDDEbxP2/oosszcRlehWXUvzHv4TpBVktHqwenFo8uLVmy4DKLa5d3RtLrmrM3aMFr1183E4sewf+85VWeg1c5ag276NZrM9IJVNcmLEvDNaV62aq+14IAOGFsBt973Ra8Xv11YzXwNfmft7Jg2oS+XOyoC8/cwzi66Dhmgk38kUmP1CUiYWOX1bpD2zWXt2FCp7uq8703APAa9dfNdscR/M/bZLIyouVxqJfeWvG9Je+JVckHQ9+CI9NWxz+blX/KYYvO5n2tAP/vrlZ7+8/h9y+9qeB/Hnt967e5mevX10rALDWK//FaAT5MXdBXdP0C/BAes792c40H+AiAp1e1oH8HgH94g/Lttx1gp63op1eyoM/Bvw5/G/7xFbqJPcCXnmBiwDPb/YKO4FX4OjyCb289db2/Noqicw4i7N6TVtoz8tNwDH+8x/i6Ae7lmaQVENzJFb3Di/BFeAwz+Is9SjeQySpPqbLFlNmyz47z5a/AF+AYFvDmHqibSXTEzoT4Gc3OALaqAP4KPFUJ6n+1x+rGAM6Zd78bgJ0a8QN4GU614vxwD9e1Amy6CcskNrczLx1JIp6HE5UZD/DBHrFr2oNlgG4Odv226BodoryjGJ9q2T/AR3vQrsOCS0ctXZi3ruLlhpFDJYl4HmYtjQCP9rhdn4suySLKDt6wLcC52h8xPlcjju1fn+yhuw4LZsAGUuo2b4Fx2UwQu77uqRHXGtg92aN3tQCbFexc0uk93vhTXbct6y7MulLycoUljx8ngDMBg1tvJjAazpEmOtxlzclvj1vQf1Tx7QlPDpGpqgtdSKz/d9/hdy1vTfFHSmC9dGDZbLiezz7Ac801HirGZsWjydfZyPvHXL/Y8Mjzg8BxTZiuwKz4Eb8sBE9zznszmjvFwHKPIWUnwhqfVRcd4Ck0K6ate48m1oOfrX3/yOtvAsJ8zsPAM89sjnddmuLuDPjX9Bu/L7x7xpMzFk6nWtyQfPg278Gn4Aekz2ZgOmU9eJ37R14vwE/BL8G3aibCiWMWWDQ0ZtkPMnlcGeAu/Ag+8ZyecU5BPuy2ILD+sQqyZhAKmn7XZd+jIMTN9eBL7x95xVLSX4On8EcNlXDqmBlqS13jG4LpmGbkF/0CnOi3H8ETOIXzmnmtb0a16Tzxj1sUvQCBiXZGDtmB3KAefPH94xcUa/6vwRn80GOFyjEXFpba4A1e8KQfFF+259tx5XS4egYn8fQsLGrqGrHbztr+uByTahWuL1NUGbDpsnrwBfePPwHHIf9X4RnM4Z2ABWdxUBlqQ2PwhuDxoS0vvqB1JzS0P4h2nA/QgTrsJFn+Y3AOjs9JFC07CGWX1oNX3T/yHOzgDjwPn1PM3g9Jk9lZrMEpxnlPmBbjyo2+KFXRU52TJM/2ALcY57RUzjObbjqxVw++4P6RAOf58pcVsw9Daje3htriYrpDOonre3CudSe6bfkTEgHBHuDiyu5MCsc7BHhYDx7ePxLjqigXZsw+ijMHFhuwBmtoTPtOxOrTvYJDnC75dnUbhfwu/ZW9AgYd+peL68HD+0emKquiXHhWjJg/UrkJYzuiaL3E9aI/ytrCvAd4GcYZMCkSQxfUg3v3j8c4e90j5ZTPdvmJJGHnOCI2nHS8081X013pHuBlV1gB2MX1YNmWLHqqGN/TWmG0y6clJWthxNUl48q38Bi8vtMKyzzpFdSDhxZ5WBA5ZLt8Jv3895DduBlgbPYAj8C4B8hO68FDkoh5lydC4FiWvBOVqjYdqjiLv92t8yPDjrDaiHdUD15qkSURSGmXJwOMSxWAXYwr3zaAufJ66l+94vv3AO+vPcD7aw/w/toDvL/2AO+vPcD7aw/wHuD9tQd4f+0B3l97gPfXHuD9tQd4f+0B3l97gG8LwP8G/AL8O/A5OCq0Ys2KIdv/qOIXG/4mvFAMF16gZD+2Xvu/B8as5+8bfllWyg0zaNO5bfXj6vfhhwD86/Aq3NfRS9t9WPnhfnvCIw/CT8GLcFTMnpntdF/z9V+PWc/vWoIH+FL3Znv57PitcdGP4R/C34avw5fgRVUInCwbsn1yyA8C8zm/BH8NXoXnVE6wVPjdeCI38kX/3+Ct9dbz1pTmHFRu+Hm4O9Ch3clr99negxfwj+ER/DR8EV6B5+DuQOnTgUw5rnkY+FbNU3gNXh0o/JYTuWOvyBf9FvzX663HH/HejO8LwAl8Hl5YLTd8q7sqA3wbjuExfAFegQdwfyDoSkWY8swzEf6o4Qyewefg+cHNbqMQruSL/u/WWc+E5g7vnnEXgDmcDeSGb/F4cBcCgT+GGRzDU3hZYburAt9TEtHgbM6JoxJ+6NMzzTcf6c2bycv2+KK/f+l6LBzw5IwfqZJhA3M472pWT/ajKxnjv4AFnMEpnBTPND6s2J7qHbPAqcMK74T2mZ4VGB9uJA465It+/eL1WKhYOD7xHOkr1ajK7d0C4+ke4Hy9qXZwpgLr+Znm/uNFw8xQOSy8H9IzjUrd9+BIfenYaylf9FsXr8fBAadnPIEDna8IBcwlxnuA0/Wv6GAWPd7dDIKjMdSWueAsBj4M7TOd06qBbwDwKr7oleuxMOEcTuEZTHWvDYUO7aHqAe0Bbq+HEFRzOz7WVoTDQkVds7A4sIIxfCQdCefFRoIOF/NFL1mPab/nvOakSL/Q1aFtNpUb/nFOVX6gzyg/1nISyDfUhsokIzaBR9Kxm80s5mK+6P56il1jXic7nhQxsxSm3OwBHl4fFdLqi64nDQZvqE2at7cWAp/IVvrN6/BFL1mPhYrGMBfOi4PyjuSGf6wBBh7p/FZTghCNWGgMzlBbrNJoPJX2mW5mwZfyRffXo7OFi5pZcS4qZUrlViptrXtw+GQoyhDPS+ANjcGBNRiLCQDPZPMHuiZfdFpPSTcQwwKYdRNqpkjm7AFeeT0pJzALgo7g8YYGrMHS0iocy+YTm2vyRUvvpXCIpQ5pe666TJrcygnScUf/p0NDs/iAI/nqDHC8TmQT8x3NF91l76oDdQGwu61Z6E0ABv7uO1dbf/37Zlv+Zw/Pbh8f1s4Avur6657/+YYBvur6657/+YYBvur6657/+YYBvur6657/+aYBvuL6657/+VMA8FXWX/f8zzcN8BXXX/f8zzcNMFdbf93zP38KLPiK6697/uebtuArrr/u+Z9vGmCusP6653/+1FjwVdZf9/zPN7oHX339dc//fNMu+irrr3v+50+Bi+Zq6697/uebA/jz8Pudf9ht/fWv517J/XUzAP8C/BAeX9WCDrUpZ3/dEMBxgPcfbtTVvsYV5Yn32u03B3Ac4P3b8I+vxNBKeeL9dRMAlwO83959qGO78sT769oB7g3w/vGVYFzKE++v6wV4OMD7F7tckFkmT7y/rhHgpQO8b+4Y46XyxPvrugBeNcB7BRiX8sT767oAvmCA9woAHsoT76+rBJjLBnh3txOvkifeX1dswZcO8G6N7sXyxPvr6i340gHe3TnqVfLE++uKAb50gHcXLnrX8sR7gNdPRqwzwLu7Y/FO5Yn3AK9jXCMGeHdgxDuVJ75VAI8ljP7PAb3/RfjcZfePHBB+79dpfpH1CanN30d+mT1h9GqAxxJGM5LQeeQ1+Tb+EQJrElLb38VHQ94TRq900aMIo8cSOo+8Dp8QfsB8zpqE1NO3OI9Zrj1h9EV78PqE0WMJnUdeU6E+Jjyk/hbrEFIfeWbvId8H9oTRFwdZaxJGvziW0Hn0gqYB/wyZ0PwRlxJST+BOw9m77Amj14ii1yGM/txYQudN0qDzGe4EqfA/5GJCagsHcPaEPWH0esekSwmjRxM6b5JEcZ4ww50ilvAOFxBSx4yLW+A/YU8YvfY5+ALC6NGEzhtmyZoFZoarwBLeZxUhtY4rc3bKnjB6TKJjFUHzJoTOozF2YBpsjcyxDgzhQ1YRUse8+J4wenwmaylB82hC5w0zoRXUNXaRBmSMQUqiWSWkLsaVqc/ZE0aPTFUuJWgeTei8SfLZQeMxNaZSIzbII4aE1Nmr13P2hNHjc9E9guYNCZ032YlNwESMLcZiLQHkE4aE1BFg0yAR4z1h9AiAGRA0jyZ03tyIxWMajMPWBIsxYJCnlITU5ShiHYdZ94TR4wCmSxg9jtB5KyPGYzymAYexWEMwAPIsAdYdV6aObmNPGD0aYLoEzaMJnTc0Ygs+YDw0GAtqxBjkuP38bMRWCHn73xNGjz75P73WenCEJnhwyVe3AEe8TtKdJcYhBl97wuhNAObK66lvD/9J9NS75v17wuitAN5fe4D31x7g/bUHeH/tAd5fe4D3AO+vPcD7aw/w/toDvL/2AO+vPcD7aw/w/toDvAd4f/24ABzZ8o+KLsSLS+Pv/TqTb3P4hKlQrTGh+fbIBT0Axqznnb+L/V2mb3HkN5Mb/nEHeK7d4IcDld6lmDW/iH9E+AH1MdOw/Jlu2T1xNmY98sv4wHnD7D3uNHu54WUuOsBTbQuvBsPT/UfzNxGYzwkP8c+Yz3C+r/i6DcyRL/rZ+utRwWH5PmfvcvYEt9jLDS/bg0/B64DWKrQM8AL8FPwS9beQCe6EMKNZYJol37jBMy35otdaz0Bw2H/C2Smc7+WGB0HWDELBmOByA3r5QONo4V+DpzR/hFS4U8wMW1PXNB4TOqYz9urxRV++ntWCw/U59Ty9ebdWbrgfRS9AYKKN63ZokZVygr8GZ/gfIhZXIXPsAlNjPOLBby5c1eOLvmQ9lwkOy5x6QV1j5TYqpS05JtUgUHUp5toHGsVfn4NX4RnMCe+AxTpwmApTYxqMxwfCeJGjpXzRF61nbcHhUBPqWze9svwcHJ+S6NPscKrEjug78Dx8Lj3T8D4YxGIdxmJcwhi34fzZUr7olevZCw5vkOhoClq5zBPZAnygD/Tl9EzDh6kl3VhsHYcDEb+hCtJSvuiV69kLDm+WycrOTArHmB5/VYyP6jOVjwgGawk2zQOaTcc1L+aLXrKeveDwZqlKrw8U9Y1p66uK8dEzdYwBeUQAY7DbyYNezBfdWQ97weEtAKYQg2xJIkuveAT3dYeLGH+ShrWNwZgN0b2YL7qznr3g8JYAo5bQBziPjx7BPZ0d9RCQp4UZbnFdzBddor4XHN4KYMrB2qHFRIzzcLAHQZ5the5ovui94PCWAPefaYnxIdzRwdHCbuR4B+tbiy96Lzi8E4D7z7S0mEPd+eqO3cT53Z0Y8SV80XvB4Z0ADJi/f7X113f+7p7/+UYBvur6657/+YYBvur6657/+aYBvuL6657/+aYBvuL6657/+aYBvuL6657/+aYBvuL6657/+VMA8FXWX/f8z58OgK+y/rrnf75RgLna+uue//lTA/CV1V/3/M837aKvvv6653++UQvmauuve/7nTwfAV1N/3fM/fzr24Cuuv+75nz8FFnxl9dc9//MOr/8/glixwRuUfM4AAAAASUVORK5CYII="}getSearchTexture(){return"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEIAAAAhCAAAAABIXyLAAAAAOElEQVRIx2NgGAWjYBSMglEwEICREYRgFBZBqDCSLA2MGPUIVQETE9iNUAqLR5gIeoQKRgwXjwAAGn4AtaFeYLEAAAAASUVORK5CYII="}dispose(){this.edgesRT.dispose(),this.weightsRT.dispose(),this.areaTexture.dispose(),this.searchTexture.dispose(),this.materialEdges.dispose(),this.materialWeights.dispose(),this.materialBlend.dispose(),this.fsQuad.dispose()}},QU=ee(ae()),eF=ee(_e()),d3=ee(J()),tF=ee(Q()),rF=ee(te());function zw(e,t){if(!(e>0)||!Number.isFinite(e)||!Number.isFinite(t))return{steps:1,limited:!1};let r=Math.min(Math.PI/48,2*Math.acos(Math.max(-1,1-Math.min(.005,e)/e))),i=Math.max(8,Math.ceil(Math.abs(t)/Math.max(r,1e-8)));return{steps:Math.min(512,i),limited:i>512}}var iF=Object.freeze({side:2,depthWrite:!0,transparent:!1,opacity:1}),Bw=e=>e&&typeof e=="object"&&!Array.isArray(e)?e.quoted:e;function jw(e,t,r,i){for(let n of["uuid","tstamp"]){let s=Bw(e.find(a=>Array.isArray(a)&&Bw(a[0])===n)?.[1]);if(typeof s=="string"&&s||typeof s=="number"&&Number.isFinite(s))return String(s)}if(!Number.isSafeInteger(r)||r<0||!Number.isSafeInteger(i)||i<0)throw TypeError("Choose bounded source pad occurrences.");return`display-pad:${r}:${i}`}function Vw(e,t=0,r=t){let i=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY,s=0;for(let a of e)Number.isFinite(a)&&(a<i&&(i=a),a>n&&(n=a),s+=1);return s?{minimum:i,maximum:n,count:s}:{minimum:t,maximum:r,count:0}}var p3=new Set(["signal","power","mixed","jumper"]);function f3(e){return!e.name||e.name.includes("*")?!1:e.name.endsWith(".Cu")||p3.has(e.kind.toLowerCase())}function m3(e,t){return e==="F.Cu"?-1:t==="F.Cu"||e==="B.Cu"?1:t==="B.Cu"?-1:e.localeCompare(t,void 0,{numeric:!0})}function g3(e,t=[],r=[]){let i=[...e].filter(f3).map(c=>c.name),n=[...new Set(r)].filter(c=>c.endsWith(".Cu")&&!c.includes("*")),s=new Set(n),a=i.length>0&&i.every(c=>s.has(c))?[...n,...i.filter(c=>!s.has(c))]:i,o=new Set(a),l=[...new Set(t)].filter(c=>c.endsWith(".Cu")&&!c.includes("*")&&!o.has(c)).sort(m3);return[...a,...l]}var y3=.015;function vl(e){return Array.isArray(e)}function*v3(e){let t="",r=!1,i=!1;for(let n of e)i?(t+=n,i=!1):r&&n==="\\"?i=!0:n==='"'?r=!r:r?t+=n:n==="("||n===")"?(t&&(yield t,t=""),yield n):/\s/.test(n)?t&&(yield t,t=""):t+=n;t&&(yield t)}function x3(e){let t=[],r=[t];for(let i of e)if(i==="("){let n=[];r[r.length-1].push(n),r.push(n)}else i===")"?r.length>1&&r.pop():r[r.length-1].push(i);return t.find(vl)??[]}function ki(e,t){return e.find(r=>vl(r)&&r[0]===t)}function da(e,t){return e.filter(r=>vl(r)&&r[0]===t)}function un(e,t,r=0){let i=Number(Rf(e?.[t]));return Number.isFinite(i)?i:r}function Rf(e){return e&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof Float64Array)?e.quoted:typeof e=="string"||typeof e=="number"?e:void 0}function Ni(e,t,r=""){let i=Rf(e?.[t]);return typeof i=="string"?i:typeof i=="number"?String(i):r}function gn(e,t){let r=e?ki(e,t):void 0;if(!(!r||r.length<3))return[un(r,1),un(r,2)]}function n0(e,t,r){let i=ki(ki(e??[],t)??[],"xyz");return i?[un(i,1,r[0]),un(i,2,r[1]),un(i,3,r[2])]:r}function Hw(e){let t=e?ki(e,"pts"):void 0;if(!t)return[];let r=t[1];if(r instanceof Float64Array){let i=[];for(let n=0;n<r.length;n+=2)i.push([r[n],r[n+1]]);return i}return da(t,"xy").map(i=>[un(i,1),un(i,2)])}function vu(e,t){return Ni(ki(e,"uuid"),1,Ni(ki(e,"tstamp"),1,t))}function xu(e,t="F.Cu"){return Ni(ki(e,"layer"),1,Ni(ki(e,"layers"),1,t))}function Gw(e,t){return Ni(da(e,"property").find(r=>Ni(r,1).toLowerCase()===t.toLowerCase()),2)}function b3(e,t,r){let i=e[0],n=-r*Math.PI/180,s=Math.cos(n),a=Math.sin(n);return[t[0]+i*s-e[1]*a,t[1]+i*a+e[1]*s]}function Ww(e,t,r){let[i,n]=e,[s,a]=t,[o,l]=r,c=2*(i*(a-l)+s*(l-n)+o*(n-a));if(Math.abs(c)<1e-9)return null;let u=((i*i+n*n)*(a-l)+(s*s+a*a)*(l-n)+(o*o+l*l)*(n-a))/c,d=((i*i+n*n)*(o-s)+(s*s+a*a)*(i-o)+(o*o+l*l)*(s-i))/c,f=Math.atan2(n-d,i-u),y=Math.atan2(a-d,s-u),b=Math.atan2(l-d,o-u),x=Math.PI*2,g=M=>(M%x+x)%x,v=g(y-f),_=g(b-f),E=v<=_?_:_-x;return{center:[u,d],radius:Math.hypot(i-u,n-d),sweep:E,startAngle:f}}function Xw(e,t,r){let i=Ww(e,t,r);if(!i)return[e,r];let{steps:n}=zw(i.radius,i.sweep);return Array.from({length:n+1},(s,a)=>{let o=i.startAngle+i.sweep*a/n;return[i.center[0]+i.radius*Math.cos(o),i.center[1]+i.radius*Math.sin(o)]})}function w3(e,t){let r=Math.hypot(t[0]-e[0],t[1]-e[1]);return Array.from({length:65},(i,n)=>{let s=Math.PI*2*n/64;return[e[0]+r*Math.cos(s),e[1]+r*Math.sin(s)]})}function Yw(e,t,r,i){let n=Ni(e,0),s=xu(e,"Dwgs.User"),a=ki(e,"stroke"),o=un(ki(a??e,"width"),1,.12),l=r??(d=>d),c,u;if(n.endsWith("_line")){let d=gn(e,"start"),f=gn(e,"end");if(!d||!f)return null;c="line",u=[l(d),l(f)]}else if(n.endsWith("_arc")){let d=gn(e,"start"),f=gn(e,"mid"),y=gn(e,"end");if(!d||!f||!y)return null;c="arc",u=Xw(d,f,y).map(l)}else if(n.endsWith("_circle")){let d=gn(e,"center"),f=gn(e,"end");if(!d||!f)return null;c="circle",u=w3(d,f).map(l)}else if(n.endsWith("_rect")){let d=gn(e,"start"),f=gn(e,"end");if(!d||!f)return null;c="rect",u=[l(d),l([f[0],d[1]]),l(f),l([d[0],f[1]]),l(d)]}else if(n.endsWith("_poly"))c="poly",u=Hw(e).map(l),u.length>2&&u.push(u[0]);else return null;return{id:t,type:c,points:u,layer:s,width:o,ref:i}}function xl(e,t){return Math.hypot(e[0]-t[0],e[1]-t[1])<=y3}function bu(e){let t=0;for(let r=0;r<e.length-1;r+=1)t+=e[r][0]*e[r+1][1]-e[r+1][0]*e[r][1];return t/2}function qw(e,t="Edge.Cuts"){let r=[],i=[];for(e.filter(n=>n.layer===t).forEach(n=>{let s=n.points;s.length>2&&xl(s[0],s[s.length-1])?r.push(s):s.length>1&&i.push([...s])});i.length;){let n=i.shift(),s=!0;for(;s&&!xl(n[0],n[n.length-1]);){s=!1;for(let a=0;a<i.length;a+=1){let o=i[a];if(xl(n[n.length-1],o[0]))n.push(...o.slice(1));else if(xl(n[n.length-1],o[o.length-1]))n.push(...o.slice(0,-1).reverse());else if(xl(n[0],o[o.length-1]))n.unshift(...o.slice(0,-1));else if(xl(n[0],o[0]))n.unshift(...o.slice(1).reverse());else continue;i.splice(a,1),s=!0;break}}n.length>2&&xl(n[0],n[n.length-1])&&(n[n.length-1]=n[0],r.push(n))}return r.sort((n,s)=>Math.abs(bu(s))-Math.abs(bu(n)))}function _3(e){let t=`${e.name} ${e.userName??""}`.trim().toLowerCase();return/rigid[ ._-]*flex/.test(t)?null:/(^|[ ._-])bend(?:[ ._-]|\d|$)/.test(t)?"bend":/(^|[ ._-])stiffener(?:[ ._-]|\d|$)/.test(t)?"stiffener":/(^|[ ._-])transition(?:[ ._-]|\d|$)/.test(t)?"transition":/(^|[ ._-])flex(?:ible)?(?:[ ._-]*(?:region|outline|area))?(?:[ ._-]|\d|$)/.test(t)?"flex":/(^|[ ._-])rigid(?:[ ._-]*(?:region|outline|area))?(?:[ ._-]|\d|$)/.test(t)?"rigid":null}function Kw(e,t){let r=t==="r"||t==="radius"?/(?:^|[ _.-])(?:r|radius)\s*=?\s*(-?\d+(?:\.\d+)?)\s*(?:mm)?(?:$|[ _.-])/i:/(?:^|[ _.-])(?:a|angle)\s*=?\s*(-?\d+(?:\.\d+)?)\s*(?:deg)?(?:$|[ _.-])/i,i=Number(e.match(r)?.[1]);return Number.isFinite(i)?i:void 0}function Zw(e){if(!e.length)return{minX:0,minY:0,maxX:100,maxY:70};let t=Vw(e.map(i=>i[0])),r=Vw(e.map(i=>i[1]));return{minX:t.minimum,minY:r.minimum,maxX:t.maximum,maxY:r.maximum}}function E3(e,t,r={}){let i=t||x3(v3(e));if(i[0]!=="kicad_pcb")throw new Error("The selected file is not a KiCad PCB document.");let n=[],s=[],a=[],o=[],l=[],c=[],u=new Set,d=[],f=new Set,y=[],b=[],x={};for(let Pe of i)vl(Pe)&&Pe[0]==="net"&&(x[Ni(Pe,1)]=Ni(Pe,2));let g=Pe=>{let ue=ki(Pe,"net"),Te=Ni(ue,1),de=Ni(ue,2)||Ni(ki(Pe,"net_name"),1)||x[Te]||(/^\d+$/.test(Te)?"":Te);return de&&(x[Te||de]=de),de||void 0},v=-1;for(let Pe of i){if(!vl(Pe)||!Pe.length)continue;let ue=Ni(Pe,0);if((ue==="footprint"||ue==="module")&&v++,ue==="layers")Pe.slice(1).filter(vl).forEach(Te=>{let de=Ni(Te,1);de&&!de.includes("*")&&y.push({id:un(Te,0,y.length),name:de,kind:Ni(Te,2)||"user",userName:Ni(Te,3)||void 0}),de.endsWith(".Cu")&&!de.includes("*")&&f.add(de)});else if(ue==="setup"){let Te=ki(Pe,"stackup");da(Te??[],"layer").forEach(de=>{let Ie=Ni(de,1);if(!Ie)return;let Re=ki(de,"thickness"),Be=ki(de,"epsilon_r"),Se=ki(de,"loss_tangent");b.push({name:Ie,type:Ni(ki(de,"type"),1,"unknown"),thickness:Re?un(Re,1):void 0,material:Ni(ki(de,"material"),1)||void 0,epsilonR:Be?un(Be,1):void 0,lossTangent:Se?un(Se,1):void 0}),Ie.endsWith(".Cu")&&f.add(Ie)})}else if(ue==="segment"||ue==="arc"){let Te=un(ki(Pe,"width"),1,.25),de=xu(Pe),Ie=g(Pe),Re=vu(Pe,`track-${n.length+1}`);if(ue==="arc"){let Se=gn(Pe,"start"),U=gn(Pe,"mid"),ie=gn(Pe,"end"),Ae=Se&&U&&ie?Ww(Se,U,ie):null;Ae&&zw(Ae.radius,Ae.sweep).limited&&s.length<100&&s.push("Saved copper arc "+Re+" exceeds the 512-segment/5 \xC2\xB5m chord budget and is shown approximately.")}let Be=ue==="arc"?Xw(gn(Pe,"start")??[0,0],gn(Pe,"mid")??[0,0],gn(Pe,"end")??[0,0]):[gn(Pe,"start"),gn(Pe,"end")].filter(Boolean);for(let Se=0;Se<Be.length-1;Se+=1)n.push({id:Be.length>2?`${Re}:${Se}`:Re,start:Be[Se],end:Be[Se+1],width:Te,layer:de,net:Ie});f.add(de)}else if(ue==="via"){let Te=gn(Pe,"at");if(!Te)continue;let de=ki(Pe,"layers")?.slice(1).map(Rf).filter(Ie=>typeof Ie=="string")??["F.Cu","B.Cu"];a.push({id:vu(Pe,`via-${a.length+1}`),at:Te,size:un(ki(Pe,"size"),1,.8),drill:un(ki(Pe,"drill"),1,.4),layers:de,net:g(Pe)})}else if(ue==="zone"){let Te=xu(Pe),de=da(Pe,"filled_polygon");(de.length?de:da(Pe,"polygon")).forEach((Ie,Re)=>{let Be=ki(Ie,"pts"),Se=Be?.[1]instanceof Float64Array?Be[1].length/2:0;for(let Ue of Be||[])vl(Ue)&&Ni(Ue,0)==="xy"&&Se++;if(Se<3)return;let U=xu(Ie,Te),ie=g(Pe);if(f.add(U),u.add(U),r.zonePoints===!1)return;let Ae=Hw(Ie);c.push({id:`${vu(Pe,`zone-${c.length+1}`)}:${Re}`,points:Ae,layer:U,net:ie})})}else if(ue.startsWith("gr_")){let Te=Yw(Pe,vu(Pe,`drawing-${d.length+1}`));Te&&d.push(Te)}else if(ue==="footprint"||ue==="module"){let Te=gn(Pe,"at")??[0,0],de=ki(Pe,"at"),Ie=un(de,3),Re=xu(Pe),Be=Re.startsWith("B."),Se=ye=>b3(ye,Te,Ie),U=Gw(Pe,"Reference")||Ni(da(Pe,"fp_text").find(ye=>Ni(ye,1)==="reference"),2)||`REF${l.length+1}`,ie=Gw(Pe,"Value")||Ni(da(Pe,"fp_text").find(ye=>Ni(ye,1)==="value"),2)||"",Ae=[],Ue=[];da(Pe,"pad").forEach((ye,dt)=>{let xt=gn(ye,"at")??[0,0];Ue.push(xt);let Dt=ki(ye,"size"),We=ki(ye,"layers")?.slice(1).map(Rf).filter(F=>typeof F=="string")??[Re],mt=We.includes("F.Cu")||We.includes("*.Cu")?Be?"B.Cu":"F.Cu":We.find(F=>F.endsWith(".Cu"))??Re,it=ki(ye,"drill"),st=Ni(it,1)==="oval"?un(it,2):un(it,1),oe={id:jw(ye,U,v,dt),name:Ni(ye,1,String(dt+1)),at:Se(xt),width:un(Dt,1,1),height:un(Dt,2,1),rotation:un(ki(ye,"at"),3),shape:Ni(ye,3,"rect"),drill:st,layers:We,layer:mt,net:g(ye),ref:U};o.push(oe),Ae.push(oe),We.filter(F=>F.endsWith(".Cu")&&!F.includes("*")).forEach(F=>f.add(F))});for(let ye of["fp_line","fp_arc","fp_circle","fp_rect","fp_poly"])da(Pe,ye).forEach((dt,xt)=>{let Dt=Yw(dt,`${U}:${ye}:${xt}`,Se,U);Dt&&d.push(Dt)});let Ge=Zw(Ue),nt=Ue.length?Math.max(Ge.maxX-Ge.minX+2.5,2.5):5,Qe=Ue.length?Math.max(Ge.maxY-Ge.minY+2.5,2.5):5,ct=ki(Pe,"model");l.push({id:vu(Pe,`component-${U}`),ref:U,value:ie,library:Ni(Pe,1),at:Te,width:nt,height:Qe,rotation:Ie,layer:Re,model:!!ct,modelPath:Ni(ct,1),modelPaths:da(Pe,"model").map(ye=>Ni(ye,1)).filter(Boolean),modelOffset:n0(ct,"offset",[0,0,0]),modelScale:n0(ct,"scale",[1,1,1]),modelRotation:n0(ct,"rotate",[0,0,0])}),f.add(Re==="B.Cu"?"B.Cu":"F.Cu")}}let _=qw(d),E=_[0]??n.flatMap(Pe=>[Pe.start,Pe.end]).concat(o.map(Pe=>Pe.at)),M=Zw(E),P=new Set(y.map(Pe=>Pe.name)),k=Math.max(-1,...y.map(Pe=>Pe.id))+1;[...n.map(Pe=>Pe.layer),...o.flatMap(Pe=>Pe.layers),...u,...d.map(Pe=>Pe.layer)].forEach(Pe=>{!Pe||Pe.includes("*")||P.has(Pe)||(P.add(Pe),y.push({id:k++,name:Pe,kind:Pe.endsWith(".Cu")?"signal":"user"}))});let z=g3(y,f,b.map(Pe=>Pe.name)),D=[],I=[];y.forEach(Pe=>{let ue=_3(Pe);if(!ue)return;let Te=Pe.userName||Pe.name;if(ue==="bend"){d.filter(de=>de.layer===Pe.name&&de.points.length>=2).forEach((de,Ie)=>{I.push({id:`bend:${de.id}`,name:`${Te} ${Ie+1}`,points:de.points,sourceLayer:Pe.name,radiusMm:Kw(Te,"radius"),angleDeg:Kw(Te,"angle")})});return}qw(d,Pe.name).forEach((de,Ie)=>{D.push({id:`region:${Pe.id}:${Ie}`,name:`${Te}${Ie?` ${Ie+1}`:""}`,kind:ue,outline:de,sourceLayer:Pe.name,source:"kicad-user-layer"})})});let L=_[0]??[],Z=Math.abs(bu(L)),se=D.filter(Pe=>Pe.kind==="flex").reduce((Pe,ue)=>Pe+Math.abs(bu(ue.outline)),0),ce=se>0,fe=D.some(Pe=>Pe.kind==="rigid"),ze=ce?!fe&&Z>0&&se>=Z*.92?"flex":"rigid-flex":"rigid",Fe=[...D];return L.length&&ze!=="flex"&&!Fe.some(Pe=>Pe.kind==="rigid"&&Math.abs(bu(Pe.outline))>=Z*.92)&&Fe.unshift({id:"region:implicit-rigid-board",name:"Rigid board",kind:"rigid",outline:L,sourceLayer:"Edge.Cuts",source:"implicit-board-outline"}),{width:Math.max(M.maxX-M.minX,1),height:Math.max(M.maxY-M.minY,1),bounds:M,outlineLoops:_,tracks:n,geometryWarnings:s,vias:a,pads:o,components:l,zones:c,drawings:d,layers:z,layerDefinitions:y,stackup:b,nets:x,technology:ze,regions:Fe,bendLines:I}}var nF=ee(he()),$w=e=>e&&(e.type==="Component"||typeof e.library=="string"),Cc=e=>{for(let t=e;t;t=t.parent)if(!t.visible)return!1;return!0},s0=(e,t)=>{if(typeof e!="string"||!e||e.length>128||/[\x00-\x1f\x7f]/.test(e))throw new TypeError("Choose a bounded "+t+".");return e},Jw={top:[0,0,1],bottom:[0,0,-1],front:[0,-1,0],back:[0,1,0],left:[-1,0,0],right:[1,0,0]};function S3(e,t,r){let i=t?.getAttribute?.("position"),n=t?.index;if(!i||i.itemSize<3||t.morphAttributes?.position?.length)throw new Error("Demo faces require a static triangle mesh.");let s=Math.floor((n?n.count:i.count)/3);if(!s||s>5e4)throw new Error("Selected mesh exceeds the 50,000-triangle face-selection budget.");let a=Math.ceil((t.drawRange?.start||0)/3),o=Math.min(s,Math.floor(((t.drawRange?.start||0)+(Number.isFinite(t.drawRange?.count)?t.drawRange.count:s*3))/3));if(!Number.isInteger(r)||r<a||r>=o)throw new Error("Choose a visible triangle face.");let l=U=>new e.Vector3().fromBufferAttribute(i,n?n.getX(U):U),c=[l(r*3),l(r*3+1),l(r*3+2)],u=new e.Vector3().subVectors(c[1],c[0]).cross(new e.Vector3().subVectors(c[2],c[0]));if(u.lengthSq()<1e-20)throw new Error("The selected triangle has no usable planar area.");u.normalize(),t.computeBoundingBox();let d=t.boundingBox.getSize(new e.Vector3).length(),f=Math.max(1e-7,d*1e-7),y=u.dot(c[0]),b=t.groups||[];if(b.length>256)throw new Error("Selected mesh exceeds the 256 material-group face budget.");let x=new Int32Array(s);x.fill(-1);for(let U of b){if(!Number.isInteger(U.start)||!Number.isInteger(U.count)||U.start<0||U.count<0||U.start%3||U.count%3||!Number.isInteger(U.materialIndex)||U.materialIndex<0||U.materialIndex>1e6)throw new Error("Unsupported triangle material groups.");for(let ie=U.start/3;ie<Math.min(s,(U.start+U.count)/3);ie++){if(x[ie]!==-1)throw new Error("Overlapping material groups make the selected face ambiguous.");x[ie]=U.materialIndex}}let g=U=>x[U],v=g(r);if(b.length&&v===-1)throw new Error("The selected face has no supported material group.");let _=U=>[U.x,U.y,U.z].map(ie=>Math.round(ie/f)).join(","),E=(U,ie)=>U<ie?U+"|"+ie:ie+"|"+U,M=new Map,P=new Map,k=new e.Vector3,z=new e.Vector3;for(let U=a;U<o;U++){if(g(U)!==v)continue;let ie=[l(U*3),l(U*3+1),l(U*3+2)];if(ie.some(nt=>!Number.isFinite(nt.x)||!Number.isFinite(nt.y)||!Number.isFinite(nt.z)||Math.abs(u.dot(nt)-y)>f))continue;let Ae=k.subVectors(ie[1],ie[0]).cross(z.subVectors(ie[2],ie[0]));if(Ae.lengthSq()<1e-20||Ae.normalize().dot(u)<.99999)continue;let Ue=ie.map(_),Ge=[E(Ue[0],Ue[1]),E(Ue[1],Ue[2]),E(Ue[2],Ue[0])];M.set(U,{points:ie,edges:Ge});for(let nt of Ge){let Qe=P.get(nt)||[];Qe.push(U),P.set(nt,Qe)}}let D=[r],I=new Set(D),L=new Set,Z=new Set;for(let U=0;U<D.length;U++){let ie=D[U],Ae=M.get(ie);if(Ae){L.add(ie);for(let Ue of Ae.edges)if(!Z.has(Ue)){Z.add(Ue);for(let Ge of P.get(Ue)||[])I.has(Ge)||(I.add(Ge),D.push(Ge))}}}if(!L.size)throw new Error("No connected planar face was found.");let se=new e.Vector3(Math.abs(u.x)<.9?1:0,Math.abs(u.x)<.9?0:1,0);se.addScaledVector(u,-se.dot(u)).normalize();let ce=new e.Vector3().crossVectors(u,se).normalize(),fe=1/0,ze=-1/0,Fe=1/0,Pe=-1/0,ue=0,Te=[];for(let U of L){let ie=M.get(U).points;ue+=new e.Vector3().subVectors(ie[1],ie[0]).cross(new e.Vector3().subVectors(ie[2],ie[0])).length()/2;for(let Ae of ie){let Ue=Ae.dot(se),Ge=Ae.dot(ce);fe=Math.min(fe,Ue),ze=Math.max(ze,Ue),Fe=Math.min(Fe,Ge),Pe=Math.max(Pe,Ge),Te.push(Ae)}}let de=ze-fe,Ie=Pe-Fe;if(!(de>f&&Ie>f&&ue>f*f))throw new Error("The selected face is too small for a display.");let Re=new Float32Array(Te.length*3),Be=new Float32Array(Te.length*2);Te.forEach((U,ie)=>{Re.set([U.x,U.y,U.z],ie*3),Be.set([(U.dot(se)-fe)/de,(U.dot(ce)-Fe)/Ie],ie*2)});let Se=u.clone().multiplyScalar(y).addScaledVector(se,(fe+ze)/2).addScaledVector(ce,(Fe+Pe)/2);return{positions:Re,uvs:Be,normal:u,u:se,v:ce,center:Se,width:de,height:Ie,area:ue,triangles:L.size,faceIndex:Math.min(...L),faceIndices:[...L]}}function M3(e,{scene:t,objects:r,document:i=globalThis.document,invalidate:n=()=>{},onError:s=()=>{}}){if(!t?.add||typeof r!="function"||!i?.createElement)throw new TypeError("Choose a 3D scene, saved component meshes and document.");let a=new e.Group;a.name="Scripted demo surfaces",t.add(a);let o="demo-face-"+Math.random().toString(36).slice(2)+"-",l=new Map,c=new Map,u=0,d=!1,f=null,y=null,b=0,x=0,g=()=>{if(d)throw new Error("Demo surfaces have been disposed.")};function v(U,ie){U.updateWorldMatrix(!0,!1);let Ae=U.matrixWorld.clone();if(U.isInstancedMesh){if(!Number.isInteger(ie)||ie<0||ie>=U.count)return null;let Ue=new e.Matrix4;if(U.getMatrixAt(ie,Ue),Math.abs(Ue.determinant())<1e-15)return null;Ae.multiply(Ue)}return Math.abs(Ae.determinant())<1e-15?null:Ae}function _(U,ie){return U?.isInstancedMesh?U.userData.records?.[ie]:U?.userData.record}function E(U,ie,Ae){if(!r().includes(U)||!Cc(U)||U.isSkinnedMesh)throw new Error("Choose a visible static component face.");let Ue=_(U,ie),Ge=v(U,ie);if(!$w(Ue)||!Ge)throw new Error("Choose a visible component body, not a pad or board surface.");let nt=S3(e,U.geometry,Ae),Qe=nt.normal.clone().applyMatrix3(new e.Matrix3().getNormalMatrix(Ge)).normalize(),ct=new e.Vector3().applyMatrix4(Ge),ye=nt.u.clone().multiplyScalar(nt.width).applyMatrix4(Ge).sub(ct),dt=nt.v.clone().multiplyScalar(nt.height).applyMatrix4(Ge).sub(ct);return{object:U,instanceId:ie,record:Ue,geometry:U.geometry,patch:nt,normal:Qe,width:ye.length(),height:dt.length(),key:U.uuid+":"+ie+":"+nt.faceIndex}}function M(U){let ie=[...l.values()].reduce((Ue,Ge)=>Ue+Ge.patch.triangles,0);for(;l.size>=128||ie+U.patch.triangles>1e5;){let Ue=[...l].find(([,Ge])=>![...c.values()].some(nt=>nt.face===Ge));if(!Ue)throw new Error("Selected demo faces exceed the geometry budget.");ie-=Ue[1].patch.triangles,l.delete(Ue[0])}let Ae=o+ ++u;return U.token=Ae,l.set(Ae,U),P(U)}function P(U){let ie=v(U.object,U.instanceId);return ie?Object.freeze({token:U.token,shape:"face",uuid:String(U.record.uuid||U.record.id||""),reference:String(U.record.ref||""),center:U.patch.center.clone().applyMatrix4(ie).toArray(),normal:U.patch.normal.clone().applyMatrix3(new e.Matrix3().getNormalMatrix(ie)).normalize().toArray(),up:U.patch.v.clone().transformDirection(ie).toArray(),right:U.patch.u.clone().transformDirection(ie).toArray(),width:U.width,height:U.height,triangles:U.patch.triangles}):null}function k(U){if(g(),!U||!Number.isInteger(U.faceIndex))throw new Error("Select a component triangle face.");return M(E(U.object,U.instanceId,U.faceIndex))}function z(U){if(!U||typeof U!="object"||!Jw[U.face||"top"])throw new TypeError("Choose a saved component and top/bottom/front/back/left/right face.");let ie=U.uuid===void 0?null:s0(U.uuid,"component UUID"),Ae=U.reference===void 0?null:s0(U.reference,"component reference");if(!ie&&!Ae)throw new TypeError("A demo face needs a component UUID or unique reference.");let Ue=[],Ge=new Set,nt=0;for(let Qe of r()){let ct=Qe.userData.records||[Qe.userData.record];for(let ye=0;ye<ct.length;ye++){if(++nt>2e5)throw new Error("Component face lookup exceeds its record budget.");let dt=ct[ye];if(!$w(dt)||ie&&ie!==(dt.uuid||dt.id)||Ae&&Ae!==dt.ref)continue;let xt=Qe.isInstancedMesh?ye:void 0;if(!Cc(Qe)||!v(Qe,xt))continue;let Dt=String(dt.uuid||dt.id||"")+"|"+String(dt.ref||"")+"|"+JSON.stringify(dt.at||[]);Ge.add(Dt),Ue.push({object:Qe,instanceId:xt})}}if(Ge.size!==1)throw new Error("The component anchor is absent or ambiguous.");return Ue}function D(U){let ie=z(U),Ae=new e.Vector3(...Jw[U.face||"top"]),Ue=null,Ge=25e4;for(let nt of ie){let Qe=nt.object.geometry,ct=Qe?.getAttribute?.("position"),ye=Qe?.index;if(!ct||nt.object.isSkinnedMesh||Qe.morphAttributes?.position?.length)continue;let dt=Math.floor((ye?ye.count:ct.count)/3);if(dt>5e4)throw new Error("Selected mesh exceeds the 50,000-triangle face-selection budget.");let xt=v(nt.object,nt.instanceId),Dt=new e.Matrix3().getNormalMatrix(xt),We=new Set,mt=Math.ceil((Qe.drawRange?.start||0)/3),it=Math.min(dt,Math.floor(((Qe.drawRange?.start||0)+(Number.isFinite(Qe.drawRange?.count)?Qe.drawRange.count:dt*3))/3));for(let st=mt;st<it;st++){if(We.has(st))continue;let oe=new e.Vector3().fromBufferAttribute(ct,ye?ye.getX(st*3):st*3),F=new e.Vector3().fromBufferAttribute(ct,ye?ye.getX(st*3+1):st*3+1),le=new e.Vector3().fromBufferAttribute(ct,ye?ye.getX(st*3+2):st*3+2);if(F.sub(oe).cross(le.sub(oe)).normalize().applyMatrix3(Dt).normalize().dot(Ae)<.9999)continue;if((Ge-=dt)<0)throw new Error("Automatic face selection exceeds its triangle-work budget. Select an actual face manually.");let pe=E(nt.object,nt.instanceId,st);for(let ht of pe.patch.faceIndices)We.add(ht);let Le=v(pe.object,pe.instanceId),He=new e.Vector3().applyMatrix4(Le),at=pe.patch.u.clone().multiplyScalar(pe.patch.width).applyMatrix4(Le).sub(He),rt=pe.patch.v.clone().multiplyScalar(pe.patch.height).applyMatrix4(Le).sub(He);pe.worldArea=pe.patch.area*at.cross(rt).length()/(pe.patch.width*pe.patch.height),pe.depth=pe.patch.center.clone().applyMatrix4(Le).dot(Ae),(!Ue||pe.depth>Ue.depth+1e-5||Math.abs(pe.depth-Ue.depth)<=1e-5&&pe.worldArea>Ue.worldArea)&&(Ue=pe)}}if(!Ue)throw new Error("This component has no supported planar face in that direction. Select an actual face instead.");return M(Ue)}function I(U){let ie=U.face||U.anchor&&D(U.anchor),Ae=typeof ie=="string"?ie:ie?.token,Ue=l.get(Ae);if(!Ue)throw new Error("The selected face belongs to another or closed 3D view. Select it again.");if(!r().includes(Ue.object)||!Cc(Ue.object)||Ue.object.geometry!==Ue.geometry||!v(Ue.object,Ue.instanceId))throw new Error("The selected source geometry is no longer available. Select it again.");return Ue}function L(U,ie,Ae,Ue,Ge={}){if(typeof f=="function")try{f({id:U.id,type:ie,...ie==="change"?{value:U.value}:{},...Ue?{uv:{x:Ue.x,y:Ue.y}}:{},source:"pointer",originalEvent:Ae,...Ge})}catch(nt){f=null;try{s(nt)}catch{}}}function Z(U){let ie=U.width??(U.kind==="led"?32:128),Ae=U.height??(U.kind==="led"?32:U.kind==="button"?64:128);if(!Number.isInteger(ie)||!Number.isInteger(Ae)||ie<1||Ae<1||ie>1024||Ae>1024)throw new TypeError("Demo canvases need integer dimensions from 1 to 1024.");return{width:ie,height:Ae}}function se(U){if(U.kind==="led"&&!U.canvas){U.material.color.set(U.color).multiplyScalar(U.on?U.brightness:.025);return}let ie=U.canvas.getContext("2d");if(!ie)throw new Error("Canvas drawing is unavailable.");U.kind!=="display"&&(ie.clearRect(0,0,U.canvas.width,U.canvas.height),U.kind==="led"?(ie.fillStyle=U.color,ie.fillRect(0,0,U.canvas.width,U.canvas.height),U.material.color.setScalar(U.on?U.brightness:.025)):(ie.fillStyle=U.pressed?"#77d4df":"#182f3e",ie.fillRect(0,0,U.canvas.width,U.canvas.height),ie.fillStyle=U.pressed?"#10202c":"#e1eaf3",ie.textAlign="center",ie.textBaseline="middle",ie.font="600 "+Math.max(9,Math.round(U.canvas.height*.22))+"px system-ui",ie.fillText(U.kind==="knob"?String(U.value):U.label,U.canvas.width/2,U.canvas.height/2,U.canvas.width-8)),U.texture.needsUpdate=!0)}function ce(U){if(U.bindings){let Ue=!1;for(let Ge of U.bindings){let nt=v(Ge.object,Ge.instanceId);Ge.mesh.visible=r().includes(Ge.object)&&Ge.object.geometry===Ge.geometry&&Cc(Ge.object)&&!!nt,Ge.mesh.visible&&(Ge.mesh.matrix.copy(nt),Ge.mesh.matrixWorldNeedsUpdate=!0,Ue=!0)}return Ue}let ie=U.face,Ae=v(ie.object,ie.instanceId);if(U.mesh.visible=r().includes(ie.object)&&ie.object.geometry===ie.geometry&&Cc(ie.object)&&!!Ae,U.mesh.visible){let Ue=ie.patch.normal.clone().applyMatrix3(new e.Matrix3().getNormalMatrix(Ae)).normalize(),Ge=Math.max(1e-5,Math.min(.006,Math.min(ie.width,ie.height)*.002));U.mesh.matrix.copy(Ae),U.mesh.matrix.elements[12]+=Ue.x*Ge,U.mesh.matrix.elements[13]+=Ue.y*Ge,U.mesh.matrix.elements[14]+=Ue.z*Ge,U.mesh.matrixWorldNeedsUpdate=!0}return!U.mesh.visible&&y?.entry===U&&Ie("cancel",null),U.mesh.visible}function fe(U){if(!(!c.has(U.id)||c.get(U.id)!==U)&&(y?.entry===U&&Ie("cancel",null),c.get(U.id)===U)){c.delete(U.id),b-=U.pixels,x-=U.triangles;for(let ie of U.meshes||[U.mesh])ie.removeFromParent();U.texture?.dispose(),U.material.dispose(),U.bindings||U.mesh.geometry.dispose(),n()}}function ze(U){if(typeof U!="string"||U.length>64||!/^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(U)&&!Object.hasOwn(e.Color.NAMES,U.toLowerCase()))throw new TypeError("Choose a hex or named LED color.");return"#"+new e.Color(U).getHexString()}function Fe(U,ie={}){let Ae={on:ie.on===void 0?U.on:!!ie.on,color:ie.color===void 0?U.color:ze(ie.color),brightness:ie.brightness===void 0?U.brightness:ie.brightness};if(!Number.isFinite(Ae.brightness)||Ae.brightness<0||Ae.brightness>1)throw new TypeError("Choose LED brightness from 0 to 1.");Object.assign(U,Ae),se(U),n()}function Pe(U){let ie=new e.Box3;for(let Ge of U.bindings){let nt=v(Ge.object,Ge.instanceId);nt&&(Ge.geometry.boundingBox||Ge.geometry.computeBoundingBox(),ie.union(Ge.geometry.boundingBox.clone().applyMatrix4(nt)))}if(ie.isEmpty())return null;let Ae=ie.getSize(new e.Vector3),Ue=U.bindings[0].record;return{shape:"component",uuid:String(Ue.uuid||Ue.id||""),reference:String(Ue.ref||""),center:ie.getCenter(new e.Vector3).toArray(),normal:null,width:Ae.x,height:Ae.y,triangles:U.triangles}}function ue(U,ie){let Ae=z(ie.anchor),Ue=c.get(U),Ge=Ae.reduce((ye,dt)=>{let xt=dt.object.geometry;if(dt.object.isSkinnedMesh||xt.morphAttributes?.position?.length)throw new Error("LED body binding requires static geometry.");return ye+Math.floor((xt.index?.count||xt.getAttribute("position")?.count||0)/3)},0);if(!Ge||Ge>5e4||c.size-(Ue?1:0)>=64||x-(Ue?.triangles||0)+Ge>1e5)throw new Error("LED component geometry exceeds the demo surface budget.");let nt=ze(ie.color||"#59f3a5");if(ie.brightness!==void 0&&(!Number.isFinite(ie.brightness)||ie.brightness<0||ie.brightness>1))throw new TypeError("Choose LED brightness from 0 to 1.");let Qe=new e.MeshBasicMaterial({color:16777215,depthTest:!0,depthWrite:!0,toneMapped:!1,polygonOffset:!0,polygonOffsetFactor:-1,polygonOffsetUnits:-2}),ct={id:U,kind:"led",bindings:Ae,material:Qe,pixels:0,triangles:Ge,on:!1,brightness:1,color:nt};for(let ye of Ae)ye.geometry=ye.object.geometry,ye.record=_(ye.object,ye.instanceId),ye.mesh=new e.Mesh(ye.geometry,Qe),ye.mesh.matrixAutoUpdate=!1,ye.mesh.userData.demoSurface=U,ye.mesh.renderOrder=10;ct.meshes=Ae.map(ye=>ye.mesh),Fe(ct,ie),Ue&&fe(Ue),c.set(U,ct),x+=Ge;for(let ye of ct.meshes)a.add(ye);return ce(ct),n(),{get face(){return Pe(ct)},getFace(){return Pe(ct)},setLED(ye){if(g(),c.get(U)!==ct)throw new Error("LED surface is closed.");Fe(ct,ye)},update(){return g(),ce(ct)},setValue(){throw new Error("An LED uses setLED().")},isAvailable(){return!d&&c.get(U)===ct&&ce(ct)},dispose(){fe(ct)}}}function Te(U,ie={}){if(g(),s0(U,"demo surface ID"),!["led","display","button","knob"].includes(ie.kind))throw new TypeError("Choose an LED, display, button or knob.");if(ie.kind==="led"&&!ie.face&&ie.anchor&&!ie.anchor.face)return ue(U,ie);let Ae=I(ie),Ue=c.get(U),Ge=Z(ie),nt=Ge.width*Ge.height;if(c.size-(Ue?1:0)>=64||b-(Ue?.pixels||0)+nt>4194304||x-(Ue?.triangles||0)+Ae.patch.triangles>1e5)throw new Error("Demo surfaces exceed their canvas or geometry budget.");if([...c.values()].some(le=>le!==Ue&&le.face?.key===Ae.key))throw new Error("This geometry face already has a demo surface.");let Qe=ie.kind==="led"?ze(ie.color||"#59f3a5"):"#59f3a5";if(ie.brightness!==void 0&&(!Number.isFinite(ie.brightness)||ie.brightness<0||ie.brightness>1))throw new TypeError("Choose LED brightness from 0 to 1.");let ct=i.createElement("canvas");ct.width=Ge.width,ct.height=Ge.height;let ye=ie.kind==="display"?i.createElement("canvas"):ct;ye.width=Ge.width,ye.height=Ge.height;let dt=new e.CanvasTexture(ye);dt.colorSpace=e.SRGBColorSpace,dt.minFilter=e.LinearFilter,dt.magFilter=ie.mode==="matrix"?e.NearestFilter:e.LinearFilter,dt.generateMipmaps=!1;let xt=new e.BufferGeometry;xt.setAttribute("position",new e.BufferAttribute(Ae.patch.positions.slice(),3)),xt.setAttribute("uv",new e.BufferAttribute(Ae.patch.uvs.slice(),2)),xt.computeVertexNormals();let Dt=new e.MeshBasicMaterial({map:dt,color:16777215,side:e.FrontSide,depthTest:!0,depthWrite:!0,toneMapped:!1,polygonOffset:!0,polygonOffsetFactor:-1,polygonOffsetUnits:-2}),We=new e.Mesh(xt,Dt);We.matrixAutoUpdate=!1,We.userData.demoSurface=U,We.renderOrder=10;let mt=ie.min??0,it=ie.max??100,st=ie.step??1;if(![mt,it,st].every(Number.isFinite)||it<=mt||st<=0)throw dt.dispose(),Dt.dispose(),xt.dispose(),new TypeError("Choose a finite increasing knob range and positive step.");let oe=le=>Math.max(mt,Math.min(it,mt+Math.round((le-mt)/st)*st)),F={id:U,kind:ie.kind,face:Ae,canvas:ct,uploadCanvas:ye,texture:dt,material:Dt,mesh:We,pixels:nt,triangles:Ae.patch.triangles,min:mt,max:it,step:st,clamp:oe,value:oe(Number.isFinite(ie.value)?ie.value:mt),pressed:!1,color:Qe,on:!!ie.on,brightness:Number.isFinite(ie.brightness)?Math.max(0,Math.min(1,ie.brightness)):1,label:typeof ie.label=="string"?ie.label.slice(0,64):U};try{se(F)}catch(le){throw dt.dispose(),Dt.dispose(),xt.dispose(),le}return Ue&&fe(Ue),c.set(U,F),b+=nt,x+=Ae.patch.triangles,a.add(We),ce(F),n(),{canvas:ct,get face(){return P(Ae)},getFace(){return P(Ae)},update(){if(g(),c.get(U)!==F)throw new Error("Demo surface is closed.");let le=Z({width:ct.width,height:ct.height}),pe=le.width*le.height;if(b-F.pixels+pe>4194304)throw new Error("Demo surfaces exceed their canvas budget.");if(F.kind==="display"){let Le=ct.getContext("2d");if(!Le)throw new Error("Canvas drawing is unavailable.");try{Le.getImageData(0,0,1,1)}catch(at){let rt=new Error("Display graphics must be CORS-enabled and origin-clean before upload.");throw rt.cause=at,rt}let He=ye.getContext("2d");if(!He)throw new Error("Canvas upload is unavailable.");ye.width!==ct.width&&(ye.width=ct.width),ye.height!==ct.height&&(ye.height=ct.height),He.clearRect(0,0,ye.width,ye.height),He.drawImage(ct,0,0)}return b+=pe-F.pixels,F.pixels=pe,dt.needsUpdate=!0,n(),ce(F)},setLED(le={}){if(g(),F.kind!=="led"||c.get(U)!==F)throw new Error("Choose an active LED surface.");Fe(F,le)},setValue(le){if(g(),!Number.isFinite(le)||c.get(U)!==F)throw new TypeError("Choose a finite active control value.");return F.value=F.clamp(le),F.kind==="button"&&(F.pressed=!!F.value),se(F),n(),F.value},isAvailable(){return!d&&c.get(U)===F&&ce(F)},dispose(){fe(F)}}}function de(U){let ie=U?.object?.userData?.demoSurface&&c.get(U.object.userData.demoSurface);return ie&&Cc(U.object)&&(ie.mesh===U.object||ie.meshes?.includes(U.object))&&ce(ie)?ie:null}function Ie(U,ie){let Ae=y;return Ae?(y=null,Ae.entry.pressed=!1,se(Ae.entry),n(),L(Ae.entry,"release",ie,Ae.uv,{cancelled:U==="cancel"}),!0):!1}function Re(U,ie,Ae={}){if(d)return!1;if(ie==="release"||ie==="cancel")return!y||Ae.pointerId!==void 0&&Ae.pointerId!==y.pointerId?!1:Ie(ie,Ae);if(ie==="move"){if(!y||Ae.pointerId!==void 0&&Ae.pointerId!==y.pointerId)return!1;let Ge=y.entry;if(Ge.kind==="knob"&&Number.isFinite(Ae.clientY)){let nt=Ge.clamp(y.startValue+(y.startY-Ae.clientY)*Ge.step);nt!==Ge.value&&(Ge.value=nt,se(Ge),n(),L(Ge,"change",Ae,U?.uv||y.uv))}return!0}if(ie!=="press"||y)return!1;let Ue=de(U);return!Ue||Ue.kind==="led"?!1:(y={entry:Ue,pointerId:Ae.pointerId,startY:Number.isFinite(Ae.clientY)?Ae.clientY:0,startValue:Ue.value,uv:U.uv?{x:U.uv.x,y:U.uv.y}:void 0},Ue.pressed=!0,se(Ue),n(),L(Ue,"press",Ae,y.uv),!0)}function Be(){if(!d)for(let U of c.values())ce(U)}function Se(){if(!d){Ie("cancel",null);for(let U of[...c.values()])fe(U);d=!0,l.clear(),f=null,a.removeFromParent()}}return{selectFace:k,createSurface:Te,setInputHandler(U){if(d&&U===null){f=null;return}if(g(),U!==null&&typeof U!="function")throw new TypeError("Choose an input callback or null.");U===null&&Ie("cancel",null),f=U},getPickables(){return Be(),[...c.values()].flatMap(U=>U.meshes||[U.mesh]).filter(U=>U.visible)},getFace(U){let ie=c.get(U);return ie?ie.bindings?Pe(ie):P(ie.face):null},objects(){return this.getPickables()},isHit(U){return!!de(U)},pointer:Re,sync:Be,get hasActivePointer(){return!!y},dispose:Se}}function A3(e){let t=c=>{let u=e?.[c];if(!Array.isArray(u)||u.length!==3||!u.every(d=>typeof d=="number"&&Number.isFinite(d)&&Math.abs(d)<=1e7))throw new TypeError("Choose finite bounded 3D camera vectors.");return[...u]},r=t("position"),i=t("target"),n=t("up"),s=r.map((c,u)=>c-i[u]),a=Math.hypot(...s),o=Math.hypot(...n),l=[s[1]*n[2]-s[2]*n[1],s[2]*n[0]-s[0]*n[2],s[0]*n[1]-s[1]*n[0]];if(a<1e-4||o<1e-8||Math.hypot(...l)<a*o*1e-6)throw new TypeError("Choose a nondegenerate 3D camera direction and up vector.");return{position:r,target:i,up:n}}function Qw(e,t,r,i=1.1){if(!(e>0)||!Number.isFinite(e)||!(r>0)||!Number.isFinite(r)||!(t>0&&t<180))return null;let n=t*Math.PI/360,s=Math.atan(Math.tan(n)*r);return e*Math.max(1,i)/Math.sin(Math.min(n,s))}function e_(e,t,r,i,n=.85,s=[0,1,0]){if(!Array.isArray(e)||e.length!==3||e.some(g=>!Number.isFinite(g)||g<0)||!Array.isArray(t)||t.length!==3||t.some(g=>!Number.isFinite(g))||!Array.isArray(s)||s.length!==3||s.some(g=>!Number.isFinite(g))||Math.hypot(...s)<1e-10||!(i>0&&Number.isFinite(i))||!(r>0&&r<180)||!(n>0&&n<1))return null;let a=Math.hypot(...t);if(a<1e-10)return null;let o=t.map(g=>g/a),l=(g,v)=>[g[1]*v[2]-g[2]*v[1],g[2]*v[0]-g[0]*v[2],g[0]*v[1]-g[1]*v[0]],c=(g,v)=>g.reduce((_,E,M)=>_+E*v[M],0),u=l(s,o);Math.hypot(...u)<1e-8&&(u=l(Math.abs(o[2])<.9?[0,0,1]:[0,1,0],o));let d=Math.hypot(...u);u=u.map(g=>g/d);let f=l(o,u),y=Math.tan(r*Math.PI/360)*n,b=y*i,x=.01;for(let g of[-1,1])for(let v of[-1,1])for(let _ of[-1,1]){let E=[g*e[0]/2,v*e[1]/2,_*e[2]/2],M=c(E,o);x=Math.max(x,M+Math.abs(c(E,u))/b,M+Math.abs(c(E,f))/y,M+.01)}return x}function T3(e,t,r,i,n){if(!["F.Cu","B.Cu"].includes(r)||![e,t].every(u=>Array.isArray(u)&&u.length===3&&u.every(Number.isFinite))||e.some((u,d)=>u>t[d]))return null;let s=e.map((u,d)=>(u+t[d])/2),a=e.map((u,d)=>Math.max(d===2?1:8,t[d]-u)),o=r==="B.Cu"?-1:1,l=[0,1,0],c=e_(a,[0,0,o],i,n,.55,l);return c===null?null:{target:s,position:[s[0],s[1],s[2]+o*c],up:l}}var wu=e=>e&&typeof e=="object"&&!Array.isArray(e)?e.quoted:e,C3=e=>Array.isArray(e)?wu(e[0]):void 0,a0=(e,t)=>(Array.isArray(e)?e:[]).filter(r=>C3(r)===t),o0=(e,t)=>a0(e,t)[0],Rc=e=>Number.isFinite(e)&&e>0;function R3(e={},t=[],r=1.6){let i=[],n=new Map,s=0,a=z=>{i.length<64?i.push(z):s++},o=[...new Set((e.layers||[]).filter(z=>typeof z=="string"&&/^(?:F|B|In[1-9]\d*)\.Cu$/.test(z)))],l=o.slice(0,64);o.length>64&&a("Copper layer display is limited to 64 layers; additional source layers are omitted.");let c=new Set(l),u=Array.isArray(e.stackup)?e.stackup:[],d=Rc(r)?r:1.6;Rc(r)||a("Board thickness is unavailable; copper elevation uses an estimated 1.6 mm board depth.");let f=u.filter(z=>c.has(z.name)),y=new Map(f.filter(z=>Rc(z.thickness)).map(z=>[z.name,z.thickness])),b=l.filter(z=>!y.has(z));b.length&&a(`Saved copper thickness is unavailable for ${b.join(", ")}; 0.035 mm is used for display only.`);let x=z=>/^dielectric\b/i.test(z.name||"")||/^(core|prepreg|dielectric)$/i.test(z.type||""),g=l.length>0&&f.length===l.length&&f.every((z,D)=>z.name===l[D]&&Rc(z.thickness))&&u.every(z=>!(c.has(z.name)||x(z))||Rc(z.thickness)),v;if(g){let z=0,D=new Map;for(let I of u){let L=Rc(I.thickness)?I.thickness:0;c.has(I.name)&&D.set(I.name,d/2-z-L/2),z+=L}Math.abs(z-d)>Math.max(1e-6,d*1e-6)?a("Saved stackup thickness differs from board depth; copper elevations are estimated uniformly."):v=l.map(I=>({name:I,z:D.get(I),thickness:y.get(I)}))}let _=!!v;if(!v){g||a("Complete saved stackup depths are unavailable; copper elevations are estimated uniformly across the board.");let z=y.get(l[0])||.035,D=y.get(l.at(-1))||.035;v=l.map((I,L)=>({name:I,thickness:y.get(I)||.035,z:l.length<2?0:d/2-z/2-L/(l.length-1)*(d-(z+D)/2)}))}let E=new Map(v.map(z=>[z.name,z])),M=new Map,P=new Set,k=0;for(let z of a0(t,"via")){if((o0(z,"at")?.length||0)<3)continue;k++;let D=String(wu(o0(z,"uuid")?.[1])||wu(o0(z,"tstamp")?.[1])||`via-${k}`);M.has(D)&&P.add(D),M.set(D,z)}for(let z of e.vias||[]){let D=M.get(z.id),I=a0(D,"layers"),L=I.length===1?I[0].slice(1).map(wu):[],Z=Re=>a(`Via ${z.id}: ${Re}; span omitted.`);if(!D||P.has(z.id)||L.length!==2||L.some(Re=>typeof Re!="string"||!E.has(Re))||L[0]===L[1]){Z("saved copper endpoint pair is absent, ambiguous or unknown");continue}let se=D.slice(1).filter(Re=>!Array.isArray(Re)).map(wu),ce=se.filter(Re=>["through","blind","buried","micro"].includes(Re));if(ce.length>1||se.some(Re=>!["through","blind","buried","micro","locked"].includes(Re))){Z("saved via type is ambiguous or unsupported");continue}let fe=L.map(Re=>l.indexOf(Re)).sort((Re,Be)=>Re-Be),ze=l[fe[0]],Fe=l[fe[1]],Pe=ze==="F.Cu"&&Fe==="B.Cu",ue=ce[0]||"through",Te=[ze,Fe].filter(Re=>Re==="F.Cu"||Re==="B.Cu").length;if(ue==="through"&&!Pe||ue!=="through"&&Pe||ue==="micro"&&fe[1]-fe[0]!==1||ue==="buried"&&Te!==0){Z("saved via type does not agree with its layer endpoints");continue}let de=E.get(ze),Ie=E.get(Fe);n.set(z.id,{zMin:Math.min(de.z,Ie.z),zMax:Math.max(de.z,Ie.z),from:ze,to:Fe,through:Pe,type:ue==="blind"&&Te===0?"buried":ue})}return s&&i.push(`${s} additional saved-geometry diagnostics omitted.`),{layers:v,byLayer:E,viaSpans:n,warnings:i,savedDepths:_}}var _u=e=>typeof e=="number"&&Number.isFinite(e)&&Math.abs(e)<=1e4,Qs=(e,t)=>Math.abs(e-t)<=1e-9;function P3(e){let t=e.customPrimitives;if(e.customAnchor!=="rect"||!Array.isArray(t)||t.length!==3||!_u(e.width)||!_u(e.height)||e.width<=0||e.height<=0)return null;let r=t.filter(g=>g?.shape==="circle"),i=t.filter(g=>g?.shape==="polygon");if(r.length!==2||i.length!==1)return null;let n=e.width/2,s=e.height/2;for(let g of r)if(!Array.isArray(g.center)||g.center.length!==2||!g.center.every(_u)||!_u(g.radius)||!Qs(g.radius,n)||!Qs(g.center[0],0))return null;if(!(Qs(r[0].center[1],s)&&Qs(r[1].center[1],-s)||Qs(r[1].center[1],s)&&Qs(r[0].center[1],-s)))return null;let a=i[0].points;if(!Array.isArray(a)||a.length<4||a.length>5||!a.every(g=>Array.isArray(g)&&g.length===2&&g.every(_u)))return null;if(a.length===5){if(!a[0].every((g,v)=>Qs(g,a[4][v])))return null;a=a.slice(0,4)}let o=a.some(g=>Qs(g[0],n))?1:a.some(g=>Qs(g[0],-n))?-1:0;if(!o)return null;let l=[[0,-s-n],[o*n,-s-n],[o*n,s+n],[0,s+n]],c=new Set;for(let g of a){let v=l.findIndex(_=>_.every((E,M)=>Qs(E,g[M])));if(v<0||c.has(v))return null;c.add(v)}let u=a.map(g=>l.findIndex(v=>v.every((_,E)=>Qs(_,g[E]))));if(!u.every((g,v)=>(u[(v+1)%4]-g+4)%4===(u[1]-u[0]+4)%4)||![1,3].includes((u[1]-u[0]+4)%4))return null;let d=Math.ceil(Math.PI/Math.acos(Math.max(-1,1-.0025/n))),f=Math.min(128,Math.max(64,Math.ceil(d/4)*4)),y=f/4,b=[];for(let g=0;g<=y;g++){let v=Math.PI/2+g*Math.PI/2/y;b.push([n*Math.cos(v),s+n*Math.sin(v)])}for(let g=0;g<=y;g++){let v=Math.PI+g*Math.PI/2/y;b.push([n*Math.cos(v),-s+n*Math.sin(v)])}if(b.push([n,-s-n],[n,s+n]),o<0){for(let g of b)g[0]=-g[0];b.reverse()}b.push([...b[0]]);let x=n*(1-Math.cos(Math.PI/f));return{outline:b,tessellation:{error:x,limited:x>.00250000000025,tolerance:.0025}}}var t_=1e4,r_=16,Pf=1e-10,i_=e=>typeof e=="number"&&Number.isFinite(e)&&e>0&&e<=t_,If=e=>typeof e=="number"&&Number.isFinite(e)&&Math.abs(e)<=t_;function I3(e){let t=[];for(let r of e){let i=t.at(-1);(!i||Math.hypot(r[0]-i[0],r[1]-i[1])>Pf)&&t.push(r)}return t.length>1&&Math.hypot(t[0][0]-t.at(-1)[0],t[0][1]-t.at(-1)[1])<=Pf&&t.pop(),t.push([...t[0]]),t}function Nf(e,t,r){let i=e/2,n=t/2;if(r===0)return[[-i,-n],[i,-n],[i,n],[-i,n],[-i,-n]];let s=[],a=[[i-r,-n+r],[i-r,n-r],[-i+r,n-r],[-i+r,-n+r]];for(let o=0;o<4;o++)for(let l=0;l<=r_;l++){let c=(-.5+o*.5+l*.5/r_)*Math.PI;s.push([a[o][0]+r*Math.cos(c),a[o][1]+r*Math.sin(c)])}return I3(s)}function l0(e,t,r,i){return!i_(t)||!i_(r)?null:e==="rect"?Nf(t,r,0):e==="oval"?Nf(t,r,Math.min(t,r)/2):e==="circle"?Math.abs(t-r)<=Pf*Math.max(1,t,r)?Nf(t,r,t/2):null:e==="roundrect"&&typeof i=="number"&&Number.isFinite(i)&&i>=0&&i<=.5?Nf(t,r,Math.min(t,r)*i):null}function c0(e){if(!e||typeof e!="object"||!["circle","oval"].includes(e.drillShape))return null;let t=e.drillWidth??e.drill,r=e.drillHeight??(e.drillShape==="circle"?t:void 0),i=l0(e.drillShape,t,r);if(!i)return null;let n=e.drillOffset??[0,0];if(!Array.isArray(n)||n.length!==2||!n.every(If))return null;let s=i.map(([a,o])=>[a+n[0],o+n[1]]).reverse();return s.every(a=>a.every(If))?s:null}function N3(e){if(!e||typeof e!="object")return null;let t=e.shape,r=t==="custom"?P3(e):null,i=r?.outline||l0(t,e.width,e.height,e.roundrectRatio??e.roundrect_rratio);if(!i)return null;let n=null;return(e.drill!==void 0&&e.drill!==0||e.drillWidth!==void 0||e.drillHeight!==void 0)&&(n=c0(e),!n||!n.every(s=>n_(i,s)))?null:{shape:t,outline:i,drill:n,...r?{tessellation:r.tessellation}:{}}}function n_(e,[t,r],i=!1){let n=!1;for(let s=0,a=e.length-2;s<e.length-1;a=s++){let[o,l]=e[a],[c,u]=e[s],d=c-o,f=u-l,y=((t-o)*d+(r-l)*f)/(d*d+f*f),b=Math.max(0,Math.min(1,y));if(Math.hypot(t-(o+b*d),r-(l+b*f))<=Pf)return i;l>r!=u>r&&t<(c-o)*(r-l)/(u-l)+o&&(n=!n)}return n}function L3(e){if(e?.padType!=="np_thru_hole")return!1;let t=l0(e.shape,e.width,e.height,e.roundrectRatio??e.roundrect_rratio),r=c0(e);return!!(t&&r&&t.every(i=>n_(r,i,!0)))}var dn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e.quoted:e,bs=(e,t)=>e.find(r=>Array.isArray(r)&&dn(r[0])===t);function k3(e){let t=bs(e,"primitives");if(!t||t.length>17)return null;let r=[],i=(n,s)=>{let a=bs(n,s)?.slice(1).map(dn);return a?.length===2&&a.every(If)?a:null};for(let n of t.slice(1)){if(!Array.isArray(n)||dn(bs(n,"fill")?.[1])!=="yes"||dn(bs(n,"width")?.[1])!==0)return null;if(dn(n[0])==="gr_circle"){let s=i(n,"center"),a=i(n,"end");if(!s||!a)return null;r.push({shape:"circle",center:s,radius:Math.hypot(a[0]-s[0],a[1]-s[1])})}else if(dn(n[0])==="gr_poly"){let s=bs(n,"pts");if(!s||s.length<4||s.length>17)return null;let a=[];for(let o of s.slice(1)){if(!Array.isArray(o)||dn(o[0])!=="xy")return null;let l=o.slice(1).map(dn);if(l.length!==2||!l.every(If))return null;a.push(l)}r.push({shape:"polygon",points:a})}else return null}return r}function O3(e){let t=new Map,r=new Set,i=0;if(!Array.isArray(e)||dn(e[0])!=="kicad_pcb"||e.length>1e6)return t;let n=-1;for(let s of e){if(!Array.isArray(s)||!["footprint","module"].includes(dn(s[0]))||(n++,s.length>1e6))continue;let a=s.find(l=>Array.isArray(l)&&dn(l[0])==="property"&&dn(l[1])==="Reference")?.[2],o=-1;for(let l of s){if(!Array.isArray(l)||dn(l[0])!=="pad"||(o++,l.length>1e4))continue;if(++i>2e5)return t;let c=jw(l,dn(a),n,o);if(typeof c!="string"||!c||c.length>128)continue;if(r.has(c)){t.delete(c);continue}r.add(c);let u=bs(l,"roundrect_rratio")?.[1],d=bs(l,"drill"),f={type:"Pad",padType:String(dn(l[2])||""),uuid:c,ownerUuid:dn(bs(s,"uuid")?.[1]??bs(s,"tstamp")?.[1]),pinNumber:String(dn(l[1])??""),pinName:String(dn(bs(l,"pinfunction")?.[1])??"")};if(typeof u=="number"&&(f.roundrectRatio=u),dn(l[3])==="custom"&&(f.customAnchor=dn(bs(bs(l,"options")||[],"anchor")?.[1]),f.customPrimitives=k3(l)),d){let y=dn(d[1])==="oval";f.drillShape=y?"oval":"circle",f.drillWidth=d[y?2:1],f.drillHeight=y?d[3]:f.drillWidth;let b=bs(d,"offset");b&&(f.drillOffset=[b[1],b[2]])}if(t.set(c,f),t.size>=2e5)return t}}return t}var Pc=Math.PI*2,h0=1e-9,Eu=.0025,yn=e=>typeof e=="number"&&Number.isFinite(e);function Lf(e,{tolerance:t=Eu,min:r=24,max:i=128}={}){if(!yn(e)||e<=0||!yn(t)||t<=0||!Number.isInteger(r)||!Number.isInteger(i)||r<4||i<r||i>4096)throw Error("Invalid circular tessellation parameters.");let n=2*Math.acos(Math.max(-1,Math.min(1,1-t/e))),s=n>0?Math.ceil(Pc/n):i,a=Math.min(i,Math.max(r,Math.ceil(s/4)*4)),o=e*(1-Math.cos(Math.PI/a));return{segments:a,error:o,limited:o>t*1.0000000001,tolerance:t}}function D3(e,t,{world:r,z:i,thickness:n}){if(!Array.isArray(t)||typeof r!="function"||!yn(i)||!yn(n)||n<=0)throw Error("Invalid copper stroke batch parameters.");let s=t.filter(x=>yn(x.width)&&x.width>0&&Array.isArray(x.start)&&Array.isArray(x.end)&&x.start.length===2&&x.end.length===2&&[...x.start,...x.end].every(yn)),a=t.length-s.length;if(!s.length)return{batches:[],tracks:s,invalid:a,plan:null,triangles:0};let o=[12,16,24,32,48,64,96,128],l=new Map,c=new Map,u=[],d=0,f=!1;for(let x of s){let g=c.get(x.width);if(!g){let _=Lf(x.width/2,{min:12});g=o.find(E=>E>=_.segments)||128,c.set(x.width,g)}let v=x.width/2*(1-Math.cos(Math.PI/g));d=Math.max(d,v),f||=v>Eu*1.0000000001,l.has(g)||l.set(g,[]),l.get(g).push(x)}let y=s.filter(x=>Math.hypot(x.end[0]-x.start[0],x.end[1]-x.start[1])>1e-12);y.length&&u.push({part:"core",records:y,geometry:new e.BoxGeometry(1,1,1),place(x,g){let v=r(g.start),_=r(g.end);x.position.set((v[0]+_[0])/2,(v[1]+_[1])/2,i),x.rotation.set(0,0,Math.atan2(_[1]-v[1],_[0]-v[0])),x.scale.set(Math.hypot(_[0]-v[0],_[1]-v[1]),g.width,n)}});for(let[x,g]of[...l].sort((v,_)=>v[0]-_[0])){let v=new e.CylinderGeometry(1,1,1,x/2,1,!1,0,Math.PI);v.rotateX(Math.PI/2);for(let _ of["start","end"])u.push({part:_+"-"+x,records:g,geometry:v,place(E,M){let[P,k]=r(M[_]),z=r(M.start),D=r(M.end);E.position.set(P,k,i),E.rotation.set(0,0,Math.atan2(D[1]-z[1],D[0]-z[0])+(_==="start"?Math.PI:0)),E.scale.set(M.width/2,M.width/2,n)}})}let b={segments:Math.max(...l.keys()),error:d,limited:f,tolerance:Eu};return{batches:u,tracks:s,invalid:a,plan:b,triangles:u.reduce((x,g)=>x+(g.geometry.index?.count||g.geometry.getAttribute("position").count)/3*g.records.length,0)}}function U3(e,t,r){if(!r)return[[-e/2,-t/2],[e/2,-t/2],[e/2,t/2],[-e/2,t/2],[-e/2,-t/2]];let i=Lf(r,{min:64}),n=i.segments/4,s=[],a=e/2,o=t/2,l=[[a-r,-o+r],[a-r,o-r],[-a+r,o-r],[-a+r,-o+r]];for(let c=0;c<4;c++)for(let u=0;u<=n;u++){let d=(-.5+c*.5+u*.5/n)*Math.PI,f=[l[c][0]+r*Math.cos(d),l[c][1]+r*Math.sin(d)],y=s.at(-1);(!y||Math.hypot(f[0]-y[0],f[1]-y[1])>h0)&&s.push(f)}return Math.hypot(s[0][0]-s.at(-1)[0],s[0][1]-s.at(-1)[1])<h0&&s.pop(),s.push([...s[0]]),s}function s_(e,t,r,i){return U3(t,r,e==="rect"?0:e==="roundrect"?Math.min(t,r)*i:Math.min(t,r)/2)}function u0(e){if(!c0(e))return null;let t=e.drillWidth??e.drill,r=e.drillHeight??(e.drillShape==="circle"?t:void 0),i=e.drillOffset||[0,0];return s_(e.drillShape,t,r,0).map(([n,s])=>[n+i[0],s+i[1]]).reverse()}function F3(e,t){let r=0;for(let i=0;i<e.length-1;i++){let n=e[i],s=e[i+1],a=(s[0]-n[0])*(t[1]-n[1])-(s[1]-n[1])*(t[0]-n[0]);if(Math.abs(a)<1e-12)return!1;let o=Math.sign(a);if(r&&o!==r)return!1;r=o}return!0}function a_(e){let t=N3(e);if(!t)return null;if(e.shape==="custom"){let o=t.drill?Math.min(e.drillWidth??e.drill,e.drillHeight??e.drill)/2:0,l=Math.max(t.tessellation.error,o*(1-Math.cos(Math.PI/64)));return{...t,tessellation:{...t.tessellation,error:l,limited:l>Eu*1.0000000001}}}let r=e.roundrectRatio??e.roundrect_rratio,i=s_(e.shape,e.width,e.height,r),n=e.drill||e.drillWidth||e.drillHeight?u0(e):null,s=[e.shape==="rect"?0:e.shape==="roundrect"?Math.min(e.width,e.height)*r:Math.min(e.width,e.height)/2,n?Math.min(e.drillWidth??e.drill,e.drillHeight??e.drill)/2:0].filter(o=>o>0),a=s.map(o=>Lf(o,{min:64}));return n&&n.some(o=>!F3(i,o))?{...t,tessellation:{error:Math.max(0,...s.map(o=>o*(1-Math.cos(Math.PI/64)))),limited:!0,reason:"Refined hole containment requires retaining the validated contour resolution."}}:{shape:e.shape,outline:i,drill:n,tessellation:{error:Math.max(0,...a.map(o=>o.error)),limited:a.some(o=>o.limited)}}}function z3(e,t,r){if(!Array.isArray(t)||t.length<4||!t.every(o=>Array.isArray(o)&&o.length===2&&o.every(yn))||!yn(r)||r<=0||Math.hypot(t[0][0]-t.at(-1)[0],t[0][1]-t.at(-1)[1])>h0)throw Error("Invalid saved drill wall.");let i=t.length-1,n=[],s=[];for(let o=0;o<i;o++){let[l,c]=t[o];n.push(l,-c,0,l,-c,r);let u=(o+1)%i;s.push(o*2,u*2,o*2+1,u*2,u*2+1,o*2+1)}let a=new e.BufferGeometry;return a.setAttribute("position",new e.Float32BufferAttribute(n,3)),a.setIndex(s),a.computeVertexNormals(),a}function B3(e,t,r=.035,i){if(!["F.Cu","B.Cu"].includes(e)||!yn(t)||t<=0||!yn(r)||r<=0||i!==void 0&&!yn(i))throw Error("Invalid outer copper placement.");let n=e==="F.Cu"?1:-1,s=.001,a=i??n*(t/2-r/2),o=a+n*s;return{center:o,sourceCenter:a,base:o-r/2,thickness:r,displayOffset:s}}function j3(e,t){if(!["F.Cu","B.Cu"].includes(e)||!yn(t?.base)||!yn(t?.thickness)||t.thickness<=0)throw Error("Invalid zone display placement.");let r=Math.min(.005,t.thickness/4);return e==="F.Cu"?t.base+t.thickness-r:t.base+r}function V3(e,t){if(!yn(e)||e<=0||!t?.get)throw Error("Invalid substrate depth plan.");let r=t.get("F.Cu"),i=t.get("B.Cu"),n=o=>o&&yn(o.z)&&yn(o.thickness)&&o.thickness>0,s=n(r)?r.z-r.thickness/2:e/2,a=n(i)?i.z+i.thickness/2:-e/2;if(!yn(s-a)||s<=a)throw Error("Outer copper inner faces do not enclose a valid substrate.");return{top:s,bottom:a,depth:s-a,missingOuterDepths:!n(r)||!n(i)}}var bl=e=>e&&typeof e=="object"&&!Array.isArray(e)?e.quoted:e,Su=(e,t)=>e.find(r=>Array.isArray(r)&&bl(r[0])===t),d0=(e,t)=>{let r=Su(e,t),i=r?.slice(1,3).map(bl);return i?.length===2&&i.every(yn)?i:null};function H3(e,t,r){let i=t[0]-e[0],n=t[1]-e[1],s=r[0]-e[0],a=r[1]-e[1],o=2*(i*a-n*s);if(Math.abs(o)<1e-12)return null;let l=i*i+n*n,c=s*s+a*a,u=[e[0]+(l*a-c*n)/o,e[1]+(c*i-l*s)/o],d=Math.atan2(e[1]-u[1],e[0]-u[0]),f=g=>(g%Pc+Pc)%Pc,y=f(Math.atan2(r[1]-u[1],r[0]-u[0])-d),b=f(Math.atan2(t[1]-u[1],t[0]-u[0])-d),x=Math.hypot(e[0]-u[0],e[1]-u[1]);return u.every(yn)&&yn(x)?{center:u,radius:x,start:d,sweep:b<=y?y:y-Pc}:null}function G3(e,t,{maxSegments:r=2e5}={}){if(!Array.isArray(e)||!Array.isArray(t)||!Number.isInteger(r)||r<1||r>1e6)throw Error("Invalid saved track refinement input.");let i=[],n=new Map,s=new Map,a=new Set,o=Math.max(0,r-e.length);for(let d of e){let f=String(d.id||"").replace(/:\d+$/,"");n.has(f)||n.set(f,[]),n.get(f).push(d)}let l=(d,f)=>d&&f&&Math.hypot(d[0]-f[0],d[1]-f[1])<1e-6;for(let d of t){if(!Array.isArray(d)||bl(d[0])!=="arc")continue;let f=d0(d,"start"),y=d0(d,"mid"),b=d0(d,"end"),x=bl(Su(d,"uuid")?.[1])??bl(Su(d,"tstamp")?.[1]),g=bl(Su(d,"layer")?.[1]),v=bl(Su(d,"width")?.[1]);if(!f||!y||!b)continue;let _=typeof x=="string"&&n.has(x)?[[x,n.get(x)]]:[...n].filter(([,L])=>L[0].layer===g&&L[0].width===v&&l(L[0].start,f)&&l(L.at(-1).end,b));if(_.length!==1){i.push("A saved copper arc could not be matched unambiguously; existing parsed segments are retained.");continue}let[E,M]=_[0];if(a.has(E)){s.delete(E),i.push("Duplicate saved copper arc identity retained without refinement.");continue}a.add(E);let P=H3(f,y,b);if(!P){i.push("Degenerate saved copper arc retained without refinement.");continue}let k=Lf(P.radius,{min:24,max:4096}),z=Math.max(M.length,2,Math.ceil(k.segments*Math.abs(P.sweep)/Pc)),D=Math.max(0,z-M.length);if(k.limited||D>o){i.push("Saved copper arc refinement reached its geometric error or segment budget; parsed segments are retained.");continue}o-=D;let I=Array.from({length:z+1},(L,Z)=>{let se=P.start+P.sweep*Z/z;return[P.center[0]+P.radius*Math.cos(se),P.center[1]+P.radius*Math.sin(se)]});I[0]=f,I[z]=b,s.set(E,Array.from({length:z},(L,Z)=>({...M[Math.min(M.length-1,Math.floor(Z*M.length/z))],...typeof x=="string"?{uuid:x}:{},start:I[Z],end:I[Z+1]})))}let c=[],u=new Set;for(let d of e){let f=String(d.id||"").replace(/:\d+$/,"");s.has(f)?u.has(f)||(c.push(...s.get(f)),u.add(f)):c.push(d)}return{tracks:c,warnings:[...new Set(i)],tolerance:Eu}}var o_=e=>encodeURIComponent(e?.trim()||"global");function Ic(e,t,r){return`spike:${e}:${o_(t)}:${o_(r)}`}function l_(e){let t=new Map;return e.forEach((r,i)=>{let n=r?.ref;typeof n!="string"||!n||t.set(n,t.has(n)?null:i)}),t}function W3(e,t){let r=e.map(()=>!0),i=l_(e);if(!Array.isArray(t))return r;let n=new Map;for(let s of t)typeof s?.reference!="string"||!s.reference||typeof s.populated!="boolean"||n.set(s.reference,n.has(s.reference)?null:s.populated);for(let[s,a]of n){let o=i.get(s);o!=null&&a!=null&&(r[o]=a)}return r}function X3(e){let t=new Map,r=new Map,i=new Map;for(let n of e.components)r.set(n.ref,(r.get(n.ref)||0)+1);for(let n of[...e.drawings,...e.pads])n.ref&&(t.has(n.ref)||t.set(n.ref,[]),t.get(n.ref).push(n));for(let n of e.components){if(r.get(n.ref)!==1)continue;let s=t.get(n.ref)||[],a=n.layer?.startsWith("B.")?"B":"F",o=[],l=null;for(let P of[a+".Fab",a+".CrtYd"]){let k=s.filter(z=>z.layer===P&&z.points).map(z=>z.points);if(o=k.flat(),l=Y3(k),o.length)break}if(!o.length)for(let P of s.filter(k=>k.at&&k.width>0&&k.height>0)){let k=-(P.rotation||0)*Math.PI/180,z=Math.cos(k),D=Math.sin(k);for(let I of[-P.width/2,P.width/2])for(let L of[-P.height/2,P.height/2])o.push([P.at[0]+I*z-L*D,P.at[1]+I*D+L*z])}let c=(n.rotation||0)*Math.PI/180,u=Math.cos(c),d=Math.sin(c),f=o.filter(P=>P?.length>=2&&P.every(Number.isFinite)).map(([P,k])=>(P-=n.at[0],k-=n.at[1],[P*u-k*d,P*d+k*u]));if(!f.length)continue;let y=1/0,b=1/0,x=-1/0,g=-1/0;for(let[P,k]of f)y=Math.min(y,P),b=Math.min(b,k),x=Math.max(x,P),g=Math.max(g,k);let v=x-y,_=g-b;if(!(v>1e-6&&_>1e-6))continue;let E=(y+x)/2,M=(b+g)/2;if(l){let P=l.map(([D,I])=>(D-=n.at[0],I-=n.at[1],[D*u-I*d,D*d+I*u]));if(!c_([E,M],P))continue;let k=0,z=1;for(let D=0;D<30;D++){let I=(k+z)/2,L=[[-1,-1],[1,-1],[1,1],[-1,1]].map(([Z,se])=>[E+Z*v*I/2,M+se*_*I/2]);L.every(Z=>c_(Z,P))&&!L.some((Z,se)=>P.some((ce,fe)=>q3(Z,L[(se+1)%4],ce,P[(fe+1)%P.length])))?k=I:z=I}if(v*=k,_*=k,!(v>1e-6&&_>1e-6))continue}i.set(n,{at:[n.at[0]+E*u+M*d,n.at[1]-E*d+M*u],width:v,height:_,rotation:c})}return i}var Mu=(e,t)=>Math.hypot(e[0]-t[0],e[1]-t[1])<1e-5;function Y3(e){if(e.length>512)return[];let t=e.filter(i=>i.length>1).map(i=>[...i]),r=[];for(;t.length;){let i=t.shift();for(;!Mu(i[0],i.at(-1));){let n=t.findIndex(a=>Mu(i.at(-1),a[0])||Mu(i.at(-1),a.at(-1)));if(n<0)break;let s=t.splice(n,1)[0];Mu(i.at(-1),s[0])||s.reverse(),i.push(...s.slice(1))}i.length>3&&Mu(i[0],i.at(-1))&&r.push(i.slice(0,-1))}return r.length===1?r[0]:r.length?[]:null}function c_(e,t){let r=!1;for(let i=0,n=t.length-1;i<t.length;n=i++){let s=t[i],a=t[n];s[1]>e[1]!=a[1]>e[1]&&e[0]<(a[0]-s[0])*(e[1]-s[1])/(a[1]-s[1])+s[0]&&(r=!r)}return r}function q3(e,t,r,i){let n=(s,a,o)=>(a[0]-s[0])*(o[1]-s[1])-(a[1]-s[1])*(o[0]-s[0]);return n(e,t,r)*n(e,t,i)<-1e-12&&n(r,i,e)*n(r,i,t)<-1e-12}function K3(e,{objects:t,camera:r,rect:i,positionToWorld:n}){let s=a=>a?.type==="Component"||typeof a?.library=="string";return function(a){if(!a||typeof a!="object")return null;let o=i();if(!(o.width>0&&o.height>0))return null;let l=b=>(b.project(r),![b.x,b.y,b.z].every(Number.isFinite)||Math.abs(b.x)>1||Math.abs(b.y)>1||b.z<-1||b.z>1?null:{x:o.left+(b.x+1)*o.width/2,y:o.top+(1-b.y)*o.height/2,visible:!0});if(a.position){let{x:b,y:x}=a.position;return![b,x].every(g=>typeof g=="number"&&Number.isFinite(g)&&Math.abs(g)<=1e6)||!["front","back",void 0].includes(a.side)?null:l(n({x:b,y:x},a.side))}let c=b=>typeof b=="string"&&b.length>0&&b.length<=500&&!/[\x00-\x1f\x7f]/.test(b);if(!["uuid","reference","pinNumber","net"].some(b=>c(a[b]))||["uuid","reference","pinNumber","net"].some(b=>a[b]!==void 0&&!c(a[b]))||a.pinNumber&&!a.uuid&&!a.reference)return null;let u=new Map,d=new e.Matrix4,f=new e.Matrix4;for(let b of t()){let x=!0;for(let v=b;v;v=v.parent)v.visible||(x=!1);if(!x)continue;let g=b.userData.records||[b.userData.record];for(let v=0;v<g.length;v++){let _=g[v];if(!_)continue;let E=_.uuid||_.id;if(a.uuid&&a.uuid!==E&&!(a.pinNumber&&a.uuid===_.ownerUuid)&&!(typeof E=="string"&&E.replace(/:\d+$/,"")===a.uuid)||a.reference&&_.ref!==a.reference||a.pinNumber&&String(_.pinNumber??_.name??"")!==a.pinNumber||a.net&&_.net!==a.net||a.reference&&!a.uuid&&!a.pinNumber&&!a.net&&!s(_)||(b.updateWorldMatrix(!0,!1),b.geometry?.boundingBox||b.geometry?.computeBoundingBox(),!b.geometry?.boundingBox))continue;let M=b.geometry.boundingBox.clone();if(b.isInstancedMesh){if(b.getMatrixAt(v,f),f.determinant()===0)continue;d.multiplyMatrices(b.matrixWorld,f),M.applyMatrix4(d)}else M.applyMatrix4(b.matrixWorld);if(M.isEmpty())continue;let P=E||_.ref;P&&(u.has(P)?u.get(P).union(M):u.set(P,M))}}if(!a.net&&u.size!==1)return null;let y=[...u.values()].map(b=>l(b.getCenter(new e.Vector3))).filter(Boolean);return y.sort((b,x)=>Math.hypot(b.x-o.left-o.width/2,b.y-o.top-o.height/2)-Math.hypot(x.x-o.left-o.width/2,x.y-o.top-o.height/2)),y[0]||null}}function p0(e={}){if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("Selection style must be an object.");let{mode:t="dim",color:r="accent"}=e;if(!["dim","bright","isolate"].includes(t))throw new TypeError("Choose dim, bright or isolate selection mode.");if(!["accent","source"].includes(r))throw new TypeError("Choose accent or source selection color.");return{mode:t,color:r}}function Z3(e,t){let r=new Map,i=new Map,n=new Map,s=new Map,a={owned:[]},o="",l=_=>Array.isArray(_)?_:[_];function c(){for(let[_,E]of r){_.material=E.material,_.isInstancedMesh&&(_.instanceColor!==E.instanceColor&&_.dispose?.(),_.instanceColor=E.instanceColor,_.customDepthMaterial=E.depth,_.customDistanceMaterial=E.distance);for(let M of E.owned)M.dispose()}for(let _ of a.owned)_.dispose();a.owned.length=0,i.clear(),n.clear(),s.clear(),r.clear(),o=""}function u(_){if(r.has(_))return r.get(_);let E={material:_.material,instanceColor:_.instanceColor,depth:_.customDepthMaterial,distance:_.customDistanceMaterial,owned:[]};return r.set(_,E),E}function d(_,E){let M=_.clone();return M.onBeforeCompile=_.onBeforeCompile,M.customProgramCacheKey=()=>_.customProgramCacheKey(),E.owned.push(M),M}function f(_,E,M){if(_.has(E))return _.get(E);let P=d(E,a);return M(P),_.set(E,P),P}function y(_,E,M=!1){if(M&&i.has(_))return i.get(_);let P=d(_,M?a:E),k=_.onBeforeCompile;return P.userData??={},P.userData.selectionOpacityCap=.24,P.opacity=Math.min(_.opacity??1,.24),P.transparent=!0,P.depthWrite=!1,P.onBeforeCompile=(z,D)=>{k?.call(P,z,D),z.fragmentShader=z.fragmentShader.replace("#include <opaque_fragment>",`outgoingLight = vec3(dot(outgoingLight, vec3(0.2126, 0.7152, 0.0722))) * 0.24;
#include <opaque_fragment>`)},P.customProgramCacheKey=()=>_.customProgramCacheKey()+":selection-grey",M&&i.set(_,P),P}function b(_){return _.accent||(_.accent=l(_.material).map(E=>f(s,E,M=>{M.color?.setHex(6547182),M.emissive?.setHex(1201756),M.metalness=0,M.roughness=.55}))),Array.isArray(_.material)?_.accent:_.accent[0]}function x(_,E,M=!1,P=!1){let k=_.onBeforeCompile,z=_.customProgramCacheKey(),D=M?_:d(_,E);return M&&E.owned.push(D),P&&(D.transparent=!0,D.depthWrite=!1),D.onBeforeCompile=(I,L)=>{k?.call(D,I,L),I.vertexShader=I.vertexShader.replace("#include <common>",`#include <common>
varying float vSelectionStyle;`).replace("#include <begin_vertex>",`#include <begin_vertex>
vSelectionStyle = 0.0;
#ifdef USE_INSTANCING_COLOR
  if (instanceColor.r < -1.0e25) { vSelectionStyle = 3.0; }
  else if (instanceColor.r < -1.0e15) { vSelectionStyle = 2.0; }
  else if (instanceColor.r < 0.0) { vSelectionStyle = 1.0; }
#endif`),I.vertexShader=I.vertexShader.replace("#include <color_vertex>",`#ifdef USE_INSTANCING_COLOR
vec3 selectionDecodedColor = instanceColor.r < -1.0e15 ? vec3(1.0) : instanceColor.r < 0.0 ? -instanceColor - vec3(1.0) : instanceColor;
#endif
`+e.ShaderChunk.color_vertex.replace(/\binstanceColor\b/g,"selectionDecodedColor")),I.fragmentShader=I.fragmentShader.replace("#include <common>",`#include <common>
varying float vSelectionStyle;`).replace("#include <clipping_planes_fragment>",`#include <clipping_planes_fragment>
if (vSelectionStyle > 2.5) discard;`).replace("#include <color_fragment>",`#include <color_fragment>
if (vSelectionStyle > 1.5 && vSelectionStyle < 2.5) diffuseColor.rgb = vec3(0.1247718, 0.7912979, 0.8549926);`).replace("#include <opaque_fragment>","if (vSelectionStyle > 0.5 && vSelectionStyle < 1.5) { outgoingLight = vec3(dot(outgoingLight, vec3(0.2126, 0.7152, 0.0722))) * 0.24;"+(P?" diffuseColor.a *= 0.24;":"")+` }
#include <opaque_fragment>`)},D.customProgramCacheKey=()=>z+":selection-instances-v1"+(P?":translucent-context":""),D}function g(_,E,M=null,P={}){let k=p0(P),z=P.expanded===!0,D=P.netContext===!0,I=k.mode+":"+k.color+":"+z+":"+D,L=k.mode==="dim"&&D,Z=ce=>_(ce)&&!(L&&(ce?.type==="Component"||typeof ce?.library=="string"));if(!E){c();return}o&&o!==I&&c(),o=I;let se=k.mode==="dim"&&k.color==="accent";for(let ce of t()){if(!ce.material)continue;let fe=u(ce),ze=ce.userData.records,Fe=ce.userData.identity?.startsWith("spike:via-barrel:"),Pe=se&&!Fe&&!L;if(Fe&&k.mode!=="isolate"&&!((z||D)&&k.mode==="dim")){ce.material=fe.material,ce.instanceColor!==fe.instanceColor&&(ce.instanceColor=fe.instanceColor);continue}if(ce.isInstancedMesh&&ze){if(Pe){fe.white||(fe.white=l(fe.material).map(de=>{let Ie=d(de,fe);return Ie.color?.setHex(16777215),Ie}),ce.instanceColor=fe.instanceColor?.clone()||null),ce.material=Array.isArray(fe.material)?fe.white:fe.white[0];let ue=l(fe.material)[0].color||new e.Color(16777215),Te=new e.Color;for(let de=0;de<ze.length;de++){if(fe.instanceColor?Te.fromArray(fe.instanceColor.array,de*3).multiply(ue):Te.copy(ue),M?.(ze[de]))Te.setHex(6547182);else if(!_(ze[de])){let Ie=(Te.r*.2126+Te.g*.7152+Te.b*.0722)*.24;Te.setRGB(Ie,Ie,Ie)}ce.setColorAt(de,Te)}}else{fe.instances||(fe.instances=l(fe.material).map(Te=>x(Te,fe,!1,k.mode==="dim"&&(D||Fe&&z))),ce.instanceColor=fe.instanceColor?.clone()||null,k.mode==="isolate"&&(ce.customDepthMaterial=x(fe.depth||new e.MeshDepthMaterial({depthPacking:e.RGBADepthPacking}),fe,!fe.depth),ce.customDistanceMaterial=x(fe.distance||new e.MeshDistanceMaterial,fe,!fe.distance))),ce.material=Array.isArray(fe.material)?fe.instances:fe.instances[0];let ue=new e.Color;for(let Te=0;Te<ze.length;Te++){fe.instanceColor?ue.fromArray(fe.instanceColor.array,Te*3):ue.setHex(16777215);let de=ze[Te],Ie=Z(de);!Ie&&k.mode==="isolate"?ue.setRGB(-1e30,-1e30,-1e30):!Fe&&k.color==="accent"&&M?.(de)?ue.setRGB(-1e20,-1e20,-1e20):!Ie&&k.mode==="dim"&&ue.setRGB(-ue.r-1,-ue.g-1,-ue.b-1),ce.setColorAt(Te,ue)}}ce.instanceColor&&(ce.instanceColor.needsUpdate=!0)}else k.mode==="isolate"&&ce.userData.record&&ce.userData.record.type!=="Board"&&!_(ce.userData.record)?(fe.hidden||(fe.hidden=l(fe.material).map(ue=>f(n,ue,Te=>{Te.visible=!1}))),ce.material=Array.isArray(fe.material)?fe.hidden:fe.hidden[0]):!Fe&&k.color==="accent"&&M?.(ce.userData.record)?ce.material=b(fe):Z(ce.userData.record)||k.mode!=="dim"?ce.material=fe.material:(fe.dim||(fe.dim=l(fe.material).map(ue=>y(ue,fe,!ce.isInstancedMesh))),ce.material=Array.isArray(fe.material)?fe.dim:fe.dim[0])}}function v(_,E){let M=_.isInstancedMesh&&_.instanceColor;return M&&Number.isInteger(E)&&M.array[E*3]<-1e25?!1:l(_.material).some(P=>P&&P.visible!==!1)}return{update:g,restore:c,dispose:c,isVisible:v,stats:()=>({capturedObjects:r.size,sharedDimMaterials:i.size})}}var $3=Object.freeze(["realistic","layers","translucent"]);function h_(e){if(!$3.includes(e))throw new TypeError("Choose realistic, layers or translucent appearance.");return e}function J3(){let e=new Map,t=new Map,r=!1,i=!1,n={substrate:.12,component:.22,zone:.08,silkscreen:.45};function s(c){return Array.isArray(c)?c:[c]}function a(c,u){if(!c||!c.clone)return c;let d=t.get(c);if(d||(d=new Map,t.set(c,d)),d.has(u))return d.get(u);let f=c.clone();return f.onBeforeCompile=c.onBeforeCompile,f.customProgramCacheKey=()=>c.customProgramCacheKey(),f.transparent=!0,f.opacity=(Number.isFinite(c.opacity)?c.opacity:1)*n[u],f.depthWrite=!1,f.forceSinglePass=!0,f.needsUpdate=!0,d.set(u,f),f}function o(c,u){let d=s(u.material).map(f=>a(f,u.role));c.material=Array.isArray(u.material)?d:d[0]}function l(){for(let[c,u]of e)c.material=u.material;for(let c of t.values())for(let u of c.values())u.dispose();t.clear()}return{add(c,u){if(i||!c?.material||!Object.hasOwn(n,u)||e.has(c))return;let d={material:c.material,role:u};e.set(c,d),r&&o(c,d)},setEnabled(c){if(i)return!1;let u=!!c;if(u===r)return r;if(u||l(),r=u,r)for(let[d,f]of e)o(d,f);return r},stats(){return{enabled:r,objects:e.size,materials:[...t.values()].reduce((c,u)=>c+u.size,0)}},dispose(){i||(l(),e.clear(),r=!1,i=!0)}}}function f0(e,t,r){if(r==="translucent"&&e===t)return!1;for(let i=e;i;i=i.parent)if(!i.visible)return!1;return!0}function Q3(e,t){if(!(t>0)||!Number.isFinite(t))throw new TypeError("A positive board thickness is required.");let r=["F.Cu",...[...new Set(e.layers||[])].filter(u=>typeof u=="string"&&/^In(?:[1-9]|[1-5][0-9]|6[0-2])\.Cu$/.test(u)).slice(0,62),"B.Cu"],i=Array.isArray(e.stackup)?e.stackup:[],n=new Map,s=0,a=i.findIndex(u=>u.name==="F.Cu"),o=i.findIndex(u=>u.name==="B.Cu"),l=a>=0&&o>a&&i.slice(a,o+1).every(u=>Number.isFinite(u.thickness)&&u.thickness>=0);if(l)for(let u of i){let d=Number.isFinite(u.thickness)&&u.thickness>=0?u.thickness:0;if(r.includes(u.name)){if(n.has(u.name)){n.clear();break}n.set(u.name,t/2-s-d/2)}s+=d}let c=l&&r.every(u=>n.has(u))&&Math.abs(s-t)<1e-6&&r.every((u,d)=>!d||n.get(r[d-1])>n.get(u));return r.map((u,d)=>({name:u,internal:d>0&&d<r.length-1,z:d===0?t/2+.025:d===r.length-1?-t/2-.025:c?n.get(u):t/2-d*t/(r.length-1),basis:d===0||d===r.length-1?"outer-surface":c?"saved-stackup":"illustrative"}))}function eO(e,t){let r=!1,i=!1,n=0,s=0;return{request(){if(!i&&(n++,!r)){r=!0;try{t()}catch(a){throw r=!1,a}}},flush(){i||!r||(r=!1,s++,e())},dispose(){i=!0,r=!1},stats(){return{requestCount:n,flushCount:s,pending:r}}}}function u_({request:e,cancel:t,render:r,canRender:i=()=>!0,state:n={}}){let s={documentVisible:!0,intersecting:!0,hasSize:!0,contextAvailable:!0,...n},a=null,o=!1,l=!1,c=0,u=0,d=0,f=0,y=0,b=0,x=0,g=()=>!l&&s.documentVisible&&s.intersecting&&s.hasSize&&s.contextAvailable&&i();function v(){a!==null&&(t(a),a=null,y++)}function _(){!o||a!==null||!g()||(u++,a=e(()=>{if(a=null,!g()){b++;return}o&&(o=!1,d++,r())}))}return{invalidate(){l||(c++,o=!0,g()?_():f++)},setState(E){if(l)return;let M=g();Object.assign(s,E),g()?(M||(x++,o=!0),_()):v()},stats(){return{...s,paused:!g(),dirty:o,pending:a!==null,requestCount:c,scheduledFrames:u,renderCallbacks:d,suppressedInvalidations:f,cancelledFrames:y,skippedFrames:b,resumeCount:x}},dispose(){l||(l=!0,v(),o=!1)}}}function d_(e,t,r=globalThis.IntersectionObserver){if(typeof r!="function")return null;let i;try{return i=new r(n=>{let s=n.find(a=>a.target===t);s&&e.setState({intersecting:!!s.isIntersecting&&s.intersectionRatio!==0})}),i.observe(t),i}catch{return i?.disconnect(),e.setState({intersecting:!0}),null}}function tO(e){let t=!0,r=0;return{invalidate(){t=!0},check(){return t?(t=!1,r++,e.getError()===e.NO_ERROR):!0},stats:()=>({checks:r,pending:t})}}function rO(e,t={}){let r=new Set((Array.isArray(e.netNames)?e.netNames:[]).filter(i=>typeof i=="string"&&i));for(let i of Array.isArray(e.netCodes)?e.netCodes:[]){if(i===0||i==="0"||i==null||i==="")continue;let n=t.nets?.[String(i)];n?r.add(n):typeof i=="string"&&!/^\d+$/.test(i)&&r.add(i)}return r}function iO(e,t){return t.size>0&&!["references","uuids"].some(r=>Array.isArray(e[r])&&e[r].some(i=>typeof i=="string"&&i))}function nO(e,t){let r=e.instanceMatrix?.array,i=t*16;if(!r||i+15>=r.length)return!1;let n=r[i]*(r[i+5]*r[i+10]-r[i+9]*r[i+6])-r[i+4]*(r[i+1]*r[i+10]-r[i+9]*r[i+2])+r[i+8]*(r[i+1]*r[i+6]-r[i+5]*r[i+2]);return Number.isFinite(n)&&n!==0}function sO(e,t){let r=new Set,i=0,n=0,s=0;for(let a of e){let o=!0;for(let c=a;c;c=c.parent)if(!c.visible){o=!1;break}if(!o||!a.geometry?.attributes?.position?.count)continue;s++;let l=(c,u)=>{i++,!(!t(c)||a.isInstancedMesh&&Number.isInteger(u)&&!nO(a,u))&&(n++,r.add(c?.ref?"part:"+c.ref:c?.uuid||c?.id||a.uuid+":"+u))};Array.isArray(a.userData.records)?a.userData.records.forEach(l):l(a.userData.record)}return{matched:r.size,matchedRecords:n,visitedRecords:i,visibleObjects:s}}function kf(e={}){return["references","uuids","netNames"].some(t=>Array.isArray(e[t])&&e[t].some(r=>typeof r=="string"&&r.length>0))||Array.isArray(e.netCodes)&&e.netCodes.some(t=>typeof t=="number"&&Number.isFinite(t)&&t!==0||typeof t=="string"&&t!==""&&t!=="0")}function aO(e={},t={}){let r=o=>new Set(Array.isArray(o)?o.filter(l=>typeof l=="string"&&l):[]),i=r(e.references),n=r(e.uuids),s=r(e.netNames);for(let o of Array.isArray(e.netCodes)?e.netCodes:[]){if(o===0||o==="0"||o==null||o==="")continue;let l=t.nets?.[String(o)];l?s.add(l):typeof o=="string"&&!/^\d+$/.test(o)&&s.add(o)}let a=new Set;for(let o of t.pads||[])s.has(o.net)&&o.ref&&a.add(o.ref);return o=>!!(o&&(i.has(o.ref)||s.has(o.net)||n.has(o.uuid)||n.has(o.id)||typeof o.id=="string"&&n.has(o.id.split(":")[0])||a.has(o.ref)&&(o.type==="Component"||typeof o.library=="string")))}function p_(e=6){let t=new Map,r=!1;return{down(i){t.size||(r=!1),t.set(i.pointerId,[i.clientX,i.clientY]),t.size>1&&(r=!0)},move(i){let n=t.get(i.pointerId);n&&Math.hypot(i.clientX-n[0],i.clientY-n[1])>=e&&(r=!0)},up(i){let n=t.get(i.pointerId),s=!!(n&&!r&&t.size===1&&Math.hypot(i.clientX-n[0],i.clientY-n[1])<e);return t.delete(i.pointerId),s},cancel(i){t.delete(i.pointerId),r=!0}}}function oO(e,{later:t=setTimeout,clear:r=clearTimeout,delay:i=550,limit:n=8}={}){let s=new Set,a=null,o=null,l=!1,c=()=>{a!==null&&r(a),a=null};return{down(u){s.size||(l=!1),s.add(u.pointerId),c(),!(u.pointerType!=="touch"||s.size!==1)&&(o={pointerId:u.pointerId,clientX:u.clientX,clientY:u.clientY},a=t(()=>{a=null,l=!0,e(o)},i))},move(u){o?.pointerId===u.pointerId&&Math.hypot(u.clientX-o.clientX,u.clientY-o.clientY)>=n&&c()},up(u){return c(),s.delete(u.pointerId),l},isHeld(){return l},dispose(){c(),s.clear(),o=null}}}function lO(e,t="all"){if(!e)return!1;let r=e.type==="Pad"||typeof e.ref=="string"&&typeof e.name=="string"&&Array.isArray(e.at)&&Number.isFinite(e.width)&&Number.isFinite(e.height);return t==="pin"?r:t==="part"?!r&&(e.type==="Component"||typeof e.library=="string"):t==="net"?typeof e.net=="string"&&!!e.net:!0}function cO(e,{scene:t,renderer:r,extent:i,bottom:n,constrained:s=!1}){let a=new e.ShadowMaterial({color:0,opacity:.18,depthWrite:!1}),o=new e.Mesh(new e.PlaneGeometry(i*6,i*6),a);o.name="Presentation stage",o.position.z=n-Math.max(3,i*.035),o.receiveShadow=!0,o.visible=!1,t.add(o);let l=new Map,c=[];t.traverse(d=>{d.isDirectionalLight&&d.castShadow&&c.push(d)});function u(d,{fast:f=!1}={}){for(let[b,x]of l)b.castShadow=d||x;o.visible=d,t.environmentIntensity=d?1:.65,r.toneMappingExposure=d?1.05:1;let y=d&&!s&&!f?2048:1024;for(let b of c)b.shadow.mapSize.x!==y&&(b.shadow.map?.dispose(),b.shadow.map=null,b.shadow.mapSize.set(y,y),b.shadow.needsUpdate=!0);r.shadowMap.needsUpdate=!0}return{apply:u,addCaster(d){l.set(d,d.castShadow),d.castShadow=o.visible||d.castShadow},get enabled(){return o.visible},dispose(){for(let[d,f]of l)d.castShadow=f;l.clear(),t.remove(o),o.geometry.dispose(),a.dispose()}}}function m0(e,t,r=1,i=4096){let n=Number.isFinite(e)&&e>0?e:1,s=Number.isFinite(t)&&t>0?t:1,a=Number.isFinite(r)&&r>0?r:1,o=Number.isFinite(i)&&i>0?i:4096;return Math.min(a,3,Math.sqrt(4e6/n/s),o/n,o/s)}function g0(e){return["low","balanced","high","presentation","photoreal-fast"].includes(e)?e:"balanced"}function hO({maxTextureSize:e=4096,maxRenderbufferSize:t=e,deviceMemory:r,hardwareConcurrency:i=0,floatTargets:n=!1,android:s=!1}={}){let a=Math.min(...[e,t].map(u=>Number.isFinite(u)&&u>0?u:4096)),o=Number.isFinite(r)&&r>0?r:null,l=a<=4096||o!==null&&o<=2,c=!l&&n&&a>=8192&&(o!==null?o>=6:a>=16384&&i>=8);return{tier:l?"constrained":c?"premium":"standard",constrained:l,premium:c,maxDimension:a,defaultQuality:s&&c?"high":"balanced",highMaxPixels:l?1e6:c?3e6:2e6}}function f_(e,t,r=1,i=4096,n="balanced",s=!1){let a=g0(n),o=Number.isFinite(e)&&e>0?e:1,l=Number.isFinite(t)&&t>0?t:1,c=s&&typeof s=="object"?s:null,u=c?c.constrained:s,d=a==="high"||a==="presentation",f=a==="photoreal-fast"?1e6:a==="presentation"?u?1e6:c?.premium?4e6:3e6:a==="high"?c?c.highMaxPixels:u?1e6:2e6:a==="low"||u?1e6:2e6,y=Math.min(m0(o,l,a==="presentation"&&!u?Math.max(1.5,r):r,i),Math.sqrt(f/o/l)),b=Math.floor(o*y)*Math.floor(l*y),x=d?96:a==="low"?12:48;return{quality:a,ratio:y,width:Math.max(1,Math.floor(o*y)),height:Math.max(1,Math.floor(l*y)),pixels:b,maxPixels:f,estimatedBytes:b*x+(a==="low"?0:2*(a==="presentation"&&!u?2048:1024)**2*4)}}function uO(e=1.6,t="high"){let r=Number.isFinite(e)&&e>0?e:1.6;return{radius:Math.max(.35,Math.min(3,r*.85)),thickness:Math.max(.12,Math.min(1,r*.3)),distanceExponent:2,distanceFallOff:1,scale:1,samples:t==="presentation"?24:12,screenSpaceRadius:!1}}function dO(e,t){let r=t==="B.Cu"?"B.Mask":"F.Mask";return Array.isArray(e?.layers)&&(e.layers.includes(r)||e.layers.includes("*.Mask"))}var Au=Object.freeze({coatedCopper:1459761,exposedCopper:12954220});function pO(e,t,r,i){let n=0,s=0;for(let a=0;a<3;a++)n+=((r[a]+i[a])/2-e[a])*t[a],s+=(i[a]-r[a])/2*Math.abs(t[a]);return n-s}function fO(e,t,r){let i=Number.isFinite(e)&&e>0?e:1,n=Number.isFinite(t)&&t>0?t:1,s=Number.isFinite(r)?r:i-n,a=Math.max(.005,s*.5);return{near:a,far:Math.max(10,i+n*4,a+1)}}var mO=Object.freeze([{x:.65,y:-.45,z:1,intensity:1.25,color:16774632},{x:.65,y:-.45,z:-1,intensity:1.25,color:16774632},{x:-.8,y:.35,z:.6,intensity:.65,color:15069183},{x:-.8,y:.35,z:-.6,intensity:.65,color:15069183}].map(Object.freeze)),pa=Object.freeze({solderMask:Object.freeze({color:870709,roughness:.46,metalness:.04,clearcoat:.3,clearcoatRoughness:.5}),substrateEdge:Object.freeze({color:11049070,roughness:.92,metalness:0}),copper:Object.freeze({metalness:.62,roughness:.38}),proxy:Object.freeze({color:3489097,metalness:.06,roughness:.66})});function gO(e){let t=e.onBeforeCompile;e.onBeforeCompile=function(i,n){t?.call(this,i,n);let s="#include <logdepthbuf_fragment>";if(!i.fragmentShader.includes(s))throw Error("Unsupported occlusion depth shader.");i.fragmentShader=i.fragmentShader.replace(s,"")};let r=e.customProgramCacheKey;e.customProgramCacheKey=function(){return r.call(this)+"|perspective-occlusion-depth-v1"}}var yO=2e5,vO=6e5;function y0(e){if(!e||!Array.isArray(e.points)||!Array.isArray(e.triangles)||!Array.isArray(e.values))throw new Error("A saved triangular result surface is required.");if(e.points.length>vO||e.triangles.length>yO)throw new Error("Saved surface exceeds the 200,000 triangle / 600,000 point limit.");let t=e.nodal!==!1;if(e.values.length!==(t?e.points.length:e.triangles.length))throw new Error("Saved result values do not match the surface.");for(let r of e.points)if(!Array.isArray(r)||r.length!==3||!r.every(i=>Number.isFinite(i)&&Number.isFinite(Math.fround(i))))throw new Error("Saved surface contains an invalid coordinate.");for(let r of e.triangles)if(!Array.isArray(r)||r.length!==3||!r.every(i=>Number.isSafeInteger(i)&&i>=0&&i<e.points.length))throw new Error("Saved surface contains an invalid triangle index.");for(let r of e.values)if(r!==null&&!Number.isFinite(r))throw new Error("Saved surface contains an invalid result value.");return{...e,nodal:t}}function m_(e){e.traverse(t=>{t.geometry?.dispose(),(Array.isArray(t.material)?t.material:[t.material]).forEach(r=>{r?.map?.dispose(),r?.dispose()})}),e.clear()}function v0(e,t=i=>i,r={}){let i=y0(e),n=r.palette;if(n!==void 0&&(!Array.isArray(n)||n.length!==4||n.some(P=>!Array.isArray(P)||P.length!==3||P.some(k=>!Number.isFinite(k)||k<0||k>255))))throw new TypeError("Choose four finite RGB palette stops.");if(r.range!==void 0&&(!Array.isArray(r.range)||r.range.length!==2||!r.range.every(Number.isFinite)||r.range[1]<=r.range[0]))throw new TypeError("Choose an increasing finite result range.");let s=new Wi,a=new Wi,o=1/0,l=-1/0;for(let P of i.values)P!==null&&(o=Math.min(o,P),l=Math.max(l,P));r.range&&(o=r.range[0],l=r.range[1]);let c=[],u=[],d=[],f=[],y=[new or(2639291),new or(52179),new or(16769114),new or(15154225)],b=P=>Number.isFinite(l-o)?(P-o)/(l-o):(P/2-o/2)/(l/2-o/2),x=P=>l>o?Math.max(0,Math.min(1,b(P))):.5,g=P=>{let k=x(P)*3,z=Math.min(2,Math.floor(k)),D=k-z;if(n){let I=n[z].map((L,Z)=>Math.round(L+(n[z+1][Z]-L)*D)/255);return new or().setRGB(...I,xi)}return y[z].clone().lerp(y[z+1],D)};i.triangles.forEach((P,k)=>{let z=i.nodal?P.map(se=>i.values[se]):P.map(()=>i.values[k]);if(z.some(se=>se===null))return;let D=P.map(se=>t(i.points[se]));if(D.some(se=>!Array.isArray(se)||se.length!==3||!se.every(ce=>Number.isFinite(ce)&&Number.isFinite(Math.fround(ce)))))throw new Error("Invalid result coordinate mapping.");let I=new je(...D[0]),L=new je(...D[1]),Z=new je(...D[2]);L.clone().sub(I).cross(Z.clone().sub(I)).lengthSq()!==0&&(D.forEach((se,ce)=>{c.push(...se);let fe=g(z[ce]);u.push(fe.r,fe.g,fe.b),r.range&&f.push(b(z[ce]))}),d.push(k))});let v=new Hr;v.setAttribute("position",new hr(c,3)),v.setAttribute("color",new hr(u,3)),r.range&&v.setAttribute("resultScalar",new hr(f,1)),v.computeBoundingSphere();let _=new en({vertexColors:!0,toneMapped:!1,side:Ze,transparent:!0,opacity:.85,depthWrite:!1,polygonOffset:!0,polygonOffsetFactor:-2,polygonOffsetUnits:-2}),E=new qr(v,_);s.add(E,a);function M(P){if(!P||P.object!==E||P.faceIndex==null)return null;let k=d[P.faceIndex],z=i.triangles[k];if(!z)return null;let D=z.map(ce=>new je(...t(i.points[ce]))),I=new je;if(ka.getBarycoord(P.point,...D,I),![I.x,I.y,I.z].every(Number.isFinite))return null;let L=z.map(ce=>i.points[ce]),Z=ce=>L[0][ce]*I.x+L[1][ce]*I.y+L[2][ce]*I.z,se=i.nodal?i.values[z[0]]*I.x+i.values[z[1]]*I.y+i.values[z[2]]*I.z:i.values[k];return{x:Z(0),y:Z(1),z:Z(2),value:se,unit:String(i.unit||""),method:i.nodal?"nodal barycentric interpolation":"saved cell value",triangle:k}}return{group:s,mesh:E,surface:i,min:o,max:l,range:Number.isFinite(o)&&Number.isFinite(l)?[o,l]:null,sample:M,setOpacity(P){Number.isFinite(P)&&(_.opacity=Math.max(0,Math.min(1,P)),E.visible=_.opacity>0)},setProbes(P=[]){if(m_(a),!Array.isArray(P))return;let k=Math.max((v.boundingSphere?.radius||1)*.012,.001);for(let z of P.slice(0,100)){if(![z.x,z.y,z.z].every(Number.isFinite))continue;let D=new qr(new po(k,12,8),new en({color:16777215,depthTest:!1}));if(D.position.set(...t([z.x,z.y,z.z])),D.renderOrder=10,D.userData.label=String(z.label||""),a.add(D),z.label){let I=document.createElement("canvas");I.width=256,I.height=64;let L=I.getContext("2d");if(L){L.fillStyle="#101d28",L.fillRect(0,0,256,64),L.fillStyle="#fff",L.font="bold 32px system-ui",L.textBaseline="middle",L.fillText(String(z.label).slice(0,12),8,32,240);let Z=new Fp(I);Z.colorSpace=xi;let se=new kg(new yp({map:Z,depthTest:!1}));se.position.copy(D.position).add(new je(0,0,k*4)),se.scale.set(k*12,k*3,1),se.renderOrder=11,a.add(se)}}}},dispose(){m_(s),s.removeFromParent()}}}function xO(e,t={}){let r=document.createElement("div");r.style.cssText="height:100%;min-height:240px;display:flex;flex-direction:column;position:relative";let i=r.attachShadow({mode:"open"}),n=document.createElement("style");n.textContent=":host{font:12px system-ui}*{box-sizing:border-box}.shell{height:100%;min-height:240px;display:flex;flex-direction:column}.bar{display:flex;flex-wrap:wrap;gap:8px;align-items:center;padding:8px}button{padding:5px 10px;border-radius:4px;border:1px solid #819597;background:transparent;color:inherit;cursor:pointer}button:focus-visible,input:focus-visible{outline:2px solid #42bd95}.stage{position:relative;flex:1;min-height:200px;overflow:hidden}.stage canvas{display:block;width:100%;height:100%;touch-action:none}.notice{padding:6px 8px}.value{padding:6px 8px;min-height:28px}label{display:flex;gap:4px;align-items:center}.title{font-weight:700}";let s=document.createElement("div");s.className="shell";let a=document.createElement("div");a.className="bar";let o=document.createElement("span");o.className="title",a.append(o);let l=document.createElement("div");l.className="stage";let c=document.createElement("div");c.className="notice";let u=document.createElement("div");u.className="value",u.setAttribute("aria-live","polite"),s.append(a,l,c,u),i.append(n,s),e.append(r);let d;try{d=new df({antialias:!0,alpha:!1})}catch{return c.textContent="3D rendering is unavailable on this device. Use the 2D result view.",{host:r,unavailable:!0,setSurface(){},setOpacity(){},setTheme(){},setProbes(){},fit(){},dispose(){r.remove()}}}d.outputColorSpace=xi,d.domElement.setAttribute("role","img"),d.domElement.setAttribute("aria-label","3D saved result surface"),l.append(d.domElement);let f=new Yo;f.background=new or(1056040);let y=new cn(45,1,.001,1e6);y.up.set(0,0,1);let b=new Wy(y,d.domElement);b.enableDamping=!0;let x=null,g=!0,v=0,_=.85,E=[],M=new Ft,P=new ou;function k(Se=!1){if(!g||!x)return;let U=new Xi().setFromObject(x.mesh),ie=U.getBoundingSphere(new on);if(U.isEmpty())return;let Ae=Math.max(ie.radius,.001),Ue=Ae/Math.sin($d.degToRad(y.fov/2))*1.25/Math.min(y.aspect,1);b.target.copy(ie.center),y.position.copy(ie.center).add(new je(...Se?[0,-1e-6,1]:[1,-1,1]).normalize().multiplyScalar(Ue)),y.near=Math.max(Ae*1e-5,1e-6),y.far=Ue+Ae*1e3,y.updateProjectionMatrix(),b.minDistance=Ae*.005,b.maxDistance=Ae*1e3,b.update()}function z(Se){if(!g)return;let U=v0(Se,([ie,Ae,Ue])=>[ie,-Ae,Ue]);x?.dispose(),x=U,f.add(U.group),U.setOpacity(_),U.setProbes(E),o.textContent=String(Se.title||"Saved result surface"),c.textContent=`${Se.zKnown?"Saved surface geometry":"No saved layer elevation; flat field"} \xB7 drag to orbit \xB7 right-drag / two fingers to pan \xB7 pinch / wheel to zoom${Number.isFinite(U.min)?` \xB7 ${U.min.toPrecision(5)}\u2013${U.max.toPrecision(5)} ${Se.unit||""}`:" \xB7 no valid samples"}`,u.textContent="Click a colored surface to probe.",k()}let D=(Se,U)=>{let ie=document.createElement("button");ie.textContent=Se,ie.type="button",ie.addEventListener("click",U),a.append(ie)};D("Fit",()=>k()),D("Top",()=>k(!0));let I=document.createElement("label");I.textContent="Opacity";let L=document.createElement("input");L.type="range",L.min="0",L.max="1",L.step=".05",L.value=String(_),L.setAttribute("aria-label","Result surface opacity"),I.append(L),a.append(I);let Z=Se=>{!g||!Number.isFinite(Se)||(_=Math.max(0,Math.min(1,Se)),L.value=String(_),x?.setOpacity(_))};L.addEventListener("input",()=>Z(Number(L.value)));function se(Se){if(!x||!x.mesh.visible)return null;let U=d.domElement.getBoundingClientRect();return!U.width||!U.height?null:(M.set((Se.clientX-U.left)/U.width*2-1,-(Se.clientY-U.top)/U.height*2+1),P.setFromCamera(M,y),x.sample(P.intersectObject(x.mesh,!1)[0]))}let ce=null,fe=Se=>{ce={id:Se.pointerId,x:Se.clientX,y:Se.clientY,moved:!1}},ze=Se=>{ce&&(ce.id!==Se.pointerId||Math.hypot(Se.clientX-ce.x,Se.clientY-ce.y)>5)&&(ce.moved=!0),t.onHover?.(se(Se))},Fe=Se=>{let U=ce&&ce.id===Se.pointerId&&!ce.moved&&(Se.button===0||Se.pointerType==="touch");if(ce=null,!U)return;let ie=se(Se);ie&&(u.textContent=`${ie.value.toPrecision(6)} ${ie.unit} at (${ie.x.toFixed(3)}, ${ie.y.toFixed(3)}, ${ie.z.toFixed(3)}) \xB7 ${ie.method}`,t.onProbe?.(ie))},Pe=()=>{ce=null},ue=()=>t.onHover?.(null);for(let[Se,U]of[["pointerdown",fe],["pointermove",ze],["pointerup",Fe],["pointercancel",Pe],["pointerleave",ue]])d.domElement.addEventListener(Se,U);let Te=()=>{if(!g)return;let Se=Math.max(l.clientWidth,1),U=Math.max(l.clientHeight,1),ie=m0(Se,U,globalThis.devicePixelRatio,d.capabilities.maxTextureSize);d.getPixelRatio()!==ie&&d.setPixelRatio(ie),d.setSize(Se,U,!1),y.aspect=Se/U,y.updateProjectionMatrix()},de=new ResizeObserver(Te);de.observe(l),Te();let Ie=Se=>{Se.preventDefault(),c.textContent="3D graphics context lost. Reopen this view to restore rendering.",g=!1,cancelAnimationFrame(v)};d.domElement.addEventListener("webglcontextlost",Ie);let Re=Se=>{r.style.background=Se?"#101d28":"#f3f7f5",r.style.color=Se?"#e7f3ef":"#172e36",f.background.setHex(Se?1056040:15988725)};Re(t.dark!==!1);try{z(t.surface)}catch(Se){throw de.disconnect(),b.dispose(),d.dispose(),r.remove(),Se}let Be=()=>{g&&(v=requestAnimationFrame(Be),b.update(),d.render(f,y))};return Be(),{host:r,setSurface:z,setOpacity:Z,setTheme:Re,fit:k,setProbes(Se){E=Array.isArray(Se)?Se:[],x?.setProbes(E)},dispose(){g=!1,cancelAnimationFrame(v),de.disconnect(),b.dispose(),x?.dispose(),d.domElement.removeEventListener("webglcontextlost",Ie);for(let[Se,U]of[["pointerdown",fe],["pointermove",ze],["pointerup",Fe],["pointercancel",Pe],["pointerleave",ue]])d.domElement.removeEventListener(Se,U);d.dispose(),r.remove()}}}var g_=Object.freeze([[26,64,115],[20,136,156],[107,196,151],[255,225,112]].map(e=>Object.freeze(e))),y_=Object.freeze({wayricad:g_,viridis:Object.freeze([[68,1,84],[49,104,142],[53,183,121],[253,231,37]].map(e=>Object.freeze(e))),inferno:Object.freeze([[0,0,4],[120,28,109],[237,105,37],[252,255,164]].map(e=>Object.freeze(e))),grayscale:Object.freeze([[0,0,0],[85,85,85],[170,170,170],[255,255,255]].map(e=>Object.freeze(e)))});function x0(e="wayricad"){if(typeof e!="string"||!Object.hasOwn(y_,e))throw new TypeError("Choose wayricad, viridis, inferno or grayscale palette.");return y_[e]}function v_(e){let t=1/0,r=-1/0;for(let i of e)Number.isFinite(i)&&(t=Math.min(t,i),r=Math.max(r,i));if(!Number.isFinite(t))return null;if(t===r){let i=.5*Math.max(1,Math.abs(t));return[Math.max(-Number.MAX_VALUE,t-i),Math.min(Number.MAX_VALUE,r+i)]}return[t,r]}var bO=1e4,wO=2e5,b0="Source XYZ translated by the saved bounds center; +Z up; no PCB registration",x_=e=>Array.isArray(e)&&e.length===3&&e.every(t=>Number.isFinite(t)&&Number.isFinite(Math.fround(t)));function w0(e,t){return Object.assign(new Error(e),{code:t,fallback:"2d"})}function b_(){return new DOMException("Saved result view was aborted.","AbortError")}function w_(e,t){for(let r=0;r<3;r++)e.min[r]=Math.min(e.min[r],t[r]),e.max[r]=Math.max(e.max[r],t[r])}function _O(e){let[t,r,i]=e,n=r.map((a,o)=>a-t[o]),s=i.map((a,o)=>a-t[o]);return Math.hypot(n[1]*s[2]-n[2]*s[1],n[2]*s[0]-n[0]*s[2],n[0]*s[1]-n[1]*s[0])>0}function _0(e,{contextPrimitives:t=[],coordinateUnit:r="source units",range:i,palette:n="wayricad"}={}){let s=x0(n),a=y0(e);if(i!==void 0&&(!Array.isArray(i)||i.length!==2||!i.every(Number.isFinite)||i[1]<=i[0]))throw new TypeError("Choose an increasing finite saved-field range.");if(a.zKnown!==!0)throw w0("No saved Z coordinates or layer elevation. Use the 2D field view.","SAVED_Z_REQUIRED");if(typeof r!="string"||r.length>80||/[\x00-\x1f]/.test(r))throw new TypeError("Choose a bounded source coordinate unit label.");if(!Array.isArray(t)||t.length>bO)throw new TypeError("Saved context exceeds 10,000 primitives.");let o={min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]},l=[],c=[],u=0,d=0,f=0,y=0;if(a.triangles.forEach((x,g)=>{if((a.nodal?x.map(v=>a.values[v]):[a.values[g]]).some(v=>v===null)||!_O(x.map(v=>a.points[v]))){d++;return}u++;for(let v of x)w_(o,a.points[v])}),!u)throw w0("No valid saved triangles with known field values. Missing samples remain holes in the 2D field view.","NO_SAVED_FIELD_VALUES");for(let x of t){let g=x?.points;if(!["line","polygon"].includes(x?.type)||!Array.isArray(g)||g.length<(x.type==="polygon"?3:2)||!g.every(x_)){y++;continue}if(f+=g.length,f>wO)throw new TypeError("Saved context exceeds 200,000 explicit XYZ points.");let v=g.map(_=>[..._]);l.push({type:x.type,points:v}),v.forEach(_=>w_(o,_))}y&&c.push(y+" context primitives without supported explicit XYZ geometry were omitted; no elevation was invented."),d&&c.push(d+" triangles with missing values or degenerate geometry remain unrendered.");let b=o.min.map((x,g)=>x/2+o.max[g]/2);if(o.max.some((x,g)=>x-o.min[g]>1e7))throw w0("Saved geometry exceeds the bounded 3D coordinate span. Use the 2D field view.","SAVED_GEOMETRY_RANGE");return{surface:a,context:l,bounds:o,origin:b,palette:n,stops:s,range:i?[...i]:v_(a.values),coordinateUnit:r||"source units",coordinateConvention:b0,renderedTriangles:u,omittedTriangles:d,diagnostics:c}}function __(e,t=g_){let r=e.mesh.material,i=r.clone(),n=r.onBeforeCompile,s=r.customProgramCacheKey(),a=!1,o=i;i.vertexColors=!1,i.onBeforeCompile=(u,d)=>{if(n.call(i,u,d),!u.vertexShader.includes("#include <begin_vertex>")||!u.fragmentShader.includes("#include <color_fragment>"))throw new Error("Unsupported saved-field color shader.");u.uniforms.savedFieldPalette={value:t.map(f=>new je(...f.map(y=>y/255)))},u.vertexShader=u.vertexShader.replace("#include <common>",`#include <common>
attribute float resultScalar;
varying float vSavedResultScalar;`).replace("#include <begin_vertex>",`#include <begin_vertex>
vSavedResultScalar = resultScalar;`),u.fragmentShader=u.fragmentShader.replace("#include <common>",`#include <common>
varying float vSavedResultScalar;
uniform vec3 savedFieldPalette[4];`).replace("#include <color_fragment>",`#include <color_fragment>
float fieldBand = clamp(vSavedResultScalar, 0.0, 1.0) * 3.0;
vec3 fieldRGB = fieldBand < 1.0 ? mix(savedFieldPalette[0], savedFieldPalette[1], fieldBand) : fieldBand < 2.0 ? mix(savedFieldPalette[1], savedFieldPalette[2], fieldBand - 1.0) : mix(savedFieldPalette[2], savedFieldPalette[3], fieldBand - 2.0);
fieldRGB = floor(fieldRGB * 255.0 + 0.5) / 255.0;
diffuseColor.rgb = sRGBTransferEOTF(vec4(fieldRGB, 1.0)).rgb;`)},i.customProgramCacheKey=()=>s+":wayricad-scalar-palette-v1",e.mesh.material=i;let l=e.setOpacity;e.setOpacity=u=>{l(u),o&&(o.opacity=r.opacity)};let c={material:i,fallbackMaterial:r,get mode(){return o?"scalar":"vertex-color"},useFallback(){return a||!o?!1:(e.mesh.material=r,o.dispose(),o=null,!0)},dispose(){a||(a=!0,o&&r.dispose())}};return e.mesh.geometry.getAttribute("resultScalar").array.every(Number.isFinite)||c.useFallback(),c}function EO(e,t={}){let r=_0(e,t),i=u=>u.map((d,f)=>d-r.origin[f]),n=v0(r.surface,i,{palette:r.stops,range:r.range}),s=__(n,r.stops),a=new Wi,o=[];s.mode==="vertex-color"&&r.diagnostics.push("Scalar values exceed the GPU normalization range; vertex-color interpolation is active. Probe values remain exact.");let l=null,c=!1;try{for(let u of r.context){let d=u.points;for(let f=1;f<d.length;f++)o.push(...i(d[f-1]),...i(d[f]));u.type==="polygon"&&o.push(...i(d.at(-1)),...i(d[0]))}if(o.length){let u=new Hr;u.setAttribute("position",new hr(o,3)),l=new Fn(u,new tn({color:8886951,transparent:!0,opacity:.65})),a.add(l)}a.add(n.group)}catch(u){throw s.dispose(),n.dispose(),l?.geometry.dispose(),l?.material.dispose(),u}return{group:a,overlay:n,prepared:r,contextMesh:l,scalarAppearance:s,dispose(){c||(c=!0,s.dispose(),n.dispose(),l?.geometry.dispose(),l?.material.dispose(),a.clear(),a.removeFromParent())}}}function SO(e){let t=u=>{let d=e?.[u];if(!x_(d)||d.some(f=>Math.abs(f)>1e12))throw new TypeError("Choose finite bounded source-view camera vectors.");return[...d]},r=t("position"),i=t("target"),n=t("up"),s=r.map((u,d)=>u-i[d]),a=Math.hypot(...s),o=Math.hypot(...n);if(!(a>0)||!(o>0))throw new TypeError("Choose a nondegenerate source-view camera.");let l=s.map(u=>u/a),c=n.map(u=>u/o);if(Math.hypot(l[1]*c[2]-l[2]*c[1],l[2]*c[0]-l[0]*c[2],l[0]*c[1]-l[1]*c[0])<1e-6)throw new TypeError("Choose a camera up vector independent of its direction.");return{position:r,target:i,up:n}}function MO(e,t,r={}){if(r.signal?.aborted)throw b_();let i=e?.ownerDocument;if(!i||typeof e.append!="function")throw new TypeError("Choose a saved result viewer container.");let n,s;try{n=_0(t,r)}catch(Se){if(Se.fallback!=="2d")throw Se;s=Se}n&&r.range!==void 0&&(r={...r,range:[...n.range]});let a=i.createElement("div"),o=i.createElement("div"),l=i.createElement("div"),c=i.createElement("div");a.style.cssText="height:100%;min-height:240px;display:flex;flex-direction:column;position:relative;font:12px/1.5 system-ui",o.style.cssText="position:relative;flex:1;min-height:180px;overflow:hidden",l.style.cssText=c.style.cssText="padding:6px 8px;overflow-wrap:anywhere",l.setAttribute("role","status"),c.setAttribute("aria-live","polite"),a.append(o,l,c),e.append(a);let u=Se=>{a.style.background=Se?"#101d28":"#f3f7f5",a.style.color=Se?"#e7f3ef":"#172e36"};u(r.dark!==!1);let d=Se=>{let U=!1;l.textContent=Se.message,o.hidden=!0;let ie=()=>{U||(U=!0,r.signal?.removeEventListener("abort",ie),a.remove())};r.signal?.addEventListener("abort",ie,{once:!0});let Ae={host:a,unavailable:!0,diagnostic:{code:Se.code||"WEBGL_UNAVAILABLE",message:Se.message,fallback:"2d"},setSurface(Ue){return _0(Ue,r),!1},setTheme:u,setOpacity(){},fit(){return!1},getCameraState(){return null},setCameraState(){return!1},getRenderStats(){return{unavailable:!0,renderCount:0,coordinateConvention:b0,coordinateUnit:r.coordinateUnit||"source units"}},dispose:ie};try{r.onDiagnostics?.([Se.message])}catch(Ue){throw ie(),Ue}return Ae};if(s)return d(s);let f;try{f=new df({antialias:!0,alpha:!1})}catch{return d(new Error("3D graphics are unavailable on this device. Use the 2D field view."))}let y=!0,b=null,x=.85,g=0,v=0,_=!1,E=null,M=null,P=null,k=null,z=new Yo,D=new cn(45,1,.001,1e3);D.up.set(0,0,1),f.outputColorSpace=xi,f.domElement.style.cssText="display:block;width:100%;height:100%;touch-action:none",f.domElement.setAttribute("role","img"),f.domElement.setAttribute("aria-label","3D saved field in source XYZ coordinates"),o.append(f.domElement);let I=[],L=new Ft,Z=new ou,se=p_(),ce=(Se,U,ie)=>{Se.addEventListener(U,ie),I.push(()=>Se.removeEventListener(U,ie))},fe=()=>o.clientWidth>0&&o.clientHeight>0,ze=()=>{y&&(P.setState({documentVisible:!i.hidden,hasSize:fe()}),P.invalidate())};f.debug.onShaderError=()=>{_=!0};function Fe(){if(y){k.update(),_=!1;try{if(f.render(z,D),_)throw new Error("Saved scalar color shader failed.");g++}catch(Se){if(b?.scalarAppearance.useFallback()){v++,b.prepared.diagnostics.push("Scalar color mapping is unavailable; vertex-color interpolation is active. Probe values remain exact."),Te(b.prepared),r.onDiagnostics?.([...b.prepared.diagnostics]),_=!1;try{if(f.render(z,D),_)throw Se;g++}catch{l.textContent="3D graphics could not draw this field. Use the 2D field view."}}else l.textContent="3D graphics could not draw this field. Use the 2D field view."}}}function Pe(){if(!b)return;let Se=Math.max(b.sphere.radius,1e-12),U=D.position.distanceTo(b.sphere.center);D.near=Math.max(Se*1e-7,(U-Se)*.5,1e-15),D.far=Math.max(U+Se*4,D.near*2),D.updateProjectionMatrix()}function ue(Se=!1){if(!y||!b||new Xi().setFromObject(b.group).isEmpty())return!1;let U=b.sphere,ie=Math.max(U.radius,1e-12),Ae=Qw(ie,D.fov,D.aspect,1.2);return k.target.copy(U.center),D.position.copy(U.center).add(new je(...Se?[0,-1e-6,1]:[1,-1,1]).normalize().multiplyScalar(Ae)),Pe(),k.minDistance=ie*1e-4,k.maxDistance=ie*100,k.update(),ze(),!0}function Te(Se){l.textContent="Independent saved field \xB7 "+Se.coordinateUnit+" \xB7 source XYZ, +Z up \xB7 saved Z"+(Se.surface.zBasis?" ("+String(Se.surface.zBasis).slice(0,160)+")":"")+" \xB7 no PCB registration"+(Se.context.length?" \xB7 retained source context":"")+" \xB7 "+Se.renderedTriangles+" colored triangles \xB7 "+Se.range.map(U=>Number(U.toPrecision(6))).join(" \u2013 ")+(Se.surface.unit?" "+String(Se.surface.unit).slice(0,80):"")+(b?.scalarAppearance.mode==="vertex-color"?" \xB7 vertex-color interpolation fallback":""),c.textContent="Drag to orbit \xB7 right-drag or two fingers to pan \xB7 pinch or wheel to zoom \xB7 tap a colored triangle to probe."}function de(Se,{retainCamera:U=!1}={}){if(!y)return!1;let ie=EO(Se,r);ie.overlay.setOpacity(x),z.add(ie.group),ie.sphere=new Xi().setFromObject(ie.group).getBoundingSphere(new on);let Ae=b;return b=ie,Ae?.dispose(),Te(b.prepared),U?Pe():ue(),r.onDiagnostics?.([...b.prepared.diagnostics]),ze(),!0}function Ie(){if(!y)return;let Se=fe();if(P.setState({hasSize:Se}),!Se){ze();return}let U=o.clientWidth,ie=o.clientHeight,Ae=m0(U,ie,globalThis.devicePixelRatio,f.capabilities.maxTextureSize);f.getPixelRatio()!==Ae&&f.setPixelRatio(Ae),f.setSize(U,ie,!1),D.aspect=U/ie,D.updateProjectionMatrix(),ze()}function Re(Se){if(!b?.overlay.mesh.visible)return null;let U=f.domElement.getBoundingClientRect();return!U.width||!U.height?null:(L.set((Se.clientX-U.left)/U.width*2-1,-(Se.clientY-U.top)/U.height*2+1),Z.setFromCamera(L,D),b.overlay.sample(Z.intersectObject(b.overlay.mesh,!1)[0]))}function Be(){if(y){y=!1,P?.dispose(),E?.disconnect(),M?.disconnect();for(let Se of I)Se();I.length=0,r.signal?.removeEventListener("abort",Be),k?.dispose(),b?.dispose(),b=null,z.clear(),f.dispose(),f.domElement.width=f.domElement.height=1,a.remove()}}try{if(k=new Wy(D,f.domElement),k.enableDamping=!1,P=u_({request:Se=>requestAnimationFrame(Se),cancel:Se=>cancelAnimationFrame(Se),render:Fe,canRender:()=>y&&!i.hidden&&fe(),state:{documentVisible:!i.hidden,hasSize:fe()}}),ce(k,"change",()=>{Pe(),ze()}),ce(i,"visibilitychange",()=>{P.setState({documentVisible:!i.hidden}),i.hidden||ze()}),ce(f.domElement,"pointerdown",Se=>se.down(Se)),ce(f.domElement,"pointermove",Se=>{se.move(Se),r.onHover&&r.onHover(Re(Se))}),ce(f.domElement,"pointerup",Se=>{if(!se.up(Se)||Se.button!==0&&Se.pointerType!=="touch")return;let U=Re(Se);U&&(c.textContent=U.value.toPrecision(6)+" "+U.unit+" at source XYZ ("+[U.x,U.y,U.z].map(ie=>Number(ie.toPrecision(7))).join(", ")+") "+b.prepared.coordinateUnit+" \xB7 "+U.method,r.onProbe?.(U))}),ce(f.domElement,"pointercancel",Se=>se.cancel(Se)),ce(f.domElement,"pointerleave",()=>r.onHover?.(null)),ce(f.domElement,"webglcontextlost",Se=>{Se.preventDefault(),P.setState({contextAvailable:!1}),l.textContent="3D graphics context interrupted. Saved field geometry is retained."}),ce(f.domElement,"webglcontextrestored",()=>{P.setState({contextAvailable:!0}),b&&Te(b.prepared),ze()}),typeof ResizeObserver=="function"?(E=new ResizeObserver(Ie),E.observe(o)):i.defaultView&&ce(i.defaultView,"resize",Ie),M=d_(P,o),r.signal?.addEventListener("abort",Be,{once:!0}),z.background=new or(r.dark!==!1?1056040:15988725),Ie(),de(n.surface),r.signal?.aborted)throw Be(),b_()}catch(Se){throw Be(),Se}return{host:a,unavailable:!1,setSurface:de,setPalette(Se){if(x0(Se),!y)return!1;let U=r;r={...r,palette:Se};try{return de(b.prepared.surface,{retainCamera:!0})}catch(ie){throw r=U,ie}},setProbes(Se){b?.overlay.setProbes(Se),ze()},setTheme(Se){y&&(u(!!Se),z.background.setHex(Se?1056040:15988725),ze())},setOpacity(Se){if(y){if(!Number.isFinite(Se)||Se<0||Se>1)throw new TypeError("Choose result opacity between 0 and 1.");x=Se,b.overlay.setOpacity(Se),ze()}},fit:ue,getCameraState(){return{position:D.position.toArray(),target:k.target.toArray(),up:D.up.toArray()}},setCameraState(Se){if(!y)return!1;let U=SO(Se);D.position.fromArray(U.position),k.target.fromArray(U.target),D.up.fromArray(U.up);let ie=D.position.distanceTo(k.target);return k.minDistance=Math.min(k.minDistance,ie),k.maxDistance=Math.max(k.maxDistance,ie),k.update(),ze(),!0},getRenderStats(){let Se=b?.prepared;return{unavailable:!1,renderCount:g,renderActivity:{...P.stats(),observesIntersection:!!M},drawCalls:f.info.render.calls,gpuTextures:f.info.memory.textures,renderedTriangles:Se?.renderedTriangles||0,omittedTriangles:Se?.omittedTriangles||0,contextPrimitives:Se?.context.length||0,range:Se?[...Se.range]:null,palette:Se?.palette||"wayricad",colorInterpolation:b?.scalarAppearance.mode||null,scalarColorFallbacks:v,coordinateUnit:Se?.coordinateUnit||r.coordinateUnit||"source units",coordinateConvention:b0,sourceOrigin:Se?[...Se.origin]:null,sourceBounds:Se?{min:[...Se.bounds.min],max:[...Se.bounds.max]}:null}},dispose:Be}}function Tu(e){return Object.assign(new Error(e),{code:"UNSUPPORTED_RESULT_REGISTRATION"})}function AO(e,{bounds:t,thickness:r,layers:i=[]},n={}){let s=y0(e),a=s.zBasis,o=s.layer??n.layer??null;if(n.layer!==void 0&&s.layer!==void 0&&n.layer!==s.layer)throw Tu("Selected layer does not match the saved result layer.");if(o!==null&&(typeof o!="string"||!i.includes(o)))throw Tu("Saved result layer is not present on this board.");if(a!=null&&!["front-depth","board-center"].includes(a))throw Tu("Saved result elevation basis is unsupported; use the standalone result scene.");if(s.zKnown===!0?!["front-depth","board-center"].includes(a):!["F.Cu","B.Cu"].includes(s.layer))throw Tu("Saved elevation requires front-depth or board-center; without saved Z only saved F.Cu/B.Cu layers can be placed.");if(!t||![t.minX,t.minY,t.maxX,t.maxY,r].every(Number.isFinite)||t.minX>t.maxX||t.minY>t.maxY||r<=0)throw new TypeError("Choose finite board bounds and a positive thickness.");let l=n.palette===void 0?null:x0(n.palette);if(n.range!==void 0&&(!Array.isArray(n.range)||n.range.length!==2||!n.range.every(Number.isFinite)||n.range[1]<=n.range[0]))throw new TypeError("Choose an increasing finite result range.");let c=t.minX/2+t.maxX/2,u=t.minY/2+t.maxY/2,d=([y,b,x])=>[y-c,u-b,s.zKnown===!0?a==="front-depth"?r/2-x:x:s.layer==="F.Cu"?r/2:-r/2],f=n.range?[...n.range]:l?v_(s.values):null;if(l&&!f)throw Tu("No known saved field values are available for placement.");return{surface:s,transform:d,stops:l,palette:n.palette??null,layer:o,basis:s.zKnown===!0?a:s.layer,flat:s.zKnown!==!0,range:f,throughBoard:n.throughBoard!==!1}}function TO(e,t,r={}){let i=AO(e,t,r),n=v0(i.surface,i.transform,{...i.range?{range:i.range}:{},...i.stops?{palette:i.stops}:{}}),s=n.sample;n.sample=c=>{let u=s(c);return u?{...u,overlayOwner:r.owner}:null};let a=null,o=!1;try{n.mesh.material.depthTest=!i.throughBoard,n.mesh.renderOrder=i.throughBoard?20:0,i.stops&&(a=__(n,i.stops))}catch(c){throw a?.dispose(),n.dispose(),c}let l=[];return a?.mode==="vertex-color"&&l.push("Scalar values exceed the GPU normalization range; vertex-color interpolation is active. Probe values remain exact."),{overlay:n,prepared:i,scalarAppearance:a,diagnostics:l,state(){return{placed:!0,palette:i.palette,layer:i.layer,basis:i.basis,flat:i.flat,throughBoard:i.throughBoard,triangles:n.mesh.geometry.getAttribute("position").count/3,range:n.range?[...n.range]:null,diagnostics:[...l]}},useColorFallback(){return a?.useFallback()?(l.push("Scalar color mapping is unavailable; vertex-color interpolation is active. Probe values remain exact."),!0):!1},dispose(){o||(o=!0,a?.dispose(),n.dispose())}}}function CO(e,{scene:t,invalidate:r=()=>{},isActive:i=()=>!0}={}){let n=null,s,a=l=>l?.owner===void 0||l.owner===s,o=l=>({placed:!1,layer:null,basis:null,throughBoard:!1,triangles:0,range:null,diagnostics:[],...l?{reason:l}:{}});return{get overlay(){return n?.overlay||null},getAnalysisOverlayState(){return n?n.state():o()},setAnalysisOverlay(l,c={}){if(!i())return o("3D viewer is closed.");if(!l)return a(c)?(n?.dispose(),n=null,s=void 0,r(),o("Overlay cleared.")):o("Overlay belongs to another owner.");let u;try{u=TO(l,e,c)}catch(f){if(f.code==="UNSUPPORTED_RESULT_REGISTRATION")return o(f.message);throw f}t.add(u.overlay.group);let d=n;return n=u,s=c.owner,d?.dispose(),r(),n.state()},setAnalysisProbes(l,c={}){return!n||!a(c)?!1:(n.overlay.setProbes(l),r(),!0)},setAnalysisOpacity(l,c={}){return!n||!a(c)?!1:(n.overlay.setOpacity(l),r(),!0)},useColorFallback(){return n?.useColorFallback()||!1},dispose(){n?.dispose(),n=null,s=void 0}}}var ks=e=>e&&typeof e=="object"&&!Array.isArray(e)?e.quoted:e,Of=e=>Array.isArray(e)?String(ks(e[0])):"",E0=(e,t)=>e.filter(r=>Of(r)===t),yo=(e,t)=>E0(e,t)[0],Cu=(e,t,r)=>(t[0]-e[0])*(r[1]-e[1])-(t[1]-e[1])*(r[0]-e[0]),Ru=(e,t,r)=>Math.abs(Cu(e,t,r))<1e-8&&r[0]>=Math.min(e[0],t[0])-1e-8&&r[0]<=Math.max(e[0],t[0])+1e-8&&r[1]>=Math.min(e[1],t[1])-1e-8&&r[1]<=Math.max(e[1],t[1])+1e-8;function RO(e,t,r,i){let n=Cu(e,t,r),s=Cu(e,t,i),a=Cu(r,i,e),o=Cu(r,i,t);return n*s<0&&a*o<0||Ru(e,t,r)||Ru(e,t,i)||Ru(r,i,e)||Ru(r,i,t)}function E_(e,t){let r=!1;for(let i=0,n=t.length-1;i<t.length;n=i++){let s=t[i],a=t[n];if(Ru(s,a,e))return!1;s[1]>e[1]!=a[1]>e[1]&&e[0]<(a[0]-s[0])*(e[1]-s[1])/(a[1]-s[1])+s[0]&&(r=!r)}return r}function PO(e,t,r=[]){if(!Array.isArray(e)||e.length<3||!Array.isArray(t)||t.length<3||e.some(i=>!i.every(Number.isFinite)||!E_(i,t)||r.some(n=>E_(i,n))))return!1;for(let i of[t,...r])for(let n=0;n<e.length;n++)for(let s=0;s<i.length;s++)if(RO(e[n],e[(n+1)%e.length],i[s],i[(s+1)%i.length]))return!1;return!0}function IO(e,{maxContours:t=1e5}={}){if(!Number.isSafeInteger(t)||t<1)throw TypeError("Invalid zone contour index limit.");let r=new Map;for(let d of e)Of(d)==="net"&&r.set(ks(d[1]),String(ks(d[2])||""));let i=new Map,n=0,s=0,a=0,o=0,l=0,c=0,u=0;for(let d of e){if(Of(d)!=="zone")continue;let f=E0(d,"filled_polygon"),y=f.length>0;y||n++;let b=yo(d,"layers")?.slice(1).map(ks)??[ks(yo(d,"layer")?.[1])],x=ks(yo(d,"uuid")?.[1])||ks(yo(d,"tstamp")?.[1]),g=ks(yo(d,"net")?.[1]),v=String(ks(yo(d,"net_name")?.[1])||r.get(g)||(typeof g=="string"?g:""));for(let _ of y?f:E0(d,"polygon")){let E=yo(_,"pts")||[],M=E[1]instanceof Float64Array?E[1].length/2:0,P=!1;for(let z of E)Of(z)==="xy"&&((!Number.isFinite(Number(ks(z[1])))||!Number.isFinite(Number(ks(z[2]))))&&(P=!0),M++);if(P||M<3){o++;continue}let k=ks(yo(_,"layer")?.[1]);for(let z of k?[k]:b){if(typeof z!="string")continue;if(s>=t){l++;continue}let D={id:String(x||"saved-zone-"+s),net:v,layer:z,filled:y,size:M,contour:s,sourcePoints:E};i.has(z)||i.set(z,[]),i.get(z).push(D),s++,a+=M,z.endsWith(".Cu")?c++:u++}}}return{forLayer:d=>i.get(d)||[],stats:()=>({contours:s,copperContours:c,nonCopperContours:u,points:a,unfilled:n,invalid:o,omitted:l,layers:i.size,retainsCoordinateCopies:!1})}}var Df=e=>e&&["x","y","z"].every(t=>typeof e[t]=="number"&&Number.isFinite(e[t])),Nc=e=>({x:e.x,y:e.y,z:e.z,approximate:!!e.approximate});function NO(e,t){if(!Df(e)||!Df(t))return null;let r={x:t.x-e.x,y:t.y-e.y,z:t.z-e.z},i=Math.hypot(r.x,r.y,r.z);return Number.isFinite(i)?{from:Nc(e),to:Nc(t),delta:r,distance:i,approximate:!!(e.approximate||t.approximate)}:null}function S0(e,t="mm"){return typeof e!="number"||!Number.isFinite(e)||e<0?"\u2014":t==="mil"?(e/.0254).toFixed(2)+" mil":e.toFixed(3)+" mm"}var LO=class{constructor(){this.pending=null,this.records=[],this.selected=null,this.nextId=1}add(e){if(!Df(e))return null;if(!this.pending)return this.pending=Nc(e),this.selected=null,{pending:this.pending};let t=NO(this.pending,e);return t?(t.id=this.nextId++,this.pending=null,this.records.unshift(t),this.records.length>5&&(this.records.length=5),this.selected=t,t):null}replay(e){let t=this.records.find(r=>r.id===Number(e));return t?(this.pending=null,this.selected=t,t):null}clear(){this.pending=null,this.records=[],this.selected=null}snapshot(){return{pending:this.pending?Nc(this.pending):null,records:this.records.map(e=>({...e,from:Nc(e.from),to:Nc(e.to),delta:{...e.delta}})),selected:this.selected?.id??null}}};function kO(e,t,r,{mode:i="edges",tolerance:n=12}={}){if(!e||![e.x,e.y,n].every(Number.isFinite)||n<=0||!["edges","corners"].includes(i)||!Array.isArray(t))return null;let s=null,a=(o,l,c)=>{let u=Math.hypot(l.x-e.x,l.y-e.y);u<=n&&(!s||u<s.distance)&&(s={point:{x:o.x,y:o.y,z:o.z},screen:{x:l.x,y:l.y},kind:c,distance:u})};for(let o of t.slice(0,1e4)){if(!Array.isArray(o)||o.length!==2||!o.every(Df))continue;let[l,c]=o,u=r(l),d=r(c);if(!u||!d||![u.x,u.y,u.z,d.x,d.y,d.z].every(Number.isFinite)||u.z<-1||u.z>1||d.z<-1||d.z>1)continue;if(i==="corners"){a(l,u,"mesh vertex"),a(c,d,"mesh vertex");continue}let f=d.x-u.x,y=d.y-u.y,b=f*f+y*y;if(b<1e-10)continue;let x=Math.max(0,Math.min(1,((e.x-u.x)*f+(e.y-u.y)*y)/b)),g=Number.isFinite(u.w)&&u.w>0?u.w:1,v=Number.isFinite(d.w)&&d.w>0?d.w:1,_=x*g/((1-x)*v+x*g);a({x:l.x+(c.x-l.x)*_,y:l.y+(c.y-l.y)*_,z:l.z+(c.z-l.z)*_},{x:u.x+f*x,y:u.y+y*x},"mesh edge")}return s}var Uf=[{id:"top",label:"Top",direction:[0,0,1],up:[0,1,0]},{id:"bottom",label:"Bottom",direction:[0,0,-1],up:[0,-1,0]},{id:"front",label:"Front",direction:[0,-1,0],up:[0,0,1]},{id:"back",label:"Back",direction:[0,1,0],up:[0,0,1]},{id:"left",label:"Left",direction:[-1,0,0],up:[0,0,1]},{id:"right",label:"Right",direction:[1,0,0],up:[0,0,1]},{id:"isometric",label:"Isometric",direction:[.45,-.38,1],up:[0,0,1]}];function OO(e){let t=e===!0?"top":e===!1?"iso":e;return Uf.find(r=>r.id===t)||Uf.at(-1)}function DO({onChange:e=()=>{}}={}){let t=!1,r=0,i=-1,n=null,s=new Set,a=new WeakSet,o=new Map;function l(v){let _=v.source?.data,E=0,M=P=>{Number.isFinite(P?.width)&&Number.isFinite(P?.height)&&(E+=Math.ceil(P.width*P.height*4*(P.data?.BYTES_PER_ELEMENT||1)*(v.generateMipmaps?4/3:1)))};if(Array.isArray(_))for(let P of _)M(P);else M(_);return E}function c(){for(let[v,_]of o)if(v.instanceMatrix?.array!==_.matrix||v.instanceColor?.array!==_.color||v.boneMatrices!==_.bones||v.isTexture&&l(v)!==_.textureBytes)return!1;return!0}function u(v){return!v||typeof v!="object"||typeof v.dispose!="function"||(t?d(v):s.has(v)||(s.add(v),r++,e())),v}function d(v){a.has(v)||(a.add(v),v.dispose(),v.isTexture&&v.source?.data?.close?.())}function f(v,_=!1){let E=new Set,M=k=>{k&&typeof k.dispose=="function"&&!s.has(k)&&E.add(k)},P=k=>{if(!(!k||_&&s.has(k))){for(let z in k)Object.hasOwn(k,z)&&k[z]?.isTexture&&M(k[z]);M(k)}};return v?.traverse?.(k=>{if(k.isInstancedMesh&&M(k),M(k.geometry),Array.isArray(k.material))for(let z of k.material)P(z);else P(k.material);k.skeleton&&M(k.skeleton)}),E}function y(v,_=1/0,E=1/0,M=!1){let P=f(v,M),k=M&&!P.size&&i===r&&c()?n:g(P);if(!t&&(k.retainedGeometryBytes>_||k.retainedTextureBytes>E)){for(let z of P)d(z);throw Error("Decoded model geometry or textures exceed this device\u2019s memory budget.")}for(let z of P)u(z);return t||(k!==n&&b(),n=k,i=r),v}function b(){for(let v of s)if(v.isInstancedMesh||v.boneMatrices||v.isTexture){let _=o.get(v);_||(_={},o.set(v,_)),_.matrix=v.instanceMatrix?.array,_.color=v.instanceColor?.array,_.bones=v.boneMatrices,v.isTexture&&(_.textureBytes=l(v))}}function x(){if(!t){t=!0;for(let v of s)d(v);s.clear(),o.clear(),n=null,i=-1}}function g(v){let _=new Set,E=0,M=0,P=0,k=D=>{let I=D?.buffer;I&&!_.has(I)&&(_.add(I),E+=I.byteLength)},z=D=>{if(D.isTexture&&(M++,P+=l(D)),D.isInstancedMesh&&(k(D.instanceMatrix?.array),k(D.instanceColor?.array)),D.boneMatrices&&k(D.boneMatrices),D.isBufferGeometry){let I=L=>k(L?.array||L?.data?.array);for(let L in D.attributes)Object.hasOwn(D.attributes,L)&&I(D.attributes[L]);for(let L in D.morphAttributes)if(Object.hasOwn(D.morphAttributes,L))for(let Z of D.morphAttributes[L])I(Z);I(D.index)}};for(let D of s)z(D);if(v)for(let D of v)z(D);return{retainedResources:s.size+(v?.size||0),retainedGeometryBytes:E,retainedTextures:M,retainedTextureBytes:P}}return{track:u,retain:y,dispose:x,stats:()=>g(),discard(v){for(let _ of f(v))d(_)},retainClone:(v,_,E)=>y(v,_,E,!0)}}function UO({onPick:e,onContextMenu:t,isHeld:r=()=>!1},i=6){let n=p_(i);return{down:s=>n.down(s),move:s=>n.move(s),cancel:s=>n.cancel(s),up(s,{select:a=!0}={}){let o=n.up(s);return a&&o&&!r()&&(s.button===0?e(s):s.button===2&&t(s)),o},context(s){s.preventDefault?.(),s.button!==2&&!r()&&t(s)}}}var S_=e=>{let t=Math.max(0,Math.min(1,e));return t*t*(3-2*t)};function Lc(e){if(!Number.isFinite(e))throw new TypeError("Expand amount must be finite.");let t=Math.max(0,Math.min(100,e));return{amount:t,components:S_(t/35),layers:S_((t-35)/65)}}function FO({request:e,cancel:t,now:r=()=>performance.now(),update:i,canRun:n=()=>!0,reducedMotion:s=()=>!1,settle:a=()=>{}}){let o=0,l=0,c=null,u=0,d=!1;function f(){!d&&c===null&&o!==l&&n()&&(u=r(),c=e(y))}function y(b){if(c=null,d||!n())return;let x=Math.max(1,Math.min(64,b-u));u=b,o+=(l-o)*(1-Math.exp(-x/85)),Math.abs(l-o)<.04&&(o=l),i(o),!d&&(o!==l?c=e(y):a(o))}return{set(b,{immediate:x=!1}={}){return d||(l=Lc(b).amount,x||s()?(c!==null&&t(c),c=null,o=l,i(o),d||a(o)):f()),l},resume:f,get:()=>o,target:()=>l,running:()=>c!==null,dispose(){d=!0,c!==null&&t(c),c=null}}}function zO(e,t,{maxGap:r=4,componentLift:i=8}={}){let n=[...t.layers||[]].filter(g=>typeof g.name=="string"&&Number.isFinite(g.z)).sort((g,v)=>v.z-g.z).slice(0,64),s=new Map(n.map((g,v)=>[g.name,(n.length-1)/2-v])),a=new WeakMap,o=new WeakMap,l=0,c=g=>{let v=Lc(l).layers;return v===0?0:(s.get(g)||0)*r*v},u=g=>c(g)+(g==="B.Cu"?-1:1)*i*Lc(l).components,d=g=>n.reduce((v,_)=>!v||Math.abs(_.z-g)<Math.abs(v.z-g)?_:v,null)?.name;function f(g,v){a.has(g)||a.set(g,g.position.z),g.position.z=a.get(g)+c(v),g.updateMatrix?.()}function y(g,v){a.has(g)||a.set(g,g.position.z),g.position.z=a.get(g)+u(v),g.updateMatrix?.()}function b(g,v){if(!g?.isInstancedMesh||!v||!(v.zMax>v.zMin))return;o.has(g)||o.set(g,g.instanceMatrix.array.slice());let _=o.get(g),E=c(d(v.zMin)),M=c(d(v.zMax)),P=(v.zMax-v.zMin+M-E)/(v.zMax-v.zMin),k=new e.Matrix4,z=new e.Vector3(1,1,P);for(let D=0;D<g.count;D++)k.fromArray(_,D*16),k.elements[14]+=E,k.scale(z),g.setMatrixAt(D,k);g.instanceMatrix.needsUpdate=!0,g.computeBoundingSphere?.(),g.computeBoundingBox?.()}function x(g){g.traverse(v=>{v.geometry&&(v.userData.explodeSpan?b(v,v.userData.explodeSpan):f(v,v.userData.layer||v.userData.record?.layer))})}return{offset:c,componentOffset:u,component:y,layer:f,barrels:b,overlay:x,set(g){return l=Lc(g).amount,l},get:()=>l,phases:()=>Lc(l),span:()=>r*Lc(l).layers*Math.max(0,n.length-1),layers:n.map(g=>g.name)}}function BO(){let e=new WeakMap;return{sync(t,r){let i=t?.group;return i?r>0?(e.has(i)||e.set(i,i.visible),i.visible=!1,!0):(e.has(i)&&(i.visible=e.get(i),e.delete(i)),!1):!1}}}function jO(e,{scene:t,objects:r,visible:i=()=>!0,colorForLayer:n=()=>7534079,maxInstances:s=5e4,maxMeshes:a=2048}){let o=new e.Group;o.name="Selected net shine-through",t.add(o);let l=new Map,c=new Map,u=new e.Matrix4,d="",f=0,y=0,b=!1,x={sourceScans:0,recordScans:0,transformSyncs:0};function g(P,k=!1,z=!1,D="accent",I=!1){let L=[P,k,z,D,I].join("|");if(c.has(L))return c.get(L);let Z={color:I||P==="through"?12954220:D==="source"?n(P):7534079,transparent:!0,opacity:k?.14:.95,depthTest:!1,depthWrite:!1,toneMapped:!1},se=z?new e.LineBasicMaterial(Z):new e.MeshBasicMaterial({...Z,side:e.DoubleSide});return c.set(L,se),se}function v(){for(let P of l.values())o.remove(P.mesh),P.mesh.dispose?.(),P.edge&&(o.remove(P.edge),P.edge.geometry.dispose());l.clear();for(let P of c.values())P.dispose();c.clear(),f=0,y=0,b=!1,d=""}function _(P,{color:k="accent"}={}){let z=JSON.stringify([[...P].sort(),k]);if(!P.size){l.size&&v();return}z!==d&&(v(),d=z);for(let D of l.values())D.mesh.visible=!1,D.edge&&(D.edge.visible=!1);for(let D of r()){if(x.sourceScans++,D.userData?.record?.type==="Component")continue;let I=D.userData?.identity||"",L=D.userData?.record?.type==="Zone",Z=I.startsWith("spike:via-barrel:");if(!D.geometry?.attributes?.position||!L&&!/^spike:(copper-track|copper-pad|via-barrel):/.test(I))continue;let se=L?D.userData.record.layer:decodeURIComponent(I.split(":")[2]||"");if(!i(D,se))continue;let ce=l.get(D);if(!ce){if(l.size>=a){b=!0;continue}let fe=D.userData.records,ze=[],Fe=Math.max(0,s-f);if(D.isInstancedMesh&&fe){for(let Te=0;Te<Math.min(fe.length,D.count);Te++)if(x.recordScans++,P.has(fe[Te].net)){if(ze.length>=Fe){b=!0;break}ze.push(Te)}}else P.has(D.userData.record?.net)&&ze.push(null);if(!ze.length)continue;let Pe=Math.max(0,s-f);if(ze.length>Pe&&(ze.length=Pe,b=!0),!ze.length)continue;let ue=D.isInstancedMesh?new e.InstancedMesh(D.geometry,g(se,!1,!1,k,Z),ze.length):new e.Mesh(D.geometry,g(se,L,!1,k,Z));if(ue.matrixAutoUpdate=!1,ue.renderOrder=201,ue.frustumCulled=!1,o.add(ue),ce={mesh:ue,indices:ze,edge:null,layer:se},L)if(D.geometry.attributes.position.count*6+y<=2e5){let Te=new e.LineSegments(new e.EdgesGeometry(D.geometry,1),g(se,!1,!0,k));y+=Te.geometry.attributes.position.count,Te.matrixAutoUpdate=!1,Te.renderOrder=202,Te.frustumCulled=!1,o.add(Te),ce.edge=Te}else b=!0;l.set(D,ce),f+=ze.length}E(D,ce)}}function E(P,k){if(x.transformSyncs++,P.updateWorldMatrix(!0,!1),k.mesh.matrix.copy(P.matrixWorld),k.mesh.matrixWorldNeedsUpdate=!0,k.mesh.visible=!0,P.isInstancedMesh){for(let z=0;z<k.indices.length;z++)P.getMatrixAt(k.indices[z],u),k.mesh.setMatrixAt(z,u);k.mesh.instanceMatrix.needsUpdate=!0}k.edge&&(k.edge.matrix.copy(P.matrixWorld),k.edge.matrixWorldNeedsUpdate=!0,k.edge.visible=!0)}function M(){for(let[P,k]of l)k.mesh.visible=i(P,k.layer),k.edge&&(k.edge.visible=k.mesh.visible),k.mesh.visible&&E(P,k)}return{update:_,syncTransforms:M,clear:v,stats:()=>{let P=0,k=0;for(let z of l.values())z.mesh.visible&&(P++,k+=z.indices.length);return{meshes:P,instances:k,retainedMeshes:l.size,limited:b,throughBoard:!0,...x}},dispose(){v(),t.remove(o)}}}function Pu(e,t="all"){let r={zone:1,track:-1,pad:-2,via:-3}[e];if(typeof r!="number")throw Error("Unknown copper surface role.");if(!["all","cap","wall"].includes(t))throw Error("Unknown copper surface kind.");return{polygonOffset:t!=="wall",polygonOffsetFactor:t==="cap"?r/2:0,polygonOffsetUnits:t==="wall"?0:r*2}}function M_(e,t,r){return["cap","wall"].map(i=>M0(new e.MeshStandardMaterial({...r,...Pu(t,i)}),t,i))}function M0(e,t,r="all"){let i=Pu(t,r);if(!i.polygonOffset)return e;let n=e.onBeforeCompile,s=e.customProgramCacheKey();return e.onBeforeCompile=function(a,o){n?.call(this,a,o),this.polygonOffset=!o?.capabilities?.logarithmicDepthBuffer;let l="#include <logdepthbuf_fragment>";if(!a.fragmentShader.includes(l))throw Error("Unsupported copper depth shader.");a.fragmentShader=a.fragmentShader.replace(l,l+`
#ifdef USE_LOGDEPTHBUF
 gl_FragDepth = clamp(gl_FragDepth + `+(i.polygonOffsetUnits*4/16777215).toPrecision(12)+`, 0.0, 1.0);
#endif`)},e.customProgramCacheKey=()=>s+"|copper-log-depth-v1:"+t+":"+r,e}var A_=e=>e&&typeof e=="object"&&!Array.isArray(e)?e.quoted:e,Ff=e=>Array.isArray(e)?String(A_(e[0])):"",VO=(e,t)=>Array.isArray(e)?e.find(r=>Ff(r)===t):void 0,A0=e=>["F.SilkS","B.SilkS"].includes(A_(VO(e,"layer")?.[1]));function HO(e){let t=[e[0]];for(let r of e.slice(1)){let i=Ff(r);if(["version","generator","layers"].includes(i)||A0(r)&&i.startsWith("gr_"))t.push(r);else if(i==="footprint"){let n=r.filter((s,a)=>a<2||["at","layer","uuid","tstamp"].includes(Ff(s))||A0(s)&&["fp_line","fp_arc","fp_rect","fp_circle","fp_poly","fp_text","fp_curve","property"].includes(Ff(s)));n.some(s=>A0(s))&&t.push(n)}}return t}function GO(e,t,r=2048,i=!1){if(![e,t,r].every(Number.isFinite)||e<=0||t<=0||r<1)return null;let n=Math.min(2048,r),s=i?524288:1048576,a=Math.min(16,n/e,n/t,Math.sqrt(s/e/t)),o=Math.max(1,Math.floor(e*a)),l=Math.max(1,Math.floor(t*a));return{width:o,height:l,scale:Math.min(o/e,l/t),pixels:o*l,maxPixels:s}}function T_(e,t,r,i,n,s){let a=l=>({x:(l.x-r.minX)*i.width/(r.maxX-r.minX),y:(l.y-r.minY)*i.height/(r.maxY-r.minY)}),o=i.scale;if(e.clearRect(0,0,i.width,i.height),e.save(),n?.length){e.beginPath();for(let l of n)l.forEach((c,u)=>{let d=a({x:c[0],y:c[1]});u?e.lineTo(d.x,d.y):e.moveTo(d.x,d.y)}),e.closePath();e.clip("evenodd")}for(let l of t){if(e.save(),e.strokeStyle=e.fillStyle="#f2efda",e.lineWidth=Math.max(.6,(l.width||.15)*o),e.lineCap=e.lineJoin="round",l.type==="text"){let c=a(l),u=(l.fontHeight||l.size||1)*o;e.translate(c.x,c.y),e.rotate((l.angle||0)*Math.PI/180),(l.mirror||l.mirrored)&&e.scale(-1,1),e.font=`${l.bold?"bold ":""}${l.italic?"italic ":""}${u*4/3}px Arial,sans-serif`,e.textAlign=l.align||"center",e.textBaseline=l.baseline||"middle",l.fontWidth&&l.fontHeight&&e.scale(l.fontWidth/l.fontHeight,1),String(l.text||"").split(`
`).forEach((d,f,y)=>e.fillText(d,0,(f-(y.length-1)/2)*u*(l.lineSpacing||1.5))),e.restore();continue}if(e.beginPath(),l.type==="arc"){let c=s?.(l.start,l.mid,l.end);if(c){let u=a(c);e.arc(u.x,u.y,c.r*o,c.start,c.end,c.ccw)}}else if(l.type==="circle"){let c=a(l);e.arc(c.x,c.y,l.r*o,0,2*Math.PI)}else{for(let[c,u]of(l.points||[]).entries()){let d=a(u);c?e.lineTo(d.x,d.y):e.moveTo(d.x,d.y)}l.type==="polygon"&&e.closePath()}l.fill&&e.fill(),l.stroke!==!1&&e.stroke(),e.restore()}e.restore()}function T0(e,t,r,i,n,s,a=.2){t.updateMatrixWorld();let o=[];for(let x of[-1,1])for(let g of[-1,1])for(let v of[-1,1])o.push(new e.Vector3(v,g,x).unproject(t));let l=[];for(let x=0;x<8;x++)for(let g of[1,2,4]){let v=x^g;if(v<x)continue;let _=o[x],E=o[v],M=E.z-_.z;if(Math.abs(M)<1e-12)continue;let P=(r-_.z)/M;P>=0&&P<=1&&l.push({x:_.x+(E.x-_.x)*P+n,y:s-_.y-(E.y-_.y)*P})}if(!l.length)return null;let c=Math.max(i.minX,Math.min(...l.map(x=>x.x))),u=Math.min(i.maxX,Math.max(...l.map(x=>x.x))),d=Math.max(i.minY,Math.min(...l.map(x=>x.y))),f=Math.min(i.maxY,Math.max(...l.map(x=>x.y)));if(u-c<1e-6||f-d<1e-6)return null;let y=(u-c)*a,b=(f-d)*a;return{minX:Math.max(i.minX,c-y),maxX:Math.min(i.maxX,u+y),minY:Math.max(i.minY,d-b),maxY:Math.min(i.maxY,f+b)}}function C_(e,t,r=4096,i=!1){if(![e,t,r].every(Number.isFinite)||e<=0||t<=0||r<1)return null;let n=Math.min(i?1024:2048,r),s=i?1048576:4194304,a=Math.min(n/e,n/t,Math.sqrt(s/e/t)),o=Math.max(1,Math.floor(e*a)),l=Math.max(1,Math.floor(t*a));return{width:o,height:l,scale:Math.min(o/e,l/t),pixels:o*l,maxPixels:s}}function WO(e,{camera:t,document:r,bounds:i,centerX:n,centerY:s,graphics:a,resources:o,invalidate:l,arcThrough:c,setTimer:u=setTimeout,clearTimer:d=clearTimeout,onError:f=()=>{}}){let y=[],b=!1,x=null,g=null,v=!1,_=0;function E(P){P.crop=null,P.scale=null,P.mesh.material.map=P.base,P.mesh.position.set(0,0,P.z),P.mesh.scale.set(1,1,1)}function M(){if(x=null,!(b||v)){if(r.hidden){g=null;return}for(let P of y){if(!P.mesh.visible||!P.mesh.parent?.visible||(P.front?t.position.z<=P.z:t.position.z>=P.z))continue;let k=T0(e,t,P.z,i,n,s);if(!k)continue;let z=k.maxX-k.minX,D=k.maxY-k.minY,I=C_(z,D,a.maxDimension,a.constrained);if(I)try{let L=Math.floor(Math.min(a.constrained?1024:2048,a.maxDimension));P.texture||(P.canvas.width=P.canvas.height=L);let Z=P.canvas.getContext("2d");if(!Z)continue;Z.clearRect(0,0,L,L),T_(Z,P.primitives,k,I,P.clips,c),_++,P.texture||(P.texture=o.track(new e.CanvasTexture(P.canvas)),P.texture.colorSpace=e.SRGBColorSpace,P.texture.anisotropy=P.base.anisotropy),P.texture.repeat.set(I.width/L,I.height/L),P.texture.offset.set(0,1-I.height/L),P.texture.needsUpdate=!0,P.mesh.material.map=P.texture,P.crop=k,P.scale=I.scale,P.mesh.scale.set(z/(i.maxX-i.minX),D/(i.maxY-i.minY),1),P.mesh.position.set((k.minX+k.maxX)/2-n,s-(k.minY+k.maxY)/2,P.z)}catch(L){E(P),f(L)}}l()}}return{add(P,k,z,D){y.push({mesh:P,primitives:k,clips:z,front:D,z:P.position.z,base:P.material.map,canvas:r.createElement("canvas"),texture:null})},sync({moving:P=!1}={}){if(b)return;for(let D of y)D.z=D.mesh.position.z;if(P){x!==null&&d(x),x=null;for(let D of y){if(D.crop){let I=T0(e,t,D.z,i,n,s,0),L=D.crop;(!I||I.minX<L.minX||I.maxX>L.maxX||I.minY<L.minY||I.maxY>L.maxY)&&E(D)}D.mesh.material.map=D.crop?D.texture:D.base}v=!0,g=null;return}v=!1;for(let D of y){let I=D.crop?D.texture:D.base;D.mesh.material.map!==I&&(D.mesh.material.map=I)}t.updateMatrixWorld();let k=[...t.matrixWorld.elements,...t.projectionMatrix.elements,...y.flatMap(D=>[D.mesh.visible&&D.mesh.parent?.visible?1:0,D.z])];if(g&&k.every((D,I)=>Math.abs(D-g[I])<=1e-5*Math.max(1,Math.abs(D),Math.abs(g[I]))))return;g=k;let z=!1;for(let D of y){if(!D.mesh.visible||!D.mesh.parent?.visible||(D.front?t.position.z<=D.z:t.position.z>=D.z))continue;let I=T0(e,t,D.z,i,n,s,0),L=D.crop;if(!(I&&L&&I.minX>=L.minX&&I.maxX<=L.maxX&&I.minY>=L.minY&&I.maxY<=L.maxY)){E(D),z=!0;continue}let Z=C_(I.maxX-I.minX,I.maxY-I.minY,a.maxDimension,a.constrained);Z&&Z.scale>D.scale*1.5&&(z=!0)}z&&x===null&&(x=u(M,100))},stats:()=>({repaints:_,moving:v,pending:x!==null,detailTextures:y.filter(P=>P.texture).length}),dispose(){if(!b){b=!0,x!==null&&d(x),x=null;for(let P of y)E(P),P.canvas.width=P.canvas.height=1;y.length=0}}}}var XO=GL(Wy),zf=e=>Number.parseInt(globalThis.KiCadLayerColors.hexFor(e).slice(1),16),YO=`
  :host{display:block;width:100%;height:100%;container-type:inline-size;font:12px/1.4 system-ui,-apple-system,"Segoe UI",sans-serif;
    --ink:#e6e9ef;--surface:#151820;--bar:#1e2128;--border:#343944;--accent:#91b9ff;
    --muted:#9ca5b5;--button:#292d36;--button-border:#343944;--button-ink:#e6e9ef;
    --hint:#1e2128e8;--panel:#1e2128f2;--menu:#252a34;--notice:#1e2128;color:var(--ink);color-scheme:dark;--tools-bottom:58px}
  :host([data-theme="light"]){--ink:#252c38;--surface:#e7ebf1;--bar:#fff;--border:#d9dee7;
    --accent:#336ac2;--muted:#616d80;--button:#edf0f5;--button-border:#d9dee7;--button-ink:#252c38;
    --hint:#ffffffed;--panel:#fffffff2;--menu:#fff;--notice:#fff;color-scheme:light}
  *{box-sizing:border-box}.shell{display:flex;flex-direction:column;width:100%;height:100%;min-height:0;background:var(--surface)}
  .bar{display:flex;align-items:center;gap:6px;min-height:40px;padding:5px 10px;background:var(--bar);border-bottom:1px solid var(--border);flex-wrap:nowrap;flex-shrink:0;min-width:0}
  .title{font-size:10px;font-weight:650;letter-spacing:.07em;color:var(--muted);white-space:nowrap}.detail{font-size:11px;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--muted)}.spacer{flex:1;min-width:0}
  button,select{background:var(--button);border:1px solid var(--button-border);color:var(--button-ink);padding:4px 8px;border-radius:5px;font:500 11px/1.4 system-ui;min-height:28px;cursor:pointer;flex-shrink:0}
  select{color-scheme:dark}select option{background:var(--menu);color:var(--ink)}select option:disabled{color:var(--muted)}:host([data-theme="light"]) select{color-scheme:light}
  button:hover,select:hover{border-color:var(--accent)}button:focus-visible,select:focus-visible,input:focus-visible,summary:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
  .bar button{display:inline-flex;align-items:center;justify-content:center;gap:5px;background:transparent;border-color:transparent}.bar button:hover,.bar button[aria-expanded=true]{background:var(--button);border-color:var(--button-border)}.bar svg{width:15px;height:15px;flex-shrink:0}.view-select{max-width:105px;background:transparent}.bar .divider{width:1px;height:18px;background:var(--border);flex-shrink:0}
  label{display:flex;align-items:center;gap:7px;white-space:nowrap;color:var(--muted);font-size:11px}input{accent-color:var(--accent)}.visibility-options{position:absolute;right:10px;top:10px;z-index:6;width:min(260px,calc(100% - 20px));max-height:calc(100% - 20px);overflow:auto;padding:12px;background:var(--menu);border:1px solid var(--border);border-radius:8px;box-shadow:0 8px 24px #0004;display:grid;gap:12px}.visibility-options[hidden]{display:none}.visibility-options fieldset{min-width:0;margin:0;padding:0;border:0;display:grid;gap:9px}.visibility-options fieldset+fieldset{border-top:1px solid var(--border);padding-top:12px}.visibility-options legend{padding:0 0 8px;color:var(--muted);font-size:10px;font-weight:650;letter-spacing:.06em;text-transform:uppercase}.visibility-options label{white-space:normal;min-width:0}.visibility-options select{min-width:0;width:130px;max-width:65%;margin-left:auto;flex-shrink:1}.visibility-options label>span{min-width:0}.visibility-options{overscroll-behavior:contain;scrollbar-gutter:stable}.display-heading{position:sticky;top:-12px;z-index:1;margin:-12px -12px 0;padding:10px 12px;background:var(--menu);border-bottom:1px solid var(--border)}.visibility-options input{width:16px;height:16px;margin:0}.display-heading{display:flex;align-items:center;justify-content:space-between;font-weight:600}.display-heading button{min-height:24px;padding:1px 6px}.quality-help{margin:0;color:var(--muted);font-size:10px;line-height:1.5}
  .stage{position:relative;flex:1;min-height:0;overflow:hidden}.canvas{position:absolute;inset:0}.canvas canvas{display:block;width:100%;height:100%}
  .hint{padding:4px 10px;color:var(--muted);background:var(--bar);font-size:10px;border-top:1px solid var(--border);flex-shrink:0}
  .inspector{position:absolute;right:12px;bottom:12px;width:min(280px,45%);max-height:50%;overflow:auto;background:var(--panel);border:1px solid var(--border);border-radius:7px;padding:10px;box-shadow:0 8px 28px #0005}
  .inspector[hidden],.menu[hidden]{display:none}.inspector h2{font-size:13px;margin:0 0 6px;color:var(--accent)}.inspector dl{display:grid;grid-template-columns:auto 1fr;gap:3px 8px;margin:0}.inspector dt{color:var(--muted)}.inspector dd{margin:0;overflow-wrap:anywhere}
  .menu{position:absolute;z-index:4;display:grid;gap:3px;padding:5px;border:1px solid var(--border);border-radius:5px;background:var(--menu);box-shadow:0 7px 25px #0005}
  .notice{padding:3px 9px;background:var(--notice);color:var(--muted);font-size:10px;border-top:1px solid var(--border);flex-shrink:0}.notice details{display:inline;margin-left:8px}.notice summary{display:inline;cursor:pointer;color:var(--accent)}.notice details[open]{display:block;margin:6px 0 0}.notice ul{max-height:120px;overflow:auto;margin:6px 0;padding-left:16px;line-height:1.6}.quality-notice{position:absolute;left:12px;right:12px;top:10px;z-index:7;padding:10px 12px;border:1px solid #bf725c;border-radius:7px;background:var(--panel);color:var(--ink);font-size:12px;max-width:560px;max-height:calc(100% - 20px);overflow:auto}.quality-notice[hidden]{display:none}.quality-notice button{margin:6px 0 0 8px}
  button[aria-pressed=true]{border-color:var(--accent);color:var(--accent)}.measurement-panel{position:absolute;bottom:10px;left:10px;z-index:5;width:min(350px,calc(100% - 20px));padding:10px 12px;border:1px solid var(--border);border-radius:8px;background:var(--panel);box-shadow:0 4px 18px #0003;display:grid;gap:6px;max-height:calc(100% - 20px);overflow:auto;overscroll-behavior:contain}.measurement-panel[hidden],.measurement-label[hidden]{display:none}.measurement-heading{display:flex;align-items:center;gap:6px}.measurement-heading strong{font-size:12px;margin-right:auto}.measurement-panel output{font:600 18px/1.3 system-ui;color:var(--ink);font-variant-numeric:tabular-nums}.measurement-panel small{color:var(--muted);font-size:10px}.measurement-panel .measurement-tools{display:flex;align-items:center;gap:6px}.measurement-panel .measurement-tools select{min-width:0;flex:1}.measurement-panel p{margin:0;color:var(--muted);font-size:11px}.measurement-label{position:absolute;z-index:4;pointer-events:none;padding:4px 7px;border:1px solid #c5a35f;border-radius:5px;background:var(--panel);color:var(--ink);font:600 12px/1.4 system-ui;white-space:nowrap;box-shadow:0 2px 8px #0004}:host([data-measuring=true]) .hint{display:none}
  @media(max-width:700px){.detail{display:none}.bar{gap:4px;padding-inline:6px}.hint{display:none}.inspector{width:min(260px,65%)}}@media(max-width:380px){.title{display:none}.bar{gap:2px}.bar button{padding-inline:5px}.view-select{max-width:90px}}
  @media(pointer:coarse){button,select{min-height:40px}.bar{min-height:50px}.visibility-options label{min-height:32px}}
  :host([data-embedded="true"]) .shell{position:relative}
  :host([data-embedded="true"]) .bar{position:absolute;z-index:5;top:12px;left:12px;right:auto;max-width:calc(100% - 24px);flex-wrap:wrap;gap:3px;min-height:36px;padding:4px;border:1px solid var(--border);border-radius:9px;box-shadow:0 4px 16px #0002;background:var(--bar)}
  :host([data-embedded="true"]) .bar .title,:host([data-embedded="true"]) .bar .detail,:host([data-embedded="true"]) .bar .spacer,:host([data-embedded="true"]) .bar .divider,:host([data-embedded="true"]) .bar .fit-action,:host([data-embedded="true"]) .hint,:host([data-embedded="true"]) .notice{display:none}
  :host([data-embedded="true"]) .bar button{min-height:28px;padding:5px 7px}
  :host([data-embedded="true"]) .visibility-options{top:var(--tools-bottom);max-height:calc(100% - var(--tools-bottom) - 10px)}
  :host([data-embedded="true"]) .quality-notice{top:calc(var(--tools-bottom) + 4px);max-height:calc(100% - var(--tools-bottom) - 16px)}
  .bar{gap:3px;min-height:34px;height:34px;padding:2px 5px}.bar .title,.bar .detail,.bar .spacer,.bar .divider{display:none}
  .bar button,.bar select,.bar summary{appearance:none;box-sizing:border-box;min-height:28px;height:28px;margin:0;padding:3px 6px;font:600 11px/1 system-ui}
  .bar .view-select{max-width:86px}.bar .tools-more{position:relative;flex:0 0 auto}.bar .tools-more>summary{display:inline-flex;align-items:center;justify-content:center;min-width:42px;border:1px solid transparent;border-radius:5px;color:var(--button-ink);cursor:pointer;list-style:none}.bar .tools-more>summary::-webkit-details-marker{display:none}.bar .tools-more[open]>summary{background:var(--button);border-color:var(--button-border)}
  .bar .tools-panel{position:absolute;z-index:9;right:0;top:calc(100% + 4px);display:grid;gap:4px;width:min(230px,calc(100cqw - 12px));max-height:var(--tools-panel-height,240px);overflow:auto;overscroll-behavior:contain;padding:6px;border:1px solid var(--border);border-radius:7px;background:var(--menu);box-shadow:0 8px 24px #0004}
  .bar .tools-panel>button{justify-content:flex-start;width:100%;min-height:30px;height:30px}.bar .tools-panel .explode-control{display:grid!important;grid-template-columns:auto 1fr auto;gap:5px;min-width:0;white-space:nowrap}.bar .tools-panel .explode-control input{width:100%!important;min-width:0!important}
  :host([data-embedded="true"]) .bar{top:6px;left:6px;right:auto;max-width:calc(100% - 12px);min-height:34px;height:34px;padding:2px 4px;flex-wrap:nowrap}
  :host([data-embedded="true"]) .bar button,:host([data-embedded="true"]) .bar select,:host([data-embedded="true"]) .bar summary{min-height:28px;height:28px;padding:3px 5px}
  :host([data-embedded="true"]) .bar .tools-panel{left:0;right:auto}
  @media(pointer:coarse){.bar{min-height:34px;height:34px}.bar button,.bar select,.bar summary{min-height:28px;height:28px}}

`;function C0(e={}){let t=["arcs","pads","vias","tracks","fills","polygons","bodies","silkscreen"],r=[...new Set((Array.isArray(e.hiddenTypes)?e.hiddenTypes:[]).filter(n=>typeof n=="string"&&n.length<=40).slice(0,64))],i=["top","bottom"].includes(e.side)?e.side:"all";return{hiddenTypes:r,side:i,supportedTypes:t,unsupportedTypes:r.filter(n=>!t.includes(n)),visible(n,s){return!r.includes(n)&&!(i==="top"&&s?.startsWith("B."))&&!(i==="bottom"&&s?.startsWith("F."))}}}function Iu(e,t){let r=new mc;return e.forEach((i,n)=>{let[s,a]=t(i);n===0?r.moveTo(s,a):r.lineTo(s,a)}),r}function qO(e,t){let r=e.outlineLoops?.filter(s=>s.length>=3)||[],i=r[0]||[[e.bounds.minX,e.bounds.minY],[e.bounds.maxX,e.bounds.minY],[e.bounds.maxX,e.bounds.maxY],[e.bounds.minX,e.bounds.maxY]],n=new Fa;Iu(i,t).getPoints().forEach((s,a)=>{a===0?n.moveTo(s.x,s.y):n.lineTo(s.x,s.y)});for(let s of r.slice(1))n.holes.push(Iu(s,t));return n}function Nu(e,t,r,i,n,s){if(!i.length)return null;let a=new Mp(t,r,i.length),o=new mi;return i.forEach((l,c)=>{n(o,l),o.updateMatrix(),a.setMatrixAt(c,o.matrix)}),a.instanceMatrix.needsUpdate=!0,a.userData.records=i,a.userData.identity=s,e.add(a),a}function KO(e,t,r={}){r||={};let i=h_(r.appearance??"realistic"),n=r.dark!==!1,s=r.sourceSnapshot?(r.sourceParser||globalThis.KiCadDesignDiff).preparedFile(r.sourceSnapshot,r.sourceKey,t):globalThis.KiCadDesignDiff.parse(t),a=IO(s),o=E3(t,s,{zonePoints:!1}),l=O3(s),c=o.pads.map(q=>({...q,...l.get(q.id)})),u=[...o.geometryWarnings||[]];if(!o?.bounds||!Number.isFinite(o.width)||!Number.isFinite(o.height))throw new Error("SPIKE could not parse this PCB layout.");let d=document.createElement("div");d.dataset.theme=n?"dark":"light",d.dataset.embedded=r.embedded===!0&&typeof r.onDiagnostics=="function"?"true":"false";let f=d.attachShadow({mode:"open"}),y=document.createElement("style");y.textContent=YO;let b=document.createElement("div");b.className="shell";let x=document.createElement("div");x.className="bar",x.setAttribute("role","toolbar"),x.setAttribute("aria-label","3D tools");let g=document.createElement("div");g.className="stage";let v=document.createElement("div");v.className="canvas";let _=document.createElement("div");_.className="hint",_.textContent="Drag to orbit \xB7 right-drag to pan \xB7 wheel to zoom \xB7 click to inspect";let E=document.createElement("div");E.className="inspector",E.hidden=!0;let M=document.createElement("div");M.className="menu",M.hidden=!0;let P=document.createElement("div");P.className="notice",P.textContent="Material preview \xB7 mask openings follow saved pad layer flags \xB7 footprint stand-ins where linked models are unavailable.";let k=document.createElement("div");k.className="quality-notice",k.hidden=!0,k.setAttribute("role","status"),g.append(k),g.append(v,E,M),b.append(x,g,_,P),f.append(y,b),e.append(d);let z=document.createElement("strong");z.className="title",z.textContent="3D VIEW";let D=document.createElement("span");D.className="detail",D.textContent=`${o.width.toFixed(1)} \xD7 ${o.height.toFixed(1)} mm \xB7 ${o.components.length} parts \xB7 ${o.tracks.length} tracks`;let I=document.createElement("span");I.className="spacer";function L(q,Oe,ot,Nt=q){let Lt=document.createElement("button");if(Lt.type="button",Lt.title=Nt,Lt.setAttribute("aria-label",Nt),ot){let lr=document.createElementNS("http://www.w3.org/2000/svg","svg"),pr=document.createElementNS("http://www.w3.org/2000/svg","path");lr.setAttribute("viewBox","0 0 24 24"),lr.setAttribute("fill","none"),lr.setAttribute("stroke","currentColor"),lr.setAttribute("stroke-width","1.6"),lr.setAttribute("stroke-linecap","round"),lr.setAttribute("stroke-linejoin","round"),lr.setAttribute("aria-hidden","true"),pr.setAttribute("d",ot),lr.append(pr),Lt.append(lr)}let Ot=document.createElement("span");return Ot.textContent=q,Lt.append(Ot),Lt.addEventListener("click",()=>{Oe(),Ct()}),x.append(Lt),Lt}let Z=document.createElement("section");Z.className="visibility-options",Z.id="display-options",Z.hidden=!0,Z.setAttribute("aria-label","3D display settings"),g.append(Z);let se=document.createElement("div");se.className="display-heading",se.append(document.createTextNode("Display"));let ce=document.createElement("button");ce.type="button",ce.textContent="\xD7",ce.title="Close display settings",ce.setAttribute("aria-label","Close display settings"),ce.onclick=()=>Te(!1,!0),se.append(ce);let fe=document.createElement("fieldset"),ze=document.createElement("legend");ze.textContent="Rendering",fe.append(ze);let Fe=document.createElement("fieldset"),Pe=document.createElement("legend");Pe.textContent="Visible geometry",Fe.append(Pe),Z.append(se,fe,Fe);function ue(){if(b.clientHeight&&d.style.setProperty("--tools-panel-height",Math.max(72,Math.min(280,b.clientHeight-50))+"px"),d.dataset.embedded!=="true")return;let q=g.getBoundingClientRect(),Oe=x.getBoundingClientRect(),ot=Math.min(Math.max(8,Math.ceil(Oe.bottom-q.top+6)),Math.max(8,q.height-180));d.style.setProperty("--tools-bottom",ot+"px")}function Te(q,Oe=!1){q&&(ue(),typeof Sl<"u"&&(Sl.open=!1)),Z.hidden=!q,Bc.setAttribute("aria-expanded",String(q)),Oe&&Bc.focus()}function de(q,Oe,ot){let Nt=document.createElement("label"),Lt=document.createElement("input");return Lt.type="checkbox",Lt.checked=Oe,Lt.addEventListener("change",()=>{ot(Lt.checked),Ct()}),Nt.append(Lt,document.createTextNode(q)),Fe.append(Nt),Lt}x.append(z,D,I);let Ie="pocket-kivi:3d-quality:v1",Re="balanced",Be=!1;try{let q=localStorage.getItem(Ie);["low","balanced","high"].includes(q)&&(Re=q,Be=!0)}catch{}r.quality&&(Re=g0(r.quality));let Se=document.createElement("label");Se.className="quality-label";let U=document.createElement("span");U.textContent="Quality";let ie=document.createElement("select");ie.setAttribute("aria-label","3D rendering quality"),ie.title="Photoreal Fast: studio stage, reflections and cached shadows, without screen-space effects. Presentation: studio stage, dense occlusion and enhanced shadows. High: ambient occlusion and enhanced antialiasing. Balanced: responsive studio lighting. Low: reduced memory.";for(let[q,Oe]of[["low","Low"],["balanced","Balanced"],["high","High"],["photoreal-fast","Photoreal Fast"],["presentation","Presentation"]]){let ot=document.createElement("option");ot.value=q,ot.textContent=Oe,ie.append(ot)}ie.value=Re,Se.append(U,ie);let Ae=(o.bounds.minX+o.bounds.maxX)/2,Ue=(o.bounds.minY+o.bounds.maxY)/2,Ge=([q,Oe])=>[q-Ae,Ue-Oe],nt=([q,Oe])=>[q,-Oe],Qe=De(),ct=(q,Oe)=>Qe.get(JSON.stringify([q.outline,q.drill||null,Oe]),()=>new Kp(ye(q),{depth:Oe,bevelEnabled:!1,curveSegments:8})),ye=q=>{let Oe=new Fa;return Iu(q.outline,nt).getPoints().forEach((ot,Nt)=>Nt?Oe.lineTo(ot.x,ot.y):Oe.moveTo(ot.x,ot.y)),q.drill&&Oe.holes.push(Iu(q.drill,nt)),Oe},dt=Math.max(1,o.width),xt=Math.max(1,o.height),Dt=Math.max(dt,xt),We=o.stackup?.filter(q=>Number.isFinite(q.thickness)).reduce((q,Oe)=>q+Oe.thickness,0)||1.6,mt=We/2,it=-mt,st=new Yo;st.background=new or(n?1382432:15199217);let oe=null,F=DO({onChange:()=>oe?.invalidate()}),le=new cn(45,1,.1,Math.max(3e3,Dt*30));le.up.set(0,0,1);let pe=new df({antialias:!1,logarithmicDepthBuffer:!0,alpha:!1,powerPreference:"high-performance"}),Le=pe.getContext(),He=hO({maxTextureSize:pe.capabilities.maxTextureSize,maxRenderbufferSize:Le.getParameter(Le.MAX_RENDERBUFFER_SIZE),deviceMemory:globalThis.navigator?.deviceMemory,hardwareConcurrency:globalThis.navigator?.hardwareConcurrency,floatTargets:pe.extensions.has("EXT_color_buffer_float"),android:/Android/i.test(globalThis.navigator?.userAgent||"")});oe=tO(Le);let at=(He.constrained?32:He.premium?96:64)*1024*1024,rt=(He.constrained?32:64)*1024*1024,ht={budgetBytes:rt,retainedBytes:0,renderedContours:0,vertices:0,rejected:0},Tt=(He.constrained?16:He.premium?64:32)*1024*1024,Mt=V(He.constrained?8192:32768),Ut=R(He.constrained,o.components.length);!Be&&!r.quality&&(Re=He.defaultQuality);let Kt=!0,fr=!1,er=0,Zt=null,Gt=Re,Er=!1;function ut(){st.background.setHex(d.dataset.theme==="dark"?1513237:16250350)}let zt=()=>v.clientWidth>0&&v.clientHeight>0,It=u_({request:q=>requestAnimationFrame(q),cancel:q=>cancelAnimationFrame(q),render:yD,canRender:()=>Kt&&!fr&&!document.hidden&&zt(),state:{documentVisible:!document.hidden,hasSize:zt()}});function Ct(){Kt&&(It.setState({documentVisible:!document.hidden,hasSize:zt()}),It.invalidate())}function rr(q,Oe=!1){k.replaceChildren(document.createTextNode(q)),k.hidden=!1;let ot=document.createElement("button");if(ot.type="button",ot.textContent="Dismiss",ot.onclick=()=>{k.hidden=!0},k.append(ot),Oe){let Nt=document.createElement("button");Nt.type="button",Nt.textContent="Retry graphics",Nt.onclick=()=>pe.forceContextRestore(),k.append(Nt)}}function $t(){if(Zt){for(let q of Zt.passes)q.dispose?.(),q instanceof r0&&(q.gtaoMaterial.dispose(),q.blendMaterial.dispose(),q.depthTexture?.dispose());Zt.composer.dispose(),Zt=null}}function xr(){if($t(),oe.invalidate(),Gt==="low")return;let q=["high","presentation"].includes(Gt)&&Kr!=="translucent"&&dr.get()===0,Oe=pe.extensions.has("EXT_color_buffer_float");if(q&&!Oe)throw Error("Floating-point render targets are unavailable.");let ot=new In(1,1,{type:Oe?Ts:Ji,depthBuffer:!0,stencilBuffer:!1}),Nt=new i3(pe,ot),Lt=[];Zt={composer:Nt,passes:Lt,occlusion:q};let Ot=new n3(st,le);if(Lt.push(Ot),q){let wr=new r0(st,le,1,1,void 0,uO(We,Gt));gO(wr.normalMaterial),wr.blendIntensity=.65,wr.updatePdMaterial({radius:4,rings:2,samples:Gt==="presentation"?24:12});let Pr=wr.overrideVisibility.bind(wr);wr.overrideVisibility=()=>{Pr(),st.traverse(Qt=>{(Array.isArray(Qt.material)?Qt.material:[Qt.material]).some($r=>$r&&($r.transparent||$r.depthTest===!1))&&(Qt.visible=!1)})},Lt.push(wr)}let lr=new h3,pr=new u3(1,1);for(let wr of[pr.areaTexture,pr.searchTexture])wr.image?.addEventListener?.("load",()=>{oe.invalidate(),Ct()},{once:!0});Lt.push(lr,pr);for(let wr of Lt)Nt.addPass(wr)}function cr(q){$t(),Gt="balanced",ie.value=Gt,d.dataset.quality=Gt,Er=!1,pe.setRenderTarget(null),ea.apply(!1),ut(),rr(q),xo()}function yr(q,Oe=!0){if(Gt=g0(q),ie.value=Gt,d.dataset.quality=Gt,k.hidden=!0,Er=!1,ut(),Oe)try{localStorage.setItem(Ie,Gt==="presentation"?"high":Gt==="photoreal-fast"?"balanced":Gt)}catch{}ea.apply(["presentation","photoreal-fast"].includes(Gt)&&Kr!=="translucent",{fast:Gt==="photoreal-fast"}),pe.shadowMap.enabled=Gt!=="low"&&Kr!=="translucent"&&dr.get()===0,pe.shadowMap.needsUpdate=!0;try{xr()}catch{cr("Enhanced quality is unavailable on this graphics device. Balanced rendering is active.")}return zc(),xo(),Ct(),Gt}ie.onchange=()=>yr(ie.value),pe.debug.onShaderError=()=>{Er=!0},pe.outputColorSpace=xi,pe.toneMapping=Cr,pe.toneMappingExposure=1,pe.shadowMap.enabled=!0,pe.shadowMap.type=ke,pe.shadowMap.autoUpdate=!1,pe.shadowMap.needsUpdate=!0;function ir(){if(!pe.extensions.has("EXT_color_buffer_float"))return null;let q,Oe;try{return q=new Zk,Oe=new of(pe),Oe.fromScene(q,.04,.1,100)}catch{return rr("Studio reflections are unavailable on this graphics device. Direct lighting remains active."),null}finally{q?.dispose(),Oe?.dispose()}}let _r=ir();st.environment=_r?.texture||null,st.environmentIntensity=.65,v.append(pe.domElement);let Vt=new XO(le,pe.domElement),pi=!1,nn=!1,$i=null,fa=null,kc=()=>{pi=!0,nn=!0,$i!==null&&clearTimeout($i),$i=null},vo=()=>{$i!==null&&clearTimeout($i),$i=setTimeout(()=>{$i=null,nn=!1,Ct()},100)};Vt.addEventListener("start",kc),Vt.addEventListener("end",vo),Vt.addEventListener("change",Ct),Vt.enableDamping=!1,Vt.dampingFactor=.1,Vt.screenSpacePanning=!0,Vt.minDistance=.1,Vt.maxDistance=Dt*8,st.add(new wy(16777215,.35));for(let q of mO){let Oe=new $p(q.color,q.intensity);Math.abs(q.z)===1&&(Oe.castShadow=!0,Oe.shadow.mapSize.set(1024,1024),Oe.shadow.camera.left=Oe.shadow.camera.bottom=-Dt,Oe.shadow.camera.right=Oe.shadow.camera.top=Dt,Oe.shadow.camera.near=.1,Oe.shadow.camera.far=Dt*5,Oe.shadow.normalBias=.02,Oe.shadow.bias=-1e-4),Oe.position.set(Dt*q.x,Dt*q.y,Dt*q.z),st.add(Oe)}let ea=cO(C,{scene:st,renderer:pe,extent:Dt,bottom:it,constrained:He.constrained}),Sn=new Wi;st.add(Sn);let Os=new Map,sn=[],zn=C0(),wl=[],Ga=(q,Oe,ot)=>(wl.push({mesh:q,type:Oe,layer:ot}),q.visible=zn.visible(Oe,ot),q),Bf=new Set(s.filter(q=>Array.isArray(q)&&q[0]==="arc").map(q=>{let Oe=q.find(ot=>Array.isArray(ot)&&["uuid","tstamp"].includes(ot[0]))?.[1];return typeof Oe=="object"?Oe?.quoted:Oe}).filter(Boolean)),R0=q=>Bf.has(q.id)||Bf.has(q.id?.replace(/:\d+$/,""))||/^track-\d+:\d+$/.test(q.id||""),Ve=Q3(o,We).map(q=>q.name),wt=R3({...o,layers:Ve},s,We),Pt=wt.layers.map(q=>{let Oe=!["F.Cu","B.Cu"].includes(q.name);return{...q,internal:Oe,basis:Oe?wt.savedDepths?"saved-stackup":"illustrative":"outer-surface"}}),kt=new Set,bt=new Map(Pt.map(q=>[q.name,!0])),tr=o.vias.filter(q=>wt.viaSpans.get(q.id)?.through);tr.length<wt.viaSpans.size&&u.push("Blind and buried via walls follow saved endpoint layers. Partial-depth dielectric cavities are not cut.");let Sr=G3(o.tracks,s),Mr;try{Mr=V3(We,wt.byLayer)}catch{Mr={bottom:it,depth:We},u.push("Outer copper depths do not enclose a valid substrate. The nominal board envelope is shown.")}u.push(...wt.warnings,...Sr.warnings);function Lr(q){let Oe=wt.byLayer.get(q);return q==="F.Cu"||q==="B.Cu"?B3(q,We,Oe.thickness,Oe.z):{center:Oe.z,base:Oe.z-Oe.thickness/2,thickness:Oe.thickness}}let Nr=null;function Xr(q){return Nr?q.name===Nr:bt.get(q.name)&&(!q.internal||Kr==="translucent"||dr.get()>0)}let dr=zO(C,{layers:Pt},{maxGap:Math.max(.8,Math.min(8,Dt*.45/Math.max(1,Pt.length-1))),componentLift:Math.max(6,Math.min(40,Dt*.15))}),gi=[],Li=BO(),Oi=J3(),bi=[],Kr="realistic",Fr=!1,Mn=!1,ta=!1,Zn=!1,ma=document.createElement("label");ma.append(document.createTextNode("Appearance"));let vn=document.createElement("select");vn.setAttribute("aria-label","3D board appearance");for(let[q,Oe]of[["realistic","Realistic"],["layers","Layer colors"],["translucent","Translucent"]]){let ot=document.createElement("option");ot.value=q,ot.textContent=Oe,vn.append(ot)}ma.append(vn);let Wa=document.createElement("p");Wa.className="quality-help",Wa.textContent="Translucent reveals copper in layer colors through the board and models. Fills stay faint; shadows and screen-space occlusion are disabled in this inspection mode. Photoreal Fast adds studio reflections and cached shadows without a visible floor, using a bounded framebuffer, without ambient occlusion or supersampling. Presentation adds enhanced shadows and screen-space effects. Both render only when needed; source model fidelity is unchanged.",fe.append(ma,Se,Wa);function Ti(q=Kr){let Oe=h_(q),ot=Kr;Fr&&va.restore(),Oi.setEnabled(!1),Kr=Oe,vn.value=Oe,d.dataset.appearance=Oe,(Nr||Oe==="translucent"||dr.get()>0)&&Gf();let Nt=!Nr&&Oe==="realistic"&&dr.get()===0;for(let{mesh:Lt,role:Ot,layer:lr,pads:pr}of bi){let wr=Array.isArray(Lt.material)?Lt.material:[Lt.material];if(Ot==="pads"){for(let Qt of wr)Qt.color.setHex(16777215);let Pr=new or;pr.forEach((Qt,$r)=>Lt.setColorAt($r,Pr.setHex(Nt?dO(Qt,lr)?Au.exposedCopper:Au.coatedCopper:zf(lr)))),Lt.instanceColor&&(Lt.instanceColor.needsUpdate=!0)}else for(let Pr of wr)Pr.color.setHex(Nt?Au.coatedCopper:zf(lr));for(let Pr of wr)Pr.metalness=Nt&&Ot!=="pads"?.08:pa.copper.metalness,Pr.roughness=Nt&&Ot!=="pads"?.52:pa.copper.roughness}for(let Lt of Pt){let Ot=Os.get(Lt.name);Ot&&(Ot.visible=Xr(Lt))}if(Oi.setEnabled(Oe==="translucent"),ea.apply(["presentation","photoreal-fast"].includes(Gt)&&Oe!=="translucent",{fast:Gt==="photoreal-fast"}),pe.shadowMap.enabled=Gt!=="low"&&Oe!=="translucent"&&dr.get()===0,pe.shadowMap.needsUpdate=!0,ot==="translucent"!=(Oe==="translucent"))try{xr()}catch{cr("Enhanced quality is unavailable. Balanced rendering is active.")}return Lu(),Fr&&Us(Nn),r.onAppearanceChange?.(Oe),Ct(),Oe}vn.onchange=()=>Ti(vn.value);let An=q=>{if(!Os.has(q)){let Oe=new Wi;Oe.name=q,Sn.add(Oe),Os.set(q,Oe)}return Os.get(q)},Bn=qO(o,Ge),xn=new Set,ss=0,Oc=0,Ds=0,ZO=(q,Oe)=>{let ot=!1;for(let Nt=0,Lt=Oe.length-1;Nt<Oe.length;Lt=Nt++){let[Ot,lr]=[Oe[Nt],Oe[Lt]];Ot[1]>q[1]!=lr[1]>q[1]&&q[0]<(lr[0]-Ot[0])*(q[1]-Ot[1])/(lr[1]-Ot[1])+Ot[0]&&(ot=!ot)}return ot},R_=o.outlineLoops?.[0],P_=o.outlineLoops?.slice(1)||[];for(let q of[...c,...tr.map(Oe=>({...Oe,shape:"circle",width:Oe.size,height:Oe.size,drillShape:"circle",rotation:0}))]){if(!(q.drill>0))continue;let Oe=u0(q);if(!Oe){Ds++;continue}let ot=(q.rotation||0)*Math.PI/180,Nt=Math.cos(ot),Lt=Math.sin(ot),[Ot,lr]=Ge(q.at);if(P_.some(Pr=>ZO(q.at,Pr)))continue;let pr=Oe.map(([Pr,Qt])=>[Ot+Pr*Nt+Qt*Lt,lr+Pr*Lt-Qt*Nt]),wr=JSON.stringify(pr.map(Pr=>Pr.map(Qt=>Math.round(Qt*1e4)/1e4)));if(!xn.has(wr)){if(ss>=1024||Oc+pr.length>1e5||!R_||!PO(pr.map(([Pr,Qt])=>[Pr+Ae,Ue-Qt]),R_,P_)){Ds++;continue}xn.add(wr),ss++,Oc+=pr.length,Bn.holes.push(Iu(pr,Pr=>Pr))}}Ds&&u.push(`${Ds} drill loops could not be cut within the saved-geometry/triangulation budget.`);let Cn=new qr(new Kp(Bn,{depth:Mr.depth,bevelEnabled:!1,curveSegments:8}),[new vs(pa.solderMask),new is(pa.substrateEdge)]);Cn.position.z=Mr.bottom,Cn.receiveShadow=!0,ea.addCaster(Cn),Cn.userData.record={type:"Board",name:"Substrate",layer:"Edge.Cuts",id:"board"},Cn.userData.identity=Ic("substrate","Edge.Cuts","board"),Sn.add(Cn),sn.push(Cn),Oi.add(Cn,"substrate");let jf=new Fn(new tu(Cn.geometry,20),new tn({color:10205100,transparent:!0,opacity:.42}));jf.position.z=Mr.bottom,Sn.add(jf);let Dc=new Wi;Sn.add(Dc);function Lu(){let q=Math.min(1-dr.phases().layers*.98,Nr?.08:1),Oe=(Kr==="translucent"?.12:1)*q,ot=Fr&&Tl.mode==="isolate"&&kf(Nn)&&!Mn;for(let Nt of Array.isArray(Cn.material)?Cn.material:[Cn.material]){let Lt=ot?0:Math.min(Oe,Nt.userData.selectionOpacityCap??1),Ot=Lt<1;Nt.transparent!==Ot&&(Nt.transparent=Ot,Nt.needsUpdate=!0),Nt.opacity=Lt,Nt.depthWrite=!Ot}jf.material.opacity=Math.min(.42*q,jf.material.userData.selectionOpacityCap??1),Cn.castShadow=!Nr&&dr.get()===0&&ea.enabled}let Vf=WO(C,{camera:le,document,bounds:o.bounds,centerX:Ae,centerY:Ue,graphics:He,resources:F,invalidate:Ct,arcThrough:globalThis.KiCadOwnedCanvas?.arcThrough,onError:q=>rr("Silkscreen detail could not be refreshed: "+q.message)});if(globalThis.KiCadPCBRenderer&&globalThis.KiCadOwnedCanvas?.arcThrough)try{let q=globalThis.KiCadPCBRenderer.build(HO(s),r.boardPath||"").primitives.filter(Lt=>!Lt.frame&&!Lt.hidden&&["F.SilkS","B.SilkS"].includes(Lt.layer)),Oe=GO(dt,xt,He.maxDimension,He.constrained),ot=Bn.extractPoints(8),Nt=[ot.shape,...ot.holes].map(Lt=>Lt.map(Ot=>[Ot.x+Ae,Ue-Ot.y]));for(let Lt of["F.SilkS","B.SilkS"]){let Ot=q.filter(Qt=>Qt.layer===Lt);if(!Ot.length||!Oe)continue;let lr=document.createElement("canvas");lr.width=Oe.width,lr.height=Oe.height;let pr=lr.getContext("2d");if(!pr)continue;T_(pr,Ot,o.bounds,Oe,Nt,globalThis.KiCadOwnedCanvas.arcThrough);let wr=F.track(new Fp(lr));wr.colorSpace=xi,wr.anisotropy=Math.min(16,pe.capabilities.getMaxAnisotropy());let Pr=new qr(new vc(dt,xt),new is({map:wr,color:16777215,roughness:.85,metalness:0,side:Lt==="F.SilkS"?Ce:tt,transparent:!0,alphaTest:.05,depthWrite:!1}));Pr.position.z=Lt==="F.SilkS"?mt+.055:it-.055,Pr.renderOrder=1,Dc.add(Pr),Oi.add(Pr,"silkscreen"),Ga(Pr,"silkscreen",Lt),Vf.add(Pr,Ot,Nt,Lt==="F.SilkS")}}catch(q){u.push("Saved silkscreen could not be prepared: "+q.message)}let _l=new Map,Hf=0;for(let q of o.vias){let Oe=wt.viaSpans.get(q.id),ot=a_({shape:"circle",width:q.size,height:q.size,drill:q.drill,drillShape:"circle"});if(!ot||!Oe){Hf++;continue}let Nt=JSON.stringify([q.size,q.drill,Oe.zMin,Oe.zMax]);if(!_l.has(Nt)){if(_l.size>=128){Hf++;continue}_l.set(Nt,{outline:ot,span:Oe,vias:[]})}_l.get(Nt).vias.push(q)}Hf&&u.push(`${Hf} via bodies with unsupported annuli or unknown saved spans omitted.`);let P0=new Wi;Sn.add(P0);for(let[q,Oe]of _l){let ot=z3(C,u0({drill:Oe.vias[0].drill,drillShape:"circle"}),Oe.span.zMax-Oe.span.zMin),Nt=new is({color:Au.exposedCopper,...pa.copper,side:Ze,...Pu("via","wall")}),Lt=Nu(P0,ot,Nt,Oe.vias,(Ot,lr)=>{let[pr,wr]=Ge(lr.at);Ot.position.set(pr,wr,Oe.span.zMin)},Ic("via-barrel",Oe.span.through?"through":Oe.span.from+"-"+Oe.span.to,q));Lt&&(Ga(Lt,"vias",Oe.span.through?"through":Oe.span.from+"-"+Oe.span.to),sn.push(Lt),gi.push({mesh:Lt,span:Oe.span}))}u.push("Outer copper uses saved plan centers/thickness (or the disclosed stackup fallback) with a 0.001 mm outward display offset; the substrate spans the outer copper inner faces. Saved zone fills are opaque zero-height display films inset by the smaller of 0.005 mm or one quarter of the copper thickness. Via bodies show the saved drill wall; plating thickness is not inferred.");let $O=_l.size?M_(C,"via",{color:Au.exposedCopper,...pa.copper}):null;function I_(q){if(kt.has(q))return;kt.add(q);let Oe=zf(q),ot=Lr(q),Nt=ot.center;for(let Qt of["tracks","arcs"]){let $r=Sr.tracks.filter(yi=>yi.layer===q&&(R0(yi)?"arcs":"tracks")===Qt),Tr=D3(C,$r,{world:Ge,z:Nt,thickness:ot.thickness});Tr.invalid&&u.push(`${q}: invalid saved track widths or positions omitted.`),Tr.plan?.limited&&u.push(`${q}: large track caps exceed the ${Tr.plan.tolerance} mm tessellation tolerance at the 128-segment display limit.`);let jr=M0(new is({color:Oe,...pa.copper,...Pu("track")}),"track");for(let yi of Tr.batches){let ci=Nu(An(q),yi.geometry,jr,yi.records,yi.place,Ic("copper-track",q,Qt+"-"+yi.part));ci&&(Ga(ci,Qt,q),sn.push(ci),bi.push({mesh:ci,role:"tracks",layer:q}))}Tr.batches.length||jr.dispose()}let Lt=c.filter(Qt=>!L3(Qt)&&(Qt.layer===q||Qt.layers?.includes(q)||Qt.layers?.includes("*.Cu"))),Ot=new Map,lr=0;for(let Qt of Lt){let $r=JSON.stringify([Qt.shape,Qt.width,Qt.height,Qt.roundrectRatio,Qt.drill,Qt.drillShape,Qt.drillWidth,Qt.drillHeight,Qt.drillOffset,Qt.customAnchor,Qt.customPrimitives]);if(!Ot.has($r)){let Tr=a_(Qt);if(!Tr||Ot.size>=256){lr++;continue}Tr.tessellation.limited&&u.push(`${q}: a pad contour retains validated geometry because the 0.0025 mm tolerance could not be met within hole-containment/display limits.`),Ot.set($r,{outline:Tr,pads:[]})}Ot.get($r).pads.push(Qt)}lr&&u.push(`${q}: ${lr} unsupported/ambiguous pad shapes omitted; no rectangular stand-ins were substituted.`);let pr=Ot.size?M_(C,"pad",{color:16777215,...pa.copper}):null;for(let[Qt,$r]of Ot){let Tr=ct($r.outline,ot.thickness),jr=Nu(An(q),Tr,pr,$r.pads,(yi,ci)=>{let[Di,Ei]=Ge(ci.at);yi.position.set(Di,Ei,ot.base),yi.rotation.z=(ci.rotation||0)*Math.PI/180},Ic("copper-pad",q,Qt));jr&&(Ga(jr,"pads",q),sn.push(jr),bi.push({mesh:jr,role:"pads",layer:q,pads:$r.pads}))}let wr=M0(new is({color:Oe,...pa.copper,side:Ze,...Pu("zone")}),"zone"),Pr=!1;for(let Qt of a.forLayer(q)){let $r;try{let jr=PL(C,Qt,{world:Ge,triangulate:dL.triangulate,maxBytes:rt-ht.retainedBytes});$r=jr.geometry,ht.retainedBytes+=jr.bytes,ht.renderedContours++,ht.vertices+=jr.vertices}catch(jr){ht.rejected++,u.push(`${q}: saved zone ${Qt.id} contour ${Qt.contour}: ${jr.message}`);continue}if(!Qt.filled){let jr=new Lp($r,new tn({color:Oe,transparent:!0,opacity:.6}));jr.position.z=Nt,An(q).add(jr),Ga(jr,"polygons",q);continue}Pr=!0;let Tr=new qr($r,wr);Tr.position.z=["F.Cu","B.Cu"].includes(q)?j3(q,ot):Nt,Tr.userData.record={id:Qt.id,net:Qt.net,layer:q,filled:!0,contour:Qt.contour,type:"Zone"},An(q).add(Tr),Ga(Tr,"fills",q),sn.push(Tr),bi.push({mesh:Tr,role:"zone",layer:q}),Oi.add(Tr,"zone")}Pr||wr.dispose();for(let[Qt,$r]of _l){if($r.span.from!==q&&$r.span.to!==q)continue;let Tr=ct($r.outline,ot.thickness),jr=Nu(An(q),Tr,$O,$r.vias,(yi,ci)=>{let[Di,Ei]=Ge(ci.at);yi.position.set(Di,Ei,ot.base)},Ic("via-barrel",q,"annulus-"+Qt));jr&&(Ga(jr,"vias",q),sn.push(jr))}}for(let q of Pt.filter(Oe=>!Oe.internal))I_(q.name);function Gf(){let q=Pt.filter(ot=>ot.internal&&!kt.has(ot.name));if(!q.length)return;let Oe=u.length;for(let ot of q)I_(ot.name),F.retain(Os.get(ot.name));ws.push(...u.slice(Oe)),q.some(ot=>ot.basis==="illustrative")&&ws.push("Internal copper has saved XY coordinates and layer order; elevations are illustrative because a complete saved stackup is unavailable."),Uu()}let Uc=new Wi;Sn.add(Uc);let JO=X3(o),Yi=Nu(Uc,new $k(1,1,1,2,.06),new is(pa.proxy),o.components,(q,Oe)=>{let ot=JO.get(Oe),[Nt,Lt]=Ge(ot?.at||Oe.at),Ot=Oe.layer?.startsWith("B.");q.position.set(Nt,Lt,Ot?it-1.1:mt+1.1),q.rotation.set(0,0,ot?.rotation||0),q.scale.set(ot?.width||0,ot?.height||0,ot?2.1:0)},Ic("component","F.Fab","proxies"));Yi&&(sn.push(Yi),Oi.add(Yi,"component")),Yi&&(Yi.castShadow=!0,Yi.receiveShadow=!0);let N_=l_(o.components),Wf=o.components.map((q,Oe)=>{let ot=new Ir;return Yi?.getMatrixAt(Oe,ot),ot}),QO=new Ir().makeScale(0,0,0),Xa=new Map,ku=new Set,Ou=null,Fc=o.components.map(()=>!0);function Xf(){let q=new Ir;o.components.forEach((Oe,ot)=>{q.copy(Wf[ot]),q.elements[14]+=dr.componentOffset(Oe.layer?.startsWith("B.")?"B.Cu":"F.Cu"),Yi?.setMatrixAt(ot,Fc[ot]&&zn.visible("bodies",Oe.layer)&&!ku.has(ot)?q:QO)}),Yi&&(Yi.instanceMatrix.needsUpdate=!0,Yi.computeBoundingSphere());for(let[Oe,ot]of Xa)ot.visible=Fc[Oe]&&zn.visible("bodies",o.components[Oe].layer),dr.component(ot,o.components[Oe].layer?.startsWith("B.")?"B.Cu":"F.Cu");pe.shadowMap.needsUpdate=!0,Ct()}let ws=Array.isArray(r.assetWarnings)?r.assetWarnings.filter(q=>typeof q=="string").slice(0,48).map(q=>q.slice(0,500)):[];a.stats().unfilled&&ws.push(`${a.stats().unfilled} zones have no saved copper fill; only their boundaries are shown.`),(a.stats().omitted||a.stats().invalid)&&ws.push("Saved zone index: "+a.stats().omitted+" contours exceed the descriptor budget; "+a.stats().invalid+" invalid contours were rejected."),ws.push(...u),Uu();let L_=0,Du=eO(()=>{if(!Kt)return;oe.invalidate();let q=performance.now();try{Xf(),k0(),Us(Nn),Uu()}finally{L_+=performance.now()-q}},Ct);function Uu(){let q=ku.size,Oe=ws.length;P.replaceChildren(document.createTextNode(`Material preview \xB7 linked models ${q}/${o.components.length}`));let ot=document.createElement("details"),Nt=document.createElement("summary"),Lt=document.createElement("ul");Nt.textContent=Oe?`${Oe} rendering notes`:"Rendering details";let Ot=["Mask openings follow saved pad layer flags; this is not a reconstructed solder-mask solid.",o.components.length-q+" footprints have no linked model; bounded stand-ins are used only where usable saved footprint bounds exist.",...ws];for(let lr of Ot){let pr=document.createElement("li");pr.textContent=lr,Lt.append(pr)}ot.append(Nt,Lt),P.append(ot),r.onDiagnostics?.(["Linked component models: "+q+"/"+o.components.length,...Ot]),P.title=ws.join(`
`)}function I0(q,Oe){try{return Mt.checkTemplate(q,2+(Xa.has(Oe)?0:1)),F.retain(q,at,Tt)}catch(ot){throw F.discard(q),ot}}async function eD(q,Oe,ot,Nt){let Lt=Oe?.base64,Ot=q.embeddedAsset?await globalThis.KiCadEmbeddedModels.decode(Oe,d3.default.decompress):globalThis.KiCadEmbeddedModels.decodeBase64(Lt);if(Ot.byteLength>8388608)throw new Error("model asset exceeds 8 MiB");if(ot(Ot.byteLength),["step","stp"].includes(q.format)){Ou||=new globalThis.KiCadStepDecoder.Client(new URL("step-worker.js",location.href).href);let pr=await Ou.decode(Ot),wr=new Wi;for(let Pr of pr){let Qt=new Hr;Qt.setAttribute("position",new ui(Pr.positions,3)),Qt.setIndex(new ui(Pr.index,1)),Pr.normals?Qt.setAttribute("normal",new ui(Pr.normals,3)):Qt.computeVertexNormals();let $r=Pr.groups.map((jr,yi)=>(Qt.addGroup(jr.start,jr.count,yi),new is({color:new or(...jr.color),roughness:.65,metalness:.1}))),Tr=$r.length===1?$r[0]:$r;wr.add(new qr(Qt,Tr))}return I0(wr,Nt)}if(q.format==="glb"){try{O(Ot,Mt.limit,{maxAccessorBytes:at,maxTextureBytes:Tt,maxTextureDimension:He.maxDimension})}catch(pr){throw["MODEL_GRAPH_BUDGET","MODEL_ALLOCATION_BUDGET"].includes(pr.code)&&Mt.rejectPreflight(),pr}return I0((await new XL().parseAsync(Ot.buffer,"")).scene,Nt)}let lr=new TextDecoder("utf-8",{fatal:!0}).decode(Ot);if(/\b(?:Inline|ImageTexture|MovieTexture|AudioClip)\b|\burl\s*(?:\[|\")/i.test(lr))throw new Error("VRML has an external resource reference");return I0(new Wk().parse(lr),Nt)}async function tD(q){if(!r.boardPath)return;let Oe;try{Oe=globalThis.KiCadRepoModels.collectParsed(q,r.boardPath,r.assetPaths),q=null}catch(pr){ws.push(`Cannot read model references: ${pr.message}`),Uu();return}ws.push(...Oe.diagnostics),Uu();let ot=Ke(Oe.models),Nt=new Map(o.components.map((pr,wr)=>[pr.id,wr])),Lt=0,Ot=0;async function lr(pr){let wr=Nt.get(pr.footprintId);if(wr===void 0){ws.push(`${pr.reference}: footprint identity not found`),ot.release(pr);return}try{let Pr=await ot.get(pr,async()=>{let Qt=pr.embeddedAsset||await r.loadAsset?.(pr.path);if(!Kt)throw Error("3D viewer closed before model decoding.");return eD(pr,Qt,$r=>{if(Lt+=$r,Lt>25165824)throw new Error("Decoded 3D model assets exceed 24 MiB in this viewer")},wr)});if(!Kt)return;Mt.admit(Pr,2+(Xa.has(wr)?0:1),()=>{let Qt=ot.isLastUse(pr)?Pr:Pr.clone(!0);F.retainClone(Qt,at,Tt);let $r=0;if(Qt.traverse(ci=>{ci.isMesh&&ci.geometry?.attributes?.position?.count&&($r++,ci.castShadow=!0,ci.receiveShadow=!0,ci.userData.record={...o.components[wr],type:"Component",modelPath:pr.path},Oi.add(ci,"component"),sn.push(ci))}),!$r)throw new Error("asset has no drawable mesh");let Tr=globalThis.KiCadRepoModels.modelPose(pr,Ae,Ue,We),jr=new Wi;jr.position.set(...Tr.position),jr.rotation.z=Tr.footprintAngle;let yi=new Wi;if(yi.rotation.set(...Tr.modelRotation,"ZYX"),yi.scale.set(...Tr.scale),yi.add(Qt),jr.add(yi),!Xa.has(wr)){let ci=new Wi;Xa.set(wr,ci),Uc.add(ci)}Xa.get(wr).add(jr),ku.add(wr),pr.format==="glb"&&ws.push(`${pr.reference}: GLB geometry is interpreted in millimetres.`)})}catch(Pr){ws.push(`${pr.reference}: ${pr.path}: ${Pr?.message||String(Pr)}`)}finally{ot.release(pr)}Du.request()}await Promise.all(Array.from({length:Math.min(Ut,Oe.models.length)},async()=>{for(;Ot<Oe.models.length&&Kt;)await lr(Oe.models[Ot++])})),ot.clear(),Ou?.dispose(),Ou=null,Kt&&(Du.flush(),!pi&&ku.size&&El())}let N0=Math.hypot(dt,xt,We+5)/2,L0=new je,rD=new je,Fu=new Xi().setFromObject(Sn);function zc(){let q=pO(le.position.toArray(),le.getWorldDirection(rD).toArray(),Fu.min.toArray(),Fu.max.toArray()),Oe=fO(le.position.distanceTo(Vt.target),N0+Vt.target.distanceTo(L0),q);le.near=Oe.near,le.far=ea.enabled?Math.max(Oe.far,Dt*10):Oe.far,le.updateProjectionMatrix()}function k0(){Fu.setFromObject(Sn);let q=Fu.getBoundingSphere(new on);Number.isFinite(q.radius)&&q.radius>0&&(N0=q.radius,L0.copy(q.center)),zc()}Vt.addEventListener("change",zc);function k_(q){if(!fa)return;let{width:Oe,height:ot,ratio:Nt}=fa,Lt=q?Math.min(Nt,Math.sqrt(6e5/Oe/ot),Nt*.78):Nt;(pe.domElement.width!==Math.floor(Oe*Lt)||pe.domElement.height!==Math.floor(ot*Lt)||pe.getPixelRatio()!==Lt)&&pe.setDrawingBufferSize(Oe,ot,Lt)}function xo(){let q=zt();if(It.setState({hasSize:q}),!q){Ct();return}let Oe=Math.max(1,v.clientWidth),ot=Math.max(1,v.clientHeight),Nt=f_(Oe,ot,globalThis.devicePixelRatio,He.maxDimension,wo.running()?"low":Gt,He),Lt=Nt.ratio;(pe.domElement.width!==Math.floor(Oe*Lt)||pe.domElement.height!==Math.floor(ot*Lt))&&oe.invalidate(),fa={width:Oe,height:ot,ratio:Lt},k_(nn),le.aspect=Oe/ot,Zt&&(Zt.composer.setPixelRatio(Lt),Zt.composer.setSize(Oe,ot)),le.updateProjectionMatrix(),Ct()}function El(q="iso"){xo(),Sn.updateWorldMatrix(!0,!0);let Oe=new Xi().setFromObject(Sn),ot=Oe.getBoundingSphere(new on),Nt=Number.isFinite(ot.radius)&&ot.radius>0?ot.radius:Math.hypot(dt,xt,We+5)/2,Lt=ot.radius>0?ot.center:new je,Ot=OO(q),lr=new je(...Ot.direction).normalize(),pr=e_(Oe.getSize(new je).toArray(),lr.toArray(),le.fov,le.aspect,.85,Ot.up)||Qw(Nt,le.fov,le.aspect)||Dt*3;N0=Nt,L0.copy(Lt),Fu.copy(Oe),Vt.maxDistance=Math.max(Dt*8,pr*4),le.position.copy(Lt).addScaledVector(lr,pr),le.up.fromArray(Ot.up),Vt.target.copy(Lt),Vt.update(),zc()}L("Fit",()=>{pi=!0,El()},"M8 3H3v5M16 3h5v5M21 16v5h-5M8 21H3v-5M8 8h8v8H8Z","Fit board to viewport").classList.add("fit-action");let ga=document.createElement("select");ga.className="view-select",ga.title="Choose a board viewing side",ga.setAttribute("aria-label","3D camera view");let Yf=document.createElement("option");Yf.value="",Yf.disabled=!0,Yf.textContent="View",ga.append(Yf);for(let{id:q,label:Oe}of Uf){let ot=document.createElement("option");ot.value=q,ot.textContent=Oe,ga.append(ot)}ga.value="",ga.onchange=()=>{pi=!0,El(ga.value),ga.value=""},x.append(ga);let O0=document.createElement("span");O0.className="divider",O0.setAttribute("aria-hidden","true"),x.append(O0);let bo=!1;function O_(q){return bo=!!q,WL(Vt,C,bo),D0.setAttribute("aria-pressed",String(bo)),pe.domElement.style.cursor=bo?"grab":"",bo}let D0=L("Pan",()=>{Al(!1),O_(!bo)},"M12 3v18M3 12h18M8 7l4-4 4 4M8 17l4 4 4-4M7 8l-4 4 4 4M17 8l4 4-4 4","Pan view with left drag");D0.setAttribute("aria-pressed","false");let qf=L("Measure",()=>Al(!ji),"M3 17 17 3l4 4L7 21ZM7 13l3 3M10 10l2 2M13 7l3 3","Measure distance between 3D surfaces");qf.setAttribute("aria-pressed","false");let Bc=L("Display",()=>Te(Z.hidden),"M3 6h18M3 12h18M3 18h18M7 3v6M17 9v6M10 15v6","3D display settings");Bc.setAttribute("aria-expanded","false"),Bc.setAttribute("aria-controls",Z.id);let zu=document.createElement("label");zu.className="explode-control",zu.style.cssText="display:inline-flex;align-items:center;gap:5px;font-size:11px",zu.title="Expand mode: components lift first, then copper layers separate, the substrate fades and vias stretch. Saved identities remain linked.";let D_=document.createElement("span");D_.textContent="Expand mode";let _s=document.createElement("input");_s.type="range",_s.min="0",_s.max="100",_s.step="1",_s.value="0",_s.style.cssText="width:80px;min-width:50px",_s.setAttribute("aria-label","Expand assembly");let U0=document.createElement("output");U0.textContent="0%",zu.append(D_,_s,U0);let Sl=document.createElement("details");Sl.className="tools-more";let Bu=document.createElement("summary");Bu.textContent="3D tools",Bu.title="More 3D tools",Bu.setAttribute("aria-label","More 3D tools");let F0=document.createElement("div");F0.className="tools-panel",F0.append(D0,qf,Bc,zu),Sl.append(Bu,F0),x.append(Sl);let Ml=document.createElement("p");Ml.className="quality-help",Ml.setAttribute("role","status"),Ml.hidden=!0,Ml.style.cssText="position:absolute;left:10px;bottom:10px;z-index:5;max-width:calc(100% - 20px);margin:0;padding:6px 9px;background:var(--panel);border:1px solid var(--border);border-radius:5px;pointer-events:none",g.append(Ml);function U_(){Li.sync(Ka.overlay,dr.get())}function F_(q=Ka.getAnalysisOverlayState()){return dr.get()>0&&q.placed?{...q,displaySuspended:!0,diagnostics:[...q.diagnostics,"Registered result and probes are hidden while Expand mode is active; restore Expand mode to 0% to view them."]}:q}let z_=0,B_=0,z0=0;function iD(q){let Oe=performance.now();if(!Kt)return dr.get();let ot=dr.get(),Nt=dr.set(q);if(ot===0!=(Nt===0)&&(Nt>0&&$t(),Ti(Kr)),pe.shadowMap.enabled=!1,Nt>0){let Ot=kt.size;Gf(),kt.size!==Ot&&Ti(Kr)}Nt!==ot&&(pi=!0,xa(),ji&&Al(!1));for(let Ot of Pt){let lr=Os.get(Ot.name);lr&&(dr.layer(lr,Ot.name),lr.visible=Xr(Ot))}for(let Ot of Dc.children){let lr=wl.find(pr=>pr.mesh===Ot)?.layer;dr.layer(Ot,lr==="B.SilkS"?"B.Cu":"F.Cu")}for(let{mesh:Ot,span:lr}of gi)dr.barrels(Ot,lr);Xf(),Zn?Xc.syncTransforms():kf(Nn)&&Us(Nn),as?.object&&!ta&&(cE(as.object,as.instanceId),Il.getCenter(as.point)),Lu(),U_(),k0(),X_(),U0.textContent=Math.round(Nt)+"%",_s.setAttribute("aria-valuetext",Math.round(Nt)+" percent expanded"),Ml.hidden=Nt===0,Ml.textContent="Display-only expansion: components lift first, then copper separates and substrate fades. "+(Pt.some(Ot=>Ot.basis==="illustrative")?"Internal elevations are illustrative. ":"")+"Registered results and measurements resume at 0%.",z_++;let Lt=performance.now()-Oe;return B_+=Lt,z0=Math.max(z0,Lt),r.onExplodeChange?.(Nt),Ct(),Nt}let wo=FO({request:q=>requestAnimationFrame(q),cancel:q=>cancelAnimationFrame(q),update:iD,canRun:()=>Kt&&!fr&&!It.stats().paused,reducedMotion:()=>globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0,settle:q=>{if(pe.shadowMap.enabled=q===0&&Gt!=="low"&&Kr!=="translucent",pe.shadowMap.needsUpdate=!0,q===0)try{xr()}catch{cr("Enhanced quality is unavailable. Balanced rendering is active.")}xo(),Ct()}});function Kf(q,Oe=!1){if(!Kt)return dr.get();if(!Number.isFinite(q)||q<0||q>100)throw new TypeError("Expand amount must be between 0 and 100.");q>0&&Gf(),_s.value=String(q);let ot=wo.set(q,{immediate:Oe});return xo(),ot}_s.oninput=()=>Kf(Number(_s.value));let j_=new Map,B0=()=>Pt.filter(q=>bt.get(q.name)).map(q=>q.name);function V_(q){if(!Array.isArray(q)||q.some(Lt=>typeof Lt!="string"||!bt.has(Lt))||new Set(q).size!==q.length)throw new TypeError("Choose saved physical copper layer names.");let Oe=new Set(q),ot=!1;for(let Lt of Pt){let Ot=Oe.has(Lt.name);bt.get(Lt.name)!==Ot&&(ot=!0),bt.set(Lt.name,Ot);let lr=j_.get(Lt.name);lr&&(lr.checked=Ot);let pr=Os.get(Lt.name);pr&&(pr.visible=Xr(Lt))}Us(Nn),Ct();let Nt=B0();return ot&&r.onLayersChange?.([...Nt]),Nt}for(let q of Pt)j_.set(q.name,de(q.name==="F.Cu"?"Front copper":q.name==="B.Cu"?"Back copper":q.name+" copper",!0,Oe=>{let ot=new Set(B0());Oe?ot.add(q.name):ot.delete(q.name),V_([...ot])}));let H_=document.createElement("label"),ju=document.createElement("select");H_.append(document.createTextNode("Inspect copper layer"),ju),ju.setAttribute("aria-label","Inspect copper layer");for(let[q,Oe]of[["","Assembled board"],...Pt.map(ot=>[ot.name,ot.name])]){let ot=document.createElement("option");ot.value=q,ot.textContent=Oe,ju.append(ot)}Fe.append(H_);let nD=de("Parts",!0,q=>{Uc.visible=!Nr&&q,kf(Nn)&&Us(Nn),pe.shadowMap.needsUpdate=!0}),sD=de("Silkscreen",!0,q=>{Dc.visible=!Nr&&q});ju.onchange=()=>{Nr=ju.value||null,Uc.visible=!Nr&&nD.checked,Dc.visible=!Nr&&sD.checked,P0.visible=!Nr,Ti(Kr)};let G_=!1,Vu=new Wi,ya=new Map;st.add(Vu);let W_=new vc(1,1),aD=c.filter(q=>q.name&&q.net&&q.name.length<=40&&q.net.length<=48).slice(0,1e4).map(q=>{let[Oe,ot]=Ge(q.at);return{pad:q,x:Oe,y:ot}}),jc=[],Zf=new Set;function oD(q){let Oe=JSON.stringify([q.name,q.net]);if(ya.has(Oe)){let Ot=ya.get(Oe);return ya.delete(Oe),ya.set(Oe,Ot),Zf.add(Ot),Ot}if(ya.size>=150){let Ot=[...ya].find(([,lr])=>!Zf.has(lr));if(!Ot)return null;ya.delete(Ot[0]),Ot[1].dispose()}let ot=document.createElement("canvas");ot.width=512,ot.height=48;let Nt=ot.getContext("2d");Nt.font="600 14px monospace",Nt.textAlign="center",Nt.textBaseline="middle",Nt.lineJoin="round",Nt.lineWidth=5,Nt.strokeStyle="#101820",Nt.fillStyle="#f3f8fa";for(let[Ot,lr]of[[q.name,13],[q.net,34]])Nt.strokeText(Ot,256,lr),Nt.fillText(Ot,256,lr);let Lt=new Fp(ot);return Lt.colorSpace=xi,ya.set(Oe,Lt),Zf.add(Lt),Lt}let Hu=new je,lD=new je;function X_(){let q=0;if(Zf.clear(),Vu.visible=G_&&!ji,!Vu.visible)return;if(!zn.visible("pads"))return void jc.forEach(Ot=>Ot.visible=!1);let Oe=Math.max(1,v.clientHeight),ot=Math.max(1,v.clientWidth),Nt=[],Lt=le.position.z>=Vt.target.z?"F.Cu":"B.Cu";if(!An(Lt).visible||!zn.visible("pads",Lt))return void jc.forEach(Ot=>Ot.visible=!1);for(let{pad:Ot,x:lr,y:pr}of aD){if(q>=150)break;if(!(Ot.layers?.includes(Lt)||Ot.layers?.includes("*.Cu")||Ot.layer===Lt))continue;let wr=(Lt==="F.Cu"?mt+.055:it-.055)+dr.offset(Lt),Pr=le.position.distanceTo(lD.set(lr,pr,wr)),Qt=Oe/(2*Math.tan(le.fov*Math.PI/360)*Pr),$r=Math.min(Ot.width,Ot.height)*Qt;if(!Number.isFinite($r)||$r<32||(Hu.set(lr,pr,wr).project(le),Hu.z<-1||Hu.z>1))continue;let Tr=Math.min(16,Math.max(10,$r*.22)),jr=(Math.max(Ot.name.length,Ot.net.length)*.63+1)*Tr,yi=Tr*2.8,ci=(Hu.x+1)*ot/2,Di=(1-Hu.y)*Oe/2,Ei={x:ci-jr/2,y:Di-yi/2,w:jr,h:yi};if(Ei.x<0||Ei.y<0||Ei.x+jr>ot||Ei.y+yi>Oe||Nt.some(Zc=>Ei.x<Zc.x+Zc.w&&Ei.x+jr>Zc.x&&Ei.y<Zc.y+Zc.h&&Ei.y+yi>Zc.y))continue;let jn=oD(Ot);if(!jn)continue;let Fs=jc[q];Fs||(Fs=new qr(W_,new en({transparent:!0,depthTest:!0,depthWrite:!1,side:Ze})),Fs.renderOrder=5,Vu.add(Fs),jc.push(Fs)),Fs.material.map!==jn&&(Fs.material.map=jn,Fs.material.needsUpdate=!0),Fs.position.set(lr,pr,wr),Fs.quaternion.copy(le.quaternion),Fs.scale.set(36.57142857142857*Tr/Qt,3.4285714285714284*Tr/Qt,1),Fs.visible=!0,Nt.push(Ei),q++}for(let Ot=q;Ot<jc.length;Ot++)jc[Ot].visible=!1}de("Pad and net names (close zoom)",!1,q=>{G_=q}),El();let _o=new ou,Eo=new Ft,Es=new LO,ji=!1,So="mm",Vc=document.createElement("section");Vc.className="measurement-panel",Vc.hidden=!0,Vc.setAttribute("aria-label","3D surface measurement");let j0=document.createElement("div");j0.className="measurement-heading";let Y_=document.createElement("strong");Y_.textContent="Surface distance";let Gu=document.createElement("select");Gu.setAttribute("aria-label","3D measurement units");for(let q of["mm","mil"]){let Oe=document.createElement("option");Oe.value=q,Oe.textContent=q,Gu.append(Oe)}let Wu=document.createElement("button");Wu.type="button",Wu.textContent="Done",Wu.title="Exit measurement mode",Wu.onclick=()=>Al(!1),j0.append(Y_,Gu,Wu);let Xu=document.createElement("select"),Yu=document.createElement("select"),V0=document.createElement("div");V0.className="measurement-tools",Xu.setAttribute("aria-label","3D measurement snap"),Yu.setAttribute("aria-label","3D measurement selection filter");for(let[q,Oe]of[["surface","Surface"],["edges","Snap to edges"],["corners","Snap to corners"]]){let ot=document.createElement("option");ot.value=q,ot.textContent=Oe,Xu.append(ot)}for(let[q,Oe]of[["all","All geometry"],["board","Board outline/body"],["models","Component models"],["pads","Pads"],["tracks","Tracks"],["vias","Vias"]]){let ot=document.createElement("option");ot.value=q,ot.textContent=Oe,Yu.append(ot)}V0.append(Xu,Yu);let q_=new WeakMap,Ya=null,qu=null,Mo=new Set,Ss=document.createElement("canvas");Ss.width=Ss.height=240,Ss.className="measurement-label",Ss.hidden=!0,Ss.setAttribute("aria-label","3D measurement magnifier"),Ss.style.cssText="width:120px;height:120px;position:absolute;right:12px;top:50px;left:auto;pointer-events:none;border-radius:50%;z-index:8;padding:0",g.append(Ss);function cD(){if(!ji||!Ya){Ss.hidden=!0;return}let q=pe.domElement.getBoundingClientRect(),Oe=Ya.x-q.left,ot=Ya.y-q.top;Ss.hidden=!1;let Nt=Ss.getContext("2d");if(!Nt)return;let Lt=pe.domElement.width/q.width,Ot=pe.domElement.height/q.height;Nt.clearRect(0,0,240,240),Nt.drawImage(pe.domElement,(Oe-20)*Lt,(ot-20)*Ot,40*Lt,40*Ot,0,0,240,240),Nt.strokeStyle="#ffcf66",Nt.lineWidth=2,Nt.beginPath(),Nt.moveTo(110,120),Nt.lineTo(130,120),Nt.moveTo(120,110),Nt.lineTo(120,130),Nt.stroke()}let H0=document.createElement("output");H0.setAttribute("aria-live","polite");let G0=document.createElement("p");G0.setAttribute("role","status");let K_=document.createElement("small"),Z_=document.createElement("small");Z_.textContent="Model surfaces \xB7 footprint stand-ins are approximate.";let W0=document.createElement("div");W0.className="measurement-tools";let qa=document.createElement("select");qa.setAttribute("aria-label","Recent 3D measurements");let Ku=document.createElement("button");Ku.type="button",Ku.textContent="Clear",Ku.title="Clear all 3D measurements",Ku.onclick=tE,W0.append(qa,Ku),Vc.append(j0,V0,H0,G0,K_,W0,Z_),g.append(Vc);let ra=document.createElement("div");ra.className="measurement-label",ra.hidden=!0,ra.setAttribute("aria-hidden","true"),g.append(ra);let Hc=new Wi;Hc.visible=!1,st.add(Hc);let X0=new Hr;X0.setAttribute("position",new ui(new Float32Array(6),3));let hD=new tn({color:16765818,transparent:!0,opacity:.95,depthTest:!1,depthWrite:!1,toneMapped:!1}),$f=new ua(X0,hD);$f.frustumCulled=!1,$f.renderOrder=201,Hc.add($f);let $_=new po(1,12,8),J_=new en({color:16765818,transparent:!0,opacity:.95,depthTest:!1,depthWrite:!1,toneMapped:!1}),Zu=[new qr($_,J_),new qr($_,J_)];for(let q of Zu)q.renderOrder=202,Hc.add(q);let Q_=q=>new je(q.x-Ae,Ue-q.y,q.z);function Gc(q){let Oe=Es.selected,ot=Es.pending;H0.textContent=Oe?(Oe.approximate?"\u2248 ":"")+S0(Oe.distance,So):"\u2014",G0.textContent=q||(ot?"Choose the second surface point.":Oe?"Choose a point to start another measurement.":"Choose the first surface point.");let Nt=Ot=>(So==="mil"?Ot/.0254:Ot).toFixed(So==="mil"?2:3);K_.textContent=Oe?`\u0394X ${Nt(Oe.delta.x)} \xB7 \u0394Y ${Nt(Oe.delta.y)} \xB7 \u0394Z ${Nt(Oe.delta.z)} ${So}`:"",qa.replaceChildren();let Lt=document.createElement("option");Lt.value="",Lt.textContent=Es.records.length?"Recent measurements":"No measurements yet",qa.append(Lt);for(let Ot of Es.records){let lr=document.createElement("option");lr.value=String(Ot.id),lr.textContent=`#${Ot.id} \xB7 ${Ot.approximate?"\u2248 ":""}${S0(Ot.distance,So)}`,qa.append(lr)}qa.value=Oe?String(Oe.id):"",qa.disabled=!Es.records.length,ra.textContent=Oe?(Oe.approximate?"\u2248 ":"")+S0(Oe.distance,So):"",eE(),Ct()}function eE(){let q=Es.selected,Oe=Es.pending;if(Hc.visible=ji&&!!(q||Oe),ra.hidden=!ji||!q,!Hc.visible)return;let ot=Q_(q?.from||Oe),Nt=q?Q_(q.to):null;if(Zu[0].position.copy(ot),Zu[1].visible=!!Nt,$f.visible=!!Nt,Nt){Zu[1].position.copy(Nt);let Lt=X0.getAttribute("position");Lt.setXYZ(0,ot.x,ot.y,ot.z),Lt.setXYZ(1,Nt.x,Nt.y,Nt.z),Lt.needsUpdate=!0;let Ot=ot.clone().add(Nt).multiplyScalar(.5).project(le);ra.hidden=Ot.z<-1||Ot.z>1,ra.style.left=Math.max(8,Math.min(v.clientWidth-ra.offsetWidth-8,(Ot.x+1)*v.clientWidth/2+8))+"px",ra.style.top=Math.max(8,Math.min(v.clientHeight-ra.offsetHeight-8,(1-Ot.y)*v.clientHeight/2-24))+"px"}for(let Lt of Zu){let Ot=Math.max(.005,le.position.distanceTo(Lt.position)*2*Math.tan(le.fov*Math.PI/360)/Math.max(1,v.clientHeight)*3.5);Lt.scale.setScalar(Ot)}}function Al(q){return Kt?q&&dr.get()>0?(rr("Restore Expand mode to 0% before measuring saved geometry."),!1):(ji=!!q,ji&&O_(!1),d.dataset.measuring=String(ji),qf.setAttribute("aria-pressed",String(ji)),Vc.hidden=!ji,ji||(Es.pending=null,Ya=null,qu=null,Mo.clear(),Vt.enabled=!0,Ss.hidden=!0),Gc(),r.onMeasurementMode?.(ji),ji):!1}function tE(){Es.clear(),Gc(),r.onMeasurement?.(null)}Gu.onchange=()=>{So=Gu.value==="mil"?"mil":"mm",Gc()},qa.onchange=()=>{let q=Es.replay(qa.value);q&&(Gc(),r.onMeasurement?.(q))};let rE=q=>{q.key==="Escape"&&ji&&(q.preventDefault(),q.stopPropagation(),Al(!1),qf.focus())};f.addEventListener("keydown",rE);function uD(){let q=Di=>f0(Di,Cn,Nr||dr.get()>0?"translucent":Kr),Oe=_o.intersectObjects(sn.filter(q),!1).find(Di=>va.isVisible(Di.object,Di.instanceId));if(!Oe)return null;let ot=Oe.object===Cn?"board":wl.find(Di=>Di.mesh===Oe.object)?.type||"models",Nt=ot==="arcs"?"tracks":ot;if(Yu.value!=="all"&&Yu.value!==Nt)return null;if(Xu.value==="surface")return{point:Oe.point,approximate:Oe.object===Yi,kind:"surface"};let Lt=Oe.object.geometry,Ot=Lt?.getAttribute("position");if(!Ot||Ot.count>2e5)return null;let lr=q_.get(Lt);if(!lr){let Di=new tu(Lt,25),Ei=Di.getAttribute("position");lr=[];for(let jn=0;jn+1<Ei.count&&lr.length<1e4;jn+=2)lr.push([[Ei.getX(jn),Ei.getY(jn),Ei.getZ(jn)],[Ei.getX(jn+1),Ei.getY(jn+1),Ei.getZ(jn+1)]]);Di.dispose(),q_.set(Lt,lr)}let pr=Oe.object.matrixWorld.clone();if(Number.isInteger(Oe.instanceId)){let Di=new Ir;Oe.object.getMatrixAt(Oe.instanceId,Di),pr.multiply(Di)}let wr=lr.map(Di=>Di.map(Ei=>{let jn=new je(...Ei).applyMatrix4(pr);return{x:jn.x,y:jn.y,z:jn.z}})),Pr=pe.domElement.getBoundingClientRect(),Qt=Di=>{let Ei=new _i(Di.x,Di.y,Di.z,1).applyMatrix4(le.matrixWorldInverse).applyMatrix4(le.projectionMatrix);return Ei.w<=0?null:{x:(Ei.x/Ei.w+1)*Pr.width/2,y:(1-Ei.y/Ei.w)*Pr.height/2,z:Ei.z/Ei.w,w:Ei.w}},$r=kO({x:(Eo.x+1)*Pr.width/2,y:(1-Eo.y)*Pr.height/2},wr,Qt,{mode:Xu.value,tolerance:Ya?18:12});if(!$r)return null;let Tr=new je($r.point.x,$r.point.y,$r.point.z),jr=Tr.clone().project(le),yi=new ou;yi.setFromCamera(new Ft(jr.x,jr.y),le);let ci=yi.intersectObjects(sn.filter(q),!1).find(Di=>va.isVisible(Di.object,Di.instanceId));return!ci||ci.object!==Oe.object||ci.instanceId!==Oe.instanceId||ci.point.distanceTo(Tr)>Math.max(.002,le.position.distanceTo(Tr)*5e-5)?null:{point:Tr,approximate:Oe.object===Yi,kind:$r.kind}}function dD(){let q=uD();if(!q){Gc("No visible feature within snap range. Adjust snap/filter or zoom in.");return}let Oe=Es.add({x:q.point.x+Ae,y:Ue-q.point.y,z:q.point.z,approximate:q.approximate});Gc(q.kind+" selected. "+(Es.pending?"Choose the second point.":"Measurement complete.")),Oe?.distance!==void 0&&r.onMeasurement?.(Oe)}let as=null,$u=UO({onPick:q=>{bo||Z0(q)},onContextMenu:mE,isHeld:()=>Kc.isHeld()}),Wc=!0,Tl=p0(),va=Z3(C,()=>{let q=[];return Sn.traverse(Oe=>{Oe.material&&q.push(Oe)}),q});Fr=!0;let Cl=2e3,iE=new tu(new Da(1,1,1)),Ao=iE.getAttribute("position"),Rl=new Hr,Jf=new ui(new Float32Array(Cl*Ao.count*3),3);Jf.setUsage(Cx),Rl.setAttribute("position",Jf),Rl.setDrawRange(0,0);let nE=()=>new tn({color:n?16768893:10179840,depthTest:!0,depthWrite:!1,toneMapped:!1}),Pl=new Fn(Rl,nE());Pl.frustumCulled=!1,Pl.renderOrder=101,st.add(Pl);let Nn={},Xc=jO(C,{scene:st,objects:()=>sn,colorForLayer:zf,visible:(q,Oe)=>{if(Nr?Oe!==Nr:bt.has(Oe)&&!bt.get(Oe))return!1;for(let ot=q;ot;ot=ot.parent)if(!ot.visible&&ot!==Os.get(Oe))return!1;return!0}});function sE(q){Xc.update(q,Tl),Xc.stats().limited&&(os.hidden=!1,os.style.display="",os.textContent="Net shine-through reached its display budget; native selection is retained.")}let Yc={netOnlyUpdates:0,netRecordsScanned:0,netBoundsAvoided:0,boundsEvaluations:0,outlineVerticesWritten:0},os=document.createElement("div");os.className="hint",os.style.bottom="42px",os.hidden=!0,g.append(os);function Us(q={}){if(oe.invalidate(),Ct(),Nn=q||{},Zn=!1,Mn=!1,ta=!1,!kf(Nn))return Xc.clear(),Rl.setDrawRange(0,0),os.hidden=!0,os.style.display="none",ls.visible=!1,Pl.visible=!1,va.restore(),Lu(),{highlighted:0,matched:0,limited:!1};let Oe=rO(Nn,o);Oe.size&&Gf();let ot=aO(Nn,o);if(Mn=ot(Cn.userData.record),ta=Oe.size>0,iO(Nn,Oe)){Zn=!0;let Tr=sO(sn,ot);return Yc.netOnlyUpdates++,Yc.netRecordsScanned+=Tr.visitedRecords,Yc.netBoundsAvoided+=Tr.matchedRecords,Rl.setDrawRange(0,0),os.hidden=!0,os.style.display="none",ls.visible=!1,Pl.visible=!1,va.update(ot,Tr.matched>0&&Wc,jr=>Oe.has(jr?.net),{...Tl,expanded:dr.get()>0,netContext:Oe.size>0}),Lu(),sE(Oe),{highlighted:Math.min(Tr.matched,Cl),matched:Tr.matched,limited:Tr.matched>Cl}}let Nt=new Ir,Lt=new Ir,Ot=new Xi,lr=new je,pr=new je,wr=0,Pr=0,Qt=new Map,$r=(Tr,jr,yi)=>{if(Number.isInteger(jr)&&(Tr.getMatrixAt(jr,Lt),Lt.determinant()===0)||(Yc.boundsEvaluations++,Tr.updateWorldMatrix(!0,!1),Number.isInteger(jr)?(Tr.geometry.boundingBox||Tr.geometry.computeBoundingBox(),Ot.copy(Tr.geometry.boundingBox),Nt.multiplyMatrices(Tr.matrixWorld,Lt),Ot.applyMatrix4(Nt)):Ot.setFromObject(Tr),Ot.isEmpty()))return;let ci=yi?.ref?"part:"+yi.ref:yi?.uuid||yi?.id||Tr.uuid+":"+jr;Qt.has(ci)?Qt.get(ci).union(Ot):Qt.size<Cl?Qt.set(ci,Ot.clone()):Pr++};for(let Tr of sn){let jr=!0;for(let ci=Tr;ci;ci=ci.parent)ci.visible||(jr=!1);if(!jr)continue;let yi=Tr.userData.records;yi?yi.forEach((ci,Di)=>{ot(ci)&&$r(Tr,Di,ci)}):ot(Tr.userData.record)&&$r(Tr,void 0,Tr.userData.record)}for(let Tr of Qt.values()){Tr.expandByScalar(.035),Tr.getCenter(lr),Tr.getSize(pr);for(let jr=0;jr<Ao.count;jr++)Jf.setXYZ(wr*Ao.count+jr,lr.x+Ao.getX(jr)*pr.x,lr.y+Ao.getY(jr)*pr.y,lr.z+Ao.getZ(jr)*pr.z);wr++}return Pr+=Qt.size,Rl.setDrawRange(0,wr*Ao.count),Jf.needsUpdate=!0,Yc.outlineVerticesWritten+=wr*Ao.count,os.hidden=Pr<=Cl,os.textContent=`Showing ${wr} of ${Pr} selected 3D objects`,os.style.display=Pr>Cl?"block":"none",ls.visible=!1,Pl.visible=!Oe.size,va.update(ot,Pr>0&&Wc,Oe.size?Tr=>Oe.has(Tr?.net):null,{...Tl,expanded:dr.get()>0,netContext:Oe.size>0}),Lu(),sE(Oe),{highlighted:wr,matched:Pr,limited:Pr>Cl}}let ls=new Fn(iE,nE());ls.matrixAutoUpdate=!1,ls.renderOrder=100,ls.visible=!1,st.add(ls);let aE=new Ir,Il=new Xi,oE=new je,lE=new je;function cE(q,Oe){if(Ct(),q.updateWorldMatrix(!0,!1),Number.isInteger(Oe)?(q.getMatrixAt(Oe,aE),q.geometry.boundingBox||q.geometry.computeBoundingBox(),Il.copy(q.geometry.boundingBox).applyMatrix4(aE).applyMatrix4(q.matrixWorld)):Il.setFromObject(q),Il.isEmpty()){ls.visible=!1;return}Il.expandByScalar(.035),Il.getCenter(oE),Il.getSize(lE),ls.matrix.compose(oE,new pn,lE),ls.matrixWorldNeedsUpdate=!0,ls.visible=!0}function Y0(){as=null,E.hidden=!0,M.hidden=!0,ls.visible=!1,Us({}),r.onSelect?.(null)}function q0(q,Oe,ot,Nt){let Lt=r.getSelectionMode?.()||$0;Us(Lt==="net"&&q.net?{netNames:[q.net]}:q.type==="Component"||typeof q.library=="string"?{references:[q.ref]}:{uuids:[q.uuid||q.id]}),as={record:q,point:Oe.clone(),object:ot,instanceId:Nt},Rl.setDrawRange(0,0),Lt!=="net"||!q.net?cE(ot,Nt):ls.visible=!1,r.onSelect?.(q),E.replaceChildren();let Ot=document.createElement("h2");Ot.textContent=q.ref||q.name||q.type||"Board object";let lr=document.createElement("dl");for(let[pr,wr]of Object.entries({Type:q.type||(q.ref?"Component":"Copper"),Reference:q.ref,Value:q.value,Layer:q.layer||q.layers?.join(", "),Net:q.net,Model:q.modelPath||q.modelPaths?.join(", ")})){if(wr==null||wr==="")continue;let Pr=document.createElement("dt"),Qt=document.createElement("dd");Pr.textContent=pr,Qt.textContent=String(wr),lr.append(Pr,Qt)}E.append(Ot,lr),E.hidden=!!r.externalInspector}let cs=M3(C,{scene:st,objects:()=>sn,document,invalidate:Ct}),Nl=document.createElement("div");Nl.hidden=!0,Nl.setAttribute("role","status"),Nl.style.cssText="position:absolute;left:12px;right:12px;bottom:12px;z-index:8;padding:9px 12px;border:1px solid var(--accent);border-radius:7px;background:var(--menu);color:var(--ink);font:12px/1.4 system-ui;max-height:calc(100% - 24px);overflow:auto;pointer-events:none",g.append(Nl);let K0=document.createElement("span"),qc=document.createElement("button");qc.type="button",qc.textContent="Cancel",qc.setAttribute("aria-label","Cancel demo face selection"),qc.style.cssText="pointer-events:auto;margin-left:10px",qc.onclick=()=>kl(new DOMException("Face selection was cancelled.","AbortError")),Nl.append(K0,qc);let Ll=null,ia=null,pD=q=>f0(q,Cn,Nr||dr.get()>0?"translucent":Kr);function Qf(q,Oe=!0){cs.sync();let ot=pe.domElement.getBoundingClientRect();return!ot.width||!ot.height?null:(Eo.set((q.clientX-ot.left)/ot.width*2-1,-((q.clientY-ot.top)/ot.height)*2+1),_o.setFromCamera(Eo,le),_o.intersectObjects((Oe?[...sn,...cs.objects()]:sn).filter(pD),!1).find(Nt=>va.isVisible(Nt.object,Nt.instanceId))||null)}function kl(q,Oe){let ot=Ll;ot&&(Ll=null,ot.signal?.removeEventListener("abort",ot.abort),Nl.hidden=!0,pe.domElement.style.cursor="",q?ot.reject(q):ot.resolve(Oe))}function fD({signal:q}={}){return Kt?q?.aborted?Promise.reject(new DOMException("Face selection was aborted.","AbortError")):(kl(new DOMException("Face selection was replaced.","AbortError")),xa(),Al(!1),new Promise((Oe,ot)=>{let Nt=()=>kl(new DOMException("Face selection was aborted.","AbortError"));Ll={resolve:Oe,reject:ot,signal:q,abort:Nt},q?.addEventListener("abort",Nt,{once:!0}),K0.textContent="Choose a flat component face for the demo display. Drag to orbit; press Escape to cancel.",Nl.hidden=!1,pe.domElement.style.cursor="crosshair",pe.domElement.tabIndex=0,pe.domElement.focus({preventScroll:!0})})):Promise.reject(new Error("The 3D view is closed."))}function xa(q){if(ia===null)return;let Oe=ia;ia=null,cs.pointer(null,"cancel",{pointerId:Oe,clientY:q?.clientY||0,cancelled:!0}),Vt.enabled=!0;try{pe.domElement.releasePointerCapture(Oe)}catch{}}function hE(q){if(ia!==null){q.preventDefault(),q.stopImmediatePropagation();return}if(ji||bo||Ll||q.button!==0)return;let Oe=Qf(q);if(cs.isHit(Oe)&&cs.pointer(Oe,"press",q)&&(q.preventDefault(),q.stopImmediatePropagation(),!(!Kt||!cs.isHit(Oe)))){ia=q.pointerId,Vt.enabled=!1,pe.domElement.tabIndex=0,pe.domElement.focus({preventScroll:!0});try{pe.domElement.setPointerCapture(q.pointerId)}catch{}}}function uE(q){ia===q.pointerId&&(cs.pointer(Qf(q),"move",q),q.preventDefault(),q.stopImmediatePropagation())}function dE(q){if(ia!==q.pointerId)return;let Oe=ia;ia=null,cs.pointer(Qf(q),"release",q),Vt.enabled=!0;try{pe.domElement.releasePointerCapture(Oe)}catch{}q.preventDefault(),q.stopImmediatePropagation()}function em(q){ia===q.pointerId&&(xa(q),q.preventDefault(),q.stopImmediatePropagation())}let pE=q=>{q.key==="Escape"&&Ll&&(kl(new DOMException("Face selection was cancelled.","AbortError")),q.preventDefault(),q.stopImmediatePropagation())};for(let[q,Oe]of[["pointerdown",hE],["pointermove",uE],["pointerup",dE],["pointercancel",em],["lostpointercapture",em]])pe.domElement.addEventListener(q,Oe,!0);f.addEventListener("keydown",pE,!0),document.defaultView?.addEventListener("blur",xa);function Z0(q){if(Ll){try{let Qt=Qf(q,!1);kl(null,cs.selectFace(Qt))}catch(Qt){K0.textContent=Qt.message+" Choose another flat component face, or press Escape."}return}let Oe=pe.domElement.getBoundingClientRect();if(Eo.set((q.clientX-Oe.left)/Oe.width*2-1,-((q.clientY-Oe.top)/Oe.height)*2+1),_o.setFromCamera(Eo,le),ji){dD();return}let ot=null,Nt=Ka.overlay;if(Nt?.group?.visible!==!1&&Nt?.mesh.visible){let Qt=Nt.sample(_o.intersectObject(Nt.mesh,!1)[0]);Qt&&(ot=Qt)}let Lt=Qt=>f0(Qt,Cn,Nr||dr.get()>0?"translucent":Kr),Ot=_o.intersectObjects(sn.filter(Lt),!1).filter(Qt=>va.isVisible(Qt.object,Qt.instanceId)),lr=r.getSelectionMode?.()||$0,pr=Qt=>lO(Qt.object.userData.records?.[Qt.instanceId]||Qt.object.userData.record,lr),wr=Kr==="translucent"&&Ot.find(Qt=>pr(Qt)&&(Qt.object.userData.records?.[Qt.instanceId]||Qt.object.userData.record)?.type!=="Zone")||Ot.find(pr);if(!wr){ot?r.onAnalysisProbe?.(ot):Y0();return}let Pr=wr.object.userData.records?.[wr.instanceId]||wr.object.userData.record;Pr&&q0(Pr,wr.point,wr.object,wr.instanceId),ot&&r.onAnalysisProbe?.(ot)}let $0="all",Kc=oO(q=>mE(q)),fE=q=>{ji&&q.pointerType==="touch"&&Mo.size&&(Vt.enabled=!0)};pe.domElement.addEventListener("pointerdown",fE,!0),pe.domElement.addEventListener("pointerdown",q=>{$u.down(q),Kc.down(q),M.hidden=!0,ji&&q.pointerType==="touch"&&(Mo.add(q.pointerId),qu=Mo.size===1?q.pointerId:null,Vt.enabled=Mo.size!==1,Ya={x:q.clientX,y:q.clientY},Ct())}),pe.domElement.addEventListener("pointermove",q=>{$u.move(q),Kc.move(q),ji&&q.pointerType==="touch"&&(Ya={x:q.clientX,y:q.clientY},Ct());let Oe=Ka.overlay;if(Oe&&r.onAnalysisHover){let ot=pe.domElement.getBoundingClientRect();Eo.set((q.clientX-ot.left)/ot.width*2-1,-((q.clientY-ot.top)/ot.height)*2+1),_o.setFromCamera(Eo,le),r.onAnalysisHover(Oe.group.visible&&Oe.mesh.visible?Oe.sample(_o.intersectObject(Oe.mesh,!1)[0]):null)}}),pe.domElement.addEventListener("pointercancel",q=>{$u.cancel(q),Kc.up(q),Mo.delete(q.pointerId),qu=null,Vt.enabled=!0,Ya=null,Ss.hidden=!0}),pe.domElement.addEventListener("pointerup",q=>{Kc.up(q),$u.up(q,{select:!(ji&&q.pointerType==="touch")}),ji&&q.pointerType==="touch"&&(qu===q.pointerId&&Mo.size===1&&Z0(q),Mo.delete(q.pointerId),qu=null,Vt.enabled=!0),Ya=null,Ss.hidden=!0});function mE(q){if(q.preventDefault?.(),ji||Ll||(Z0(q),!as))return;M.replaceChildren();let Oe=[["Focus object",()=>{Vt.target.copy(as.point),Vt.update()}],["Copy reference",()=>navigator.clipboard.writeText(as.record.ref||as.record.name||"")]];typeof r.onInspect=="function"&&Oe.unshift(["Properties",()=>r.onInspect(as.record)]),typeof r.onComment=="function"&&Oe.push(["Comment on object",()=>r.onComment(as.record)]);for(let[Lt,Ot]of Oe){let lr=document.createElement("button");lr.textContent=Lt,lr.type="button",lr.addEventListener("click",()=>{Ot(),M.hidden=!0}),M.append(lr)}let ot=g.getBoundingClientRect();M.hidden=!1,M.style.maxWidth="calc(100% - 16px)",M.style.maxHeight="calc(100% - 16px)",M.style.overflowY="auto";let Nt=M.getBoundingClientRect();M.style.left=`${Math.max(8,Math.min(q.clientX-ot.left,ot.width-Nt.width-8))}px`,M.style.top=`${Math.max(8,Math.min(q.clientY-ot.top,ot.height-Nt.height-8))}px`}pe.domElement.addEventListener("contextmenu",q=>{$u.context(q)});let tm=xo,gE=new ResizeObserver(()=>{tm(),ue()});gE.observe(v);let yE=d_(It,v);tm(),ue();let Ka=CO({bounds:o.bounds,thickness:We,layers:o.layers||[]},{scene:st,invalidate:Ct,isActive:()=>Kt}),mD=requestAnimationFrame(()=>{Kt&&(tm(),pi||El())}),vE=K3(C,{objects:()=>sn,camera:le,rect:()=>pe.domElement.getBoundingClientRect(),positionToWorld:(q,Oe)=>{let[ot,Nt]=Ge([q.x,q.y]);return new je(ot,Nt,Oe==="back"?it+dr.offset("B.Cu"):mt+dr.offset("F.Cu"))}}),Ju=null,J0="",xE="";function bE(){if(!Ju)return;let q=vE(Ju),Oe=JSON.stringify(q);Oe!==J0&&(J0=Oe,r.onAnchor?.({anchor:Ju,point:q}))}function gD(){let q=pe.domElement.getBoundingClientRect(),Oe=JSON.stringify([le.matrixWorld.elements,le.projectionMatrix.elements,q.left,q.top,q.width,q.height]);Oe!==xE&&(xE=Oe,r.onViewChange?.()),bE()}function yD(){if(wo.resume(),!Kt||fr||document.hidden)return;let q=nn&&!ji;q||Du.flush(),Vt.update(),k_(q),Vf.sync({moving:nn||wo.running()}),cs.sync(),ia!==null&&!cs.hasActivePointer&&xa(),eE(),q?Vu.visible=!1:X_();let Oe=!1;Er=!1;try{if(Zt&&!q){if(Zt.composer.render(),Er||!oe.check())throw Error("Enhanced rendering failed.")}else if(pe.render(st,le),Er)throw Error("Board rendering shader failed.");er++,Oe=!0}catch{Er&&Ka.useColorFallback()?(Er=!1,Ct()):Zt&&!q?(cr("Enhanced rendering could not complete. Balanced rendering is active."),Ct()):rr("The graphics device could not draw this view. Try Low quality or reopen 3D.")}Oe&&(cD(),gD())}let wE=q=>{xa(),kl(new DOMException("The graphics context was interrupted.","AbortError")),q.preventDefault(),fr=!0,It.setState({contextAvailable:!1}),ie.disabled=!0,rr("The graphics context was interrupted. The board and selection are retained while the browser recovers.",!0)},_E=()=>{Kt&&(fr=!1,It.setState({contextAvailable:!0}),ie.disabled=!1,$t(),_r?.dispose(),_r=ir(),st.environment=_r?.texture||null,pe.shadowMap.needsUpdate=!0,Gt="balanced",ea.apply(!1),ut(),ie.value=Gt,d.dataset.quality=Gt,rr("Graphics restored. Balanced rendering is active; High quality can be selected again."),xo(),Ct())};pe.domElement.addEventListener("webglcontextlost",wE),pe.domElement.addEventListener("webglcontextrestored",_E);let EE=()=>{document.hidden&&xa(),It.setState({documentVisible:!document.hidden}),document.hidden||(wo.resume(),Ct())};document.addEventListener("visibilitychange",EE);let SE=q=>{let Oe=q.composedPath();!Oe.includes(Bc)&&!Oe.includes(Z)&&Te(!1)},ME=q=>{q.key==="Escape"&&!Z.hidden?(Te(!1,!0),q.preventDefault(),q.stopImmediatePropagation()):q.key==="Escape"&&Sl.open&&(Sl.open=!1,Bu.focus(),q.preventDefault(),q.stopImmediatePropagation())};return document.addEventListener("pointerdown",SE),f.addEventListener("keydown",ME,!0),F.retain(st),Ti(i),yr(Re,!1),tD(r.boardPath?globalThis.KiCadRepoModels.modelSource(s):null),{host:d,board:o,pickDemoFace:fD,createDemoSurface(q,Oe){if(oe.invalidate(),!Kt)throw new Error("The 3D view is closed.");return cs.createSurface(q,Oe)},setDemoInputHandler(q){q===null&&xa(),cs.setInputHandler(q)},objectVisibilityCapabilities(){return{supportedTypes:[...zn.supportedTypes],unsupportedTypes:["graphics","texts","regions","dimensions","rooms","footprints"]}},setObjectVisibility(q={}){let Oe=C0(q||{});(Oe.side!==zn.side||JSON.stringify(Oe.hiddenTypes)!==JSON.stringify(zn.hiddenTypes))&&(pi=!0),zn=Oe;for(let{mesh:ot,type:Nt,layer:Lt}of wl)ot.visible=zn.visible(Nt,Lt);return Xf(),Us(Nn),{hiddenTypes:[...zn.hiddenTypes],side:zn.side,supportedTypes:[...zn.supportedTypes],unsupportedTypes:[...zn.unsupportedTypes]}},setMeasurementMode:Al,clearMeasurements:tE,measurementState(){return{mode:ji,unit:So,...Es.snapshot()}},setQuality(q){return Kt?yr(q):Gt},setAppearance(q){return Kt?Ti(q):Kr},getAppearance(){return Kr},getCopperLayers(){return Pt.map(q=>q.name)},getVisibleCopperLayers(){return B0()},setVisibleCopperLayers:V_,getRenderStats(){return{...f_(v.clientWidth,v.clientHeight,globalThis.devicePixelRatio,He.maxDimension,Gt,He),...F.stats(),zones:{...a.stats(),...ht},modelGraph:{...Mt.stats(),decodeConcurrency:Ut,imagePreflight:"png-jpeg"},padGeometryCache:Qe.stats(),selectionMaterials:va.stats(),appearance:Kr,netGlow:Xc.stats(),effectiveLayerColors:!!Nr||dr.get()>0||Kr!=="realistic",renderedPixels:pe.domElement.width*pe.domElement.height,expansion:{amount:dr.get(),target:wo.target(),running:wo.running(),...dr.phases(),frames:z_,cpuMilliseconds:B_,maxFrameMilliseconds:z0,frontComponentOffset:dr.componentOffset("F.Cu"),backComponentOffset:dr.componentOffset("B.Cu"),layerOffsets:Pt.map(q=>({name:q.name,offset:dr.offset(q.name)}))},renderActivity:{...It.stats(),observesIntersection:!!yE},selectionWorkload:{...Yc},modelUpdates:{...Du.stats(),cpuMilliseconds:L_},copperLayers:[...kt],translucency:Oi.stats(),graphicsTier:He.tier,defaultQuality:He.defaultQuality,maxDimension:He.maxDimension,antialias:Le.getContextAttributes()?.antialias===!0,logarithmicDepth:pe.capabilities.logarithmicDepthBuffer,floatTargets:He.premium||pe.extensions.has("EXT_color_buffer_float"),presentationStage:ea.enabled,environmentLighting:!!st.environment,ambientOcclusion:!!Zt?.occlusion,graphicsHealth:oe.stats(),silkscreenDetail:Vf.stats(),antialiasMethod:Zt?"smaa":"none",renderCount:er,contextLost:fr,gpuTextures:pe.info.memory.textures,drawCalls:pe.info.render.calls,loadedModelCount:ku.size,componentCount:o.components.length}},restoreExpand:q=>Kf(q,!0),setExplode:Kf,getExplode:()=>dr.get(),setExpand:Kf,getExpand:()=>dr.get(),setAnalysisOverlay(q,Oe){oe.invalidate();let ot=Ka.setAnalysisOverlay(q,Oe);return U_(),F_(ot)},getAnalysisOverlayState:()=>F_(),setAnalysisProbes:Ka.setAnalysisProbes,setAnalysisOpacity:Ka.setAnalysisOpacity,setSelection:Us,focusPart(q){if(!Kt||typeof q!="string")return!1;let Oe=o.components.flatMap((pr,wr)=>pr.id===q?[wr]:[]);if(Oe.length!==1)return!1;let ot=Oe[0];if(!Fc[ot]||!Yi||!Wf[ot])return!1;Sn.updateWorldMatrix(!0,!0);let Nt=Xa.get(ot),Lt=new Xi;if(Nt?.children.length)Lt.setFromObject(Nt);else{let pr=new Ir;if(Yi.getMatrixAt(ot,pr),pr.determinant()===0)return!1;Yi.geometry.boundingBox||Yi.geometry.computeBoundingBox(),Lt.copy(Yi.geometry.boundingBox).applyMatrix4(new Ir().multiplyMatrices(Yi.matrixWorld,pr))}if(Lt.isEmpty())return!1;xo();let Ot=T3(Lt.min.toArray(),Lt.max.toArray(),o.components[ot].layer,le.fov,le.aspect);if(!Ot)return!1;le.position.fromArray(Ot.position),Vt.target.fromArray(Ot.target),le.up.fromArray(Ot.up);let lr=le.position.distanceTo(Vt.target);return Vt.minDistance=Math.min(Vt.minDistance,lr),Vt.maxDistance=Math.max(Vt.maxDistance,lr),pi=!0,Vt.update(),k0(),Ct(),!0},clearSelection:Y0,projectAnchor:vE,setAnchor(q){Ju=q&&typeof q=="object"?q:null,J0="",Ju?bE():r.onAnchor?.({anchor:null,point:null})},setSelectionDim(q){return Wc=!!q,Us(Nn),Wc},setSelectionStyle(q){let Oe=p0(q);return Wc&&Oe.mode===Tl.mode&&Oe.color===Tl.color?{...Oe}:(Wc=!0,Tl=Oe,Us(Nn),{...Oe})},selectionAppearanceCapabilities(){return{dim:!0,bright:!0,isolate:!0,sourceColors:!0,instanceColors:!0,desaturatesTextures:!0}},setSelectionMode(q){$0=["all","part","net","pin"].includes(q)?q:"all"},fit(q=!1){Kt&&El(q)},getCameraState(){return{position:le.position.toArray(),target:Vt.target.toArray(),up:le.up.toArray()}},setCameraState(q){if(!Kt)return!1;let Oe=A3(q),ot=Vt.enableDamping;kc(),vo(),Vt.enableDamping=!1,Vt.update(),le.position.fromArray(Oe.position),Vt.target.fromArray(Oe.target),le.up.fromArray(Oe.up);let Nt=le.position.distanceTo(Vt.target);return Vt.minDistance=Math.min(Vt.minDistance,Nt),Vt.maxDistance=Math.max(Vt.maxDistance,Nt),Vt.update(),Vt.enableDamping=ot,pi=!0,zc(),Ct(),!0},setView(q){return!Kt||!Uf.some(Oe=>Oe.id===q)?!1:(pi=!0,El(q),!0)},zoom(q){if(!Kt||!Number.isFinite(q)||q<=0)return;let Oe=le.position.clone().sub(Vt.target),ot=Math.max(Vt.minDistance,Math.min(Vt.maxDistance,Oe.length()/q));Oe.length()>0&&le.position.copy(Vt.target).add(Oe.setLength(ot)),Vt.update()},setTheme(q){Kt&&(d.dataset.theme=q?"dark":"light",ut(),ls.material.color.setHex(q?16768893:10179840),Pl.material.color.setHex(q?16768893:10179840),tm(),Ct())},selectReference(q){let Oe=N_.get(q);if(Oe==null||!Yi||!Wf[Oe]||!Kt||!Fc[Oe])return!1;let ot=Xa.get(Oe);if(ot?.children.length){let wr=o.components[Oe],[Pr,Qt]=Ge(wr.at);return q0(wr,new je(Pr,Qt,(wr.layer?.startsWith("B.")?it:mt)+dr.componentOffset(wr.layer?.startsWith("B.")?"B.Cu":"F.Cu")),ot),!0}let Nt=new Ir;if(Yi.getMatrixAt(Oe,Nt),Nt.determinant()===0)return!1;let Lt=o.components[Oe],[Ot,lr]=Ge(Lt.at),pr=new je(Ot,lr,(Lt.layer?.startsWith("B.")?it-1.1:mt+1.1)+dr.componentOffset(Lt.layer?.startsWith("B.")?"B.Cu":"F.Cu"));return Yi.localToWorld(pr),q0(Lt,pr,Yi,Oe),!0},setPopulation(q){if(!(!Yi||!Kt)&&(Fc=W3(o.components,q),Xf(),Us(Nn),as?.record?.ref)){let Oe=N_.get(as.record.ref);Oe!=null&&!Fc[Oe]&&Y0()}},dispose(){Vf.dispose(),xa(),kl(new DOMException("The 3D view was closed.","AbortError")),cs.dispose();for(let[q,Oe]of[["pointerdown",hE],["pointermove",uE],["pointerup",dE],["pointercancel",em],["lostpointercapture",em]])pe.domElement.removeEventListener(q,Oe,!0);f.removeEventListener("keydown",pE,!0),document.defaultView?.removeEventListener("blur",xa),ji&&r.onMeasurementMode?.(!1),Kt=!1,wo.dispose(),_s.oninput=null,Du.dispose(),Ka.dispose(),Ou?.dispose(),It.dispose(),cancelAnimationFrame(mD),gE.disconnect(),yE?.disconnect(),Vt.removeEventListener("change",Ct),Vt.removeEventListener("change",zc),Vt.removeEventListener("start",kc),Vt.removeEventListener("end",vo),$i!==null&&clearTimeout($i),$i=null,Vt.dispose(),$t(),_r?.dispose(),pe.domElement.removeEventListener("webglcontextlost",wE),pe.domElement.removeEventListener("webglcontextrestored",_E),document.removeEventListener("pointerdown",SE),f.removeEventListener("keydown",ME,!0),f.removeEventListener("keydown",rE),pe.domElement.removeEventListener("pointerdown",fE,!0),document.removeEventListener("visibilitychange",EE),Xc.dispose(),va.dispose(),Oi.dispose(),st.traverse(q=>q.shadow?.dispose?.()),F.retain(st),ya.forEach(q=>F.track(q)),F.track(W_),F.dispose(),st.clear(),Sn.clear(),Uc.clear(),Dc.clear(),Os.clear(),sn.length=0,wl.length=0,bi.length=0,Wf.length=0,Xa.clear(),ya.clear(),Qe.clear(),Kc.dispose(),pe.dispose(),pe.domElement.width=1,pe.domElement.height=1,d.remove()}}}return X(be)})()});var Rv={};Ol(Rv,{applySavedWorksheet:()=>aU,parseWorksheet:()=>nU,worksheetLimit:()=>Cv});function nU(m,h){if(typeof m!="string"||m.length>Cv||h.sourceByteLength(m)>Cv)throw new Error("Worksheet must be text within 2 MiB.");let p=h.parse(m);if(!["kicad_wks","page_layout"].includes(p[0]))throw new Error("Expected a KiCad worksheet template.");return(w,S,A,T,H)=>sU(p,w,S,A,T,H)}function sU(m,h,p,w,S,A){let T=Gn(m,"setup"),H=Ee=>ro(Gn(T,Ee+"_margin")?.[1],10),Y=H("left"),ee=H("top"),X=h.width-H("right"),G=h.height-H("bottom"),ae=(Ee,me,N)=>{if(typeof Ee?.[1]!="number"||typeof Ee?.[2]!="number")return null;let re=Ee[3]||"rbcorner";return["ltcorner","lbcorner","rtcorner","rbcorner"].includes(re)?{x:re[0]==="l"?Y+wa(Ee[1])+me:X-wa(Ee[1])-me,y:re[1]==="t"?ee+wa(Ee[2])+N:G-wa(Ee[2])-N}:null},{title:_e="",date:J="",rev:Q="",company:te="",comments:he=[]}=h.titleBlock||{},be={T:_e,D:J,R:Q,Y:te,Z:h.format,F:p.split("/").at(-1),S:w.sheetNumber??1,N:w.sheetCount??1,P:w.sheetName??"/",K:w.kicadVersion||"KiCad","%":"%"},De={PAPER:h.format,"#":be.S,"##":be.N},Ke=[],qe=0,$e=0,Xe=Gn(T,"textsize"),ve=Ee=>Ee.x>=Y&&Ee.x<=X&&Ee.y>=ee&&Ee.y<=G;for(let Ee of m){if(!Array.isArray(Ee)||["setup","version","generator","generator_version"].includes(Ee[0]))continue;let me=Ee[0];if(!["line","rect","polygon","tbtext"].includes(me)){A('Worksheet object "'+String(me).slice(0,80)+'" is not rendered.');continue}let N=Gn(Ee,"option")?.[1],re=String(w.sheetNumber??1)==="1";if(N==="page1only"&&!re||N==="notonpage1"&&re)continue;let R=Math.max(1,Math.trunc(ro(Gn(Ee,"repeat")?.[1],1)));if(R>1e3)throw new Error("Worksheet repeat count exceeds 1,000.");let $=wa(Gn(Ee,"incrx")?.[1]),V=wa(Gn(Ee,"incry")?.[1]),O=ro(Gn(Ee,"rotate")?.[1]),C=O*Math.PI/180,j=Math.cos(C),B=Math.sin(C),W=Gn(Ee,"font"),K=Gn(W,"size")||Xe,ge=Gn(Ee,"justify"),Ne=Gn(Ee,me==="line"||me==="rect"?"start":"pos"),ne=Gn(Ee,"end"),we={frame:!0,kind:"custom-worksheet",color:"#a0a0a0",width:ro(Gn(Ee,"linewidth")?.[1],ro(Gn(T,"linewidth")?.[1],.15))||.15};for(let xe=0;xe<R;xe++){let ke=ae(Ne,$*xe,V*xe),Me=ae(ne,$*xe,V*xe);if(!(!ke||xe>0&&me!=="polygon"&&(!ve(ke)||Me&&!ve(Me)))){if(me==="line"&&Me&&Ke.push({...we,type:"line",points:[ke,Me]}),me==="rect"&&Me&&Ke.push({...we,type:"polygon",points:[ke,{x:Me.x,y:ke.y},Me,{x:ke.x,y:Me.y}]}),me==="polygon")for(let Ce of Ee){if(!Array.isArray(Ce)||Ce[0]!=="pts")continue;if(qe+=Ce.length-1,qe>1e5)throw new Error("Worksheet exceeds 100,000 polygon vertices.");let tt=Ce.slice(1).filter(Ze=>Array.isArray(Ze)&&Ze[0]==="xy").map(([,Ze,Ye])=>({x:ke.x+wa(Ze)*j+wa(Ye)*B,y:ke.y-wa(Ze)*B+wa(Ye)*j}));tt.length>=2&&(!xe||tt.every(ve))&&Ke.push({...we,type:"polygon",points:tt,fill:tt.length>2})}if(me==="tbtext"){let Ce=String(iU(Ee[1])??"");if(xe&&!/[%$\n]/.test(Ce)){let tt=xe*ro(Gn(Ee,"incrlabel")?.[1],1);Ce=/\d+$/.test(Ce)?Ce.replace(/\d+$/,Ze=>String(Number(Ze)+tt)):Ce.replace(/[A-Za-z]$/,Ze=>String.fromCharCode(Ze.charCodeAt(0)+tt))}if(m[0]==="page_layout"&&(Ce=Ce.replace(/%([C][0-8]|[TDRYZFSNPK%])/g,(tt,Ze)=>Ze.length===2?he[Number(Ze[1])]??"":be[Ze]??"")),Ce=S(Ce.replace(/\$\{(PAPER|##?)\}/g,(tt,Ze)=>String(De[Ze]??tt))),$e+=Ce.length,$e>25e4)throw new Error("Worksheet exceeds its display text budget.");Ce&&Ke.push({...we,type:"text",...ke,text:Ce,angle:-O,fontWidth:ro(K?.[1],1.5),fontHeight:ro(K?.[2],1.5),align:ge?.includes("right")?"right":ge?.includes("center")?"center":"left",baseline:ge?.includes("top")?"top":ge?.includes("bottom")?"bottom":"middle",bold:W?.includes("bold"),italic:W?.includes("italic")})}if(Ke.length>1e4)throw new Error("Worksheet exceeds 10,000 drawing elements.")}}}return Ke}function aU(m,h,p){let w=m.find(S=>S.path.replace(/\.kicad_pro$/i,"")===h.replace(/\.kicad_(pcb|sch)$/i,""))||(m.length===1?m[0]:null);if(w){let S=w.path.split("/").slice(0,-1),A=/\.kicad_pcb$/i.test(h)?w.pcb:w.sch;if(typeof A=="string"&&A){let T=A.replace(/^\$\{KIPRJMOD\}[\\/]/,"").replaceAll("\\","/"),H=[...S,T].join("/");Bs(T)&&p.files.some(Y=>Y.path===H&&Hn(Y.path))?p.worksheet=H:p.notes.push("The saved project worksheet is not in the loaded files. Include the template or supply worksheetSource.")}}}var iU,Gn,ro,wa,Cv,Pv=Ui(()=>{Qa();iU=m=>m?.quoted??m,Gn=(m,h)=>m?.find(p=>Array.isArray(p)&&p[0]===h),ro=(m,h=0)=>typeof m=="number"&&Number.isFinite(m)&&Math.abs(m)<=1e5?m:h,wa=m=>Math.trunc(ro(m)*1e3)/1e3,Cv=2*1024*1024});var Lv={};Ol(Lv,{fitCamera:()=>Iv,manufacturingDesign:()=>cU,mountManufacturing:()=>lU,screenToWorld:()=>Nv,zoomCamera:()=>SM});function Iv(m,h,p){let w=m||{x:0,y:0,w:100,h:100};return{x:w.x+w.w/2,y:w.y+w.h/2,zoom:Math.max(.001,Math.min(h/Math.max(.01,w.w),p/Math.max(.01,w.h))*.88)}}function Nv(m,h,p,w,S){return{x:m.x+(w-h/2)/m.zoom,y:m.y-(S-p/2)/m.zoom}}function SM(m,h,p,w,S,A){let T=Nv(m,h,p,w,S),H=Math.max(.001,Math.min(1e5,m.zoom*A));return{x:T.x-(w-h/2)/H,y:T.y+(S-p/2)/H,zoom:H}}function lU(m,{dark:h=!1}={}){let p=m.ownerDocument,w=p.createElement("canvas"),S=p.createElement("canvas"),A=p.createElement("div");w.style.cssText="width:100%;height:100%;display:block;touch-action:none;outline:none",w.tabIndex=0,w.setAttribute("role","img"),w.setAttribute("aria-label","Interactive manufacturing layers; drag to pan, wheel to zoom, click to inspect; use toolbar to measure"),A.setAttribute("role","status"),A.style.cssText="position:absolute;left:12px;right:12px;bottom:12px;width:fit-content;max-width:calc(100% - 24px);padding:8px 12px;border-radius:8px;font:12px/1.5 system-ui;overflow-wrap:anywhere;pointer-events:none",A.hidden=!0,m.append(w,A);let T=w.getContext("2d"),H=S.getContext("2d");if(!T||!H)throw new Error("Canvas2D is required for manufacturing viewing.");let Y=new EventTarget,ee,X,G=1,ae=1,_e=1,J=!1,Q=null,te=!1,he=null,be=null,De=!1,Ke=null,qe=new Map,$e=[],Xe=(C,j,B)=>{w.addEventListener(C,j,B),$e.push([C,j,B])},ve=Object.assign(Y,{dark:h,visibleLayers:new Set,measuring:!1,setDocument(C){ee=C,qe.clear(),Ke=null,he=be=null;for(let j of ee.camLayers)for(let B of j.operations)qe.set(B,new Path2D(B.path));ve.visibleLayers=new Set(ee.layers),Ee(),ve.zoom_to_board(),ve.draw()},zoom_to_board(){X=Iv(ee?.bounds,G,ae)},clearSelection(){Ke=null,A.textContent="",re()},setMeasuring(C){ve.measuring=!!C,he=be=null,De=!1,ve.draw()},draw:re,dispose(){J=!0,O?.disconnect();for(let[C,j,B]of $e)w.removeEventListener(C,j,B);qe.clear(),w.remove(),A.remove(),w.width=w.height=S.width=S.height=1}});function Ee(){if(J)return;let C=m.getBoundingClientRect();G=Math.max(1,C.width),ae=Math.max(1,C.height),_e=Math.min(globalThis.devicePixelRatio||1,3,Math.sqrt(8e6/G/ae),8192/G,8192/ae),w.width=S.width=Math.max(1,Math.floor(G*_e)),w.height=S.height=Math.max(1,Math.floor(ae*_e)),X||=Iv(ee?.bounds,G,ae),re()}function me(C){C.setTransform(_e*X.zoom,0,0,-_e*X.zoom,_e*(G/2-X.x*X.zoom),_e*(ae/2+X.y*X.zoom))}function N(C,j){let B=qe.get(j);j.fill===!1?(C.lineWidth=j.width,C.lineCap="round",C.lineJoin="round",C.stroke(B)):C.fill(B,"evenodd")}function re(){if(J||!X)return;let C=Ke?.operation.metadata;if(A.hidden=!Ke||ve.measuring,A.style.background=ve.dark?"#182330ed":"#ffffffed",A.style.color=ve.dark?"#e1eaf3":"#253445",Ke){let j=Ke.layer+" \xB7 "+Ke.operation.kind+" \xB7 "+JSON.stringify(C||{}).slice(0,400);A.textContent!==j&&(A.textContent=j)}if(T.setTransform(1,0,0,1,0,0),T.globalAlpha=1,T.globalCompositeOperation="source-over",T.fillStyle=ve.dark?"#111923":"#f1f4f8",T.fillRect(0,0,w.width,w.height),ee?.camLayers.forEach((j,B)=>{if(ve.visibleLayers.has(j.id)){H.setTransform(1,0,0,1,0,0),H.globalCompositeOperation="source-over",H.clearRect(0,0,S.width,S.height),me(H),H.fillStyle=H.strokeStyle=j.color||(ve.dark?EM:oU)[B%EM.length];for(let W of j.operations)H.globalCompositeOperation=W.polarity==="clear"?"destination-out":"source-over",N(H,W);T.globalAlpha=.82,T.drawImage(S,0,0),T.globalAlpha=1}}),Ke&&ve.visibleLayers.has(Ke.layer)&&(me(T),T.globalCompositeOperation="source-over",T.strokeStyle=ve.dark?"#ffffff":"#172d47",T.lineWidth=2/X.zoom,T.stroke(qe.get(Ke.operation))),he&&be){me(T),T.strokeStyle=ve.dark?"#f7e182":"#715800",T.lineWidth=1.5/X.zoom,T.beginPath(),T.moveTo(he.x,he.y),T.lineTo(be.x,be.y),T.stroke();let j=Math.hypot(be.x-he.x,be.y-he.y);T.setTransform(_e,0,0,_e,0,0),T.font="600 12px system-ui";let B=j.toFixed(3)+" mm";T.fillStyle=ve.dark?"#172330":"#ffffff",T.fillRect(12,ae-40,T.measureText(B).width+24,28),T.fillStyle=ve.dark?"#f7e182":"#384353",T.fillText(B,24,ae-21)}}let R=C=>{let j=w.getBoundingClientRect();return{x:C.clientX-j.left,y:C.clientY-j.top}},$=C=>{let j=R(C);return Nv(X,G,ae,j.x,j.y)};function V(C){H.save(),H.setTransform(1,0,0,1,0,0);try{for(let j of[...ee.camLayers].reverse())if(ve.visibleLayers.has(j.id))for(let B of[...j.operations].reverse()){let W=B.bounds;if(W&&(C.x<W.x||C.x>W.x+W.w||C.y<W.y||C.y>W.y+W.h))continue;let K=qe.get(B);if(H.lineWidth=B.width||.001,B.fill===!1?H.isPointInStroke(K,C.x,C.y):H.isPointInPath(K,C.x,C.y,"evenodd")){if(B.polarity==="clear")break;return{layer:j.id,operation:B}}}return null}finally{H.restore()}}Xe("pointerdown",C=>{C.button!==0&&C.button!==2||(w.focus(),w.setPointerCapture(C.pointerId),Q={point:R(C),camera:{...X},button:C.button},te=!1)}),Xe("pointermove",C=>{let j=R(C);if(Q){let B=j.x-Q.point.x,W=j.y-Q.point.y;Math.hypot(B,W)>3&&(te=!0),te&&(X={...Q.camera,x:Q.camera.x-B/X.zoom,y:Q.camera.y+W/X.zoom},re())}else ve.measuring&&he&&!De&&(be=$(C),re())}),Xe("pointerup",C=>{if(!Q)return;let j=Q.button===0;if(Q=null,te||!j)return;let B=$(C);ve.measuring?!he||De?(he=B,be=null,De=!1):(be=B,De=!0,ve.dispatchEvent(new CustomEvent("measure",{detail:{start:he,end:be,distance:Math.hypot(B.x-he.x,B.y-he.y),unit:"mm"}}))):(Ke=V(B),ve.dispatchEvent(new CustomEvent("kicad:select",{detail:{item:Ke?{...Ke.operation.metadata,id:Ke.operation.id,layer:Ke.layer,kind:ee.format}:null}}))),re()}),Xe("pointercancel",()=>{Q=null}),Xe("contextmenu",C=>C.preventDefault()),Xe("wheel",C=>{C.preventDefault();let j=R(C);X=SM(X,G,ae,j.x,j.y,Math.exp(-Math.max(-200,Math.min(200,C.deltaY))*.005)),re()},{passive:!1}),Xe("keydown",C=>{C.key==="Escape"?(Ke=null,he=be=null,re()):C.key.toLowerCase()==="f"&&(ve.zoom_to_board(),re())});let O=typeof ResizeObserver=="function"?new ResizeObserver(Ee):null;return O?.observe(m),Ee(),ve}function cU(m,h={}){let p=[],w=[],S=null,A="manufacturing",T=0,H=0;for(let Y of m){let ee=Y.source??new TextDecoder("utf-8",{fatal:!0}).decode(Y.bytes),X=pv(ee,{...h,...h.importOptions?.[Y.path],path:Y.path});m.length===1&&(A=X.format);for(let ae of X.layers)for(let _e of ae.operations)if(T++,H+=_e.path.length,T>2e5||H>16e6)throw new Error("Manufacturing collection exceeds 200000 operations or 16 million path characters.");for(let ae of X.warnings)w.length<500&&w.push(Y.path+": "+ae);for(let ae of X.layers){let _e=Y.path+(X.layers.length>1?" / "+ae.id:"");p.push({...ae,id:_e,name:_e,operations:ae.operations.map(J=>({...J,id:Y.path+":"+J.id}))})}let G=X.bounds;G&&(S=S?{x:Math.min(S.x,G.x),y:Math.min(S.y,G.y),w:Math.max(S.x+S.w,G.x+G.w)-Math.min(S.x,G.x),h:Math.max(S.y+S.h,G.y+G.h)-Math.min(S.y,G.y)}:{...G})}if(!p.length)throw new Error("No supported manufacturing layers were found.");return{format:A,layers:p.map(Y=>Y.id),camLayers:p,bounds:S,warnings:w,units:"mm",primitives:[]}}var EM,oU,kv=Ui(()=>{sd();EM=["#f56d78","#62a5ff","#e1b85c","#73d5ae","#c49af1","#73cfdd","#e995bf","#c5d673"],oU=["#a9233b","#185797","#795000","#176747","#724097","#126477","#90315f","#4d6510"]});var AM=$n((MM,Hs)=>{(m=>{"use strict";let h=m.KiCadFileCompatibility||(typeof Hs=="object"&&Hs.exports?lm():null),p=m.KiCadDesignDiff||(typeof Hs=="object"&&Hs.exports?To():null),w=m.KiCadDesignDiff||(typeof Hs=="object"&&Hs.exports?To():null),S={page:"#a0a0a0",symbol:"#840000",pin:"#840000",wire:"#008400",bus:"#000080",label:"#008400",text:"#000000"},A={A0:[1189,841],A1:[841,594],A2:[594,420],A3:[420,297],A4:[297,210],A5:[210,148],USLetter:[279.4,215.9],USLegal:[355.6,215.9],USLedger:[431.8,279.4]},T=m.KiCadWorksheet||(typeof Hs=="object"&&Hs.exports?hm():null),H=[16,10,16,21,20,24,26,10,14,14,16,26,10,26,10,22,20,20,20,20,20,20,20,20,20,20,10,10,26,26,26,18,27,18,21,21,21,19,18,21,22,10,16,21,17,24,22,22,21,22,21,20,16,22,18,24,20,18,20,14,14,14,12,16,8,19,19,18,19,18,12,19,19,10,10,17,11,28,19,19,19,19,13,17,12,19,16,22,17,16,17,14,20,14,15];function Y(ne){let we=[],xe="",ke=0;for(let Me of String(ne).matchAll(/~\{([^{}]*)\}/g)){xe+=String(ne).slice(ke,Me.index);let Ce=xe.length;xe+=Me[1],we.push({start:Ce,end:xe.length}),ke=Me.index+Me[0].length}return xe+=String(ne).slice(ke),{text:xe,bars:we}}function ee(ne,we){return Array.from(Y(ne).text).reduce((xe,ke)=>xe+(H[ke.charCodeAt(0)-32]??21)*we/21,0)+we*.16}let X=Number.isSafeInteger(p?.MAX_RENDER_PRIMITIVES)&&p.MAX_RENDER_PRIMITIVES>0?p.MAX_RENDER_PRIMITIVES:15e4,G=ne=>ne&&typeof ne=="object"&&!Array.isArray(ne)?ne.quoted:ne,ae=ne=>Array.isArray(ne)?String(G(ne[0])):"",_e=(ne,we)=>Array.isArray(ne)?ne.filter(xe=>Array.isArray(xe)&&ae(xe)===we):[],J=(ne,we)=>_e(ne,we)[0],Q=(ne,we)=>G(J(ne,we)?.[1]),te=ne=>typeof ne=="number"&&Number.isFinite(ne),he=(ne,we)=>{let xe=J(ne,we),ke=G(xe?.[1]),Me=G(xe?.[2]);return te(ke)&&te(Me)?{x:ke,y:Me}:null},be=ne=>Q(ne,"uuid")??Q(ne,"tstamp")??null,De=ne=>Math.round(ne*1e6)/1e6;function Ke(ne,we){return Array.isArray(ne)&&ne.some(xe=>{if(Array.isArray(xe)&&ae(xe)===we){let ke=G(xe[1]);return ke===void 0||ke===!0||ke==="yes"||ke==="true"||ke===1}return!Array.isArray(xe)&&!(xe&&typeof xe=="object")&&xe===we})}function qe(ne={x:0,y:0},we=0,xe="",ke=!1){let Me=we*Math.PI/180,Ce=Math.cos(Me),tt=Math.sin(Me);return Ze=>{let Ye=Ze.x,vt=ke?-Ze.y:Ze.y,Rt=Ye*Ce+vt*tt,Je=-Ye*tt+vt*Ce;return xe==="x"&&(Je=-Je),xe==="y"&&(Rt=-Rt),{x:De(ne.x+Rt),y:De(ne.y+Je)}}}function $e(ne){let we=ae(ne)==="effects"?ne:J(ne,"effects");return Ke(ne,"hide")||Ke(we,"hide")||Ke(J(we,"font"),"hide")}function Xe(ne,we=1.27){let xe=ae(ne)==="effects"?ne:J(ne,"effects"),ke=J(xe,"font"),Me=J(ke,"size"),Ce=G(Me?.[1]),tt=G(Me?.[2]);return te(Ce)&&te(tt)&&Ce>0&&tt>0?De(tt):we}function ve(ne){let we=J(ne,"effects"),xe=J(we,"font"),ke=J(xe,"size"),Me=G(ke?.[1]),Ce=G(ke?.[2]),tt=J(we,"justify")?.slice(1).map(G)||[];return{bold:Ke(xe,"bold"),italic:Ke(xe,"italic"),...typeof Q(we,"href")=="string"?{href:Q(we,"href")}:{},...te(Me)&&Me>0?{fontWidth:Me}:{},...te(Ce)&&Ce>0?{fontHeight:Ce}:{},...me(xe)&&me(xe)!=="rgba(0,0,0,0)"?{sourceColor:me(xe),color:me(xe)}:{},...Q(xe,"face")?{fontFace:Q(xe,"face")}:{},...Q(xe,"thickness")?{textThickness:Q(xe,"thickness")}:{},lineSpacing:1.5,align:tt.includes("left")?"left":tt.includes("right")?"right":"center",baseline:tt.includes("top")?"top":tt.includes("bottom")?"bottom":"middle"}}function Ee(ne,we=.15){let xe=J(ne,"stroke"),ke=Q(xe,"width")??Q(ne,"width");return te(ke)&&ke>0?ke:we}function me(ne){let we=J(ne,"color")?.slice(1).map(G);if(!we||we.length!==4||we.some(tt=>!te(tt))||we.slice(0,3).some(tt=>tt<0||tt>255))return;let[xe,ke,Me,Ce]=we;return`rgba(${xe},${ke},${Me},${Math.max(0,Math.min(1,Ce))})`}function N(ne){let we=J(ne,"stroke"),xe=me(we),ke=J(ne,"fill"),Me=me(ke),Ce=Q(we,"type");return{...xe&&xe!=="rgba(0,0,0,0)"?{sourceColor:xe,color:xe}:{},...Me?{fillColor:Me}:{},...["dash","dot","dash_dot","dash_dot_dot"].includes(Ce)?{lineStyle:Ce}:{}}}function re(ne){let we=Q(J(ne,"fill"),"type");return["outline","background","color","hatch","reverse_hatch","cross_hatch"].includes(we)?we:void 0}function R(ne){let we=J(ne,"pts");return _e(we,"xy").map(xe=>he([xe],"xy")).filter(Boolean)}let $=4*1024*1024,V=16e6,O=8*1024*1024,C=16e6,j=Uint32Array.from({length:256},(ne,we)=>{for(let xe=0;xe<8;xe++)we=we&1?3988292384^we>>>1:we>>>1;return we>>>0});function B(ne,we){let xe=J(ne,"data")?.slice(1).map(G),ke=0;if(!xe?.length)throw Error("No inline bitmap data was saved in the schematic.");if(xe.some(et=>typeof et!="string"||(ke+=et.length)>Math.ceil($/3)*4))throw Error("Embedded bitmap exceeds its 4 MiB limit or has invalid base64 data.");let Me=xe.join("");if(Me.length%4||!/^[A-Za-z0-9+/]*={0,2}$/.test(Me))throw Error("Embedded image is not base64 bitmap data.");let Ce=atob(Me);if(Ce.length>$||btoa(Ce)!==Me)throw Error("Embedded bitmap data is oversized or not canonical base64.");let tt=Uint8Array.from(Ce,et=>et.charCodeAt(0)),Ze=new DataView(tt.buffer);if(Ce.startsWith("BM"))return K(Ze,Me,we);if(tt.length<45||[137,80,78,71,13,10,26,10].some((et,St)=>tt[St]!==et))throw Error("Embedded image is not a PNG or BMP.");let Ye=et=>Ze.getUint32(et),vt=et=>String.fromCharCode(...tt.subarray(et,et+4)),Rt=[Ce.slice(0,8)],Je=0,_t=0,Et=null,gt=!1,Ht=!1,lt=0;for(let et=8;et<tt.length;){if(++lt>4096||et+12>tt.length)throw Error("Embedded PNG chunk structure is invalid.");let St=Ye(et),At=vt(et+4),Wt=et+12+St;if(Wt>tt.length||!/^[A-Za-z]{4}$/.test(At))throw Error("Embedded PNG chunk is truncated or invalid.");let nr=4294967295;for(let pt=et+4;pt<Wt-4;pt++)nr=j[(nr^tt[pt])&255]^nr>>>8;if((nr^4294967295)>>>0!==Ye(Wt-4))throw Error("Embedded PNG checksum is invalid.");if(At==="IHDR"){if(et!==8||St!==13)throw Error("Embedded PNG has an invalid header.");Je=Ye(et+8),_t=Ye(et+12);let pt=tt[et+16],ft=tt[et+17],Bt={0:[1,2,4,8,16],2:[8,16],3:[1,2,4,8],4:[8,16],6:[8,16]};if(!Je||!_t||Je*_t>V||!Bt[ft]?.includes(pt)||tt[et+18]!==0||tt[et+19]!==0||tt[et+20]>1)throw Error("Embedded PNG exceeds 16 megapixels or uses an invalid header.")}else{if(et===8)throw Error("Embedded PNG header is missing.");if(At==="pHYs"){if(St!==9||Et!==null)throw Error("Embedded PNG physical resolution is invalid.");if(tt[et+16]===1)Et=Ye(et+8);else if(tt[et+16]!==0)throw Error("Embedded PNG resolution unit is invalid.")}else if(At==="IDAT")Ht=!0;else if(At==="IEND"){if(St||!Ht)throw Error("Embedded PNG end marker is invalid.");gt=!0}else{if(["acTL","fcTL","fdAT"].includes(At))throw Error("Animated PNGs are not supported in the bounded preview.");if(At[0]===At[0].toUpperCase()&&At!=="PLTE")throw Error("Embedded PNG has an unsupported critical chunk.")}}if(["iCCP","zTXt","iTXt"].includes(At)||Rt.push(Ce.slice(et,Wt)),gt)break;et=Wt}if(!gt)throw Error("Embedded PNG end marker is missing.");return{dataUrl:"data:image/png;base64,"+btoa(Rt.join("")),pixelWidth:Je,pixelHeight:_t,ppi:W(Et,we),bytes:tt.length}}function W(ne,we){let xe=300;if(ne!==null&&ne/100>1){let ke=Math.round(ne*.0254),Me=Math.floor(ne/100)>1?Math.round(Math.floor(ne/100)*2.54):ke;xe=we<=20230121?300:we<20260623?Me:ke}if(!Number.isFinite(xe)||xe<1||xe>1e6)throw Error("Embedded PNG resolution exceeds the preview limit.");return xe}function K(ne,we,xe){let ke=ne.byteLength;if(ke<54||ne.getUint32(2,!0)!==ke||ne.getUint32(14,!0)!==40)throw Error("Embedded BMP has an unsupported or invalid header.");let Me=ne.getUint32(10,!0),Ce=ne.getInt32(18,!0),tt=Math.abs(ne.getInt32(22,!0)),Ze=ne.getUint16(28,!0);if(Ce<1||tt<1||Ce*tt>V||ne.getUint16(26,!0)!==1||![24,32].includes(Ze)||ne.getUint32(30,!0)!==0)throw Error("Embedded BMP must use uncompressed 24-bit or 32-bit pixels within the 16 megapixel limit.");let Ye=Math.ceil(Ce*Ze/32)*4*tt;if(Me<54||Me+Ye!==ke)throw Error("Embedded BMP pixel data is truncated or invalid.");return{dataUrl:"data:image/bmp;base64,"+we,pixelWidth:Ce,pixelHeight:tt,ppi:W(ne.getInt32(38,!0),xe),bytes:ke}}function ge(ne,we=()=>{}){let xe=J(ne,"paper"),ke=G(xe?.[1])||"A4",Me=A[ke];if(ke==="User"){let Ye=G(xe?.[2]),vt=G(xe?.[3]);te(Ye)&&te(vt)&&Ye>20&&vt>20&&Ye<2e3&&vt<2e3&&(Me=[Ye,vt])}Me||(we(`Unsupported paper size ${ke}; showing A4 bounds.`),Me=A.A4);let[Ce,tt]=Me;xe?.some(Ye=>G(Ye)==="portrait")&&Ce>tt&&([Ce,tt]=[tt,Ce]);let Ze=J(ne,"title_block");return{width:Ce,height:tt,format:ke,titleBlock:{title:Q(Ze,"title")||"",date:Q(Ze,"date")||"",rev:Q(Ze,"rev")||"",company:Q(Ze,"company")||"",comments:Array.from({length:9},(Ye,vt)=>G(_e(Ze,"comment").find(Rt=>G(Rt[1])===vt+1)?.[2])||"")}}}function Ne(ne,we="",xe={}){if(!Array.isArray(ne)||ae(ne)!=="kicad_sch")throw new Error("Schematic renderer requires a parsed kicad_sch root.");let ke=[],Me=[],Ce=new Set,tt=0,Ze=0,Ye=0,vt=0,Rt=h?.inspect(ne);Me.push(...Rt?.warnings||[]);let Je=yt=>{Ce.has(yt)||(Ce.add(yt),Me.push(yt))};function _t(yt){if(ke.length>=X)throw new Error("Schematic has too many drawing primitives.");ke.push({...yt,path:we})}let Et=h?.textResolver(ne,{...xe,path:we},Je),gt=new Map;for(let yt of[..._e(ne,"symbol"),..._e(ne,"sheet")])be(yt)&&gt.set(be(yt),Et?.fields(yt));let Ht=(yt,jt={})=>Et?.resolve(yt,gt.get(jt.ownerUuid||jt.uuid)||{})??String(yt??""),lt=(yt,jt={})=>h?.textLinks?.(Ht(yt,jt),jt.href===void 0?void 0:Ht(jt.href,jt))||[],et=ge(ne,Je);function St(yt,jt,Jt,sr,Xt={}){yt&&jt&&_t({type:"line",points:[yt,jt],color:Jt,width:sr,...Xt})}function At(yt,jt,Jt,sr,Xt,qt={}){if(yt&&jt!==void 0&&jt!==null&&String(jt)){let gr=Y(Ht(jt,qt)),ar=lt(jt,qt);if(_t({type:"text",x:yt.x,y:yt.y,text:gr.text,...gr.bars.length||String(jt)!==gr.text?{rawText:String(jt)}:{},size:Jt,angle:te(sr)?sr:0,color:Xt,...qt,...ar.length?{links:ar}:{}}),gr.bars.length){let Ar=qt.fontWidth||Jt,mr=qt.fontHeight||Jt,Br=gr.text.split(`
`),Dr=(sr||0)*Math.PI/180,hi=(Vr,Yr)=>({x:De(yt.x+Vr*Math.cos(Dr)-Yr*Math.sin(Dr)),y:De(yt.y+Vr*Math.sin(Dr)+Yr*Math.cos(Dr))}),Si=0;for(let Vr=0;Vr<Br.length;Vr++){let Yr=Br[Vr],Cr=ee(Yr,Ar),Or=qt.align==="left"?0:qt.align==="right"?-Cr:-Cr/2,Ur=(Vr-(Br.length-1)/2)*mr*(qt.lineSpacing||1.5)+(qt.baseline==="top"?mr/2:qt.baseline==="bottom"?-mr/2:0)-mr*1.0181;for(let ni of gr.bars){let fi=Math.max(ni.start-Si,0),Mi=Math.min(ni.end-Si,Yr.length);if(Mi<=fi)continue;let Rr=Or+ee(Yr.slice(0,fi),Ar)+Ar*.02,br=Or+ee(Yr.slice(0,Mi),Ar)-Ar*.18;St(hi(Rr,Ur),hi(br,Ur),Xt,qt.textThickness||.1524,{...qt,kind:"text-overbar",...["label","global_label","hierarchical_label","sheet-pin"].includes(qt.kind)?{electricalKind:qt.kind}:{}})}Si+=Yr.length+1}}}}function Wt(yt,jt,Jt,sr,Xt={},qt){!yt||!jt||_t({type:"polygon",points:[yt,{x:jt.x,y:yt.y},jt,{x:yt.x,y:jt.y}],color:Jt,width:sr,...qt?{fill:qt}:{},...Xt})}if(T)for(let yt of xe.worksheet?xe.worksheet(et,we,xe,Ht,Je):T.build(et,we,xe))_t(yt);else Je("Default worksheet module is unavailable.");!xe.worksheet&&et.titleBlock.comments.slice(4).some(Boolean)&&Je("The KiCad default drawing sheet displays only comments 1\u20134.");function nr(yt,jt,Jt,sr=S.symbol){let Xt=ae(yt),qt=Ee(yt,.15),gr=re(yt);if(Jt={...Jt,...N(yt)},Xt==="bezier"){let ar=_e(J(yt,"pts"),"xy").map(Ar=>({x:G(Ar[1]),y:G(Ar[2])}));try{if(ar.some(mr=>!te(mr.x)||!te(mr.y)))throw Error("Invalid Bezier control.");let Ar=p.cubicBezierPoints(ar.map(jt));if(tt+Ar.length>15e4)throw Error("Bezier point budget reached.");tt+=Ar.length,_t({type:"polyline",points:Ar,color:sr,width:qt,...gr?{fill:gr}:{},...Jt})}catch{Je("Invalid or over-budget bezier was skipped.")}}else if(Xt==="polyline"||Xt==="wire"||Xt==="bus"){let ar=R(yt).map(jt);ar.length>1?_t({type:"polyline",points:ar,color:sr,width:qt,...gr?{fill:gr}:{},...Jt}):Je(`${Xt} without two points was skipped.`)}else if(Xt==="rectangle"){let ar=he(yt,"start"),Ar=he(yt,"end");if(!ar||!Ar){Je("Rectangle without start/end was skipped.");return}let mr=[ar,{x:Ar.x,y:ar.y},Ar,{x:ar.x,y:Ar.y}].map(jt);_t({type:"polygon",points:mr,color:sr,width:qt,...gr?{fill:gr}:{},...Jt})}else if(Xt==="circle"){let ar=he(yt,"center"),Ar=Q(yt,"radius");if(!ar||!te(Ar)||Ar<=0){Je("Circle without center/radius was skipped.");return}let mr=jt(ar);_t({type:"circle",x:mr.x,y:mr.y,r:Ar,color:sr,width:qt,...gr?{fill:gr}:{},...Jt})}else if(Xt==="arc"){let ar=he(yt,"start"),Ar=he(yt,"mid"),mr=he(yt,"end");if(!ar||!Ar||!mr){Je("Legacy or incomplete arc without start/mid/end was skipped.");return}_t({type:"arc",start:jt(ar),mid:jt(Ar),end:jt(mr),color:sr,width:qt,...gr?{fill:gr}:{},...Jt})}else if(Xt==="text_box"||Xt==="table_cell"){if($e(yt))return;let ar=he(yt,"at")||he(yt,"start"),Ar=he(yt,"size"),Br=he(yt,"end")||(ar&&Ar?{x:ar.x+Ar.x,y:ar.y+Ar.y}:null);if(!ar||!Br||ar.x===Br.x||ar.y===Br.y){Je("Text box without valid position/size was skipped.");return}let Dr={...Jt};for(let Fi of["color","sourceColor","lineStyle","fillColor"])delete Dr[Fi];let hi=Math.min(ar.x,Br.x),Si=Math.max(ar.x,Br.x),Vr=Math.min(ar.y,Br.y),Yr=Math.max(ar.y,Br.y),Cr=Xe(yt),Or=ve(yt),Ur=Q(J(yt,"stroke"),"width"),ni=!(te(Ur)&&Ur<0);_t({type:"polygon",points:[{x:hi,y:Vr},{x:Si,y:Vr},{x:Si,y:Yr},{x:hi,y:Yr}].map(jt),color:sr,width:qt,stroke:ni,...gr?{fill:gr}:{},...Jt,...Or.href!==void 0?{links:lt(G(yt[1]),{...Jt,href:Or.href})}:{}});let fi=J(yt,"margins"),Mi=Cr*.75+(ni?qt/2:0),Rr=fi?.slice(1).map(G);if(Rr&&(Rr.length!==4||Rr.some(Fi=>!te(Fi)||Fi<0))){Je("Text box with invalid saved margins has no rendered text.");return}let[br,wi,an,Rn]=Rr||[Mi,Mi,Mi,Mi],vi={left:hi+br,top:Vr+wi,right:Si-an,bottom:Yr-Rn};if(vi.right<=vi.left||vi.bottom<=vi.top){Je("Text box margins leave no text area.");return}let Wr=((G(J(yt,"at")?.[3])||0)%360+360)%360;if(Wr!==0&&Wr!==90){Je("Text box with unsupported non-horizontal/non-vertical text angle has no rendered text.");return}let ei=Wr===90,Ri=ei?vi.bottom-vi.top:vi.right-vi.left,oi=ei?vi.right-vi.left:vi.bottom-vi.top,Pn=Ht(G(yt[1]),Jt),ps=[];if(Pn.length>65536){Je("Text box exceeds its 65536-character preview limit; text was skipped.");return}for(let Fi of Pn.split(/\r\n|\r|\n/)){let Xn="",Ji=0;for(let Sa of Fi.match(/\S+\s*|\s+/g)||[]){let Eh=ee(Sa,Or.fontWidth||Cr);Xn&&Ji+Eh>Ri&&(ps.push(Xn.trimEnd()),Xn="",Ji=0);for(let Ma of Sa){let Do=ee(Ma,Or.fontWidth||Cr)-(Or.fontWidth||Cr)*.16;Xn&&Ji+Do>Ri&&(ps.push(Xn.trimEnd()),Xn="",Ji=0),Xn+=Ma,Ji+=Do}}ps.push(Xn.trimEnd())}let Qn=Cr*Or.lineSpacing,As=Cr+Math.max(0,ps.length-1)*Qn,Pi=Or.baseline==="top"?0:Or.baseline==="bottom"?oi-As:(oi-As)/2,Wn=Or.align==="left"?0:Or.align==="right"?Ri:Ri/2,gd=(Fi,Xn)=>ei?{x:vi.left+Xn,y:vi.bottom-Fi}:{x:vi.left+Fi,y:vi.top+Xn};for(let Fi=0;Fi<ps.length;Fi++){let Xn=gd(Wn,Pi+Cr/2+Fi*Qn),Ji=jt(Xn),Sa=jt(gd(Wn+1,Pi+Cr/2+Fi*Qn));At(Ji,ps[Fi],Cr,Math.atan2(Sa.y-Ji.y,Sa.x-Ji.x)*180/Math.PI,sr,{...Dr,...Or,baseline:"middle"})}Je("Text-box wrapping uses preview font metrics; exact KiCad font layout may differ.")}else if(Xt==="text"){if($e(yt))return;let ar=he(yt,"at");if(!ar){Je("Text without position was skipped.");return}let Ar=!!G(J(yt,"at")?.[3]),mr=jt(ar),Br=jt({x:ar.x+1,y:ar.y}),Dr=jt({x:ar.x,y:ar.y+1}),hi=Ar?Dr:Br,Si=hi.x-mr.x,Vr=hi.y-mr.y,Yr=Math.abs(Vr)>Math.abs(Si),Cr=ve(yt);(Yr?Vr>0:Si<0)&&Cr.align!=="center"&&(Cr.align=Cr.align==="left"?"right":"left");let Or=Br.x-mr.x,Ur=Br.y-mr.y,ni=Dr.x-mr.x,fi=Dr.y-mr.y,Mi=Or*fi-Ur*ni>0,Rr=Or>.5&&fi>.5;Mi&&Ar!==Rr&&Cr.baseline!=="middle"&&(Cr.baseline=Cr.baseline==="top"?"bottom":"top"),At(mr,G(yt[1]),Xe(yt),Yr?-90:0,sr,{...Jt,...Cr})}else Je(`Unsupported graphic ${Xt} was skipped.`)}function pt(yt,jt){let Jt=Q(yt,"column_count"),sr=J(yt,"column_widths")?.slice(1).map(G),Xt=J(yt,"row_heights")?.slice(1).map(G),qt=_e(J(yt,"cells"),"table_cell");if(!Number.isInteger(Jt)||Jt<1||Jt>100||!sr||sr.length!==Jt||!Xt?.length||Xt.length>100||Jt*Xt.length>1e3||qt.length!==Jt*Xt.length||[...sr,...Xt].some(Vr=>!te(Vr)||Vr<=0)){Je("Schematic table has invalid dimensions or exceeds the 1000-cell preview limit; it was skipped.");return}let gr=[],ar=new Set,Ar=0;for(let Vr=0;Vr<qt.length;Vr++){let Yr=qt[Vr],Cr=he(Yr,"at"),Or=he(Yr,"size"),Ur=J(Yr,"span")?.slice(1).map(G)||[1,1],ni=G(J(Yr,"at")?.[3])||0,fi=Math.floor(Vr/Jt),Mi=Vr%Jt;if(ni!==0){Je("Rotated schematic tables are not rendered; open KiCad for their native layout.");return}if(Ur.length!==2||Ur.some(Rr=>!Number.isInteger(Rr)||Rr<0)||fi+Ur[1]>Xt.length||Mi+Ur[0]>Jt||!Cr||!Or||!te(Cr.x+Or.x)||!te(Cr.y+Or.y)||(Ar+=String(G(Yr[1])??"").length)>262144){Je("Schematic table has invalid cell geometry/spans or exceeds its text budget; it was skipped.");return}if(Ur[0]===0||Ur[1]===0){if(!ar.has(Vr)){Je("Schematic table contains an unbound merged cell; it was skipped.");return}gr.push(null);continue}if(Or.x<=0||Or.y<=0){Je("Schematic table has invalid cell bounds; it was skipped.");return}for(let Rr=fi;Rr<fi+Ur[1];Rr++)for(let br=Mi;br<Mi+Ur[0];br++){let wi=Rr*Jt+br;if(ar.has(wi)){Je("Schematic table has overlapping spans; it was skipped.");return}ar.add(wi)}gr.push({at:Cr,end:{x:Cr.x+Or.x,y:Cr.y+Or.y},span:Ur,row:fi,col:Mi,cell:Yr})}let mr=gr.filter(Boolean),Br=J(yt,"border"),Dr=J(yt,"separators"),hi=Vr=>Vr;for(let Vr of mr)nr([...Vr.cell.filter(Yr=>ae(Yr)!=="stroke"),["stroke",["width",-1]]],hi,{...jt,uuid:be(Vr.cell)||jt.uuid,ownerUuid:jt.uuid,kind:"table-cell"},S.text);let Si=(Vr,Yr,Cr)=>{(Q(J(Cr,"stroke"),"width")??0)<0||St(Vr,Yr,S.text,Ee(Cr),{...jt,kind:"table-border",...N(Cr)})};for(let{at:Vr,end:Yr,span:Cr,row:Or,col:Ur}of mr){let ni=Or===0&&Ke(Br,"header")?Br:Ke(Dr,"cols")?Dr:null,fi=Or===0&&Ke(Br,"header")?Br:Ke(Dr,"rows")?Dr:null;ni&&Ur+Cr[0]<Jt&&Si({x:Yr.x,y:Vr.y},Yr,ni),fi&&Or+Cr[1]<Xt.length&&Si(Yr,{x:Vr.x,y:Yr.y},fi)}if(Ke(Br,"external")){let Vr=Math.min(...mr.map(ni=>ni.at.x)),Yr=Math.min(...mr.map(ni=>ni.at.y)),Cr=Math.max(...mr.map(ni=>ni.end.x)),Or=Math.max(...mr.map(ni=>ni.end.y)),Ur=[{x:Vr,y:Yr},{x:Cr,y:Yr},{x:Cr,y:Or},{x:Vr,y:Or}];for(let ni=0;ni<4;ni++)Si(Ur[ni],Ur[(ni+1)%4],Br)}}let ft=J(ne,"lib_symbols"),Bt=new Map;for(let yt of _e(ft,"symbol")){let jt=G(yt[1]);typeof jt=="string"&&Bt.set(jt,yt)}function Yt(yt,jt,Jt,sr=new Set){if(sr.has(yt)||sr.size>8)return Je(`Symbol inheritance cycle at ${yt}.`),[];let Xt=Bt.get(yt);if(!Xt)return Je(`Embedded library symbol ${yt} is unavailable.`),[];sr.add(yt);let qt=[],gr=Q(Xt,"extends");if(gr){let ar=yt.includes(":")?yt.slice(0,yt.indexOf(":")+1):"",Ar=Bt.has(gr)?gr:`${ar}${gr}`;qt.push(...Yt(Ar,jt,Jt,sr))}for(let ar of _e(Xt,"symbol")){let Ar=G(ar[1]),mr=typeof Ar=="string"&&/_(\d+)_(\d+)$/.exec(Ar);if(!mr){Je(`Unrecognized library unit ${Ar} in ${yt} was skipped.`);continue}let Br=Number(mr[1]),Dr=Number(mr[2]);(Br===0||Br===jt)&&(Dr===0||Dr===Jt)&&qt.push(ar)}return Xt.some(ar=>Array.isArray(ar)&&["pin","polyline","rectangle","circle","arc","bezier","text","text_box"].includes(ae(ar)))&&qt.push(Xt),qt}function kr(yt,jt=new Set){if(jt.has(yt)||jt.size>8)return 1;jt.add(yt);let Jt=Bt.get(yt);if(!Jt)return 1;let sr=1,Xt=Q(Jt,"extends");if(Xt){let qt=yt.includes(":")?yt.slice(0,yt.indexOf(":")+1):"";sr=kr(Bt.has(Xt)?Xt:qt+Xt,jt)}for(let qt of _e(Jt,"symbol")){let gr=/_(\d+)_(\d+)$/.exec(G(qt[1])||"");gr&&(sr=Math.max(sr,Number(gr[1])))}return sr}function Gr(yt,jt,Jt,sr){let Xt=he(yt,"at"),qt=Q(yt,"length")??0;if(!Xt||!te(qt)||qt<0){Je("Pin without valid position/length was skipped.");return}let gr=G(J(yt,"at")?.[3])??0;if(!te(gr)){Je("Pin with invalid angle was skipped.");return}let ar=gr*Math.PI/180,Ar=Math.cos(ar),mr=Math.sin(ar),Br={x:Xt.x+qt*Ar,y:Xt.y+qt*mr},Dr=J(yt,"name"),hi=J(yt,"number"),Si=G(yt[2]),Vr={...Jt,ownerUuid:Jt.uuid,kind:"pin",pinNumber:String(G(hi?.[1])??""),pinName:String(G(Dr?.[1])??""),pinType:G(yt[1]),pinStyle:Si,connectPoint:jt(Xt)};if(Ke(yt,"hide")||$e(yt)){St(jt(Xt),jt(Xt),S.pin,0,{...Vr,hidden:!0,stroke:!1,pick:!1});return}let Cr=.635,Or=1.27,Ur=(ei,Ri)=>({x:Br.x+ei*Ar-Ri*mr,y:Br.y+ei*mr+Ri*Ar}),ni={...Vr,kind:"pin-marker"},fi=ei=>_t({type:"polyline",points:ei.map(jt),color:S.pin,width:.1524,...ni}),Mi=Br;if(["inverted","inverted_clock"].includes(Si)){let ei=jt(Ur(-Cr,0));_t({type:"circle",x:ei.x,y:ei.y,r:Cr,color:S.pin,width:.1524,...ni}),Mi=Ur(-Or,0)}["clock","inverted_clock","clock_low"].includes(Si)&&fi([Ur(0,-Cr),Ur(Or,0),Ur(0,Cr)]),["input_low","clock_low"].includes(Si)&&fi([Ur(-Or,0),Ur(-Or,Or),Ur(0,0)]),Si==="output_low"&&fi([Ur(0,Or),Ur(-Or,0)]),Si==="edge_clock_high"&&(fi([Ur(0,-Cr),Ur(-Or,0),Ur(0,Cr)]),Mi=Ur(-Or,0)),Si==="non_logic"&&(fi([Ur(Cr,Cr),Ur(-Cr,-Cr)]),fi([Ur(Cr,-Cr),Ur(-Cr,Cr)])),St(jt(Xt),jt(Mi),S.pin,.1524,Vr),["line","inverted","clock","inverted_clock","input_low","clock_low","output_low","edge_clock_high","non_logic"].includes(Si)||Je("Pin graphic style "+Si+" is simplified to a line.");let Rr=jt(Xt),br=jt(Br),wi=Math.abs(br.x-Rr.x)>=Math.abs(br.y-Rr.y),an=wi?0:-90,Rn=wi?br.x>=Rr.x?"left":"right":br.y<=Rr.y?"left":"right",vi=Ke(J(sr,"pin_names"),"hide"),Wr=Ke(J(sr,"pin_numbers"),"hide");if(!vi&&Dr&&!$e(Dr)&&G(Dr[1])&&G(Dr[1])!=="~"){let ei=Q(J(sr,"pin_names"),"offset")??.508,Ri=Xe(Dr),oi,Pn;te(ei)&&ei>0?(oi=jt(Ur(ei,0)),Pn=Rn):(oi={x:(Rr.x+br.x)/2-(wi?0:Ri/2+.3556),y:(Rr.y+br.y)/2-(wi?Ri/2+.3556:0)},Pn="center"),At(oi,G(Dr[1]),Ri,an,"#008484",{...Vr,kind:"pin-name",...ve(Dr),align:Pn})}if(!Wr&&hi&&!$e(hi)&&G(hi[1])&&G(hi[1])!=="~"){let ei=Xe(hi),Ri=ei/2+.3556,oi=Q(J(sr,"pin_names"),"offset")??.508,Pn=!vi&&G(Dr?.[1])!=="~"&&oi===0?-1:1,ps={x:(Rr.x+br.x)/2-(wi?0:Ri*Pn),y:(Rr.y+br.y)/2-(wi?Ri*Pn:0)};At(ps,G(hi[1]),ei,an,"#a90000",{...Vr,kind:"pin-number",...ve(hi),align:"center"})}}function Qr(yt){let jt=he(yt,"at");if(!jt){Je("Placed symbol without position was skipped.");return}let Jt=Q(yt,"lib_name")??Q(yt,"lib_id")??G(yt[1]);if(typeof Jt!="string"){Je("Placed symbol without library ID was skipped.");return}let sr=Q(yt,"unit")??1,Xt=Q(yt,"convert")??1,qt=G(J(yt,"at")?.[3])??0;[0,90,180,270].includes((qt%360+360)%360)||Je(`Symbol ${Jt} has non-orthogonal rotation ${qt}.`);let gr=G(J(yt,"mirror")?.[1])||"";gr&&!["x","y"].includes(gr)&&Je(`Symbol ${Jt} has unsupported mirror ${gr}.`);let ar=qe(jt,te(qt)?qt:0,gr,!0),Ar=be(yt),mr=_e(yt,"property").find(br=>G(br[1])==="Reference"),Br=G(mr?.[2])||"",Dr={uuid:Ar,reference:Br,kind:"symbol"},hi=Bt.get(Jt);J(hi,"power")&&(Dr.powerSymbol=!0);let Si=new Map(_e(yt,"pin").map(br=>[String(G(br[1])),be(br)])),Vr=Yt(Jt,te(sr)?sr:1,te(Xt)?Xt:1);Vr.length||Je(`No drawable unit ${sr} style ${Xt} for ${Jt}.`);let Yr=ke.length,Cr=new Map;for(let br of Vr)for(let wi of br){if(!Array.isArray(wi))continue;let an=ae(wi);if(an==="pin"){let Rn=ke.length;Gr(wi,ar,{...Dr,savedPinUuid:Si.get(String(G(J(wi,"number")?.[1])))},hi||br);for(let vi=Rn;vi<ke.length;vi++){let Wr=ke[vi];if(!["pin-name","pin-number"].includes(Wr.kind))continue;let ei=JSON.stringify([Wr.kind,Wr.x,Wr.y,Wr.angle,Wr.size,Wr.align,Wr.baseline,Wr.color,Wr.fontWidth,Wr.fontHeight,Wr.fontFace,Wr.bold,Wr.italic,Wr.textThickness,Wr.lineSpacing,Wr.href,Wr.connectPoint,Wr.kind==="pin-name"?Wr.text:null]),Ri=Cr.get(ei);if(!Ri){Cr.set(ei,Wr);continue}let oi=Ri.pinNumbers||[Ri.pinNumber];oi.includes(Wr.pinNumber)||oi.push(Wr.pinNumber),Ri.pinNumbers=oi,Wr.kind==="pin-number"&&(Ri.text=oi.join(", ")),ke.splice(vi--,1)}}else["polyline","rectangle","circle","arc","bezier","text","text_box"].includes(an)?nr(wi,ar,Dr):an==="image"&&Je(`Symbol graphic ${an} is not rendered.`)}let Or=1/0,Ur=1/0,ni=-1/0,fi=-1/0,Mi=br=>{!br||!te(br.x)||!te(br.y)||(Or=Math.min(Or,br.x),ni=Math.max(ni,br.x),Ur=Math.min(Ur,br.y),fi=Math.max(fi,br.y))};for(let br of ke.slice(Yr))if(br.uuid===Ar&&!br.hidden)if(Array.isArray(br.points))for(let wi of br.points)Mi(wi);else br.type==="circle"?(Mi({x:br.x-br.r,y:br.y-br.r}),Mi({x:br.x+br.r,y:br.y+br.r})):br.type==="arc"&&(Mi(br.start),Mi(br.mid),Mi(br.end));te(Or)||(Or=jt.x-1.5,ni=jt.x+1.5,Ur=jt.y-1.5,fi=jt.y+1.5);let Rr=.4;_t({type:"polygon",points:[{x:Or-Rr,y:Ur-Rr},{x:ni+Rr,y:Ur-Rr},{x:ni+Rr,y:fi+Rr},{x:Or-Rr,y:fi+Rr}],pick:!0,stroke:!1,fill:!1,...Dr});for(let br of _e(yt,"property")){if($e(br))continue;let wi=he(br,"at"),an=G(br[2]);if(!wi){Je(`Visible property ${G(br[1])} has no position.`);continue}let Rn=G(J(br,"at")?.[3])||0,vi=qt+Rn,Wr=(vi%180+180)%180,ei=qe({x:0,y:0},vi,gr),Ri=ei({x:1,y:0}),oi=ei({x:0,y:1}),Pn=Wr*Math.PI/180,ps=Math.cos(Pn),Qn=Math.sin(Pn),As=ve(br);if(Ri.x*ps-Ri.y*Qn<0&&(As.align={left:"right",right:"left"}[As.align]||As.align),oi.x*Qn+oi.y*ps<0&&(As.baseline={top:"bottom",bottom:"top"}[As.baseline]||As.baseline),G(br[1])==="Reference"&&kr(Jt)>1&&Number.isInteger(sr)&&sr>0){let Pi="",Wn=sr;for(;Wn>0;)Wn--,Pi=String.fromCharCode(65+Wn%26)+Pi,Wn=Math.floor(Wn/26);an+=Pi}At(wi,an,Xe(br),-Wr,S.symbol,{...Dr,kind:"property",property:G(br[1]),...As})}}function Zr(yt,jt,Jt=ae(yt)){if($e(yt))return;let sr=he(yt,"at");if(!sr){Je(`${Jt} without position was skipped.`);return}let Xt=Ht(G(yt[1]),jt),qt=Xe(yt),gr=G(J(yt,"at")?.[3])||0,ar=Jt==="sheet-pin"?((gr+180)%360+360)%360:gr,Ar=Q(yt,"shape")||(Jt==="sheet-pin"?G(yt[2]):"input"),mr=ve(yt),Br=Jt==="global_label"?S.symbol:"#725600",Dr={...jt,kind:Jt,connectPoint:sr},hi=qe(sr,ar);["input","output","bidirectional","tri_state","passive"].includes(Ar)||Je(`Unsupported ${Jt} shape ${Ar}; using passive outline.`);let Vr=Jt==="sheet-pin"&&{input:"output",output:"input"}[Ar]||Ar,Yr=["input","bidirectional","tri_state"].includes(Vr),Cr=["output","bidirectional","tri_state"].includes(Vr),Or,Ur,ni=-ar;if(Jt==="hierarchical_label"||Jt==="sheet-pin"){let Rr=qt/2;Yr&&Cr?Or=[{x:0,y:0},{x:Rr,y:-Rr},{x:qt,y:0},{x:Rr,y:Rr}]:Yr?Or=[{x:0,y:0},{x:Rr,y:Rr},{x:qt,y:Rr},{x:qt,y:-Rr},{x:Rr,y:-Rr}]:Cr?Or=[{x:qt,y:0},{x:Rr,y:-Rr},{x:0,y:-Rr},{x:0,y:Rr},{x:Rr,y:Rr}]:Or=[{x:0,y:-Rr},{x:qt,y:-Rr},{x:qt,y:Rr},{x:0,y:Rr}],Ur=hi({x:(mr.fontWidth||qt)+.1905,y:0})}else{let Rr=qt*.875,br=qt,wi=qt*.375,an=Math.max(qt,ee(Xt||"",mr.fontWidth||qt)),Rn=an+qt*.8905+(Yr?Rr:0)+(Cr?Rr:0);Or=[{x:0,y:0},{x:Yr?Rr:0,y:br},{x:Rn-(Cr?Rr:0),y:br},{x:Rn,y:0},{x:Rn-(Cr?Rr:0),y:-br},{x:Yr?Rr:0,y:-br}],Ur=hi({x:wi+(Yr?qt*.75:0),y:0}),mr.textWidth=an}_t({type:"polygon",points:Or.map(hi),color:Br,width:.1524,...Dr});let fi=(ar%360+360)%360,Mi="left";(fi===180||fi===270)&&(ni+=180,Mi="right"),At(Ur,Xt,qt,ni,Br,{...Dr,...mr,align:Mi,baseline:"middle"})}function ii(yt){let jt=he(yt,"at"),Jt=he(yt,"size"),sr=be(yt);if(!jt||!Jt||Jt.x<=0||Jt.y<=0){Je("Sheet without valid position/size was skipped.");return}let Xt={uuid:sr,kind:"sheet"};Wt(jt,{x:jt.x+Jt.x,y:jt.y+Jt.y},S.symbol,Ee(yt),{...Xt,...N(yt)},re(yt)||(me(J(yt,"fill"))&&!me(J(yt,"fill")).endsWith(",0)")?"color":void 0));for(let qt of _e(yt,"property")){if($e(qt))continue;let gr=he(qt,"at");At(gr,G(qt[2]),Xe(qt),-(G(J(qt,"at")?.[3])||0),S.symbol,{...Xt,kind:"sheet-property",property:G(qt[1]),...ve(qt)})}for(let qt of _e(yt,"pin"))Zr(qt,{...Xt,pinUuid:be(qt)},"sheet-pin")}function ur(yt,jt){let Jt=he(yt,"at"),sr=G(J(yt,"at")?.[3]),Xt=Q(yt,"length")??2.54,qt=Q(yt,"shape")??"round";if(!Jt||![0,90,180,270].includes(sr)||!te(Xt)||Xt<0||!["dot","round","diamond","rectangle"].includes(qt)){Je("Directive label with invalid position, orientation, length or shape was skipped.");return}let gr=qe(Jt,sr%180===0?180:270),ar="#484848",Ar=.1524,mr=qt==="dot"?.3556:qt==="rectangle"?.4064:.508,Br={...jt,connectPoint:Jt};if(St(Jt,gr({x:0,y:Xt-mr}),ar,Ar,Br),qt==="round"||qt==="dot"){let Dr=gr({x:0,y:Xt});_t({type:"circle",...Dr,r:mr,color:ar,width:Ar,...qt==="dot"?{fill:"outline"}:{},...Br})}else{let Dr=qt==="diamond"?[{x:0,y:Xt-mr},{x:-2*mr,y:Xt},{x:0,y:Xt+mr},{x:2*mr,y:Xt}]:[{x:-2*mr,y:Xt-mr},{x:-2*mr,y:Xt+mr},{x:2*mr,y:Xt+mr},{x:2*mr,y:Xt-mr}];_t({type:"polygon",points:Dr.map(gr),color:ar,width:Ar,...Br})}for(let Dr of _e(yt,"property"))$e(Dr)||At(he(Dr,"at"),G(Dr[2]),Xe(Dr),-(G(J(Dr,"at")?.[3])||0),"#840084",{...Br,...ve(Dr),property:G(Dr[1])})}let Gi=yt=>yt;for(let yt of ne){if(!Array.isArray(yt))continue;let jt=ae(yt),Jt={uuid:be(yt),kind:jt};if(jt==="symbol")Qr(yt);else if(jt==="sheet")ii(yt);else if(jt==="table")pt(yt,Jt);else if(jt==="directive_label"||jt==="netclass_flag")ur(yt,Jt);else if(jt==="rule_area"){let sr=w?.ruleAreaPoints(yt);if(!sr){Je("Rule area without a valid polygon was skipped.");continue}let Xt=J(yt,"polyline"),qt=N(Xt),gr=re(Xt),ar=Q(J(Xt,"stroke"),"type");_t({type:"polygon",points:sr,color:"#ff0000",width:Ee(Xt,.1524),...ar!=="solid"?{lineStyle:"dash"}:{},...gr?{fill:gr}:{},...Jt,...qt,uuid:Jt.uuid??be(Xt)})}else if(jt==="wire"||jt==="bus")nr(yt,Gi,Jt,jt==="bus"?S.bus:S.wire);else if(["polyline","rectangle","circle","arc","bezier","text_box"].includes(jt))nr(yt,Gi,Jt,S.text);else if(jt==="junction"){let sr=he(yt,"at"),Xt=Q(yt,"diameter");sr&&_t({type:"circle",x:sr.x,y:sr.y,r:te(Xt)&&Xt>0?Xt/2:.5,color:S.wire,width:.15,fill:"outline",...Jt,...me(yt)&&me(yt)!=="rgba(0,0,0,0)"?{color:me(yt),sourceColor:me(yt)}:{}})}else if(jt==="no_connect"){let sr=he(yt,"at");sr&&(St({x:sr.x-.7,y:sr.y-.7},{x:sr.x+.7,y:sr.y+.7},S.pin,.15,Jt),St({x:sr.x-.7,y:sr.y+.7},{x:sr.x+.7,y:sr.y-.7},S.pin,.15,Jt))}else if(["label","global_label","hierarchical_label","text"].includes(jt)){if($e(yt))continue;let sr=he(yt,"at");jt==="global_label"||jt==="hierarchical_label"?Zr(yt,Jt):At(sr,G(yt[1]),Xe(yt),jt==="label"?-(((G(J(yt,"at")?.[3])||0)%180+180)%180):-(G(J(yt,"at")?.[3])||0),jt==="text"?S.text:S.label,{...Jt,...ve(yt)})}else if(jt==="bus_entry"){let sr=he(yt,"at"),Xt=he(yt,"size");sr&&Xt&&St(sr,{x:sr.x+Xt.x,y:sr.y+Xt.y},S.bus,.3,Jt)}else if(jt==="image")try{let sr=he(yt,"at"),Xt=Q(yt,"scale")??1,qt=Q(yt,"rotate")??0,gr=Q(yt,"opacity")??1;if(!sr||!te(Xt)||Xt<=0||!te(qt)||!te(gr)||gr<0||gr>1)throw Error("Embedded bitmap has invalid position, scale, rotation or opacity.");if(vt>=16)throw Error("Schematic exceeds its 16-image preview limit.");let ar=B(yt,Number(Q(ne,"version"))||20230121),Ar=ar.pixelWidth*ar.pixelHeight;if(Ze+ar.bytes>O||Ye+Ar>C)throw Error("Schematic exceeds its total 8 MiB / 16 megapixel image preview budget.");let mr=ar.pixelWidth*25.4/ar.ppi*Xt,Br=ar.pixelHeight*25.4/ar.ppi*Xt;if(!te(mr)||!te(Br)||mr>1e5||Br>1e5)throw Error("Embedded bitmap physical size exceeds the preview limit.");let Dr=qe(sr,qt);_t({type:"image",dataUrl:ar.dataUrl,pixelWidth:ar.pixelWidth,pixelHeight:ar.pixelHeight,points:[{x:-mr/2,y:-Br/2},{x:mr/2,y:-Br/2},{x:mr/2,y:Br/2},{x:-mr/2,y:Br/2}].map(Dr),opacity:gr,...Jt}),Ze+=ar.bytes,Ye+=Ar,vt++}catch(sr){Je("Schematic image was not rendered: "+sr.message)}}return{primitives:ke,page:et,warnings:Me,compatibility:Rt,embeddedFonts:h?.embeddedFonts?.(ne)}}m.KiCadSchematicRenderer={build:Ne,pageSettings:ge},typeof Hs=="object"&&Hs.exports&&(Hs.exports=m.KiCadSchematicRenderer)})(typeof globalThis=="object"?globalThis:MM)});function fh(m="wayricad"){if(typeof m!="string"||!Object.hasOwn(TM,m))throw new TypeError("Choose wayricad, viridis, inferno or grayscale palette.");return TM[m]}function mh(m){let h=1/0,p=-1/0;for(let w of m)Number.isFinite(w)&&(h=Math.min(h,w),p=Math.max(p,w));if(!Number.isFinite(h))return null;if(h===p){let w=.5*Math.max(1,Math.abs(h));return[Math.max(-Number.MAX_VALUE,h-w),Math.min(Number.MAX_VALUE,p+w)]}return[h,p]}function Ov(m,h){let p=h[1]-h[0],w=Number.isFinite(p)?(m-h[0])/p:(m/2-h[0]/2)/(h[1]/2-h[0]/2);return Math.max(0,Math.min(1,w))}function km(m,h,p=CM){let w=Ov(m,h)*3,S=Math.min(2,Math.floor(w)),A=w-S;return p[S].map((T,H)=>Math.round(T+(p[S+1][H]-T)*A))}var CM,TM,Om=Ui(()=>{CM=Object.freeze([[26,64,115],[20,136,156],[107,196,151],[255,225,112]].map(m=>Object.freeze(m))),TM=Object.freeze({wayricad:CM,viridis:Object.freeze([[68,1,84],[49,104,142],[53,183,121],[253,231,37]].map(m=>Object.freeze(m))),inferno:Object.freeze([[0,0,4],[120,28,109],[237,105,37],[252,255,164]].map(m=>Object.freeze(m))),grayscale:Object.freeze([[0,0,0],[85,85,85],[170,170,170],[255,255,255]].map(m=>Object.freeze(m)))})});var PM={};Ol(PM,{analysisCellAt:()=>Dv,analysisColor:()=>Um,analysisSourceHash:()=>Dm,formatAnalysisValue:()=>ad,parseAnalysis:()=>RM});function RM(m){if(typeof m=="string"){if(m.length>8*1024*1024||new TextEncoder().encode(m).length>8*1024*1024)throw new RangeError("Analysis JSON exceeds 8 MiB.");m=JSON.parse(m)}if(!m||m.schema!=="kicad-webview.analysis/v1"||m.coordinateSystem!=="kicad-mm")throw new TypeError("Expected analysis/v1 in saved KiCad millimetre coordinates.");if(!/^[a-f0-9]{64}$/.test(m.board?.sha256||""))throw new TypeError("Analysis requires the exact saved PCB SHA-256.");let h={sha256:m.board.sha256};m.board.path!==void 0&&(h.path=Lo(m.board.path,"board path",1e3));let p=m.provenance;if(!p||!["computed","measured","illustrative"].includes(p.kind))throw new TypeError("Choose computed, measured or illustrative provenance.");if(!Array.isArray(p.assumptions)||p.assumptions.length>24)throw new TypeError("Supply bounded analysis assumptions (an empty array is allowed).");let w={kind:p.kind,tool:Lo(p.tool,"tool"),runId:Lo(p.runId,"run ID"),assumptions:p.assumptions.map(ee=>Lo(ee,"assumption",500))};if(p.generatedAt!==void 0){if(typeof p.generatedAt!="string"||p.generatedAt.length>40||!Number.isFinite(Date.parse(p.generatedAt)))throw new TypeError("Invalid analysis timestamp.");w.generatedAt=p.generatedAt}if(!Array.isArray(m.fields)||!m.fields.length||m.fields.length>8)throw new RangeError("Supply 1\u20138 analysis fields.");let S=new Set,A=0,T=m.fields.map(ee=>{let X=Lo(ee?.id,"field ID",80);if(S.has(X))throw new TypeError("Duplicate analysis field ID.");if(S.add(X),!Array.isArray(ee.range)||ee.range.length!==2)throw new TypeError("Supply a fixed scalar range.");let G=ee.range.map(_e=>gh(_e,"range"));if(G[1]<=G[0])throw new RangeError("Analysis range must increase.");if(!Array.isArray(ee.samples)||!ee.samples.length||(A+=ee.samples.length)>1e4)throw new RangeError("Analysis is limited to 10,000 cells in total.");let ae={id:X,name:Lo(ee.name,"field name"),unit:Lo(ee.unit,"unit",40),range:G,samples:ee.samples.map(_e=>{let J={x:gh(_e?.x,"x",1e6),y:gh(_e?.y,"y",1e6),width:gh(_e?.width,"width",1e6),height:gh(_e?.height,"height",1e6),value:gh(_e?.value,"value")};if(J.width<=0||J.height<=0)throw new RangeError("Analysis cells must have positive dimensions.");return J})};return ee.layer!==void 0&&(ae.layer=Lo(ee.layer,"layer",80)),ae}),H={schema:m.schema,coordinateSystem:m.coordinateSystem,board:h,provenance:w,fields:T},Y=ee=>{if(ee&&typeof ee=="object"){for(let X of Object.values(ee))Y(X);Object.freeze(ee)}return ee};return Y(H)}async function Dm(m){if(typeof m!="string")throw new TypeError("Load a saved PCB source first.");if(!globalThis.crypto?.subtle)throw new Error("Analysis binding requires a secure context (HTTPS or localhost).");return[...new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(m)))].map(h=>h.toString(16).padStart(2,"0")).join("")}function Um(m,h){return"rgb("+km(m,h).join(",")+")"}function Dv(m,h){for(let p=m.samples.length-1;p>=0;p--){let w=m.samples[p];if(h.x>=w.x&&h.x<=w.x+w.width&&h.y>=w.y&&h.y<=w.y+w.height)return w}return null}function ad(m){return String(Number(m.toPrecision(6)))}var Lo,gh,od=Ui(()=>{Om();Lo=(m,h,p=240)=>{if(typeof m!="string"||!m.trim()||m.length>p||/[\u0000-\u001f\u007f]/.test(m))throw new TypeError("Invalid analysis "+h+".");return m},gh=(m,h,p=1e9)=>{if(typeof m!="number"||!Number.isFinite(m)||Math.abs(m)>p)throw new TypeError("Invalid analysis "+h+".");return m}});var IM={};Ol(IM,{createAnalysisLayer:()=>hU});function hU(m,h){let p=m.host.ownerDocument,w="http://www.w3.org/2000/svg",S=(C,j)=>{let B=p.createElement(C);return j&&(B.textContent=j),B},A=p.createElementNS(w,"svg"),T=p.createElementNS(w,"g");A.append(T),A.setAttribute("aria-hidden","true"),A.style.cssText="position:absolute;inset:0;width:100%;height:100%;pointer-events:none;z-index:2";let H=S("section");H.setAttribute("aria-label","Imported analysis results"),H.style.cssText="position:absolute;left:10px;bottom:10px;z-index:4;max-width:min(340px,calc(100% - 20px));max-height:55%;overflow:auto;padding:10px;border:1px solid var(--viewer-border);border-radius:10px;background:var(--viewer-bar);color:var(--viewer-ink);box-shadow:var(--viewer-shadow);font:12px/1.5 system-ui";let Y=S("strong",h.provenance.kind==="illustrative"?"ILLUSTRATIVE \xB7 NOT SOLVER RESULTS":"IMPORTED "+h.provenance.kind.toUpperCase()+" RESULTS");Y.style.cssText="display:block;color:var(--viewer-accent);font-size:10px;letter-spacing:.06em";let ee=S("select");ee.setAttribute("aria-label","Analysis field"),ee.style.cssText="display:block;width:100%;margin:6px 0;padding:6px;background:var(--viewer-bg);color:var(--viewer-ink);border:1px solid var(--viewer-border);border-radius:5px";for(let C of h.fields){let j=S("option",C.name+" ["+C.unit+"]");j.value=C.id,ee.append(j)}let X=S("div");X.style.cssText="height:8px;border-radius:4px;background:linear-gradient(90deg,"+[0,1/3,2/3,1].map(C=>Um(C,[0,1])).join(",")+")";let G=S("div");G.style.cssText="display:flex;justify-content:space-between;font-variant-numeric:tabular-nums";let ae=S("span"),_e=S("span");G.append(ae,_e);let J=S("div","Move over the board to probe a cell.");J.setAttribute("role","status");let Q=S("label"),te=S("input");te.type="checkbox",te.checked=!0,te.setAttribute("aria-label","Show analysis overlay"),Q.append(te,S("span"," Show overlay"));let he=S("input");he.type="range",he.min="0",he.max="100",he.value="65",he.setAttribute("aria-label","Analysis opacity"),he.style.width="100%";let be=S("details"),De=S("summary","Run details & assumptions"),Ke=S("div",h.provenance.tool+" \xB7 "+h.provenance.runId+(h.provenance.generatedAt?" \xB7 "+h.provenance.generatedAt:""));Ke.style.overflowWrap="anywhere";let qe=S("ul");for(let C of h.provenance.assumptions)qe.append(S("li",C));be.append(De,Ke,qe,S("p","Fixed color scale; values outside the scale clamp to endpoint colors. Overlapping cells use the last supplied cell. This viewer does not calculate or validate engineering results.")),H.append(Y,ee,X,G,J,Q,he,be);let $e=h.fields[0],Xe=null,ve=null,Ee=null,me=!1,N=!1;function re(C){let j=h.fields.find(B=>B.id===C);if(!j)throw new TypeError("Choose an imported analysis field.");$e=j,ee.value=C,T.replaceChildren();for(let B of $e.samples){let W=p.createElementNS(w,"rect");for(let K of["x","y","width","height"])W.setAttribute(K,String(B[K]));W.setAttribute("fill",Um(B.value,$e.range)),T.append(W)}ae.textContent=ad($e.range[0])+" "+$e.unit,_e.textContent=ad($e.range[1])+" "+$e.unit,J.textContent="Move over the board to probe a cell.",$()}function R(){return m.view==="pcb"&&m.renderer?.viewport?.camera}function $(){if(me)return;let C=R(),j=!$e.layer||m.renderer?.visibleLayers?.has($e.layer);if(A.hidden=!C||!te.checked||!j,A.style.display=A.hidden?"none":"",T.setAttribute("opacity",String(Number(he.value)/100)),!C){N=!0,J.textContent="Overlay paused \xB7 switch to PCB layout.";return}if(!j){N=!0,J.textContent="Overlay paused \xB7 "+$e.layer+" is hidden.";return}if(!te.checked){N=!0,J.textContent="Overlay hidden.";return}N&&(N=!1,J.textContent="Move over the board to probe a cell.");let B=C.world_to_screen({x:0,y:0});A.setAttribute("viewBox","0 0 "+C.width+" "+C.height),T.setAttribute("transform",`translate(${B.x} ${B.y}) scale(${C.flipped?-C.zoom:C.zoom} ${C.zoom})`)}let V=C=>{if(!R()||C.target!==m.renderer.canvas||A.hidden)return;let j=m.renderer.canvas.getBoundingClientRect();Ee={x:C.clientX-j.left,y:C.clientY-j.top},ve===null&&(ve=requestAnimationFrame(()=>{if(ve=null,me||!R()||A.hidden||!Ee)return;let B=m.renderer.viewport.camera.screen_to_world(Ee),W=Dv($e,B);J.textContent=W?ad(W.value)+" "+$e.unit+" \xB7 "+B.x.toFixed(2)+", "+B.y.toFixed(2)+" mm":"No supplied result at this position."}))};m.stage.addEventListener("pointermove",V);function O(){Xe?.removeEventListener?.("kicad:viewframe",$),Xe=m.renderer,Xe?.addEventListener?.("kicad:viewframe",$),m.stage.append(A,H),$()}return ee.onchange=()=>re(ee.value),te.onchange=$,he.oninput=$,re($e.id),O(),{data:h,attach:O,sync:$,setField:re,dispose(){me=!0,Xe?.removeEventListener?.("kicad:viewframe",$),m.stage.removeEventListener("pointermove",V),ve!==null&&cancelAnimationFrame(ve),ee.onchange=te.onchange=he.oninput=null,A.remove(),H.remove()}}}var NM=Ui(()=>{od()});var kM=$n((LM,Uv)=>{(function(m){typeof Uv<"u"&&typeof LM=="object"?Uv.exports=m():typeof define<"u"&&define.amd?define(["fzstd",m]):(typeof self<"u"?self:this).fzstd=m()})(function(){var m={},h=ArrayBuffer,p=Uint8Array,w=Uint16Array,S=Int16Array,A=Uint32Array,T=Int32Array,H=function(O,C,j){if(p.prototype.slice)return p.prototype.slice.call(O,C,j);(C==null||C<0)&&(C=0),(j==null||j>O.length)&&(j=O.length);var B=new p(j-C);return B.set(O.subarray(C,j)),B},Y=function(O,C,j,B){if(p.prototype.fill)return p.prototype.fill.call(O,C,j,B);for((j==null||j<0)&&(j=0),(B==null||B>O.length)&&(B=O.length);j<B;++j)O[j]=C;return O},ee=function(O,C,j,B){if(p.prototype.copyWithin)return p.prototype.copyWithin.call(O,C,j,B);for((j==null||j<0)&&(j=0),(B==null||B>O.length)&&(B=O.length);j<B;)O[C++]=O[j++]};m.ZstdErrorCode={InvalidData:0,WindowSizeTooLarge:1,InvalidBlockType:2,FSEAccuracyTooHigh:3,DistanceTooFarBack:4,UnexpectedEOF:5};var X=["invalid zstd data","window size too large (>2046MB)","invalid block type","FSE accuracy too high","match distance too far back","unexpected EOF"],G=function(O,C,j){var B=Error(C||X[O]);if(B.code=O,Error.captureStackTrace&&Error.captureStackTrace(B,G),!j)throw B;return B},ae=function(O,C,j){for(var B=0,W=0;B<j;++B)W|=O[C++]<<(B<<3);return W},_e=function(O,C){return(O[C]|O[C+1]<<8|O[C+2]<<16|O[C+3]<<24)>>>0},J=function(O,C){var j=O[0]|O[1]<<8|O[2]<<16;if(j==3126568&&O[3]==253){var B=O[4],W=B>>5&1,K=B>>2&1,ge=3&B,Ne=B>>6;8&B&&G(0);var ne=6-W,we=ge==3?4:ge,xe=ae(O,ne,we),ke=Ne?1<<Ne:W,Me=ae(O,ne+=we,ke)+(Ne==1&&256),Ce=Me;if(!W){var tt=1<<10+(O[5]>>3);Ce=tt+(tt>>3)*(7&O[5])}Ce>2145386496&&G(1);var Ze=new p((C==1?Me||Ce:C?0:Ce)+12);return Ze[0]=1,Ze[4]=4,Ze[8]=8,{b:ne+ke,y:0,l:0,d:xe,w:C&&C!=1?C:Ze.subarray(12),e:Ce,o:new T(Ze.buffer,0,3),u:Me,c:K,m:Math.min(131072,Ce)}}if((j>>4|O[3]<<20)==25481893)return _e(O,4)+8;G(0)},Q=function(O){for(var C=0;1<<C<=O;++C);return C-1},te=function(O,C,j){var B=4+(C<<3),W=5+(15&O[C]);W>j&&G(3);for(var K=1<<W,ge=K,Ne=-1,ne=-1,we=-1,xe=K,ke=new h(512+(K<<2)),Me=new S(ke,0,256),Ce=new w(ke,0,256),tt=new w(ke,512,K),Ze=512+(K<<1),Ye=new p(ke,Ze,K),vt=new p(ke,Ze+K);Ne<255&&ge>0;){var Rt=Q(ge+1),Je=B>>3,_t=(1<<Rt+1)-1,Et=(O[Je]|O[Je+1]<<8|O[Je+2]<<16)>>(7&B)&_t,gt=(1<<Rt)-1,Ht=_t-ge-1,lt=Et&gt;if(lt<Ht?(B+=Rt,Et=lt):(B+=Rt+1,Et>gt&&(Et-=Ht)),Me[++Ne]=--Et,Et==-1?(ge+=Et,Ye[--xe]=Ne):ge-=Et,!Et)do{var et=B>>3;ne=(O[et]|O[et+1]<<8)>>(7&B)&3,B+=2,Ne+=ne}while(ne==3)}(Ne>255||ge)&&G(0);for(var St=0,At=(K>>1)+(K>>3)+3,Wt=K-1,nr=0;nr<=Ne;++nr){var pt=Me[nr];if(pt<1)Ce[nr]=-pt;else for(we=0;we<pt;++we){Ye[St]=nr;do St=St+At&Wt;while(St>=xe)}}for(St&&G(0),we=0;we<K;++we){var ft=Ce[Ye[we]]++,Bt=vt[we]=W-Q(ft);tt[we]=(ft<<Bt)-K}return[B+7>>3,{b:W,s:Ye,n:vt,t:tt}]},he=function(O,C){var j=0,B=-1,W=new p(292),K=O[C],ge=W.subarray(0,256),Ne=W.subarray(256,268),ne=new w(W.buffer,268);if(K<128){var we=te(O,C+1,6),xe=we[1],ke=we[0]<<3,Me=O[C+=K];Me||G(0);for(var Ce=0,tt=0,Ze=xe.b,Ye=Ze,vt=(++C<<3)-8+Q(Me);!((vt-=Ze)<ke);){var Rt=vt>>3;if(ge[++B]=xe.s[Ce+=(O[Rt]|O[Rt+1]<<8)>>(7&vt)&(1<<Ze)-1],(vt-=Ye)<ke)break;ge[++B]=xe.s[tt+=(O[Rt=vt>>3]|O[Rt+1]<<8)>>(7&vt)&(1<<Ye)-1],Ze=xe.n[Ce],Ce=xe.t[Ce],Ye=xe.n[tt],tt=xe.t[tt]}++B>255&&G(0)}else{for(B=K-127;j<B;j+=2){var Je=O[++C];ge[j]=Je>>4,ge[j+1]=15&Je}++C}var _t=0;for(j=0;j<B;++j)(lt=ge[j])>11&&G(0),_t+=lt&&1<<lt-1;var Et=Q(_t)+1,gt=1<<Et,Ht=gt-_t;for(Ht&Ht-1&&G(0),ge[B++]=Q(Ht)+1,j=0;j<B;++j){var lt;++Ne[ge[j]=(lt=ge[j])&&Et+1-lt]}var et=new p(gt<<1),St=et.subarray(0,gt),At=et.subarray(gt);for(ne[Et]=0,j=Et;j>0;--j){var Wt=ne[j];Y(At,j,Wt,ne[j-1]=Wt+Ne[j]*(1<<Et-j))}for(ne[0]!=gt&&G(0),j=0;j<B;++j){var nr=ge[j];if(nr){var pt=ne[nr];Y(St,j,pt,ne[nr]=pt+(1<<Et-nr))}}return[C,{n:At,b:Et,s:St}]},be=te(new p([81,16,99,140,49,198,24,99,12,33,196,24,99,102,102,134,70,146,4]),0,6)[1],De=te(new p([33,20,196,24,99,140,33,132,16,66,8,33,132,16,66,8,33,68,68,68,68,68,68,68,68,36,9]),0,6)[1],Ke=te(new p([32,132,16,66,102,70,68,68,68,68,36,73,2]),0,5)[1],qe=function(O,C){for(var j=O.length,B=new T(j),W=0;W<j;++W)B[W]=C,C+=1<<O[W];return B},$e=new p(new T([0,0,0,0,16843009,50528770,134678020,202050057,269422093]).buffer,0,36),Xe=qe($e,0),ve=new p(new T([0,0,0,0,0,0,0,0,16843009,50528770,117769220,185207048,252579084,16]).buffer,0,53),Ee=qe(ve,3),me=function(O,C,j){var B=O.length,W=C.length,K=O[B-1],ge=(1<<j.b)-1,Ne=-j.b;K||G(0);for(var ne=0,we=j.b,xe=(B<<3)-8+Q(K)-we,ke=-1;xe>Ne&&ke<W;){var Me=xe>>3;C[++ke]=j.s[ne=(ne<<we|(O[Me]|O[Me+1]<<8|O[Me+2]<<16)>>(7&xe))&ge],xe-=we=j.n[ne]}xe==Ne&&ke+1==W||G(0)},N=function(O,C,j){var B=6,W=C.length+3>>2,K=W<<1,ge=W+K;me(O.subarray(B,B+=O[0]|O[1]<<8),C.subarray(0,W),j),me(O.subarray(B,B+=O[2]|O[3]<<8),C.subarray(W,K),j),me(O.subarray(B,B+=O[4]|O[5]<<8),C.subarray(K,ge),j),me(O.subarray(B),C.subarray(ge),j)},re=function(O,C,j){var B,W=C.b,K=O[W],ge=K>>1&3;C.l=1&K;var Ne=K>>3|O[W+1]<<5|O[W+2]<<13,ne=(W+=3)+Ne;if(ge==1)return W>=O.length?void 0:(C.b=W+1,j?(Y(j,O[W],C.y,C.y+=Ne),j):Y(new p(Ne),O[W]));if(!(ne>O.length)){if(ge==0)return C.b=ne,j?(j.set(O.subarray(W,ne),C.y),C.y+=Ne,j):H(O,W,ne);if(ge==2){var we=O[W],xe=3&we,ke=we>>2&3,Me=we>>4,Ce=0,tt=0;xe<2?1&ke?Me|=O[++W]<<4|(2&ke&&O[++W]<<12):Me=we>>3:(tt=ke,ke<2?(Me|=(63&O[++W])<<4,Ce=O[W]>>6|O[++W]<<2):ke==2?(Me|=O[++W]<<4|(3&O[++W])<<12,Ce=O[W]>>2|O[++W]<<6):(Me|=O[++W]<<4|(63&O[++W])<<12,Ce=O[W]>>6|O[++W]<<2|O[++W]<<10)),++W;var Ze=j?j.subarray(C.y,C.y+C.m):new p(C.m),Ye=Ze.length-Me;if(xe==0)Ze.set(O.subarray(W,W+=Me),Ye);else if(xe==1)Y(Ze,O[W++],Ye);else{var vt=C.h;if(xe==2){var Rt=he(O,W);Ce+=W-(W=Rt[0]),C.h=vt=Rt[1]}else vt||G(0);(tt?N:me)(O.subarray(W,W+=Ce),Ze.subarray(Ye),vt)}var Je=O[W++];if(Je){Je==255?Je=32512+(O[W++]|O[W++]<<8):Je>127&&(Je=Je-128<<8|O[W++]);var _t=O[W++];3&_t&&G(0);for(var Et=[De,Ke,be],gt=2;gt>-1;--gt){var Ht=_t>>2+(gt<<1)&3;if(Ht==1){var lt=new p([0,0,O[W++]]);Et[gt]={s:lt.subarray(2,3),n:lt.subarray(0,1),t:new w(lt.buffer,0,1),b:0}}else Ht==2?(W=(B=te(O,W,9-(1&gt)))[0],Et[gt]=B[1]):Ht==3&&(C.t||G(0),Et[gt]=C.t[gt])}var et=C.t=Et,St=et[0],At=et[1],Wt=et[2],nr=O[ne-1];nr||G(0);var pt=(ne<<3)-8+Q(nr)-Wt.b,ft=pt>>3,Bt=0,Yt=(O[ft]|O[ft+1]<<8)>>(7&pt)&(1<<Wt.b)-1,kr=(O[ft=(pt-=At.b)>>3]|O[ft+1]<<8)>>(7&pt)&(1<<At.b)-1,Gr=(O[ft=(pt-=St.b)>>3]|O[ft+1]<<8)>>(7&pt)&(1<<St.b)-1;for(++Je;--Je;){var Qr=Wt.s[Yt],Zr=Wt.n[Yt],ii=St.s[Gr],ur=St.n[Gr],Gi=At.s[kr],yt=At.n[kr],jt=1<<Gi,Jt=jt+((O[ft=(pt-=Gi)>>3]|O[ft+1]<<8|O[ft+2]<<16|O[ft+3]<<24)>>>(7&pt)&jt-1);ft=(pt-=ve[ii])>>3;var sr=Ee[ii]+((O[ft]|O[ft+1]<<8|O[ft+2]<<16)>>(7&pt)&(1<<ve[ii])-1);ft=(pt-=$e[Qr])>>3;var Xt=Xe[Qr]+((O[ft]|O[ft+1]<<8|O[ft+2]<<16)>>(7&pt)&(1<<$e[Qr])-1);if(ft=(pt-=Zr)>>3,Yt=Wt.t[Yt]+((O[ft]|O[ft+1]<<8)>>(7&pt)&(1<<Zr)-1),ft=(pt-=ur)>>3,Gr=St.t[Gr]+((O[ft]|O[ft+1]<<8)>>(7&pt)&(1<<ur)-1),ft=(pt-=yt)>>3,kr=At.t[kr]+((O[ft]|O[ft+1]<<8)>>(7&pt)&(1<<yt)-1),Jt>3)C.o[2]=C.o[1],C.o[1]=C.o[0],C.o[0]=Jt-=3;else{var qt=Jt-(Xt!=0);qt?(Jt=qt==3?C.o[0]-1:C.o[qt],qt>1&&(C.o[2]=C.o[1]),C.o[1]=C.o[0],C.o[0]=Jt):Jt=C.o[0]}for(gt=0;gt<Xt;++gt)Ze[Bt+gt]=Ze[Ye+gt];Ye+=Xt;var gr=(Bt+=Xt)-Jt;if(gr<0){var ar=-gr,Ar=C.e+gr;for(ar>sr&&(ar=sr),gt=0;gt<ar;++gt)Ze[Bt+gt]=C.w[Ar+gt];Bt+=ar,sr-=ar,gr=0}for(gt=0;gt<sr;++gt)Ze[Bt+gt]=Ze[gr+gt];Bt+=sr}if(Bt!=Ye)for(;Ye<Ze.length;)Ze[Bt++]=Ze[Ye++];else Bt=Ze.length;j?C.y+=Bt:Ze=H(Ze,0,Bt)}else if(j){if(C.y+=Me,Ye)for(gt=0;gt<Me;++gt)Ze[gt]=Ze[Ye+gt]}else Ye&&(Ze=H(Ze,Ye));return C.b=ne,Ze}G(2)}},R=function(O,C){if(O.length==1)return O[0];for(var j=new p(C),B=0,W=0;B<O.length;++B){var K=O[B];j.set(K,W),W+=K.length}return j};function $(O,C){for(var j=[],B=+!C,W=0,K=0;O.length;){var ge=J(O,B||C);if(typeof ge=="object"){for(B?(C=null,ge.w.length==ge.u&&(j.push(C=ge.w),K+=ge.u)):(j.push(C),ge.e=0);!ge.l;){var Ne=re(O,ge,C);Ne||G(5),C?ge.e=ge.y:(j.push(Ne),K+=Ne.length,ee(ge.w,0,Ne.length),ge.w.set(Ne,ge.w.length-Ne.length))}W=ge.b+4*ge.c}else W=ge;O=O.subarray(W)}return R(j,K)}m.decompress=$;var V=(function(){function O(C){this.ondata=C,this.c=[],this.l=0,this.z=0}return O.prototype.push=function(C,j){if(typeof this.s=="number"){var B=Math.min(C.length,this.s);C=C.subarray(B),this.s-=B}var W=C.length+this.l;if(!this.s){if(j){if(!W)return void this.ondata(new p(0),!0);W<5&&G(5)}else if(W<18)return this.c.push(C),void(this.l=W);if(this.l&&(this.c.push(C),C=R(this.c,W),this.c=[],this.l=0),typeof(this.s=J(C))=="number")return this.push(C,j)}if(typeof this.s!="number"){if(W<(this.z||3))return j&&G(5),this.c.push(C),void(this.l=W);if(this.l&&(this.c.push(C),C=R(this.c,W),this.c=[],this.l=0),!this.z&&W<(this.z=2&C[this.s.b]?4:3+(C[this.s.b]>>3|C[this.s.b+1]<<5|C[this.s.b+2]<<13)))return j&&G(5),this.c.push(C),void(this.l=W);for(this.z=0;;){var K=re(C,this.s);if(!K){j&&G(5);var ge=C.subarray(this.s.b);return this.s.b=0,this.c.push(ge),void(this.l+=ge.length)}if(this.ondata(K,!1),ee(this.s.w,0,K.length),this.s.w.set(K,this.s.w.length-K.length),this.s.l){var Ne=C.subarray(this.s.b);return this.s=4*this.s.c,void this.push(Ne,j)}}}else j&&G(5)},O})();return m.Decompress=V,m})});var UM={};Ol(UM,{KiCadViewer:()=>ko,registerKiCadViewer:()=>DM});function dU(){return globalThis.SpikeBoard3D?Promise.resolve(globalThis.SpikeBoard3D):Promise.resolve().then(()=>(Tv(),Av)).then(m=>m.loadThree())}function yh(m,h){return new Promise((p,w)=>{let S=()=>w(new DOMException("The operation was aborted.","AbortError"));if(h.aborted){S();return}h.addEventListener("abort",S,{once:!0}),Promise.resolve(m).then(p,w).finally(()=>h.removeEventListener("abort",S))})}function DM(m="kicad-viewer"){customElements.get(m)||customElements.define(m,class extends HTMLElement{connectedCallback(){if(!this.viewer){this.viewer=new ko(this,{theme:this.getAttribute("theme")||"light",inspectOnSelect:this.getAttribute("inspect-on-select")!=="false",highlightStyle:this.getAttribute("highlight-style")||"dim",highlightColor:this.getAttribute("highlight-color")||"source",appearance:this.getAttribute("appearance")||"realistic"});for(let h of["ready","select","measure","analysis","error","viewchange","camerachange"])this.viewer.addEventListener(h,p=>this.dispatchEvent(new CustomEvent(`kicad:${h}`,{detail:p.detail})));this.getAttribute("src")&&this.viewer.load(this.getAttribute("src"),{view:this.getAttribute("view")||void 0,file:this.getAttribute("file")||void 0,ref:this.getAttribute("ref")||void 0}).catch(()=>{})}}disconnectedCallback(){this.viewer?.dispose(),this.viewer=null}})}var h6,f6,m6,g6,y6,v6,x6,b6,w6,_6,OM,uU,ko,ld=Ui(()=>{h6=Vn(tv(),1);TE();PE();iv();lv();f6=Vn(To(),1),m6=Vn(KE(),1),g6=Vn(lm(),1),y6=Vn(hm(),1),v6=Vn(cv(),1),x6=Vn(QE(),1),b6=Vn(tS(),1),w6=Vn(rS(),1),_6=Vn(iS(),1);Ul();Am();Tm();TS();Qa();sd();kS();HS();OM=globalThis.KiCadDesignDiff,uU=globalThis.KiCadNetModel;ko=class m extends EventTarget{constructor(h,{theme:p="light",loadAsset:w,assetPaths:S=[],inspectOnSelect:A=!0,appearance:T="realistic",highlightStyle:H="dim",highlightColor:Y="source"}={}){super();let ee=typeof h=="string"?document.querySelector(h):h;if(!ee?.append||!ee?.ownerDocument)throw new TypeError("Choose a viewer container element.");if(Vi.has(ee))throw new Error("This container already has a viewer.");if(!["light","dark"].includes(p))throw new TypeError("Theme must be light or dark.");if(typeof A!="boolean")throw new TypeError("inspectOnSelect must be a boolean.");if(!["realistic","layers","translucent"].includes(T))throw new TypeError("Choose realistic, layers or translucent appearance.");let X=ed(H,Y);this.highlightMode=X.mode,this.highlightColor=X.color,this.inspectOnSelect=A,this.host=ee,this.theme=p,this.modelOptions={loadAsset:w,assetPaths:S,appearance:T},this.viewMemory=new im,this.root=ee.ownerDocument.createElement("div"),this.root.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;overflow:hidden;position:relative;container-type:inline-size",this.stage=ee.ownerDocument.createElement("div"),this.stage.style.cssText="position:relative;flex:1;min-height:0;overflow:hidden",this.status=ee.ownerDocument.createElement("div"),this.status.setAttribute("role","status"),this.status.style.cssText="",this.surface=this.root.attachShadow?this.root.attachShadow({mode:"open"}):this.root,this.inspector=VS(this),this.createControls(),this.surface.append(this.chrome.style,this.inspector.style,this.toolbar,this.stage,this.status,this.inspector.panel),this.loading=CE(this),ee.append(this.root),Vi.set(ee,this),this.generation=0,this.analysisTicket=0,this.analysis=null,this.disposed=!1,this.source=null,this.renderer=null,this.project=null,this.renderingNotes=[],this.setTheme(p),this.updateControls()}assertActive(){if(this.disposed)throw new Error("Viewer has been disposed.")}emit(h,p){this.dispatchEvent(new CustomEvent(h,{detail:p}))}load(h,p={}){return this.loadInput(h,p)}loadProject(h,p={}){return this.load(h,p)}async runOperation(h,p){this.assertActive();let w=++this.generation;this.pending?.abort();let S=new AbortController;this.pending=S;let A=()=>S.abort();h?.addEventListener("abort",A,{once:!0}),h?.aborted&&A();let T={signal:S.signal,current:()=>!this.disposed&&w===this.generation,check(){if(S.signal.aborted)throw new DOMException("The operation was aborted.","AbortError")}};this.loading.show(w,()=>S.abort()),T.stage=H=>this.loading.stage(w,H);try{return T.check(),typeof requestAnimationFrame=="function"&&await RE(S.signal),T.check(),await p(T)}catch(H){if(!T.current())return!1;throw this.chrome.setStatus(H.message,!0),this.emit("error",H),H}finally{h?.removeEventListener("abort",A),this.pending===S&&(this.pending=null),this.loading.hide(w)}}loadInput(h,{view:p,signal:w,...S}={},A=null){return this.runOperation(w,async T=>{T.stage("Fetching design\xE2\u20AC\xA6");let H=await Mm(h,{...S,baseURL:S.baseURL||this.host.ownerDocument.baseURI,signal:T.signal});if(!T.current())return!1;if(T.check(),H.archive){let Y=await jl(H.archive,{signal:T.signal});return T.current()?(T.check(),this.showFileSet(Y,{...S,view:p},T)):!1}return H.files?this.showManufacturing(H.files,{...S,view:p,path:H.path,project:A||H.project},T):Co(H.source,H.path)?this.showManufacturing([{source:H.source,path:H.path}],{...S,view:p,path:H.path,project:A||H.project},T):this.showSource(H.source,{path:H.path,view:p,project:A||H.project,credentials:S.credentials,textVariables:S.textVariables,instancePath:S.instancePath,worksheetSource:S.worksheetSource},T)})}loadFiles(h,p={}){return this.loadCollection(w=>AS(h,{signal:w,lazyBoards:!0}),p)}loadArchive(h,p={}){return this.loadCollection(w=>jl(h,{signal:w}),p)}loadCollection(h,{signal:p,...w}={}){return this.runOperation(p,async S=>{let A=await h(S.signal);return S.current()?(S.check(),this.showFileSet(A,w,S)):!1})}async showFileSet(h,p={},w){let S=[],A=[],T=[...p.projectSettings||[]];for(let X of h){if(/\.kicad_pro$/i.test(X.path)){let ae=X.source??new TextDecoder("utf-8",{fatal:!0}).decode(X.bytes);if(ae.length>8*1024*1024)throw new Error("Project settings exceed the 8 MiB metadata limit.");let _e=JSON.parse(ae);T.push({path:X.path,textVariables:_e?.text_variables,pcb:_e?.pcbnew?.page_layout_descr_file,sch:_e?.schematic?.page_layout_descr_file});continue}if(!Ja(X.path)&&!X.path.toLowerCase().endsWith(".txt")){A.push(X.path);continue}if(/\.kicad_pcb$/i.test(X.path)){S.push(X);continue}let G=X.source??new TextDecoder("utf-8",{fatal:!0}).decode(X.bytes);nh(X.path)||Hn(X.path)||Co(G,X.path)?S.push({path:X.path,source:G}):A.push(X.path)}if(!S.length)throw new Error("No supported KiCad, Gerber or Excellon drawings were found.");let H=p.file?S.find(X=>X.path===p.file):S.find(X=>/\.kicad_pcb$/i.test(X.path))||S.find(X=>!Hn(X.path))||S[0];if(!H)throw new Error("The requested drawing is not in the file set.");let Y={files:S,entry:H.path,memory:!0,settings:T,textVariables:T.length===1?T[0].textVariables||{}:{},notes:A.length?["Ignored "+A.length+" unsupported bundle entries: "+A.slice(0,12).join(", ")]:[]};if(T.length>1&&Y.notes.push("Multiple project settings files supplied; text variables require an explicit textVariables option."),T.length&&nh(H.path)){let{applySavedWorksheet:X}=await yh(Promise.resolve().then(()=>(Pv(),Rv)),w.signal);X(T,H.path,Y)}if(!nh(H.path)&&!Hn(H.path))return this.showManufacturing(S.filter(X=>sh(X.path)),{...p,path:H.path,project:Y},w);let ee=await bv(H,{signal:w.signal});return w.check(),this.showSource(ee,{...p,path:H.path,project:Y},w)}async showManufacturing(h,{path:p=h[0]?.path||"Manufacturing layers",project:w=null,...S}={},A){if(this.assertActive(),S.view&&S.view!=="manufacturing")throw new TypeError("Manufacturing layers support the manufacturing view only.");let{manufacturingDesign:T}=await yh(Promise.resolve().then(()=>(kv(),Lv)),A.signal);A.check();let H=T(h,S);return this.mountView("manufacturing",{source:"manufacturing",path:p,kind:"manufacturing",design:H,project:w,credentials:S.credentials||"omit",sheetLinks:[],inspectionModel:Im(null,{kind:"manufacturing",path:p,design:H})},A)}loadSource(h,{signal:p,...w}={}){return this.runOperation(p,S=>typeof h=="string"&&(w.format||Co(h,w.path))?this.showManufacturing([{source:h,path:w.path||"manufacturing"}],w,S):this.showSource(h,w,S))}async showSource(h,{path:p="",view:w,project:S=null,credentials:A="omit",textVariables:T=S?.textVariables||{},instancePath:H,worksheetSource:Y}={},ee){if(this.assertActive(),typeof h=="string"&&Co(h,p))return this.showManufacturing([{source:h,path:p}],{path:p,view:w,project:S,credentials:A},ee);let X=Hn(p),G=h,ae=Y;if(X)Y=h,h='(kicad_sch (version 20250114) (generator eeschema) (paper "A4") (lib_symbols))';else if(Y===void 0&&nh(p)){let N=S?.files?.filter(R=>Hn(R.path))||[],re=S?.worksheet?N.find(R=>R.path===S.worksheet):N.find(R=>R.path.replace(/\.kicad_wks$/i,"")===p.replace(/\.kicad_(pcb|sch)$/i,""));re&&(Y=re.url?await eo(re.url,{signal:ee.signal,credentials:A,limit:2*1024*1024}):await bv(re,{signal:ee.signal}))}let _e;if(Y!==void 0){let{parseWorksheet:N}=await yh(Promise.resolve().then(()=>(Pv(),Rv)),ee.signal);ee.check(),_e=N(Y,OM)}if(ee.stage?.("Preparing drawing geometry\xE2\u20AC\xA6"),!T||typeof T!="object"||Array.isArray(T)||Object.keys(T).length>256||Object.entries(T).some(([N,re])=>N.length>200||typeof re!="string"||re.length>8192))throw new TypeError("Supply at most 256 text variables with string values (8192 characters each).");T=Object.freeze({...T});let J=OM,Q=p,te=/\.kicad_(?:pcb|sch)$/i.test(p)?J.prepareProject([{path:p,content:h}],{forConnectivity:!0,compactCopper:!0}):null,he=te?J.preparedFile(te,Q,h):J.parse(h),be=he[0]==="kicad_pcb"?"pcb":he[0]==="kicad_sch"?"schematic":null;if(!be)throw new TypeError("Expected a .kicad_sch or .kicad_pcb design.");w||=be,this.validateView(w,be);let De=be==="schematic"&&S?.memory?S.files.filter(N=>/\.kicad_sch$/i.test(N.path)).map(N=>({path:N.path,content:N.source,...N.path===p?{ast:he}:{}})):[{path:p,ast:he}],Ke=be==="schematic"?globalThis.KiCadFileCompatibility.textContext(De,p,{instancePath:H,parse:N=>J.parseMetadata(N)}):{};be==="schematic"&&(await yh(Promise.resolve().then(()=>Vn(AM(),1)),ee.signal),ee.check());let qe=be==="pcb"?globalThis.KiCadPCBRenderer.build(he,p,{textVariables:T,worksheet:_e,deferZonePoints:!0}):globalThis.KiCadSchematicRenderer.build(he,p,{...Ke,textVariables:T,worksheet:_e}),$e;if(Ke.rootPath&&Ke.rootPath!==p&&qe.primitives.some(N=>N.fontFace)){let N=De.find(re=>re.path===Ke.rootPath)?.content;if(N)try{let re=J.parseMetadata(N,{includeEmbeddedFonts:!0});$e=globalThis.KiCadFileCompatibility.embeddedFonts(re)}catch{qe.warnings.push("Embedded fonts from the loaded root sheet could not be read.")}}let Xe={nets:[],warnings:[]};try{X||(Xe=uU.build([{path:p||"drawing.kicad_"+(be==="pcb"?"pcb":"sch"),content:h}],new Map([[p||"drawing.kicad_"+(be==="pcb"?"pcb":"sch"),qe]]),te))}catch(N){Xe.warnings.push("Net selection unavailable: "+N.message)}be==="schematic"&&!X&&Xe.warnings.push("Schematic nets use per-file saved wires, labels and terminals; buses, implicit hidden power pins and repeated-sheet instance connectivity are not a KiCad netlist.");let ve=Im(he,{kind:be,path:p,design:qe,connectivity:Xe}),Ee=N=>N&&typeof N=="object"&&!Array.isArray(N)?N.quoted:N,me=be==="schematic"?he.filter(N=>Array.isArray(N)&&Ee(N[0])==="sheet").slice(0,256).map(N=>{let re=R=>String(Ee(N.find($=>Array.isArray($)&&Ee($[0])==="property"&&String(Ee($[1])).replaceAll(" ","").toLowerCase()===R.toLowerCase())?.[2])||"").slice(0,1e3);return{uuid:String(Ee(N.find(R=>Array.isArray(R)&&Ee(R[0])==="uuid")?.[1])||"").slice(0,1e3),name:re("Sheetname"),file:re("Sheetfile")}}):[];return this.mountView(w,{source:G,path:p,kind:be,design:qe,project:S,credentials:A,sheetLinks:me,inspectionModel:ve,inheritedFonts:$e,sourceSnapshot:te,sourceKey:Q,sourceParser:J,textVariables:T,worksheetSource:ae,textInstancePath:H},ee)}async setAnalysis(h){if(this.assertActive(),this.kind!=="pcb")throw new Error("Analysis results require a saved PCB design.");let p=++this.analysisTicket,w=this.source,S=this.design,A=()=>!this.disposed&&p===this.analysisTicket&&w===this.source&&S===this.design,{parseAnalysis:T,analysisSourceHash:H}=await Promise.resolve().then(()=>(od(),PM));if(!A())return!1;let Y=T(h);if(Y.fields.some(G=>G.layer&&!this.getLayers().includes(G.layer)))throw new TypeError("Analysis refers to a layer absent from the saved PCB.");let ee=await H(w);if(!A())return!1;if(ee!==Y.board.sha256)throw new Error("Analysis SHA-256 does not match the loaded saved PCB source.");let{createAnalysisLayer:X}=await Promise.resolve().then(()=>(NM(),IM));return A()?(this.analysis?.dispose(),this.analysis=X(this,Y),this.emit("analysis",{fields:Y.fields.map(({id:G,name:ae,unit:_e})=>({id:G,name:ae,unit:_e})),provenance:Y.provenance}),!0):!1}clearAnalysis(){this.assertActive(),++this.analysisTicket,this.analysis?.dispose(),this.analysis=null}setAnalysisField(h){if(this.assertActive(),!this.analysis)throw new Error("Load analysis results first.");this.analysis.setField(h)}getAnalysis(){return this.assertActive(),this.analysis?.data||null}getFiles(){return this.assertActive(),(this.project?.files||[]).map(({path:h,url:p})=>({path:h,url:p}))}getSheets(){return this.assertActive(),(this.kind==="schematic"?this.sheetLinks||[]:[]).map(h=>{let p=(this.path||"").split("/").slice(0,-1),w=!!h.file&&!/[\\\x00-\x1f\x7f%?#:]/.test(h.file)&&!h.file.startsWith("/");for(let A of h.file.split("/"))A===".."?p.length?p.pop():w=!1:A&&A!=="."&&p.push(A);let S=p.join("/");return{...h,path:w&&this.project?.files.some(A=>A.path===S&&/\.kicad_sch$/i.test(S))?S:null}})}openFile(h,p={}){return this.assertActive(),!this.project?.memory&&!Ja(h)||!this.project?.files.some(w=>w.path===h)?Promise.reject(new Error("Choose a file from the loaded project.")):this.project.memory?this.runOperation(p.signal,w=>this.showFileSet(this.project.files,{textVariables:this.textVariables,worksheetSource:this.worksheetSource,projectSettings:this.project.settings,...p,file:h},w)):this.loadInput({files:this.project.files,entry:h,worksheet:this.project.worksheet},{credentials:this.credentials,textVariables:this.textVariables,worksheetSource:this.worksheetSource,...p},this.project)}createControls(){this.chrome=LS(this);for(let h of["toolbar","fileSelect","layoutButton","threeButton","fitButton","themeButton","layersMenu","layerList","notesButton","measureButton","inspectorButton"])this[h]=this.chrome[h]}updateControls(){this.chrome.update(),this.inspector?.refreshLayers(),this.analysis?.sync()}setInspectOnSelect(h){if(this.assertActive(),typeof h!="boolean")throw new TypeError("inspectOnSelect must be a boolean.");this.inspectOnSelect=h,this.inspector?.autoInspect&&(this.inspector.autoInspect.checked=h)}setInspectorOpen(h){this.assertActive(),this.inspector.toggle(h)}getSelection(){return this.assertActive(),this.inspector.getSelection()}getSelectionPosition(){return this.assertActive(),this.inspector.getSelectionPosition()}selectObject(h,p){return this.assertActive(),this.inspector.selectObject(h,p)}getParts(){return this.assertActive(),this.inspector.getParts()}selectPart(h,p){return this.assertActive(),this.inspector.selectPart(h,p)}selectClass(h,p){if(this.assertActive(),!["net","component"].includes(h)||typeof p!="string")throw new TypeError("Choose a saved net or component class.");return this.inspector.selectClass(h,p)}subscribePartHover(h){return this.partHoverListeners??=new Set,this.partHoverListeners.add(h),this.renderer&&(this.renderer.partHoverEnabled=!0),()=>{this.partHoverListeners.delete(h),this.renderer&&(this.renderer.partHoverEnabled=this.partHoverListeners.size>0)}}hoverBomParts(h){this.renderer?.setPartHover?.(h.slice(0,50).flatMap(p=>this.inspector.partGeometry(p)))}getNets(){return this.assertActive(),this.inspector.getNets()}selectNet(h,p){return this.assertActive(),this.inspector.selectNet(h,p)}handleSelection(h,p=this.view){if(this.disposed)return;this.inspector.select(h.item);let w=this.inspector.getSelection();this.emit("select",{...h,item:h.item&&w?{...h.item,...w}:h.item,path:this.path,view:p})}clearSelection(){this.assertActive(),this.view!=="3d"&&this.view!=="manufacturing"&&this.renderer?.select?this.renderer.select(null):(this.renderer?.clearSelection?.(),this.renderer?.setSelection?.({}),this.handleSelection({item:null}))}updateStatus(){let h=[...this.design?.warnings||[],...this.project?.notes||[],...this.renderingNotes];this.view==="3d"&&!this.renderingNotes.length&&h.push("3D material preview; unresolved component models may use approximate stand-ins."),this.chrome.setStatus([...new Set([...h,...this.inspector.getWarnings()])])}validateView(h,p=this.kind){if(p==="manufacturing"){if(h!=="manufacturing")throw new TypeError("Manufacturing layers support the manufacturing view only.");return}if(!["schematic","pcb","3d"].includes(h)||(p==="schematic"?h!=="schematic":h==="schematic"))throw new TypeError("Use schematic for a schematic file, or pcb / 3d for a board file.")}setView(h,{signal:p}={}){return this.runOperation(p,w=>{if(!this.source)throw new Error("Load a design first.");return this.validateView(h),this.mountView(h,null,w)})}async mountView(h,p,w){w.stage?.(h==="3d"?"Preparing 3D view\xE2\u20AC\xA6":"Preparing drawing view\xE2\u20AC\xA6");let S=h==="3d"?await yh(dU(),w.signal):null,A=h==="manufacturing"?await yh(Promise.resolve().then(()=>(kv(),Lv)),w.signal):null;if(!w.current())return!1;w.check();let T=p||this,H=Symbol("mounted renderer"),Y=new AbortController,ee=this.host.ownerDocument.createElement("div");ee.style.cssText="position:absolute;inset:0;min-height:0;overflow:hidden;visibility:hidden",this.stage.append(ee);let X,G=[],ae=()=>!this.disposed&&this.rendererToken===H;try{if(S){let _e=new Map((T.project?.files||[]).filter(he=>/\.(wrl|glb)$/i.test(he.path)).map(he=>[he.path,he.url])),J=Y.signal,Q=T.credentials,te=_e.size?{assetPaths:[..._e.keys()],loadAsset:he=>_e.has(he)?SS(_e.get(he),{signal:J,credentials:Q}):void 0}:{};X=S.mountBoard3D(ee,T.source,{...this.modelOptions,...te,...this.modelOptions.loadAsset?{loadAsset:this.modelOptions.loadAsset}:{},sourceSnapshot:T.sourceSnapshot,sourceKey:T.sourceKey,sourceParser:T.sourceParser,boardPath:T.path,dark:this.theme==="dark",embedded:!0,externalInspector:!0,onAppearanceChange:he=>{ae()&&(this.modelOptions.appearance=he,this.updateControls())},onExplodeChange:he=>{ae()&&this.emit("expandchange",{amount:he,path:this.path,view:"3d"})},onLayersChange:()=>{ae()&&(this.updateControls(),this.emit("layerschange",this.getLayerState()))},onDiagnostics:he=>{G=he,ae()&&(this.renderingNotes=G,this.updateStatus())},onSelect:he=>{ae()&&this.handleSelection({item:he},"3d")},onAnalysisProbe:he=>{ae()&&this.emit("analysisprobe",{probe:he,path:this.path,view:"3d"})}})}else h==="manufacturing"?(X=A.mountManufacturing(ee,{dark:this.theme==="dark"}),X.setDocument(T.design),X.addEventListener("kicad:select",_e=>{ae()&&this.handleSelection(_e.detail,h)}),X.addEventListener("measure",_e=>{ae()&&this.emit("measure",_e.detail)})):(X=globalThis.KiCadOwnedCanvas.mount(ee,{pcb:h==="pcb",dark:this.theme==="dark",loadFontDecoder:()=>Promise.resolve().then(()=>Vn(kM(),1)).then(_e=>_e.default.decompress),onFontWarning:()=>{ae()&&this.updateStatus()}}),X.setDocument(T.design,T.path,T.inheritedFonts),X.partHoverEnabled=!!this.partHoverListeners?.size,X.addEventListener("kicad:parthover",_e=>{if(!ae())return;let J=this.inspector.partIdentity(_e.detail);for(let Q of this.partHoverListeners||[])Q(J)}),X.addEventListener("kicad:select",_e=>{ae()&&this.handleSelection(_e.detail,h)}));if(!w.current())return X.dispose(),Y.abort(),ee.remove(),!1;w.check()}catch(_e){throw X?.dispose(),Y.abort(),ee.remove(),_e}if(this.source&&this.renderer&&this.viewMemory.remember(this),this.rendererToken=H,this.assetController?.abort(),this.stopCamera?.(),this.renderer?.dispose(),p){this.clearAnalysis();let{inspectionModel:_e,...J}=p;Object.assign(this,J),this.inspector.setModel(_e)}return this.assetController=Y,this.renderer=X,this.view=h,this.renderingNotes=G,ee.style.visibility="",this.stage.replaceChildren(ee),this.analysis?.attach(),this.viewMemory.restore(this),this.inspector.syncRenderer(),this.bindCamera(),this.updateControls(),this.updateStatus(),h==="3d"&&this.design.releaseZonePoints?.(),this.emit("ready",{view:h,path:this.path,revision:this.project?.revision||null,warnings:[...this.design.warnings||[]]}),this.emit("viewchange",{view:h,path:this.path}),this.reportCamera(),!0}setRenderQuality(h){if(this.assertActive(),!["low","balanced","high","presentation","photoreal-fast"].includes(h))throw new TypeError("Choose low, balanced, high, presentation or photoreal-fast rendering.");if(this.view!=="3d"||typeof this.renderer?.setQuality!="function")throw new Error("Rendering quality requires a loaded 3D view.");return this.renderer.setQuality(h)}setExpand(h,{animate:p=!0}={}){if(this.assertActive(),!Number.isFinite(h)||h<0||h>100)throw new TypeError("Expand must be a number from 0 to 100.");if(typeof p!="boolean")throw new TypeError("animate must be a boolean.");if(this.view!=="3d"||!(this.renderer?.setExpand||this.renderer?.setExplode))throw new Error("Expand requires a loaded 3D board.");if(!p){if(typeof this.renderer.restoreExpand!="function")throw new Error("This renderer cannot restore expansion immediately.");return this.renderer.restoreExpand(h)}return(this.renderer.setExpand||this.renderer.setExplode).call(this.renderer,h)}getExpand(){return this.assertActive(),this.view==="3d"?this.renderer?.getExpand?.()??this.renderer?.getExplode?.()??0:0}setExplode(h){return m.prototype.setExpand.call(this,h)}getExplode(){return m.prototype.getExpand.call(this)}setAppearance(h){if(this.assertActive(),!["realistic","layers","translucent"].includes(h))throw new TypeError("Choose realistic, layers or translucent appearance.");if(this.view!=="3d"||typeof this.renderer?.setAppearance!="function")throw new Error("Appearance requires a loaded 3D view.");return this.modelOptions.appearance=this.renderer.setAppearance(h)}getAppearance(){return this.assertActive(),this.view==="3d"?this.renderer?.getAppearance?.()??null:null}getRenderStats(){this.assertActive();let h=this.view==="3d"?this.renderer?.getRenderStats?.():null;if(h==null)return null;let p=structuredClone(h);return this.design?.zonePointStats&&(p.zonePointCache=this.design.zonePointStats()),p}setCamera3D(h){if(this.assertActive(),this.view!=="3d")throw new Error("Named 3D cameras require the 3D view.");if(h&&typeof h=="object"){if(typeof this.renderer?.setCameraState!="function")throw new Error("3D camera restoration is unavailable.");return this.renderer.setCameraState(h)}if(!["top","bottom","front","back","left","right","isometric"].includes(h))throw new TypeError("Choose a named 3D camera preset.");if(typeof this.renderer?.setView!="function")throw new Error("Named 3D cameras are unavailable in this renderer.");return this.renderer.setView(h)}pickDemoFace(h={}){return this.assertActive(),this.view!=="3d"||typeof this.renderer?.pickDemoFace!="function"?Promise.reject(new Error("Choose the 3D view before selecting a demo face.")):this.renderer.pickDemoFace(h)}rotate3D(h,p=15){this.assertActive();let w=this.getCamera3D();if(!w)throw new Error("Rotation requires a loaded 3D view.");return this.setCamera3D(GE(w,h,p))}getCamera3D(){return this.assertActive(),this.view==="3d"&&this.renderer?.getCameraState?.()||null}getCamera(){this.assertActive();let h=this.renderer?.viewport?.camera;return!["pcb","schematic"].includes(this.view)||!h||![h.center?.x,h.center?.y,h.zoom].every(Number.isFinite)?null:{center:{x:h.center.x,y:h.center.y},zoom:h.zoom,flipped:!!h.flipped}}setCamera(h){if(this.assertActive(),!this.getCamera())throw new Error("Programmable camera requires the PCB or schematic 2D view.");if(!h||![h.center?.x,h.center?.y,h.zoom].every(w=>typeof w=="number"&&Number.isFinite(w))||Math.abs(h.center.x)>1e6||Math.abs(h.center.y)>1e6||h.zoom<.001||h.zoom>1e4||typeof h.flipped!="boolean")throw new TypeError("Choose finite camera coordinates, a zoom from .001 to 10000 and a boolean flipped state.");let p=this.renderer.viewport.camera;p.center.x=h.center.x,p.center.y=h.center.y,p.zoom=h.zoom,p.flipped=h.flipped,this.renderer.draw(),this.reportCamera()}reportCamera(){if(this.disposed)return;let h=this.getCamera();if(!h)return;let p=JSON.stringify([this.path,this.view,h]);p!==this.cameraSignature&&(this.cameraSignature=p,this.emit("camerachange",{view:this.view,path:this.path,camera:h}))}bindCamera(){this.stopCamera?.(),this.cameraSignature=null;let h=this.renderer,p=()=>{!this.disposed&&h===this.renderer&&this.reportCamera()};h?.addEventListener?.("kicad:viewframe",p),this.stopCamera=()=>h?.removeEventListener?.("kicad:viewframe",p)}fit(){this.assertActive(),this.view==="3d"?this.renderer?.fit():(this.renderer?.zoom_to_board(),this.renderer?.draw())}fitPage(){return this.assertActive(),!this.renderer?.zoom_to_page||!["pcb","schematic"].includes(this.view)?!1:(this.renderer.zoom_to_page(),this.renderer.draw(),this.reportCamera(),!0)}setTheme(h){if(this.assertActive(),!["light","dark"].includes(h))throw new TypeError("Theme must be light or dark.");this.theme=h,this.root.style.background=h==="dark"?"#111a24":"#f4f7fa",this.root.style.color=h==="dark"?"#e6e9ef":"#252c38",this.root.style.colorScheme=h,this.view==="3d"?this.renderer?.setTheme(h==="dark"):this.renderer&&(this.renderer.dark=h==="dark",this.renderer.draw()),this.chrome.setTheme(h),this.emit("themechange",{theme:h})}setMeasuring(h){if(this.assertActive(),this.view!=="manufacturing")throw new Error("Measurement requires manufacturing view.");this.renderer.setMeasuring(h),this.updateControls()}getLayers(){return this.assertActive(),[...this.design?.layers||[]]}setLayers(h){return rv(this,h)}getLayerState(){return eh(this)}setLayerPreset(h){return kE(this,h)}focusLayer(h,p){return OE(this,h,p)}clearLayerFocus(){return DE(this)}restoreLayerView(){return UE(this)}fitFocusedLayer(){return FE(this)}setHighlightStyle(h,p){return NE(this,h,p)}getHighlightStyle(){return this.assertActive(),{mode:this.highlightMode,color:this.highlightColor}}setInspectorWidth(h){return this.assertActive(),this.inspector.sizing.setWidth(h)}getPanelState(){return this.assertActive(),this.inspector.sizing.getState()}async openInset({sourceViewer:h=this,view:p,selection:w,target:S}={}){this.assertActive();let A=!S,T=A?this.floatingInsetRequest=(this.floatingInsetRequest||0)+1:null;A&&this.pendingFloatingInset?.dispose();let{ViewerInset:H}=await Promise.resolve().then(()=>(Fv(),FM));if(this.assertActive(),A&&T!==this.floatingInsetRequest)return null;let Y=null,ee=null;A&&(Y=this.host.ownerDocument.createElement("div"),Y.style.cssText="position:absolute;z-index:8;left:8px;bottom:8px;width:min(360px,calc(100% - 16px));height:min(420px,calc(100% - var(--viewer-toolbar-height,48px) - 16px));min-height:0",Y.style.visibility="hidden",S=Y,this.surface.append(Y));try{return ee=new H(S,{parent:this,sourceViewer:h,view:p,selection:w}),Y&&(this.pendingFloatingInset=ee),ee.addEventListener("dispose",()=>{Y?.remove(),this.pendingFloatingInset===ee&&(this.pendingFloatingInset=null),this.floatingInset===ee&&(this.floatingInset=null,this.pendingFloatingInset&&(++this.floatingInsetRequest,this.pendingFloatingInset.dispose()))},{once:!0}),!await ee.ready||Y&&T!==this.floatingInsetRequest?(ee.dispose(),null):(Y&&(this.pendingFloatingInset=null,this.floatingInset?.dispose(),this.floatingInset=ee,Y.style.visibility="",this.setInspectorOpen(!1)),ee)}catch(X){if(ee?.dispose(),Y?.remove(),Y&&T!==this.floatingInsetRequest)return null;throw X}finally{this.pendingFloatingInset===ee&&(this.pendingFloatingInset=null)}}dispose(){this.disposed||(this.clearAnalysis(),this.stopCamera?.(),this.stopCamera=null,this.disposed=!0,this.emit("dispose",null),this.loading.dispose(),++this.generation,this.pending?.abort(),this.assetController?.abort(),this.renderer?.dispose(),this.sourceSnapshot=this.sourceKey=this.sourceParser=null,this.partHoverListeners?.clear(),this.inheritedFonts=void 0,this.worksheetSource=void 0,this.viewMemory.clear(),this.renderer=this.source=this.design=this.pending=this.project=null,this.inspector.dispose(),this.chrome.dispose(),this.root.remove(),Vi.delete(this.host))}}});var FM={};Ol(FM,{ViewerInset:()=>Fm});var zM,BM,Fm,Fv=Ui(()=>{Qu();zM=new WeakMap,BM=m=>m&&!m.disposed&&["pcb","schematic"].includes(m.kind)&&typeof m.source=="string"&&m.source.length,Fm=class extends EventTarget{constructor(h,{parent:p,sourceViewer:w=p,view:S,selection:A}={}){if(super(),!BM(p)||!BM(w))throw new TypeError("Insets require active, loaded KiCad viewers.");let T=typeof h=="string"?p.host.ownerDocument.querySelector(h):h;if(!T?.ownerDocument||!T.append)throw new TypeError("Choose an inset container.");let H=S||w.kind;if(!["pcb","schematic","3d"].includes(H)||w.kind==="schematic"&&H!=="schematic"||w.kind==="pcb"&&H==="schematic")throw new TypeError("Inset view must match its loaded drawing.");let Y=zM.get(p)||new Set;if(Y.size>=2)throw new Error("Close an inset before opening another (maximum two per parent).");this.parent=p,this.sourceViewer=w,this.disposed=!1,this.stops=[],this.slots=Y,Y.add(this),zM.set(p,Y);let ee=T.ownerDocument,X=(te,he)=>{let be=ee.createElement(te);return he!==void 0&&(be.textContent=he),be};this.root=X("section"),this.root.className="viewer-context-inset",this.root.setAttribute("aria-label","Contextual design preview"),this.root.style.cssText="display:flex;flex-direction:column;min-width:0;height:100%;min-height:0;overflow:hidden;border:1px solid var(--viewer-border,#40566a);border-radius:8px;background:var(--viewer-bar,#182330);color:var(--viewer-ink,#e1eaf3)";let G=X("header");G.style.cssText="display:flex;align-items:center;gap:4px;padding:2px 5px;height:34px;min-height:34px;flex:0 0 auto;font:12px/1 system-ui";let ae=X("strong",w.path.split("/").at(-1)||"Design preview");ae.style.cssText="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap";let _e=(te,he,be)=>{let De=X("button"),Ke=X("span");return De.type="button",De.title=te,De.setAttribute("aria-label",te),Ke.setAttribute("aria-hidden","true"),Ke.innerHTML='<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="'+he+'"/></svg>',De.append(Ke),De.style.cssText="appearance:none;display:inline-flex;align-items:center;justify-content:center;box-sizing:border-box;flex:0 0 30px;width:30px;height:30px;margin:0;padding:0;background:transparent;color:inherit;border:1px solid var(--viewer-border,#40566a);border-radius:5px;font:600 12px/1 system-ui;cursor:pointer",De.onclick=be,De};this.closeButton=_e("Close","M5 5l14 14M19 5 5 19",()=>this.dispose()),this.fitButton=_e("Fit selection","M8 3H3v5M16 3h5v5M21 16v5h-5M8 21H3v-5M8 8h8v8H8z",()=>this.focus()),G.append(ae,this.fitButton,this.closeButton),this.mount=X("div"),this.mount.style.cssText="flex:1;min-height:0;position:relative",this.root.append(G,this.mount),T.append(this.root);let J=[...new Set([p,w])].map(te=>({viewer:te,source:te.source,path:te.path,instancePath:te.textInstancePath})),Q=(te,he,be)=>{te.addEventListener(he,be),this.stops.push(()=>te.removeEventListener(he,be))};for(let te of J)Q(te.viewer,"dispose",()=>this.dispose()),Q(te.viewer,"ready",()=>{(te.viewer.source!==te.source||te.viewer.path!==te.path||te.viewer.textInstancePath!==te.instancePath)&&this.dispose()});this.ready=this.initialize(H,A).catch(te=>{throw this.dispose(),te})}async initialize(h,p){let{KiCadViewer:w}=await Promise.resolve().then(()=>(ld(),UM));if(this.disposed)return!1;let S=this.sourceViewer;this.viewer=new w(this.mount,{theme:this.parent.theme,inspectOnSelect:!1,highlightStyle:S.getHighlightStyle().mode,highlightColor:S.getHighlightStyle().color,...S.modelOptions}),this.viewer.root.setAttribute("data-inset","true");let A=J=>{this.disposed||this.viewer.setTheme(J.detail.theme)},T=J=>{this.disposed||this.viewer.setHighlightStyle(J.detail.mode,{color:J.detail.color})};this.parent.addEventListener("themechange",A),this.parent.addEventListener("highlightstylechange",T);let H=this.parent;this.stops.push(()=>H.removeEventListener("themechange",A),()=>H.removeEventListener("highlightstylechange",T));let Y=S.source,ee=S.path,X=S.textInstancePath;if(await this.viewer.loadSource(Y,{path:ee,view:h,textVariables:S.textVariables,project:S.project,instancePath:X}),this.disposed)return!1;if(S.disposed||S.source!==Y||S.path!==ee||S.textInstancePath!==X)return this.dispose(),!1;let G=[...new Set([this.parent,S,this.viewer])],ae=!1;for(let J of G){let Q=te=>{if(ae||this.disposed||!te.detail||te.detail.path!==void 0&&te.detail.path!==J.path||te.detail.view!==void 0&&te.detail.view!==J.view)return;ae=!0;let he=G.filter(be=>!be.disposed).map(be=>[be,be.inspectOnSelect]);for(let[be]of he)be.inspectOnSelect=!1;try{for(let be of G)be!==J&&!be.disposed&&Qc(J,be,J.getSelection()||te.detail.item);J!==this.viewer&&this.focus()}finally{for(let[be,De]of he)be.inspectOnSelect=De;ae=!1}};J.addEventListener("select",Q),this.stops.push(()=>J.removeEventListener("select",Q))}let _e=p===void 0?this.parent.getSelection():p;ae=!0;try{Qc(this.parent,this.viewer,_e),_e&&this.focus()}finally{ae=!1}return!0}focus(){if(this.disposed||!this.viewer||!this.viewer.source)return!1;let h=this.viewer,p=h.getSelection();return p?p.kind==="net"?h.selectNet(p.id||p.netName,{locate:!0}):p.kind==="part"?h.selectPart(p.uuid||p.id,{locate:!0}):h.selectObject(p.uuid||p.id,{locate:!0,pinNumber:p.pinNumber}):(h.fit(),!0)}dispose(){if(!this.disposed){this.disposed=!0;for(let h of this.stops)h();this.stops.length=0,this.viewer?.dispose(),this.closeButton.onclick=this.fitButton.onclick=null,this.root.remove(),this.slots.delete(this),this.parent=this.sourceViewer=null,this.dispatchEvent(new CustomEvent("dispose"))}}}});var Qv=$n((m8,Wm)=>{(m=>{"use strict";let A=ve=>/\.(wbk|raw|csv|tsv|html?|json|txt)$/i.test(ve),T=ve=>typeof ve=="number"?Number.isFinite(ve)?ve:null:typeof ve=="string"&&/^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/.test(ve.trim())&&Number.isFinite(Number(ve))?Number(ve):null;function H(ve,Ee){let me=[],N=[],re="",R=!1,$=0,V=()=>{if(N.length>=257||N.length===256&&re!=="")throw Error("Too many data columns.");if(++$>4e6)throw Error("Too many CSV cells; split the exported data.");N.push(re),re=""},O=()=>{if(V(),N.some(C=>C.trim())){if(me.length>=2e5)throw Error("Too many data rows; split this export into smaller files.");me.push(N)}N=[]};for(let C=0;C<ve.length;C++){let j=ve[C];j==='"'?R&&ve[C+1]==='"'?(re+='"',C++):R=!R:j===Ee&&!R?V():(j===`
`||j==="\r")&&!R?(j==="\r"&&ve[C+1]===`
`&&C++,O()):re+=j}if(R)throw Error("Incomplete quoted CSV field.");return(re||N.length)&&O(),me}function Y(ve,Ee=64){let me=ve.columns.map((R,$)=>$).filter(R=>ve.rows.some($=>T($[R])!==null));if(me.length<2)return null;let N=me[0],re=me.slice(1,Ee+1).map(R=>({name:ve.columns[R],points:ve.rows.map($=>({x:T($[N]),y:T($[R])})).filter($=>$.x!==null).map($=>({...$,y:$.y===null?NaN:$.y}))})).filter(R=>R.points.length);return re.length?{title:ve.title,xLabel:ve.columns[N],series:re}:null}function ee(ve,Ee){let me=ve.split(/\r?\n/,1)[0],N=/\.tsv$/i.test(Ee)?"	":me.includes(";")?";":me.includes("	")?"	":",",re=H(ve,N);if(!re.length)throw Error("The data file is empty.");for(;re[0].length>1&&re.every(O=>O.at(-1)==="");)for(let O of re)O.pop();let R=re.shift().map((O,C)=>O.trim()||"Column "+(C+1));if(R.length>256)throw Error("Too many data columns.");if(re.some(O=>O.length!==R.length))throw Error("CSV rows have different column counts.");if(re.length*R.length>4e6)throw Error("Too many CSV cells; split the exported data.");let $={title:Ee.split("/").at(-1),columns:R,rows:re},V=Y($,256);if(V)for(let O of V.series)O.signal=_e(O.name);return{kind:"Simulation / tabular data",tables:[$],plots:V?[V]:[],fields:[],warnings:V?[]:["No pair of numeric columns was found for a graph."]}}function X(ve){let Ee=[],me=0,N=(O,C,j,B)=>{if(Ee.length>=64||!Array.isArray(C)||C.length>2e5||!C.length)return;let W=j.slice(0,O==="Illustrative eye diagram"?512:64).filter(K=>Array.isArray(K.values)&&K.values.length===C.length).map(K=>({name:K.name,points:C.map((ge,Ne)=>({x:T(ge),y:T(K.values[Ne])})).filter(ge=>ge.x!==null).map(ge=>({...ge,y:ge.y===null?NaN:ge.y}))}));W.length&&Ee.push({title:O,xLabel:B,series:W})},re=(O,C,j)=>{if(!O||typeof O!="object"||j>18||++me>12e3||Ee.length>=64)return;if(Array.isArray(O)){for(let K of O.slice(0,100))K&&typeof K=="object"&&!Array.isArray(K)&&re(K,C,j+1);return}if(Array.isArray(O.times_s)){N(C||"Transient",O.times_s,Object.entries(O).filter(([K,ge])=>Array.isArray(ge)&&/_V$|_A$/.test(K)).map(([K,ge])=>({name:K,values:ge})),"Time (s)");for(let K of[...Array.isArray(O.loads)?O.loads:[],...Array.isArray(O.components)?O.components:[],...Array.isArray(O.thermal_nodes)?O.thermal_nodes:[]])K&&typeof K=="object"&&N((C||"Transient")+" \xB7 "+(K.reference||K.name||K.label||K.id||"component"),O.times_s,Object.entries(K).filter(([ge,Ne])=>Array.isArray(Ne)&&/_V$|_A$|temperature_c|power_W/.test(ge)).map(([ge,Ne])=>({name:ge,values:Ne})),"Time (s)")}if(Array.isArray(O.history)&&O.history.length&&O.history.length<=2e5&&O.history.some(K=>T(K?.time_s)!==null)){let K=O.history,ge=K.map(ne=>ne?.time_s),Ne=[...new Set(K.flatMap(ne=>Array.isArray(ne?.boards)?ne.boards.map((we,xe)=>we?.name??String(xe)):[]))].slice(0,32);for(let ne of Ne){if(Ee.length>=64)break;let we=K.map(Me=>(Array.isArray(Me?.boards)?Me.boards:[]).find((Ce,tt)=>(Ce?.name??String(tt))===ne)),xe=[...new Set(we.flatMap(Me=>Me?.temperatures_c&&typeof Me.temperatures_c=="object"?Object.keys(Me.temperatures_c):[]))].slice(0,60);N("Saved thermal transient \xB7 "+ne,ge,[...xe.map(Me=>({name:Me+" (\xB0C)",values:we.map(Ce=>Ce?.temperatures_c?.[Me])})),...["inlet_air_c","outlet_air_c"].filter(Me=>we.some(Ce=>T(Ce?.[Me])!==null)).map(Me=>({name:Me+" (\xB0C)",values:we.map(Ce=>Ce?.[Me])}))],"Time (s)");let ke=["power_w","air_heat_w","fixture_heat_w","stored_heat_w","energy_residual_w"].filter(Me=>we.some(Ce=>T(Ce?.[Me])!==null));ke.length&&Ee.length<64&&N("Saved thermal power \xB7 "+ne,ge,ke.map(Me=>({name:Me+" (W)",values:we.map(Ce=>Ce?.[Me])})),"Time (s)")}}let B=O.spatial_index,W=O.frames;if(B&&Array.isArray(W)&&W.length&&W.length<=2e5&&Array.isArray(B.x_centers_mm)&&Array.isArray(B.y_centers_mm)&&Array.isArray(B.cells)&&Array.isArray(B.layers)){let K=B.x_centers_mm.map(T),ge=B.y_centers_mm.map(T),Ne=B.cells,ne=B.layers;if(K.length&&ge.length&&K.length*ge.length<=1e6&&K.every(xe=>xe!==null)&&ge.every(xe=>xe!==null)&&Ne.length&&Ne.length<=1e6&&ne.length&&ne.length<=64&&B.active_cells_per_layer===Ne.length&&Ne.every(xe=>Array.isArray(xe)&&xe.length===2&&xe.every(Number.isSafeInteger)&&xe[0]>=0&&xe[0]<K.length&&xe[1]>=0&&xe[1]<ge.length)&&new Set(Ne.map(xe=>xe.join(","))).size===Ne.length&&W.every(xe=>T(xe?.time_s)!==null&&Array.isArray(xe.temperatures_c)&&xe.temperatures_c.length>=Ne.length*ne.length)&&K.length*ge.length*ne.length<=1e6)for(let xe=0;xe<ne.length&&Ee.length<64;xe++){let ke={type:"heatmap",title:"Saved thermal transient field \xB7 "+(ne[xe]?.name||ne[xe]?.id||xe),x:K,y:ge,cells:Ne,frames:W,layerIndex:xe,frameIndex:W.length-1,unit:"\xB0C",layerName:ne[xe]?.name,layerZmm:T(ne[xe]?.z_mm),zBasis:"front-depth"};ke.values=De(ke,ke.frameIndex),Ee.push(ke)}}if(Array.isArray(O.time_ui)&&Array.isArray(O.traces_v)&&N("Illustrative eye diagram",O.time_ui,O.traces_v.slice(0,512).map((K,ge)=>({name:"Trace "+(ge+1)+" (V)",values:K})),"Time (UI)"),Array.isArray(O.time_ns)&&Array.isArray(O.voltage_v)&&N("Saved step response",O.time_ns,[{name:"Voltage (V)",values:O.voltage_v}],"Time (ns)"),Array.isArray(O.segments)&&C.endsWith("path")){let K=0,ge=[],Ne=[];for(let ne of O.segments){let we=T(ne?.length_mm);if(we===null||we<0){ge.push({x:K,y:NaN}),Ne.push({x:K,y:NaN});continue}let xe=K+we/2;ge.push({x:xe,y:T(ne.impedance_ohm)??NaN}),Ne.push({x:xe,y:T(ne.screening_z0_ohm)??NaN}),K+=we}ge.length&&Ee.push({title:"Saved route impedance",xLabel:"Distance along path (mm)",series:[{name:"Reference-covered impedance (\u03A9)",points:ge},{name:"Ideal continuous-plane screening (\u03A9)",points:Ne}]})}if(Array.isArray(O.x_centers_mm)&&Array.isArray(O.y_centers_mm)&&Array.isArray(O.values_c)){let K=O.x_centers_mm.map(T),ge=O.y_centers_mm.map(T),Ne=O.values_c.map(ne=>Array.isArray(ne)?ne.map(T):ne);K.length&&ge.length&&K.length*ge.length<=1e6&&K.every(ne=>T(ne)!==null)&&ge.every(ne=>T(ne)!==null)&&Ne.length===ge.length&&Ne.every(ne=>Array.isArray(ne)&&ne.length===K.length)&&Ee.push({type:"heatmap",title:C.includes("board_thermal_view")?"Illustrative junction interpolation"+(C.endsWith(".top")?" \xB7 top":C.endsWith(".bottom")?" \xB7 bottom":""):"Saved board temperature field",x:K,y:ge,values:Ne,unit:"\xB0C",label:C})}for(let K of["rows","samples"])if(Array.isArray(O[K])&&O[K].length){let ge=O[K].filter(ne=>ne&&typeof ne=="object"&&!Array.isArray(ne)),Ne=["frequency_mhz","frequency_Hz","time_s"].find(ne=>ge.some(we=>T(we?.[ne])!==null));if(Ne){let ne=[...new Set(ge.flatMap(we=>Object.keys(we)))].filter(we=>we!==Ne&&ge.some(xe=>T(xe?.[we])!==null));N(C,ge.map(we=>we[Ne]),ne.slice(0,32).map(we=>({name:we,values:ge.map(xe=>xe[we])})),Ne)}}for(let[K,ge]of Object.entries(O))["values_c","points_mm","triangles","vertices","faces","traces_v","frames","spatial_index","history"].includes(K)||re(ge,C?C+"."+K:K,j+1)};re(ve,"",0);let R=ve?.mesh,$=ve?.result;if(Array.isArray(R?.points_mm)&&Array.isArray(R?.triangles)&&R.points_mm.length<=2e5&&R.triangles.length<=2e5&&R.points_mm.every(O=>Array.isArray(O)&&(O.length===2||O.length===3)&&O.slice(0,2).every(C=>T(C)!==null))&&R.triangles.every(O=>Array.isArray(O)&&O.length===3&&O.every(C=>Number.isSafeInteger(C)&&C>=0&&C<R.points_mm.length))){let O=R.points_mm.map(j=>j.map(T)),C=(j,B,W,K)=>{if(!Array.isArray(B)||B.length!==(W?R.points_mm.length:R.triangles.length))return;let ge=Array.isArray(R.triangle_layer)&&R.triangle_layer.length===R.triangles.length?[...new Set(R.triangle_layer.map(String))].slice(0,64):[null];for(let Ne of ge){if(Ee.length>=64)break;let ne=R.triangles.map((xe,ke)=>ke).filter(xe=>Ne===null||String(R.triangle_layer[xe])===Ne),we=(Array.isArray(ve.geometry?.layers)?ve.geometry.layers:[]).find(xe=>String(xe?.id)===Ne)?.name||Ne;Ee.push({type:"mesh-field",title:j+(we?" \xB7 "+we:""),points:O,triangles:ne.map(xe=>R.triangles[xe]),values:W?B:ne.map(xe=>B[xe]),nodal:W,unit:K,layerName:we,zBasis:typeof ve.geometry?.z_convention=="string"&&ve.geometry.z_convention.includes("positive Z down from the top copper surface")?"front-depth":void 0})}};C("Saved nodal potential",$?.potential_V,!0,"V"),C("Saved cell power",$?.cell_power_W,!1,"W"),Array.isArray($?.cell_J_A_mm2)&&C("Saved current density magnitude",$.cell_J_A_mm2.map(j=>{if(!Array.isArray(j)||![2,3].includes(j.length)||!j.every(W=>typeof W=="number"&&Number.isFinite(W)))return null;let B=Math.hypot(...j);return Number.isFinite(B)?B:null}),!1,"A/mm\xB2")}let V=ve?.bodies;if(Array.isArray(V)){let O=V.filter(C=>Array.isArray(C?.mesh?.vertices)&&Array.isArray(C.mesh?.faces)&&C.mesh.vertices.length<=2e5&&C.mesh.faces.length<=1e5&&C.mesh.vertices.every(j=>Array.isArray(j)&&j.length===3&&j.every(B=>T(B)!==null))&&C.mesh.faces.every(j=>Array.isArray(j)&&j.length===3&&j.every(B=>Number.isSafeInteger(B)&&B>=0&&B<C.mesh.vertices.length)));O.length&&Ee.push({type:"mechanical",title:"Saved mechanical meshes",bodies:O.slice(0,100).map(C=>({...C,mesh:{...C.mesh,vertices:C.mesh.vertices.map(j=>j.map(T))}})),unit:"mm"})}return Ee}function G(ve){if(!ve||typeof ve!="object"||Array.isArray(ve)||typeof ve.schema!="string"||!/^kicad_monkey\.(design|netlist)\./.test(ve.schema))return null;if(!["kicad_monkey.design.a0","kicad_monkey.netlist.a0"].includes(ve.schema))throw Error("Unsupported KiCad Monkey export schema: "+ve.schema.slice(0,100));let Ee=()=>{throw Error("Invalid KiCad Monkey a0 report. Expected saved components, nets and terminals.")},me=j=>j&&typeof j=="object"&&!Array.isArray(j),N=(j,B,W=!1)=>{let K=j[B];return K===void 0&&!W?"":((typeof K!="string"||K.length>16384||W&&!K)&&Ee(),K)};if((ve.generator!=="kicad_monkey"||!Array.isArray(ve.components)||!Array.isArray(ve.nets))&&Ee(),ve.components.length>2e4||ve.nets.length>2e4)throw Error("KiCad Monkey report exceeds 20,000 components or nets. Split the export.");let re=0,R=()=>{if(++re>2e5)throw Error("KiCad Monkey report exceeds 200,000 table rows. Split the export.")},$={title:"Components",columns:["Designator","Value","Footprint","Library reference","Description","Sheet"],rows:[]},V={title:"Component properties",columns:["Designator","Property","Value"],rows:[]};for(let j of ve.components){me(j)||Ee();let B=N(j,"designator",!0);if(R(),j.hierarchy!==void 0&&!me(j.hierarchy)&&Ee(),$.rows.push([B,N(j,"value"),N(j,"footprint"),N(j,"library_ref"),N(j,"description"),j.hierarchy?N(j.hierarchy,"sheet_path"):""]),j.parameters!==void 0){me(j.parameters)||Ee();for(let W of Object.keys(j.parameters))R(),W.length>16384&&Ee(),V.rows.push([B,W,N(j.parameters,W)])}}let O={title:"Nets",columns:["Name","Net class","Source sheets","Terminal count"],rows:[]},C={title:"Net terminals",columns:["Net","Designator","Pin","Pin name","Pin type"],rows:[]};for(let j of ve.nets){(!me(j)||!Array.isArray(j.terminals))&&Ee();let B=N(j,"name");if(R(),j.terminals.length>2e5-re)throw Error("KiCad Monkey report exceeds 200,000 table rows. Split the export.");let W="";if(j.source_sheets!==void 0&&((!Array.isArray(j.source_sheets)||j.source_sheets.length>1e3||j.source_sheets.some(K=>typeof K!="string"||K.length>16384))&&Ee(),W=j.source_sheets.join(" \xB7 "),W.length>16384))throw Error("KiCad Monkey net sheet list exceeds the display budget.");O.rows.push([B,N(j,"net_class"),W,j.terminals.length]);for(let K of j.terminals)R(),me(K)||Ee(),C.rows.push([B,N(K,"designator",!0),N(K,"pin",!0),N(K,"pin_name"),N(K,"pin_type")])}return{kind:"KiCad Monkey saved "+(ve.schema.includes(".design.")?"design":"netlist"),tables:[$,O,C,V].filter(j=>j.rows.length),plots:[],fields:[{path:"Export schema",value:ve.schema},{path:"Generator",value:ve.generator},{path:"Components",value:ve.components.length},{path:"Nets",value:ve.nets.length}],warnings:["Saved KiCad Monkey a0 export; connectivity is reported as supplied, not recomputed or validated against this project. Render graphs, indexes and SVG are not executed or imported."],savedSource:ve}}function ae(ve,Ee){let me=G(ve);if(me)return me;let N={kind:/\.wbk$/i.test(Ee)?"KiCad simulation workbook":"Saved analysis report",tables:[],plots:[],fields:[],warnings:[]},re=0,R=0,$=(V,O,C)=>{if(++re>4e3||C>32)return;if(V===null||typeof V!="object"){N.fields.push({path:O,value:V});return}if(Array.isArray(V)){if(V.length>2e5)throw Error("Too many analysis rows.");if(V.length&&V.every(W=>W&&typeof W=="object"&&!Array.isArray(W))){let W=[...new Set(V.slice(0,100).flatMap(K=>Object.keys(K).filter(ge=>K[ge]===null||typeof K[ge]!="object")))].slice(0,128);if(W.length){if((R+=W.length*V.length)>4e6)throw Error("Too many analysis table cells; split this export into smaller files.");let K={title:O,columns:W,rows:V.map(ge=>W.map(Ne=>ge[Ne]??""))};N.tables.push(K)}}for(let W=0;W<Math.min(V.length,100);W++)$(V[W],O+"["+W+"]",C+1);return}let j=V.x||V.frequency_hz||V.time_s,B=V.y||V.values;Array.isArray(j)&&Array.isArray(B)&&j.length===B.length&&j.length&&j.every(W=>T(W)!==null)&&B.every(W=>T(W)!==null)&&N.plots.push({title:O,xLabel:V.x_label||V.xLabel||(V.frequency_hz?"Frequency (Hz)":V.time_s?"Time (s)":"x"),series:[{name:V.name||V.y_label||V.yLabel||O,points:j.map((W,K)=>({x:T(W),y:T(B[K])}))}]});for(let[W,K]of Object.entries(V).sort(([ge],[Ne])=>(/schema|sha|source|status|coverage|findings|checks|assumptions|limit|warning/.test(ge)?-1:/mesh|values|samples|points|traces|bodies|field/.test(ge)?1:0)-(/schema|sha|source|status|coverage|findings|checks|assumptions|limit|warning/.test(Ne)?-1:/mesh|values|samples|points|traces|bodies|field/.test(Ne)?1:0)))$(K,O?O+"."+W:W,C+1)};return N.savedSource=ve,N.plots=X(ve),$(ve,"",0),re>4e3&&N.warnings.push("Property preview limited to 4000 fields; full source remains available."),/\.wbk$/i.test(Ee)&&(N.plots=[],N.warnings.push("This workbook stores simulation commands, signals and display settings, not waveform samples. Add a KiCad CSV export or saved SPICE raw data to view graphs.")),N}function _e(ve,Ee){let me=/^v\(([^(),]+)\)(\d+)?$/i.exec(ve),N=/^i\(([^(),]+)\)$/i.exec(ve);return me&&(!Ee||Ee==="voltage")?{expression:ve,quantity:"voltage",unit:"V",net:me[1],...me[2]?{run:me[2]}:{}}:N&&(!Ee||Ee==="current")?{expression:ve,quantity:"current",unit:"A",device:N[1]}:Ee==="voltage"&&!/[(),\s]/.test(ve)?{expression:ve,quantity:Ee,unit:"V",net:ve}:{expression:ve,quantity:Ee||null,unit:{time:"s",frequency:"Hz",current:"A",voltage:"V"}[Ee]||null}}function*J(ve,Ee=0,me=ve.length){for(;Ee<me;){let N=ve.indexOf(`
`,Ee);(N<0||N>me)&&(N=me);let re=ve.slice(Ee,N).trim();Ee=N+1,re&&(yield re)}}function Q(ve){if(/(?:^|\n)Binary:/i.test(ve))throw Error("Binary SPICE raw data is not supported. Export ASCII raw data or KiCad CSV.");let Ee=ve.search(/^Variables:[ \t]*\r?$/im),me=ve.search(/^Values:[ \t]*\r?$/im);if(Ee<0||me<=Ee)throw Error("Expected an ASCII SPICE raw file with Variables and Values sections.");if(Ee>1024*1024||me-Ee>1024*1024)throw Error("SPICE header exceeds the 1 MiB metadata budget.");let N=ve.slice(0,Ee),re=we=>{let xe=[...N.matchAll(new RegExp("^"+we+":[ \\t]*(.*)\\r?$","gim"))];if(xe.length!==1)throw Error("Missing or duplicate SPICE "+we+" header.");return xe[0][1].trim()},R=[re("No\\. Variables"),re("No\\. Points")],$=Number(R[0]),V=Number(R[1]),O=re("Flags").toLowerCase().split(/\s+/),C=O.includes("complex");if(O.length!==1||!["real","complex"].includes(O[0]))throw Error("Unsupported SPICE flags; export one padded real or complex plot.");if(!R.every(we=>/^\d+$/.test(we))||!$||$>256||!Number.isSafeInteger(V)||V<1||V>2e5||V*$*(C?2:1)>4e6)throw Error("Invalid or excessive SPICE dimensions.");let j=[];for(let we of J(ve,ve.indexOf(`
`,Ee)+1,me)){let xe=we.match(/^(\d+)\s+(\S+)\s+(\S+)(?:\s+(.*))?$/);if(j.length>=$||!xe||Number(xe[1])!==j.length)throw Error("Invalid SPICE variable declaration or index.");if(/\bdims=/.test(xe[4]||""))throw Error("Variable-specific SPICE dimensions are not supported.");j.push({name:xe[2],unit:xe[3],attributes:xe[4]||"",signal:_e(xe[2],xe[3])})}if($!==j.length||new Set(j.map(we=>we.name)).size!==$)throw Error("Invalid or duplicate SPICE variables.");let B=J(ve,ve.indexOf(`
`,me)+1),W=[];for(let we=0;we<V;we++){let xe=[];for(let ke=0;ke<$;ke++){let Me=B.next();if(Me.done)throw Error("Incomplete SPICE raw samples.");let Ce=Me.value;if(ke===0){let Ze=Ce.match(/^(\d+)\s+(.*)$/);if(!Ze||Number(Ze[1])!==we)throw Error("Invalid SPICE sample index.");Ce=Ze[2]}let tt=Ce.split(",").map(T);if(tt.some(Ze=>Ze===null)||tt.length!==(C?2:1))throw Error("Invalid SPICE sample value.");if(ke===0&&C&&tt[1]!==0)throw Error("Complex SPICE sweep axes are not supported; their imaginary values cannot be discarded.");ke===0?xe.push(tt[0]):xe.push(...tt)}W.push(xe)}if(!B.next().done)throw Error("Incomplete SPICE raw samples or trailing concatenated plots.");let K=[j[0].name+" ("+j[0].unit+")",...j.slice(1).flatMap(we=>C?[we.name+" real ("+we.unit+")",we.name+" imaginary ("+we.unit+")"]:[we.name+" ("+we.unit+")"])],ge={title:"SPICE waveform samples",columns:K,rows:W},Ne=[];for(let we=1;we<$;we++)for(let xe=0;xe<(C?2:1);xe++){let ke=1+(we-1)*(C?2:1)+xe;Ne.push({name:K[ke],signal:{...j[we].signal,component:C&&xe?"imaginary":"real"},points:W.map(Me=>({x:Me[0],y:Me[ke]}))})}let ne=[];for(let we of J(N)){if(ne.length>=4e3)throw Error("Too many SPICE metadata fields.");let xe=we.indexOf(":");ne.push({path:xe<0?"Header":we.slice(0,xe),value:xe<0?we:we.slice(xe+1).trim()})}return{kind:"ASCII SPICE simulation",tables:[ge],plots:Ne.length?[{title:ne.find(we=>we.path.toLowerCase()==="plotname")?.value||ge.title,xLabel:K[0],series:Ne}]:[],fields:ne,warnings:C?["Complex traces are displayed as real and imaginary components in their saved units."]:[]}}function te(ve){let Ee="",me=!1,N=!1;for(let re=0;re<ve.length;re++){let R=ve[re];if(me){Ee+=R,N?N=!1:R==="\\"?N=!0:R==='"'&&(me=!1);continue}if(R==='"')me=!0,Ee+=R;else if(R==="/"&&ve[re+1]==="/"){for(;re<ve.length&&ve[re]!==`
`;)re++;Ee+=`
`}else if(R==="/"&&ve[re+1]==="*"){let $=ve.indexOf("*/",re+2);if($<0)throw Error("Incomplete workbook comment.");re=$+1,Ee+=" "}else Ee+=R}return Ee}function he(ve){if(ve.trimStart().startsWith("{"))return JSON.parse(te(ve));let Ee=ve.replace(/\r/g,"").split(`
`),me=0,N=()=>{if(me>=Ee.length)throw Error("Incomplete legacy KiCad workbook.");return Ee[me++]},re=()=>{let C=Number(N());if(!Number.isInteger(C)||C<0||C>1e4)throw Error("Invalid legacy workbook count.");return C},R=1;if(/^version\s+\d+$/i.test(Ee[0])&&(R=Number(N().split(/\s+/)[1])),R<1||R>5)throw Error("Unsupported legacy workbook version.");let $=[];for(let C=0,j=re();C<j;C++){let B={simulation_type:re(),command:N(),traces:[],measurements:[]};for(let W=0,K=re();W<K;W++)B.traces.push({trace_type:re(),signal:N(),parameters:N()});if(R>4)for(let W=0,K=re();W<K;W++)B.measurements.push({expression:N(),format:N()});$.push(B)}let V=[];if(me<Ee.length&&Ee[me].trim())for(let C=0,j=re();C<j;C++)V.push(N());let O=R>=5&&me<Ee.length?N():"";return{version:R,tabs:$,user_defined_signals:V,last_sch_text_sim_command:O}}function be(ve,Ee){if(typeof Ee!="string"||new TextEncoder().encode(Ee).length>67108864)throw Error("Analysis file exceeds the 64 MiB viewer budget.");Ee=Ee.replace(/^\uFEFF/,"");let me;if(/\.(csv|tsv)$/i.test(ve))me=ee(Ee,ve);else if(/\.raw$/i.test(ve))me=Q(Ee);else if(/\.(json|wbk)$/i.test(ve))try{me=ae(/\.wbk$/i.test(ve)?he(Ee):JSON.parse(Ee),ve)}catch(N){throw N instanceof SyntaxError?Error("Unsupported or incomplete JSON workbook/report."):N}else if(/\.html?$/i.test(ve))me={kind:"Saved HTML report",fields:[],tables:[],plots:[],warnings:["Report scripts and external resources are never executed."],html:Ee};else if(/\.txt$/i.test(ve))me={kind:"Saved text report",fields:[{path:"Report text",value:Ee.slice(0,512e3)}],tables:[],plots:[],warnings:[]};else throw Error("Open a JSON report, KiCad .wbk, CSV/TSV export, HTML report or ASCII SPICE .raw file.");return{...me,path:ve,title:ve.split("/").at(-1)}}function De(ve,Ee){let me=ve.frames?.[Ee];if(!me||!Number.isSafeInteger(Ee))return null;let N=ve.y.map(()=>ve.x.map(()=>null));return ve.cells.forEach(([re,R],$)=>{N[R][re]=T(me.temperatures_c[ve.layerIndex*ve.cells.length+$])}),N}function Ke(ve,Ee){let me=ve[Ee],N=ve[Ee-1],re=ve[Ee+1];if(ve.length===1)return[me-.5,me+.5];let R=N===void 0?me+(me-re)/2:(N+me)/2,$=re===void 0?me+(me-N)/2:(re+me)/2;return[Math.min(R,$),Math.max(R,$)]}function qe(ve,Ee,me,N){if(!Number.isFinite(Ee)||!ve)return null;if(ve.series){let re=ve.series.find(C=>C.name===N)||ve.series[0];if(!re)return null;let R=null,$=1/0,V=1/0,O=-1/0;for(let C of re.points){if(!Number.isFinite(C.x))continue;V=Math.min(V,C.x),O=Math.max(O,C.x);let j=Math.abs(C.x-Ee);j<$&&(R=C,$=j)}return!R||Ee<V||Ee>O?null:{x:R.x,value:T(R.y),name:re.name,axis:ve.xLabel,method:"Nearest saved sample"}}if(!Number.isFinite(me))return null;if(ve.type==="heatmap"){let re=(V,O)=>{let C=-1,j=1/0;for(let B=0;B<V.length;B++){let[W,K]=Ke(V,B);O>=W&&O<=K&&Math.abs(V[B]-O)<j&&(C=B,j=Math.abs(V[B]-O))}return C},R=re(ve.x,Ee),$=re(ve.y,me);return R<0||$<0?null:{x:ve.x[R],y:ve.y[$],value:T(ve.values[$][R]),name:ve.title,unit:ve.unit,method:"Saved cell center"}}if(ve.type==="mesh-field")for(let re=0;re<ve.triangles.length;re++){let R=ve.triangles[re],[$,V,O]=R.map(ne=>ve.points[ne]),C=(V[1]-O[1])*($[0]-O[0])+(O[0]-V[0])*($[1]-O[1]);if(Math.abs(C)<1e-14)continue;let j=((V[1]-O[1])*(Ee-O[0])+(O[0]-V[0])*(me-O[1]))/C,B=((O[1]-$[1])*(Ee-O[0])+($[0]-O[0])*(me-O[1]))/C,W=1-j-B;if(Math.min(j,B,W)<-1e-9)continue;let K=ve.nodal?R.map(ne=>T(ve.values[ne])):[T(ve.values[re])],ge=K.some(ne=>ne===null)?null:ve.nodal?K[0]*j+K[1]*B+K[2]*W:K[0],Ne=[$,V,O].every(ne=>Number.isFinite(ne[2]))?$[2]*j+V[2]*B+O[2]*W:void 0;return{x:Ee,y:me,...Ne===void 0?{}:{z:Ne},value:ge,name:ve.title,unit:ve.unit,method:ve.nodal?"Interpolated saved nodes":"Saved cell value"}}return null}function $e(ve,Ee){return!ve||!Ee||ve.name!==Ee.name||ve.unit!==Ee.unit||ve.axis!==Ee.axis?null:{dx:Ee.x-ve.x,...Number.isFinite(ve.y)&&Number.isFinite(Ee.y)?{dy:Ee.y-ve.y,distance:Math.hypot(Ee.x-ve.x,Ee.y-ve.y)}:{},delta:ve.value===null||Ee.value===null?null:Ee.value-ve.value}}let Xe={parse:be,parseJSONValue:ae,candidate:A,numeric:T,delimited:H,tablePlot:Y,cellBounds:Ke,frameValues:De,probe:qe,probeDifference:$e,MAX_BYTES:67108864};m.KiCadAnalysisData=Xe,typeof Wm=="object"&&Wm.exports&&(Wm.exports=Xe)})(globalThis)});var iA=$n((g8,Xm)=>{(m=>{"use strict";let S=ae=>typeof ae=="number"&&Number.isFinite(ae)?ae:null,A=ae=>Array.isArray(ae)&&ae.length>=2&&ae.slice(0,2).every(_e=>S(_e)!==null)?{x:ae[0],y:ae[1]}:null,T=()=>m.KiCadAnalysisData||(typeof $c=="function"?Qv():null);function H(ae){if(!ae)return null;let _e={unit:ae.unit||"",title:ae.title||"",layer:ae.layerName,zBasis:ae.zBasis,points:[],triangles:[],values:[],nodal:!1,zKnown:!1};if(ae.type==="mesh-field")return!Array.isArray(ae.points)||!ae.points.length||ae.points.length>4e5||!Array.isArray(ae.triangles)||ae.triangles.length>2e5||!Array.isArray(ae.values)||ae.values.length!==(ae.nodal?ae.points.length:ae.triangles.length)||!ae.points.every(te=>A(te)&&(!(te.length>2)||S(te[2])!==null))||!ae.triangles.every(te=>Array.isArray(te)&&te.length===3&&te.every(he=>Number.isSafeInteger(he)&&he>=0&&he<ae.points.length))?null:(_e.points=ae.points.map(te=>[te[0],te[1],te.length>2?te[2]:S(ae.layerZmm)??0]),_e.triangles=ae.triangles.map(te=>te.slice()),_e.values=ae.values.map(S),_e.nodal=!!ae.nodal,_e.zKnown=ae.points.every(te=>te.length>2)||S(ae.layerZmm)!==null,_e);if(ae.type!=="heatmap"||!Array.isArray(ae.x)||!Array.isArray(ae.y)||!ae.x.length||!ae.y.length||ae.x.length*ae.y.length>1e6||!ae.x.every(te=>S(te)!==null)||!ae.y.every(te=>S(te)!==null)||!Array.isArray(ae.values)||ae.values.length!==ae.y.length||!ae.values.every(te=>Array.isArray(te)&&te.length===ae.x.length))return null;let J=T()?.cellBounds;if(!J)return null;let Q=S(ae.layerZmm)??0;_e.zKnown=S(ae.layerZmm)!==null;for(let te=0;te<ae.y.length;te++)for(let he=0;he<ae.x.length;he++){let be=S(ae.values[te][he]);if(be===null)continue;if(_e.triangles.length+2>2e5)return null;let[De,Ke]=J(ae.x,he),[qe,$e]=J(ae.y,te),Xe=_e.points.length;_e.points.push([De,qe,Q],[Ke,qe,Q],[Ke,$e,Q],[De,$e,Q]),_e.triangles.push([Xe,Xe+1,Xe+2],[Xe,Xe+2,Xe+3]),_e.values.push(be,be)}return _e}function Y(ae){let _e=[],J=0,Q=0,te=new WeakSet,he=($e,Xe)=>{if(_e.length>=1e4||!Array.isArray($e)||$e.length<3||$e.length>5e4||J+$e.length>2e5)return;let ve=$e.map(A);ve.some(Ee=>!Ee)||(J+=ve.length,_e.push({type:"polygon",kind:"saved-context",points:ve,color:Xe,width:.12,stroke:!0}))},be=($e,Xe)=>Array.isArray($e)?$e.slice(0,Xe):[],De=($e,Xe)=>{if(Array.isArray($e)){he($e,Xe);return}if(!(!$e||typeof $e!="object")){he($e.outer||$e.outer_mm,Xe);for(let ve of be($e.holes||$e.holes_mm,1e3))he(ve,Xe)}},Ke=$e=>{for(let Xe of(Array.isArray($e.outline)?$e.outline:[]).slice(0,1e3))De(Xe,"#a5b6bc");for(let Xe of be($e.layers,64))for(let ve of be(Xe?.polygons||Xe?.polygons_mm,1e4))De(ve,"#5f8079");for(let Xe of(Array.isArray($e.polygons)?$e.polygons:[]).slice(0,1e4))De(Xe,"#5f8079");for(let Xe of be($e.tracks,1e4)){let ve=A(Xe?.start_mm||Xe?.start),Ee=A(Xe?.end_mm||Xe?.end);ve&&Ee&&_e.length<1e4&&_e.push({type:"line",kind:"saved-context",points:[ve,Ee],width:Math.min(10,Math.max(.12,S(Xe.width_mm)??.12)),color:"#5f8079"})}for(let Xe of be($e.components,1e3)){let ve=Xe?.bbox_mm||Xe?.source_bbox_mm;Array.isArray(ve)&&ve.length===4&&ve.every(Ee=>S(Ee)!==null)&&he([[ve[0],ve[1]],[ve[2],ve[1]],[ve[2],ve[3]],[ve[0],ve[3]]],"#8296ac")}},qe=($e,Xe)=>{if(!(!$e||typeof $e!="object"||Xe>12||++Q>4e3||te.has($e)||Array.isArray($e))){te.add($e),Ke($e);for(let ve of["geometry","thermal_geometry","board_thermal_view","thermal_network","top","bottom","view","coupled","baseline","result"])qe($e[ve],Xe+1)}};return qe(ae,0),_e}function ee(ae){let _e=[],J=new Set,Q=0,te=(be,De)=>{if(typeof be!="string"||be.length>4096||/[\x00-\x1f]/.test(be)||!/\.kicad_pcb$/i.test(be)||typeof De!="string"||!/^\w{64}$/.test(De)||!/^[a-f0-9]{64}$/i.test(De))return;let Ke=De.toLowerCase(),qe=be+`
`+Ke;!J.has(qe)&&_e.length<32&&(J.add(qe),_e.push({path:be,sha256:Ke}))},he=(be,De)=>{if(!(!be||typeof be!="object"||Array.isArray(be)||De>12||++Q>4e3)){te(be.source_path,be.source_sha256),te(be.board_path,be.source_sha256),te(be.request?.board_path,be.source_sha256);for(let Ke of["geometry","thermal_geometry","baseline","coupled","result","report","thermal_network","electrical","thermal"])he(be[Ke],De+1)}};return he(ae,0),_e}function X(ae,_e,J){if(ae?.type!=="heatmap"||!Array.isArray(ae.frames)||!ae.frames.length||ae.frames.length>2e5||!Array.isArray(ae.cells)||!Array.isArray(ae.x)||!Array.isArray(ae.y)||!Number.isSafeInteger(ae.layerIndex)||ae.layerIndex<0)return null;let te=T()?.probe(ae,_e,J);if(!te)return null;let he=ae.x.indexOf(te.x),be=ae.y.indexOf(te.y),De=ae.cells.findIndex(qe=>qe[0]===he&&qe[1]===be);if(De<0)return null;let Ke=ae.frames.filter(qe=>S(qe?.time_s)!==null).map(qe=>({x:qe.time_s,y:S(qe.temperatures_c?.[ae.layerIndex*ae.cells.length+De])??NaN}));return Ke.length?{title:ae.title+" \xB7 probe ("+te.x+", "+te.y+" mm)",xLabel:"Time (s)",series:[{name:(ae.title||"Saved temperature")+" ("+(ae.unit||"\xB0C")+")",points:Ke}]}:null}let G={toSurface:H,contextGeometry:Y,sourceBindings:ee,pointHistory:X,MAX_TRIANGLES:2e5};m.KiCadAnalysisSpatial=G,typeof Xm=="object"&&Xm.exports&&(Xm.exports=G)})(globalThis)});var pA=$n((dA,Km)=>{(m=>{"use strict";let h=m.KiCadDesignDiff||(typeof $c=="function"?To():null),p=J=>J&&typeof J=="object"&&!Array.isArray(J)?J.quoted:J,w=J=>Array.isArray(J)?String(p(J[0])):"",S=(J,Q)=>Array.isArray(J)?J.filter(te=>w(te)===Q):[],A=(J,Q)=>S(J,Q)[0],T=(J,Q)=>p(A(J,Q)?.[1]);function H(J,Q){if(!Array.isArray(J)||J.length>1e5)throw new Error("BOM object limit exceeded.");let te=J.filter(qe=>(!Q||qe.path===Q)&&["symbol","footprint"].includes(qe.kind)),he=new Map;for(let qe of te){let $e=JSON.stringify([qe.path,qe.kind==="footprint"?qe.uuid||qe.id:qe.reference||qe.uuid||qe.id]);he.has($e)||he.set($e,qe)}let be=[...he.values()],De=be.filter(qe=>!qe.excludeFromBom),Ke=new Map;for(let qe of De){let $e=qe.properties||{},Xe=JSON.stringify([$e.Value||"",$e.Footprint||$e["Library ID"]||"",qe.populated!==!1]);Ke.has(Xe)||Ke.set(Xe,{value:$e.Value||"",footprint:$e.Footprint||$e["Library ID"]||"",populated:qe.populated!==!1,parts:[]}),Ke.get(Xe).parts.push(qe)}return{parts:be,groups:[...Ke.values()].sort((qe,$e)=>qe.value.localeCompare($e.value)),total:be.length,fitted:be.filter(qe=>qe.populated!==!1).length,dnp:be.filter(qe=>qe.populated===!1).length,excluded:be.length-De.length,eligible:De.length}}function Y(J){let Q=he=>{let be=String(he??"");return/^[\s]*[=+@-]/.test(be)&&(be="'"+be),'"'+be.replace(/"/g,'""')+'"'},te=[["Reference","Value","Footprint","Population","File"]];for(let he of J.groups)for(let be of he.parts)te.push([be.reference||"",he.value,he.footprint,he.populated?"Fitted":"DNP",be.path]);return te.map(he=>he.map(Q).join(",")).join(`\r
`)+`\r
`}function ee(J){if(!Array.isArray(J)||J.length<3)return null;let Q=0;for(let te=0;te<J.length;te++){let he=J[te],be=J[(te+1)%J.length];if(![he.x,he.y,be.x,be.y].every(Number.isFinite)||[he.x,he.y,be.x,be.y].some(De=>Math.abs(De)>1e5))return null;Q+=he.x*be.y-be.x*he.y}return Math.abs(Q)/2}let X=(J,Q)=>{let te=A(J,Q);return{x:Number(p(te?.[1])),y:Number(p(te?.[2]))}},G=J=>J&&[J.x,J.y].every(Q=>Number.isFinite(Q)&&Math.abs(Q)<=1e5);function ae(J,Q,te){if(![J,Q,te].every(G))return null;let he=Q.x-J.x,be=Q.y-J.y,De=te.x-J.x,Ke=te.y-J.y,qe=2*(he*Ke-be*De);if(Math.abs(qe)<=1e-12*Math.max(1,Math.hypot(he,be)*Math.hypot(De,Ke)))return null;let $e=he*he+be*be,Xe=De*De+Ke*Ke,ve=($e*Ke-Xe*be)/qe,Ee=(he*Xe-De*$e)/qe,me=Math.hypot(ve,Ee),N=2*Math.PI,re=j=>(j%N+N)%N,R=Math.atan2(-Ee,-ve),$=Math.atan2(be-Ee,he-ve),V=Math.atan2(Ke-Ee,De-ve),O=re(V-R),C=me*(re($-R)<=O?O:N-O);return Number.isFinite(C)?C:null}function _e(J){if(typeof J!="string"||new TextEncoder().encode(J).length>8*1024*1024)throw new Error("Board analytics source exceeds 8 MiB.");let Q=h.parse(J);if(w(Q)!=="kicad_pcb")throw new Error("Board analytics requires a saved PCB.");let te=W=>S(Q,W).length,he=S(Q,"footprint"),be=0,De=0,Ke=0,qe=0,$e=0;for(let W of he)for(let K of S(W,"pad")){be++,A(K,"drill")&&De++;let ge=String(p(K[2]));ge==="smd"&&Ke++,(ge==="thru_hole"||ge==="np_thru_hole")&&qe++}let Xe=0,ve=[],Ee=new Map,me=[],N=new Map(S(Q,"net").map(W=>[String(p(W[1])),String(p(W[2])||"")])),re=new Map,R=new Map,$=0,V=0;for(let W of["segment","arc"])for(let K of S(Q,W)){let ge=X(K,"start"),Ne=X(K,"end"),ne=W==="arc"?ae(ge,X(K,"mid"),Ne):G(ge)&&G(Ne)?Math.hypot(Ne.x-ge.x,Ne.y-ge.y):null;if(ne===null){V++;continue}W==="arc"?$+=ne:$e+=ne;let we=A(K,"net"),xe=T(K,"net"),ke=Number(T(Q,"version"))>=20260206&&typeof xe=="string"&&we?.length===2,Me=ke?`name:${xe}`:String(xe??"0"),Ce=String(T(K,"layer")||"Unspecified");re.has(Me)||re.set(Me,{code:Me,name:ke?xe||"Unassigned":N.get(Me)||(Me==="0"?"Unassigned":`Net ${Me}`),lengthMm:0,segments:0,arcs:0});let tt=re.get(Me);tt.lengthMm+=ne,tt[W==="arc"?"arcs":"segments"]++,R.set(Ce,(R.get(Ce)||0)+ne)}V&&ve.push(`${V} malformed or unsupported tracks omitted from lengths.`);let O=[],C=!1;for(let W of Q.filter(K=>w(K).startsWith("gr_")&&T(K,"layer")==="Edge.Cuts")){let K=[];["gr_line","gr_rect"].includes(w(W))?K=[X(W,"start"),X(W,"end")]:w(W)==="gr_poly"?K=S(A(W,"pts"),"xy").map(ge=>({x:Number(p(ge[1])),y:Number(p(ge[2]))})):C=!0,!K.length||!K.every(G)?C=!0:O.push(...K)}let j=null;if(O.length&&!C){j={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};for(let W of O)j.minX=Math.min(j.minX,W.x),j.maxX=Math.max(j.maxX,W.x),j.minY=Math.min(j.minY,W.y),j.maxY=Math.max(j.maxY,W.y)}let B=[];for(let W of he){let K=X(W,"at"),ge=[];G(K)?(K.x===0&&K.y===0&&ge.push("Footprint origin at (0, 0)"),j&&(K.x<j.minX||K.x>j.maxX||K.y<j.minY||K.y>j.maxY)&&ge.push("Footprint origin outside Edge.Cuts envelope")):ge.push("No valid saved position"),ge.length&&B.push({uuid:T(W,"uuid")||T(W,"tstamp")||null,reference:String(p(S(W,"property").find(Ne=>p(Ne[1])==="Reference")?.[2])||p(S(W,"fp_text").find(Ne=>p(Ne[1])==="reference")?.[2])||""),position:G(K)?K:null,reasons:ge})}C&&ve.push("Edge.Cuts envelope unavailable: curved or unsupported edge geometry.");for(let[W,K]of S(Q,"zone").entries()){let ge={index:W,uuid:T(K,"uuid")||T(K,"tstamp")||null,name:String(T(K,"name")||T(K,"net_name")||`Zone ${W+1}`),layers:[],outlineAreaMm2:0,fillAreaMm2:0,valid:!0};for(let[Ne,ne]of[["polygon","outlineAreaMm2"],["filled_polygon","fillAreaMm2"]])for(let we of S(K,Ne)){let xe=S(A(we,"pts"),"xy").map(Me=>({x:Number(p(Me[1])),y:Number(p(Me[2]))}));if(Xe+=xe.length,Xe>2e5)throw new Error("Zone analytics exceeds 200,000 polygon points.");let ke=ee(xe);if(ke===null){ge.valid=!1,ve.push(`Zone ${W+1}: invalid polygon omitted.`);continue}if(ge[ne]+=ke,Ne==="filled_polygon"){let Me=String(T(we,"layer")||T(K,"layer")||"Unspecified");ge.layers.includes(Me)||ge.layers.push(Me),Ee.set(Me,(Ee.get(Me)||0)+ke)}}S(K,"filled_polygon").length||ve.push(`Zone ${W+1}: no saved filled polygons.`),me.push(ge)}return{footprints:he.length,pads:be,drilledPads:De,smdPads:Ke,throughHolePads:qe,segments:te("segment"),arcs:te("arc"),vias:te("via"),zones:me,straightTrackLengthMm:$e,arcTrackLengthMm:$,totalTrackLengthMm:$e+$,omittedTracks:V,netTracks:[...re.values()].sort((W,K)=>K.lengthMm-W.lengthMm),layerTracks:[...R].map(([W,K])=>({layer:W,lengthMm:K})),edgeBounds:j,placementCandidates:B,boardThicknessMm:Number(T(A(Q,"general"),"thickness"))||null,layerFill:[...Ee].map(([W,K])=>({layer:W,areaMm2:K})),warnings:ve,limits:"Areas are sums of absolute shoelace areas of saved straight-edge polygons; overlaps are counted repeatedly and hole contours are not subtracted. They are not copper union, material mass, clearance checks or a fresh zone fill. Track lengths are saved segment and circular-arc centreline sums, not point-to-point electrical lengths; vias add no length. Placement candidates require review, not confirmed unplaced components; coordinates and envelope do not prove placement intent or containment. BOM counts saved file/reference identities; reused sheet instances are not expanded."}}m.KiCadBomAnalytics={bom:H,board:_e,polygonArea:ee,arcLength:ae,csv:Y},typeof Km=="object"&&Km.exports&&(Km.exports=m.KiCadBomAnalytics)})(typeof globalThis<"u"?globalThis:dA)});Fv();ld();sd();Tm();ld();Ul();var pU="https://viewer.altium.com/client/static/js/embed.js",zv=Object.freeze({schematic:"sch",pcb:"pcb","3d":"3d",bom:"bom"}),fU=["schematic","pcb","3d","bom"],mU=m=>String(m).replace(/[&<>"']/g,h=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[h]);function jM(m,h){if(!Array.isArray(h)||!h.length||h.length>4||h.some(p=>!Object.hasOwn(zv,p))||new Set(h).size!==h.length||h.every(p=>p==="bom"))throw new TypeError("Choose schematic, pcb, 3d and optionally bom views.");if(!["schematic","pcb","3d"].includes(m)||!h.includes(m))throw new TypeError("The initial view must be an enabled schematic, pcb or 3d view.");return{view:m,views:[...h]}}function gU(m,h){let p=new URL(m,h);if(p.protocol!=="https:"||p.username||p.password)throw new TypeError("Use a public HTTPS archive URL without embedded credentials.");if(!/\.(zip|rar|7z)$/i.test(p.pathname))throw new TypeError("The Altium beta expects a publicly hosted .zip, .rar or .7z project archive.");let w=p.hostname.toLowerCase();if(w==="localhost"||w.endsWith(".localhost")||w.endsWith(".local")||w.includes(":")||/^\d+(?:\.\d+){3}$/.test(w))throw new TypeError("Use a public hostname reachable by Altium, rather than a local address or IP literal.");return p.href}function yU(m,{view:h,views:p}){return`<!doctype html><html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Altium 365 beta viewer</title><style>
html,body{height:100%;width:100%;margin:0}body{font:13px/1.4 system-ui}
.altium-ecad-viewer{height:100%;width:100%;box-sizing:border-box;overflow:hidden}
#error{padding:12px;color:#842828}
</style></head><body>
<div class="altium-ecad-viewer" data-project-src="${mU(m)}"
 data-enabled-views="${p.map(w=>zv[w]).join(",")}"
 data-active-view="${zv[h]}" data-src-type="Design" data-project-outputs="none">
<a href="https://www.altium365.com/viewer/">PCB File Viewer by Altium</a>
</div><div id="error" role="alert" hidden></div>
<script src="${pU}" onerror="document.getElementById('error').hidden=false;document.getElementById('error').textContent='Altium viewer could not load. Check network access and your site content policy.';parent.postMessage({type:'altium-beta:script-error'},'*')"
 onload="parent.postMessage({type:'altium-beta:script-loaded'},'*')"><\/script>
</body></html>`}var Bv=class extends EventTarget{constructor(h,{view:p="schematic",views:w=fU}={}){super();let S=typeof h=="string"?document.querySelector(h):h;if(!S?.append||!S?.ownerDocument?.defaultView)throw new TypeError("Choose a viewer container in a browser document.");if(Vi.has(S))throw new Error("This container already has a viewer.");let A=jM(p,w);this.host=S,this.window=S.ownerDocument.defaultView,this.view=A.view,this.views=A.views,this.disposed=!1,this.frame=null,this.url=null,this.root=S.ownerDocument.createElement("div"),this.root.style.cssText="display:flex;flex-direction:column;width:100%;height:100%;min-height:0;overflow:hidden",this.stage=S.ownerDocument.createElement("div"),this.stage.style.cssText="flex:1;min-height:0;position:relative",this.status=S.ownerDocument.createElement("div"),this.status.setAttribute("role","status"),this.status.style.cssText="font:12px/1.4 system-ui;padding:4px 8px;background:#f5f7fa;color:#253044",this.status.textContent="Altium 365 beta \xB7 online viewer",this.root.append(this.stage,this.status),S.append(this.root),Vi.set(S,this),this.onMessage=T=>{if(!(this.disposed||!this.frame||T.source!==this.frame.contentWindow||T.origin!=="null"))if(T.data?.type==="altium-beta:script-error"){let H=new Error("The Altium embed script could not load.");this.status.textContent=H.message,this.dispatchEvent(new CustomEvent("error",{detail:H}))}else T.data?.type==="altium-beta:script-loaded"&&this.dispatchEvent(new CustomEvent("providerload",{detail:{provider:"altium365"}}))},this.window.addEventListener("message",this.onMessage)}assertActive(){if(this.disposed)throw new Error("Viewer has been disposed.")}load(h,{view:p=this.view,views:w=this.views}={}){this.assertActive();let S=gU(h,this.host.ownerDocument.baseURI),A=jM(p,w),T=this.host.ownerDocument.createElement("iframe");return T.title="Interactive Altium schematic, PCB and 3D viewer (beta)",T.style.cssText="display:block;width:100%;height:100%;border:0",T.setAttribute("sandbox","allow-scripts allow-downloads"),T.setAttribute("referrerpolicy","no-referrer"),T.srcdoc=yU(S,A),this.stage.replaceChildren(T),this.frame=T,this.url=S,this.view=A.view,this.views=A.views,this.status.textContent="Altium 365 beta \xB7 online viewer",this.dispatchEvent(new CustomEvent("mount",{detail:{provider:"altium365",view:this.view,views:[...this.views]}})),this}setView(h){if(this.assertActive(),!this.url)throw new Error("Load a public project archive first.");return this.load(this.url,{view:h})}dispose(){this.disposed||(this.disposed=!0,this.window.removeEventListener("message",this.onMessage),this.stage.replaceChildren(),this.frame=this.url=null,this.root.remove(),Vi.delete(this.host))}};od();ld();Ul();Qu();function VM(m){let h=ee=>{let X=m?.[ee];if(!Array.isArray(X)||X.length!==3||!X.every(G=>typeof G=="number"&&Number.isFinite(G)&&Math.abs(G)<=1e7))throw new TypeError("Choose finite bounded 3D camera vectors.");return[...X]},p=h("position"),w=h("target"),S=h("up"),A=p.map((ee,X)=>ee-w[X]),T=Math.hypot(...A),H=Math.hypot(...S),Y=[A[1]*S[2]-A[2]*S[1],A[2]*S[0]-A[0]*S[2],A[0]*S[1]-A[1]*S[0]];if(T<1e-4||H<1e-8||Math.hypot(...Y)<T*H*1e-6)throw new TypeError("Choose a nondegenerate 3D camera direction and up vector.");return{position:p,target:w,up:S}}var jv="kicad-webview.views/v1",Vv=16384,GM=8,Jn=(m,h)=>Object.prototype.hasOwnProperty.call(m,h);function xh(m,h,p){if(!m||typeof m!="object"||Array.isArray(m)||![Object.prototype,null].includes(Object.getPrototypeOf(m)))throw new TypeError("Invalid "+p+".");if(Object.keys(m).some(w=>!h.includes(w)))throw new TypeError("Unsupported field in "+p+".");return m}function vh(m,h,p,w=!1){if(typeof m!="string"||m.length>h||!w&&!m.length||/[\x00-\x1f\x7f]/.test(m))throw new TypeError("Invalid "+p+".");return m}function cd(m,h,p,w){if(typeof m!="number"||!Number.isFinite(m)||m<h||m>p)throw new TypeError("Invalid "+w+".");return m}function vU(m){if(vh(m,1024,"drawing path",!0),m&&(m.startsWith("/")||m.includes("%")||/[\?#:]/.test(m)||m.split("/").some(h=>!h||h==="."||h==="..")))throw new TypeError("Choose a project-relative drawing path.");return m}function xU(m){if(xh(m,["center","zoom","flipped"],"2D camera"),xh(m.center,["x","y"],"2D camera center"),typeof m.flipped!="boolean")throw new TypeError("Invalid flipped camera state.");return{center:{x:cd(m.center.x,-1e6,1e6,"camera x"),y:cd(m.center.y,-1e6,1e6,"camera y")},zoom:cd(m.zoom,.001,1e4,"camera zoom"),flipped:m.flipped}}function bU(m){return xh(m,["position","target","up"],"3D camera"),VM(m)}function wU(m){if(m===null)return null;xh(m,["kind","uuid","ownerUuid","id","netName","pinNumber"],"selection");let h={kind:vh(m.kind,64,"selection kind")};for(let p of["uuid","ownerUuid","id","netName"])Jn(m,p)&&(h[p]=vh(m[p],p==="id"?2048:1024,"selection "+p));if(Jn(m,"pinNumber")&&(h.pinNumber=typeof m.pinNumber=="number"?cd(m.pinNumber,-1e6,1e6,"pin number"):vh(m.pinNumber,64,"pin number")),h.kind==="net"?!h.id&&!h.netName:!h.uuid&&!h.id&&!h.ownerUuid)throw new TypeError("Selection needs a saved identity.");return h}function Vl(m){if(xh(m,["schema","views","theme","layout","activePane","linkedSelection"],"view state"),m.schema!==jv)throw new TypeError("Unsupported view-state schema.");if(!Array.isArray(m.views)||m.views.length<1||m.views.length>GM)throw new TypeError("Choose 1 to 8 linked views.");let h={schema:jv,views:m.views.map(p=>{if(xh(p,["path","sha256","view","camera","camera3D","layers","selection","instancePath","expand"],"saved view"),!["pcb","schematic","3d"].includes(p.view))throw new TypeError("View links support native KiCad views only.");if(typeof p.sha256!="string"||!/^[a-f0-9]{64}$/.test(p.sha256))throw new TypeError("Invalid source SHA-256.");let w={path:vU(p.path),sha256:p.sha256,view:p.view};if(Jn(p,"instancePath")){if(p.view!=="schematic")throw new TypeError("Sheet occurrence requires a schematic view.");if(w.instancePath=p.instancePath===null?null:vh(p.instancePath,8192,"sheet instance path"),w.instancePath!==null&&!w.instancePath.startsWith("/"))throw new TypeError("Choose a saved UUID instance path.")}if(Jn(p,"expand")){if(p.view!=="3d")throw new TypeError("Expansion requires a 3D view.");w.expand=cd(p.expand,0,100,"expansion")}if(Jn(p,"camera")){if(p.view==="3d")throw new TypeError("Use a 3D camera for the 3D view.");w.camera=xU(p.camera)}if(Jn(p,"camera3D")){if(p.view!=="3d")throw new TypeError("A 3D camera requires the 3D view.");w.camera3D=bU(p.camera3D)}if(Jn(p,"layers")){if(p.view!=="pcb"||!Array.isArray(p.layers)||p.layers.length>128)throw new TypeError("Layer state requires a bounded PCB layer list.");if(w.layers=p.layers.map(S=>vh(S,128,"saved layer")),new Set(w.layers).size!==w.layers.length)throw new TypeError("Duplicate saved layers.")}return Jn(p,"selection")&&(w.selection=wU(p.selection)),w})};if(Jn(m,"theme")){if(!["light","dark"].includes(m.theme))throw new TypeError("Invalid view theme.");h.theme=m.theme}if(Jn(m,"layout")){if(!["single","split"].includes(m.layout))throw new TypeError("Invalid view layout.");h.layout=m.layout}if(Jn(m,"activePane")){if(!Number.isInteger(m.activePane)||m.activePane<0||m.activePane>=h.views.length)throw new TypeError("Invalid active view.");h.activePane=m.activePane}if(Jn(m,"linkedSelection")){if(typeof m.linkedSelection!="boolean")throw new TypeError("Invalid selection linkage.");h.linkedSelection=m.linkedSelection}if(encodeURIComponent(JSON.stringify(h)).length+11>Vv)throw new TypeError("View state is too large for a link.");return h}async function WM(m){if(!globalThis.crypto?.subtle)throw new Error("View links require Web Crypto on HTTPS or localhost.");return[...new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(m)))].map(h=>h.toString(16).padStart(2,"0")).join("")}function XM(m){if(!Array.isArray(m)||!m.length||m.length>GM||new Set(m).size!==m.length)throw new TypeError("Supply 1 to 8 distinct viewers.");for(let h of m)if(h.assertActive?.(),typeof h.source!="string"||!["pcb","schematic"].includes(h.kind)||!["pcb","schematic","3d"].includes(h.view))throw new TypeError("Load native KiCad drawings before using view links.");return m}function _U(m){if(!m)return null;let h={kind:m.kind};for(let p of["uuid","ownerUuid","id","netName","pinNumber"])m[p]!==void 0&&m[p]!==""&&(h[p]=m[p]);return h}async function Hv(m,h={}){XM(m);let p=m.map(T=>({source:T.source,path:T.path||"",view:T.view,renderer:T.renderer,generation:T.generation,instancePath:T.textInstancePath??null})),w=m.map((T,H)=>{let Y={path:p[H].path,view:T.view,selection:_U(T.getSelection?.())};T.view==="schematic"&&(Y.instancePath=T.textInstancePath??null),T.view==="3d"&&typeof T.getExpand=="function"&&(Y.expand=T.getExpand());let ee=T.view==="3d"?T.getCamera3D?.():T.getCamera?.();return ee&&(Y[T.view==="3d"?"camera3D":"camera"]=JSON.parse(JSON.stringify(ee))),T.view==="pcb"&&T.renderer?.visibleLayers instanceof Set&&(Y.layers=[...T.renderer.visibleLayers].filter(X=>T.getLayers().includes(X))),Y}),S=await Promise.all(p.map(T=>WM(T.source)));if(m.some((T,H)=>T.disposed||T.source!==p[H].source||(T.path||"")!==p[H].path||T.view!==p[H].view||T.renderer!==p[H].renderer||T.generation!==p[H].generation||(T.textInstancePath??null)!==p[H].instancePath))throw new Error("A drawing changed while creating its view link. Try again.");let A={schema:jv,views:w.map((T,H)=>({...T,sha256:S[H]}))};for(let T of["theme","layout","activePane","linkedSelection"])h[T]!==void 0&&(A[T]=h[T]);return Vl(A)}function HM(){return new DOMException("View restoration was aborted.","AbortError")}async function Gv(m,h,{signal:p,openFile:w,current:S}={}){let A=Vl(h);if(XM(m),A.views.length!==m.length)throw new TypeError("View link count does not match the supplied viewers.");let T=()=>{if(p?.aborted)throw HM();return!m.some(J=>J.disposed)&&(!S||S())},H=J=>new Promise((Q,te)=>{let he=()=>te(HM());if(Promise.resolve(J).then(Q,te).finally(()=>p?.removeEventListener("abort",he)),p?.aborted){he();return}p?.addEventListener("abort",he,{once:!0})});if(!T())return!1;let Y=J=>({source:J.source,path:J.path||"",renderer:J.renderer,generation:J.generation,instancePath:J.textInstancePath??null}),ee=m.map(Y),X=(J,Q)=>J.source===ee[Q].source&&(J.path||"")===ee[Q].path&&(J.textInstancePath??null)===ee[Q].instancePath,G=(J,Q)=>X(J,Q)&&J.renderer===ee[Q].renderer&&J.generation===ee[Q].generation,ae=()=>m.every(G);for(let J=0;J<m.length;J++){if(!T()||!ae())return!1;let Q=A.views[J],te=Jn(Q,"instancePath")&&(m[J].textInstancePath??null)!==Q.instancePath;if((m[J].path||"")!==Q.path||te){if(typeof w!="function")throw new Error("Load the linked drawing first: "+A.views[J].path);let he=m[J].generation,be=await H(w(J,Q.path,p,{instancePath:Q.instancePath??void 0}));if(!T()||be===!1||!m.every((De,Ke)=>Ke===J||G(De,Ke))||Number.isInteger(he)&&m[J].generation!==he+1)return!1;if((m[J].path||"")!==A.views[J].path)throw new Error("The host did not open the linked drawing: "+A.views[J].path);if(Jn(Q,"instancePath")&&(m[J].textInstancePath??null)!==Q.instancePath)throw new Error("The host did not open the linked sheet occurrence.");ee[J]=Y(m[J])}}let _e=await H(Promise.all(ee.map(J=>WM(J.source))));if(!T()||!ae())return!1;for(let J=0;J<m.length;J++){let Q=m[J],te=A.views[J];if(te.path!==ee[J].path||te.sha256!==_e[J])throw new Error("View link source SHA-256 does not match "+te.path+".");if(!["pcb","schematic"].includes(Q.kind))throw new TypeError("View links require native KiCad drawings.");if(Q.kind==="schematic"?te.view!=="schematic":!["pcb","3d"].includes(te.view))throw new TypeError("Linked view does not match the drawing kind.");if(te.layers?.some(he=>!Q.getLayers().includes(he)))throw new TypeError("View link refers to an absent saved layer.")}for(let J=0;J<m.length;J++){let Q=m[J],te=A.views[J];if(!T()||!ae())return!1;if(Q.view!==te.view){let he=Q.generation,be=Q.setView(te.view,{signal:p}),De=Number.isInteger(he)?he+1:Q.generation,Ke=await H(be);if(!T()||Ke===!1||Q.generation!==De||!m.every((qe,$e)=>$e===J?X(qe,$e):G(qe,$e)))return!1;ee[J].renderer=Q.renderer,ee[J].generation=Q.generation}}if(m.some((J,Q)=>J.view!==A.views[Q].view))return!1;for(let J=0;J<m.length;J++){if(!T()||!ae()||m.some((De,Ke)=>De.view!==A.views[Ke].view))return!1;let Q=m[J],te=A.views[J];if(A.theme&&(Q.setTheme(A.theme),!T()||!ae()))return!1;if(Jn(te,"expand")){if(typeof Q.setExpand!="function")throw new Error("The viewer cannot restore expansion.");if(Q.setExpand(te.expand,{animate:!1}),!T()||!ae())return!1}if(te.camera&&(Q.setCamera(te.camera),!T()||!ae())||te.camera3D&&(Q.setCamera3D(te.camera3D),!T()||!ae())||te.layers&&(Q.setLayers(te.layers),!T()||!ae())||(Q.clearSelection(),!T()||!ae()))return!1;let he=te.selection;if(!he)continue;let be=he.kind==="net"?Q.selectNet(he.id||he.netName,{locate:!1}):Q.selectObject(he.kind==="pin"&&he.ownerUuid?he.ownerUuid:he.uuid||he.id||he.ownerUuid,{locate:!1,...he.pinNumber!==void 0?{pinNumber:he.pinNumber}:{}});if(!T()||!ae()||m.some((De,Ke)=>De.view!==A.views[Ke].view))return!1;if(!be)throw new Error("The linked selection is absent or ambiguous in "+te.path+".")}return!(!T()||!ae()||m.some((J,Q)=>J.view!==A.views[Q].view))}function YM(m){let h=new URL(m);if(!["http:","https:"].includes(h.protocol)||h.username||h.password)throw new TypeError("Choose an HTTP(S) view URL without credentials.");if(h.href.length>32768)throw new TypeError("View URL is too large.");return h}function Wv(m,h){let p=YM(m);if(p.hash="kicad-view="+encodeURIComponent(JSON.stringify(Vl(h))),p.hash.length>Vv)throw new TypeError("View link fragment is too large.");return p.href}function EU(m){let h=YM(m);if(!h.hash.startsWith("#kicad-view="))return null;if(h.hash.length>Vv)throw new TypeError("View link fragment is too large.");let p;try{p=JSON.parse(decodeURIComponent(h.hash.slice(12)))}catch{throw new TypeError("Malformed view-state link.")}return Vl(p)}Qu();Bl();Qa();var SU=256,qM=sa,MU=lh,KM=4096,AU=32,TU=128,Oo=m=>m&&typeof m=="object"&&!Array.isArray(m)?m.quoted:m,Xv=m=>Array.isArray(m)?Oo(m[0]):null,ZM=(m,h)=>m.filter(p=>Xv(p)===h),bh=(m,h)=>ZM(m,h)[0],zm=m=>/\.kicad_sch$/i.test(m),Bm=m=>m.split("/").at(-1),CU=m=>Bm(m).replace(/\.kicad_sch$/i,"")||Bm(m),_a=(m,h)=>String(m??"").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,"\uFFFD").slice(0,h);function hd(m,{root:h,entry:p}={}){if(!Array.isArray(m)||m.length>SU)throw new TypeError("Choose at most 256 project file entries.");for(let[R,$]of[["root",h],["entry",p]])if($!==void 0&&!Bs($))throw new TypeError("Choose a safe project-relative "+R+" path.");let w=[],S=new Set,A=!1,T=R=>{R=_a(R,1600),!S.has(R)&&(w.length<TU-1?(S.add(R),w.push(R)):A||(w.push("Additional hierarchy diagnostics were omitted."),A=!0))},H=(R,$,V)=>(R.length>$&&T(V+" was shortened for display."),R.slice(0,$)),Y=new Set,ee=new Map,X=new TextEncoder,G=0;for(let R of m){if(!R||typeof R!="object"||!Bs(R.path))throw new TypeError("Project files need safe relative paths.");let $=R.path.normalize("NFC").toLowerCase();if(Y.has($))throw new Error("Project paths must be unique, including Unicode/case variants.");if(Y.add($),!zm(R.path))continue;let V={path:R.path,title:H(CU(R.path),512,R.path+" title"),uuid:null,links:[],targets:new Set,sheetCount:0,error:null};if(R.error!==void 0){if(typeof R.error!="string")throw new TypeError("A schematic read error must be text.");V.error=_a(R.error||"The schematic could not be read.",512)}else{if(typeof R.source!="string")throw new TypeError("A schematic needs source text or an explicit read error.");if(R.source.length>qM)throw new RangeError("Schematic hierarchy sources exceed 256 MiB per file or 512 MiB per project.");let O=X.encode(R.source).length;if(G+=O,O>qM||G>MU)throw new RangeError("Schematic hierarchy sources exceed 256 MiB per file or 512 MiB per project.");V.source=R.source}ee.set(R.path,V)}let ae=(R,$)=>{if(typeof $!="string"||!$||$.length>1e3||$.startsWith("/")||/[\\\x00-\x1f\x7f%?#:]/.test($)||/\$\{|\$\(/.test($))return{path:null,status:"invalid"};let V=R.split("/").slice(0,-1);for(let C of $.split("/")){if(!C)return{path:null,status:"invalid"};if(C!==".")if(C===".."){if(!V.length)return{path:null,status:"invalid"};V.pop()}else V.push(C)}let O=V.join("/");return!Bs(O)||!zm(O)?{path:null,status:"invalid"}:ee.has(O)?{path:O,status:"ok"}:{path:null,status:"missing"}},_e=0,J=!1;for(let R of ee.values()){if(R.error){T(R.path+": "+R.error);continue}try{let $=globalThis.KiCadDesignDiff.parse(R.source);if(Xv($)!=="kicad_sch")throw new TypeError("Expected a saved kicad_sch document.");let V=Oo(bh($,"uuid")?.[1]??bh($,"tstamp")?.[1]);typeof V=="string"&&V.length<=128&&V&&!/[\x00-\x1f\x7f]/.test(V)&&(R.uuid=V);let O=Oo(bh(bh($,"title_block")||[],"title")?.[1]);typeof O=="string"&&O&&(R.title=H(O,512,R.path+" title"));for(let C of $){if(Xv(C)!=="sheet")continue;let j=R.sheetCount++,B=xe=>ZM(C,"property").filter(ke=>typeof Oo(ke[1])=="string"&&Oo(ke[1]).replaceAll(" ","").toLowerCase()===xe),W=B("sheetfile"),K=B("sheetname"),ge=W.length===1?Oo(W[0][2]):null,Ne=K.length===1?Oo(K[0][2]):null,ne=W.length===1?ae(R.path,ge):{path:null,status:"invalid"};if(ne.path&&R.targets.add(ne.path),ne.status!=="ok"&&T(R.path+": "+(ne.status==="missing"?"Missing listed child schematic: ":"Invalid saved sheet reference: ")+_a(ge||"(absent or ambiguous Sheetfile)",1e3)),_e>=KM){J=!0;continue}_e++;let we=Oo(bh(C,"uuid")?.[1]??bh(C,"tstamp")?.[1]);typeof we=="string"&&we.length>128&&T(R.path+": an oversized sheet UUID was omitted."),R.links.push({...ne,ordinal:j,file:typeof ge=="string"?_a(_a(H(ge,1e3,R.path+" Sheetfile"),1e3),1e3):"",name:typeof Ne=="string"&&Ne?_a(_a(H(Ne,512,R.path+" Sheetname"),512),512):typeof ge=="string"&&ge?_a(_a(H(ge,512,R.path+" sheet label"),512),512):"Unnamed sheet",uuid:typeof we=="string"&&we&&we.length<=128&&!/[\x00-\x1f\x7f]/.test(we)?we:null})}}catch($){R.error=_a($?.message||"The schematic could not be parsed.",512),R.links=[],R.targets.clear(),R.sheetCount=0,T(R.path+": "+R.error)}delete R.source}let Q=[...ee.keys()],te=new Set;for(let R of ee.values())for(let $ of R.targets)te.add($);let he=Q.filter(R=>!te.has(R)),be=null,De="forest";if(h!==void 0){if(!ee.has(h))throw new Error("The explicit hierarchy root is not a listed schematic.");be=h,De="explicit"}else if(p!==void 0&&zm(p)&&ee.has(p))be=p,De="entry";else if(p!==void 0&&/\.kicad_pcb$/i.test(p)){let R=Bm(p).replace(/\.kicad_pcb$/i,""),$=p.split("/").slice(0,-1).join("/"),V=Q.filter(C=>Bm(C).replace(/\.kicad_sch$/i,"")===R),O=V.filter(C=>C.split("/").slice(0,-1).join("/")===$);O.length===1?(be=O[0],De="matching-entry"):V.length===1&&(be=V[0],De="matching-entry")}be===null&&he.length===1&&(be=he[0],De="unique-root"),p!==void 0&&zm(p)&&!ee.has(p)&&T("The entry schematic is not listed; hierarchy root selection used the saved project graph.");let Ke=new Set,qe=[],$e=R=>{let $=[R];for(;$.length;){let V=$.pop();if(!Ke.has(V)){Ke.add(V);for(let O of ee.get(V).targets)Ke.has(O)||$.push(O)}}},Xe=(R,$)=>{qe.push({path:R,role:$}),$e(R)};if(be!==null)Xe(be,"root");else for(let R of he)Ke.has(R)||Xe(R,"root");for(let R of[...he,...Q])Ke.has(R)||Xe(R,"unlinked");let ve=0,Ee=J,me=()=>{Ee=!0,T("Hierarchy expansion was truncated at 4096 instances, 32 levels or the bounded saved-sheet descriptor budget.")},N=(R,$,V,O,C,j,B=null)=>{if(ve>=C)return me(),null;ve++;let W={id:$,path:R.path,file:R.file,name:R.name,uuid:R.uuid,instancePath:B,status:R.status,children:[]};if(j&&(W.role=j),W.status!=="ok")return W;let K=ee.get(W.path);if(K.error)return W.status="error",W;if(O.has(W.path))return W.status="cycle",T("Recursive sheet cycle at "+W.path+"."),W;if(V>=AU&&K.sheetCount>0)return W.status="truncated",me(),W;let ge=new Set(O);ge.add(W.path);for(let Ne of K.links){if(ve>=C){me(),W.status="truncated";break}let ne=N(Ne,$+"/s"+Ne.ordinal,V+1,ge,C,void 0,B&&Ne.uuid?B+"/"+Ne.uuid:null);ne&&W.children.push(ne)}return K.links.length<K.sheetCount&&(me(),ve<C?(ve++,W.children.push({id:$+"/more",path:null,file:"",name:"Additional saved sheets omitted",uuid:null,status:"truncated",children:[]})):W.status="truncated"),W},re=[];for(let R=0;R<qe.length;R++){let $=ee.get(qe[R].path),V=N({path:$.path,file:$.path,name:$.title,uuid:$.uuid,status:"ok"},"r"+R,0,new Set,KM-(qe.length-R-1),qe[R].role,$.uuid?"/"+$.uuid:null);V&&re.push(V)}return J&&me(),{schema:"kicad-webview.hierarchy/v1",rootPath:be,rootReason:De,roots:re,files:Q.map(R=>{let $=ee.get(R);return{path:R,sheetCount:$.sheetCount,...$.error?{error:$.error}:{}}}),warnings:w,stats:{files:Q.length,instances:ve,truncated:Ee}}}Am();Tm();Qa();Bl();var wh=sa,$M=lh,JM=m=>typeof m=="string"&&/\.kicad_sch$/i.test(m),QM=m=>new TextEncoder().encode(m).byteLength;async function Yv(m,h){if(!m||!Number.isSafeInteger(m.length)||m.length<1||m.length>256)throw new Error("Choose between 1 and 256 project files.");let p=[],w=0;for(let S of Array.from(m)){h?.throwIfAborted();let A=S?.path||S?.webkitRelativePath||S?.name;if(!Bs(A))throw new TypeError("Project files need safe relative names.");if(!JM(A))continue;let T;if(typeof S.source=="string"){if(S.source.length>wh)throw new Error("Schematic exceeds 256 MiB.");T=S.source}else{let Y=S.bytes;if(Y instanceof ArrayBuffer&&(Y=new Uint8Array(Y)),!(Y instanceof Uint8Array)){if(typeof S.arrayBuffer!="function"||!Number.isSafeInteger(S.size)||S.size<0||S.size>wh)throw new TypeError("A schematic needs bounded source text, bytes or a browser File.");if(Y=new Uint8Array(await S.arrayBuffer()),Y.byteLength!==S.size)throw new Error("File size changed while reading.")}if(Y.byteLength>wh)throw new Error("Schematic exceeds 256 MiB.");T=new TextDecoder("utf-8",{fatal:!0}).decode(Y)}h?.throwIfAborted();let H=QM(T);if(w+=H,H>wh||w>$M)throw new Error("Hierarchy exceeds 256 MiB per schematic or 512 MiB total.");p.push({path:A,source:T})}return p}async function qv(m,h={}){let{signal:p,root:w,credentials:S="omit"}=h;p?.throwIfAborted();let A,T=h.entry;if(m instanceof Uint8Array||m instanceof ArrayBuffer)A=await Yv(await jl(m,{signal:p}),p);else if(m&&typeof m=="object"&&Number.isSafeInteger(m.length))A=await Yv(m,p);else{let H=await Mm(m,{...h,metadataOnly:!0,file:h.file||w,baseURL:h.baseURL??globalThis.document?.baseURI});if(p?.throwIfAborted(),T??=H.project?.entry||H.path,H.archive)A=await Yv(await jl(H.archive,{signal:p}),p);else{let Y=H.project?.files||[{path:H.path}],ee=Y.filter(Q=>JM(Q.path));A=[];let X=0;if(ee.length>256)throw new Error("Hierarchy exceeds 256 schematic files.");A=new Array(ee.length);let G=0,ae=new AbortController,_e=()=>ae.abort(p?.reason);p?.addEventListener("abort",_e,{once:!0}),p?.aborted&&_e();async function J(){for(;G<ee.length;){ae.signal.throwIfAborted();let Q=G++,te=ee[Q],he;try{he=te.path===H.path&&typeof H.source=="string"?H.source:await eo(te.url,{signal:ae.signal,credentials:S,limit:wh})}catch(De){if(ae.signal.throwIfAborted(),De?.name==="AbortError")throw De;A[Q]={path:te.path,error:String(De.message||De).slice(0,512)};continue}ae.signal.throwIfAborted();let be=QM(he);if(X+=be,be>wh||X>$M)throw new Error("Hierarchy exceeds 256 MiB per schematic or 512 MiB total.");A[Q]={path:te.path,source:he}}}try{await Promise.all(Array.from({length:Math.min(3,ee.length)},()=>J().catch(Q=>{throw ae.abort(Q),Q})))}finally{p?.removeEventListener("abort",_e)}}}return p?.throwIfAborted(),hd(A,{root:w,entry:T})}Qa();Ul();var RU=new Set(["ok","missing","invalid","cycle","truncated","error"]);function jm(m){if(m?.schema!=="kicad-webview.hierarchy/v1"||!Array.isArray(m.roots)||m.roots.length>4096||!Array.isArray(m.warnings)||m.warnings.length>1024||m.warnings.some(T=>typeof T!="string"||T.length>8192)||!Array.isArray(m.files)||m.files.length>256)throw new TypeError("Choose a generated project hierarchy.");let h=new Set(m.files.map(T=>T.path));if(h.size!==m.files.length||m.rootPath!==null&&!h.has(m.rootPath))throw new TypeError("Hierarchy paths must be unique and root must be listed.");for(let T of h)if(!Bs(T)||!/\.kicad_sch$/i.test(T))throw new TypeError("Hierarchy files need safe schematic paths.");let p=[],w=new Set,S=new Set,A=m.roots.map(T=>({node:T,depth:0,parent:null})).reverse();for(;A.length;){let T=A.pop(),H=T.node;if(p.length>=4096||T.depth>33||!H||w.has(H)||typeof H.id!="string"||H.id.length>2048||S.has(H.id)||!RU.has(H.status)||!Array.isArray(H.children)||p.length+A.length+H.children.length+1>4096||H.path!==null&&!h.has(H.path))throw new TypeError("Hierarchy contains invalid, recursive or excessive nodes.");if(H.instancePath!==void 0&&H.instancePath!==null&&(typeof H.instancePath!="string"||H.instancePath.length>8192||!/^\/[^\x00-\x1f\x7f]+$/.test(H.instancePath)))throw new TypeError("Invalid saved sheet instance path.");for(let Y of["name","file"])if(typeof H[Y]!="string"||H[Y].length>8192)throw new TypeError("Hierarchy labels exceed their limit.");w.add(H),S.add(H.id),T.index=p.length,p.push(T);for(let Y=H.children.length-1;Y>=0;Y--)A.push({node:H.children[Y],depth:T.depth+1,parent:T.index})}return p}var ud=m=>String(m.name||m.file||m.path||"Unnamed sheet").replace(/\s+/g," ").slice(0,160),Kv=m=>String(m).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\ufffe\uffff]/g,"").replace(/[&<>"']/g,h=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&apos;"})[h]);function eA(m,{theme:h="dark"}={}){if(!["light","dark"].includes(h))throw new TypeError("Choose light or dark theme.");let p=jm(m),w=p.slice(0,512),S=Math.max(0,...w.map(J=>J.depth)),A=Math.max(440,Math.min(1600,S*28+410)),T=72+w.length*64+(p.length>w.length?32:0),H=h==="dark",Y=H?"#101b28":"#f5f8fc",ee=H?"#e8f1fa":"#203347",X=H?"#9fb5ca":"#52697e",G=H?"#3c566d":"#b8cad9",ae=H?"#7de3d4":"#126d70",_e=['<svg xmlns="http://www.w3.org/2000/svg" width="'+A+'" height="'+T+'" viewBox="0 0 '+A+" "+T+'" role="img" aria-label="Project schematic hierarchy"><rect width="100%" height="100%" fill="'+Y+'"/><g font-family="system-ui,sans-serif"><text x="20" y="30" font-size="18" font-weight="700" fill="'+ee+'">Project schematic hierarchy</text>'];for(let J of w){let Q=20+J.depth*28,te=48+J.index*64,he=Math.min(350,A-Q-20),be=J.node;if(J.parent!==null){let De=w[J.parent],Ke=20+De.depth*28+10,qe=48+De.index*64+48;_e.push('<path d="M '+Ke+" "+qe+" V "+(te+23)+" H "+Q+'" fill="none" stroke="'+G+'"/>')}_e.push('<rect x="'+Q+'" y="'+te+'" width="'+he+'" height="48" rx="7" fill="'+(H?"#192a3a":"#fff")+'" stroke="'+(be.status==="ok"?G:"#bd794f")+'"/><text x="'+(Q+10)+'" y="'+(te+20)+'" font-size="13" font-weight="600" fill="'+ee+'">'+Kv(ud(be).slice(0,42))+'</text><text x="'+(Q+10)+'" y="'+(te+37)+'" font-size="10" fill="'+(be.status==="ok"?X:ae)+'">'+Kv((be.path||be.file||"No saved Sheetfile").slice(0,48))+" \xB7 "+Kv(be.status)+"</text>")}return p.length>w.length&&_e.push('<text x="20" y="'+(T-14)+'" font-size="12" fill="'+ee+'">Export limited to512 of '+p.length+" sheet instances. Use the interactive tree for the full hierarchy.</text>"),_e.join("")+"</g></svg>"}var PU=':host{display:flex;flex-direction:column;min-height:0;height:100%;font:13px/1.4 system-ui;--bg:#f6f9fc;--card:#fff;--ink:#24384a;--muted:#5e7489;--line:#cbd9e6;--accent:#126f79;color:var(--ink);background:var(--bg)}:host([data-theme="dark"]){--bg:#101b28;--card:#192a3a;--ink:#e8f1fa;--muted:#a1b5c8;--line:#375169;--accent:#7de3d4;color-scheme:dark}*{box-sizing:border-box}[hidden]{display:none!important}.tools{display:flex;align-items:center;gap:6px;flex-wrap:wrap;padding:12px;border-bottom:1px solid var(--line)}.tools strong{margin-right:auto}.tools button,.node-button,.branch-toggle{font:inherit;color:var(--ink);border:1px solid var(--line);background:var(--card);border-radius:6px;padding:6px 8px;cursor:pointer}button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}button:hover{border-color:var(--accent)}button:disabled{cursor:default}.status{margin:0;padding:9px 14px;color:var(--muted);font-size:12px;overflow-wrap:anywhere}.diagram{overflow:auto;flex:1;min-height:0;padding:8px 16px 24px}.tree-content{display:inline-block;min-width:100%;vertical-align:top}.diagram[data-panning="true"]{cursor:grabbing;user-select:none}.tree-list{list-style:none;margin:0;padding:0}.tree-list .tree-list{margin-left:13px;padding-left:22px;border-left:1px solid var(--line)}li{position:relative;padding:6px 0}.tree-list .tree-list>li:before{content:"";position:absolute;left:-22px;top:28px;width:22px;border-top:1px solid var(--line)}.node-row{display:flex;align-items:center;gap:5px;min-width:200px;max-width:480px}.branch-toggle{width:27px;flex:0 0 27px;padding:5px 0}.branch-spacer{width:27px;flex:0 0 27px}.node-button{display:grid;gap:3px;min-width:0;text-align:left;flex:1;padding:8px 10px;overflow-wrap:anywhere}.node-button[aria-pressed="true"]{border-color:var(--accent);box-shadow:inset 3px 0 var(--accent)}.node-button small{font-size:11px;color:var(--muted)}.node-state{font-size:10px;color:var(--accent);text-transform:uppercase;letter-spacing:.05em}.warnings{padding:8px 14px;border-top:1px solid var(--line);color:var(--muted);font-size:12px;max-height:120px;overflow:auto;white-space:pre-line}',dd=class extends EventTarget{constructor(h,{theme:p="dark",onSelect:w}={}){super();let S=typeof h=="string"?document.querySelector(h):h;if(!S?.ownerDocument||!S.append)throw new TypeError("Choose a tree container.");if(Vi.has(S))throw new Error("This container already has a viewer.");if(w!==void 0&&typeof w!="function")throw new TypeError("onSelect must be a function.");this.host=S,this.doc=S.ownerDocument,this.onSelect=w,this.disposed=!1,this.ticket=0,this.model=null,this.expanded=new Set,this.buttons=new Map,this.branches=new Map,this.listeners=[],this.root=this.doc.createElement("div"),this.root.style.cssText="height:100%;min-height:0;display:flex;flex-direction:column",this.surface=this.root.attachShadow?this.root.attachShadow({mode:"open"}):this.root;let A=(H,Y)=>{let ee=this.doc.createElement(H);return Y&&(ee.textContent=Y),ee};this.make=A;let T=A("style");T.textContent=PU,this.tools=A("div"),this.tools.className="tools",this.tools.append(A("strong","Project tree")),this.toolButtons=[];for(let[H,Y]of[["Expand all",()=>this.expandAll()],["Collapse all",()=>this.collapseAll()]]){let ee=A("button",H);ee.type="button",ee.onclick=Y,this.tools.append(ee),this.toolButtons.push(ee)}for(let[H,Y]of[["Zoom out",()=>this.zoomBy(1/1.25)],["Zoom in",()=>this.zoomBy(1.25)],["Fit",()=>this.fit()],["Reset view",()=>this.resetView()]]){let ee=A("button",H);ee.type="button",ee.onclick=Y,this.tools.append(ee),this.toolButtons.push(ee)}this.camera={zoom:1,x:0,y:0},this.drag=null,this.status=A("p","Load a project to see its saved schematic hierarchy."),this.status.className="status",this.status.setAttribute("role","status"),this.diagram=A("nav"),this.diagram.className="diagram",this.diagram.setAttribute("aria-label","Project schematic hierarchy"),this.diagram.tabIndex=0,this.content=A("div"),this.content.className="tree-content",this.diagram.append(this.content),this._installNavigation(),this.warnings=A("div"),this.warnings.className="warnings",this.warnings.hidden=!0,this.surface.append(T,this.tools,this.status,this.diagram,this.warnings),this.setTheme(p),S.append(this.root),Vi.set(S,this)}assertActive(){if(this.disposed)throw new Error("The project tree has been disposed.")}setTheme(h){if(this.assertActive(),!["light","dark"].includes(h))throw new TypeError("Choose light or dark theme.");this.theme=h,this.root.setAttribute("data-theme",h)}_installNavigation(){let h=A=>{this.disposed||A.pointerType==="touch"||A.button!==0||!A.altKey&&A.target!==this.diagram&&A.target!==this.content&&A.target?.tagName!=="UL"&&A.target?.tagName!=="LI"||A.composedPath?.().some(T=>T?.tagName==="BUTTON")||(this.drag={id:A.pointerId,x:A.clientX,y:A.clientY,left:this.diagram.scrollLeft||0,top:this.diagram.scrollTop||0},this.diagram.setPointerCapture?.(A.pointerId),this.diagram.setAttribute("data-panning","true"),A.preventDefault())},p=A=>{!this.drag||A.pointerId!==this.drag.id||(this.diagram.scrollLeft=this.drag.left-(A.clientX-this.drag.x),this.diagram.scrollTop=this.drag.top-(A.clientY-this.drag.y),this._rememberScroll(),A.preventDefault())},w=A=>{!this.drag||A.pointerId!==this.drag.id||(this.diagram.releasePointerCapture?.(A.pointerId),this.drag=null,this.diagram.setAttribute("data-panning","false"))},S=()=>this._rememberScroll();for(let[A,T]of[["pointerdown",h],["pointermove",p],["pointerup",w],["pointercancel",w],["scroll",S]])this.diagram.addEventListener(A,T),this.listeners.push([A,T])}_rememberScroll(){!this.disposed&&this.model&&(this.camera.x=Math.max(0,Math.min(1e6,this.diagram.scrollLeft||0)),this.camera.y=Math.max(0,Math.min(1e6,this.diagram.scrollTop||0)))}_applyCamera(){this.content.style.zoom=String(this.camera.zoom),this.diagram.scrollLeft=this.camera.x,this.diagram.scrollTop=this.camera.y}getCamera(){return this.assertActive(),this._rememberScroll(),{...this.camera}}setCamera(h){if(this.assertActive(),!h||![h.zoom,h.x,h.y].every(Number.isFinite)||h.zoom<.35||h.zoom>2||h.x<0||h.x>1e6||h.y<0||h.y>1e6)throw new TypeError("Camera needs zoom 0.35\u20132 and scroll offsets 0\u20131000000.");return this.camera={zoom:h.zoom,x:h.x,y:h.y},this._applyCamera(),this.getCamera()}zoomBy(h){if(this.assertActive(),!Number.isFinite(h)||h<=0)throw new TypeError("Zoom factor must be positive.");let p=this.getCamera(),w=Math.max(.35,Math.min(2,p.zoom*h));return this.setCamera({...p,zoom:w})}fit(){this.assertActive();let h=this.diagram.clientWidth,p=this.diagram.clientHeight,w=this.content.offsetWidth,S=this.content.offsetHeight;return!this.model||![h,p,w,S].every(A=>Number.isFinite(A)&&A>0)?!1:(this.setCamera({zoom:Math.max(.35,Math.min(2,h/w,p/S)),x:0,y:0}),!0)}resetView(){return this.assertActive(),this.setCamera({zoom:1,x:0,y:0})}_error(h){this.disposed||(this.status.textContent=h.message||String(h),this.dispatchEvent(new CustomEvent("error",{detail:{error:h}})))}async load(h,p={}){this.assertActive(),this.pending?.abort();let w=new AbortController,S=++this.ticket;this.pending=w;let A=()=>w.abort();p.signal?.addEventListener("abort",A,{once:!0}),p.signal?.aborted&&A(),this.status.textContent="Reading saved sheet links\u2026";try{let T=await qv(h,{...p,signal:w.signal});return this.disposed||S!==this.ticket||w.signal.aborted?!1:(this._setHierarchy(T),this.dispatchEvent(new CustomEvent("ready",{detail:{hierarchy:this.getHierarchy()}})),!0)}catch(T){if(this.disposed||S!==this.ticket||w.signal.aborted&&!p.signal?.aborted)return!1;throw this._error(T),T}finally{p.signal?.removeEventListener("abort",A),S===this.ticket&&(this.pending=null)}}loadFiles(h,p={}){return this.load(h,p)}loadArchive(h,p={}){return this.load(h,p)}setHierarchy(h){return this.assertActive(),jm(h),this.pending?.abort(),this.pending=null,++this.ticket,this._setHierarchy(h),this}setFiles(h,p={}){return this.setHierarchy(hd(h,p))}_setHierarchy(h){let p=jm(h);this.model=structuredClone(h),this.rows=jm(this.model),this.expanded=new Set(p.filter(w=>w.depth<2).map(w=>w.node.id)),this.selectedId=null,this._render(),this.status.textContent=this.model.files.length+" schematic files \xB7 "+this.rows.length+" sheet instances \xB7 "+(this.model.rootPath?"Root: "+this.model.rootPath:"Multiple roots / no unambiguous root"),this.warnings.textContent=(this.model.warnings||[]).slice(0,256).map(String).join(`
`),this.warnings.hidden=!this.warnings.textContent}_render(){this.content.children.length&&this._rememberScroll();for(let w of this.buttons.values())w.onclick=null;for(let w of this.branches.values())w.toggle.onclick=null;this.buttons.clear(),this.branches.clear();let h=this.make("ul");h.className="tree-list";let p=new Map([[null,h]]);for(let w of this.rows){let S=w.node,A=this.make("li"),T=this.make("div");T.className="node-row";let H;if(S.children.length){let X=this.make("button",this.expanded.has(S.id)?"\u2212":"+");X.type="button",X.className="branch-toggle",X.setAttribute("aria-label","Toggle subsheets of "+ud(S)),X.setAttribute("aria-expanded",String(this.expanded.has(S.id))),H=this.make("ul"),H.className="tree-list",H.hidden=!this.expanded.has(S.id),X.onclick=()=>{this.expanded.has(S.id)?this.expanded.delete(S.id):this.expanded.add(S.id),H.hidden=!this.expanded.has(S.id),X.textContent=H.hidden?"+":"\u2212",X.setAttribute("aria-expanded",String(!H.hidden))},T.append(X),this.branches.set(S.id,{toggle:X,children:H}),p.set(w.index,H)}else{let X=this.make("span");X.className="branch-spacer",T.append(X)}let Y=this.make("button");Y.type="button",Y.className="node-button",Y.setAttribute("aria-pressed",String(S.id===this.selectedId)),Y.setAttribute("aria-label","Open schematic "+(S.path||S.file||ud(S))),Y.title=S.path||S.file||ud(S),Y.disabled=S.status!=="ok"||!S.path,Y.append(this.make("strong",ud(S)),this.make("small",S.path||S.file||"No saved Sheetfile"));let ee=this.make("span",S.status==="ok"?S.role==="unlinked"?"Unlinked / separate root":w.depth===0?"Root sheet":"Subsheet":S.status);ee.className="node-state",Y.append(ee),Y.onclick=()=>this.select(S.id),T.append(Y),A.append(T),H&&A.append(H),p.get(w.parent).append(A),this.buttons.set(S.id,Y)}this.content.replaceChildren(h),this._applyCamera()}expandAll(){this.assertActive();for(let[h,p]of this.branches)this.expanded.add(h),p.children.hidden=!1,p.toggle.textContent="\u2212",p.toggle.setAttribute("aria-expanded","true")}collapseAll(){this.assertActive(),this.expanded.clear();for(let h of this.branches.values())h.children.hidden=!0,h.toggle.textContent="+",h.toggle.setAttribute("aria-expanded","false")}select(h){this.assertActive();let p=this.rows?.find(A=>A.node.id===h)?.node;if(!p||p.status!=="ok"||!p.path)return!1;this.selectedId=h;for(let[A,T]of this.buttons)T.setAttribute("aria-pressed",String(A===h));let w={id:p.id,path:p.path,file:p.file,name:p.name,uuid:p.uuid,status:p.status,...p.instancePath?{instancePath:p.instancePath}:{}};this.dispatchEvent(new CustomEvent("select",{detail:{node:{...w}}}));let S=this.ticket;try{Promise.resolve(this.onSelect?.({...w})).catch(A=>{S===this.ticket&&this._error(A)})}catch(A){this._error(A)}return!0}clear(){this.assertActive(),this._rememberScroll(),this.pending?.abort(),this.pending=null,++this.ticket;for(let h of this.buttons.values())h.onclick=null;for(let h of this.branches.values())h.toggle.onclick=null;return this.buttons.clear(),this.branches.clear(),this.model=null,this.rows=[],this.selectedId=null,this.expanded.clear(),this.content.replaceChildren(),this.status.textContent="Load a project to see its saved schematic hierarchy.",this.warnings.textContent="",this.warnings.hidden=!0,this}getHierarchy(){return this.assertActive(),this.model?structuredClone(this.model):null}toSVG(h={}){if(this.assertActive(),!this.model)throw new Error("Load a hierarchy before exporting.");return eA(this.model,{theme:this.theme,...h})}dispose(){if(!this.disposed){this.disposed=!0,++this.ticket,this.pending?.abort(),this.pending=null;for(let[h,p]of this.listeners)this.diagram.removeEventListener(h,p);this.listeners=[],this.drag&&this.diagram.releasePointerCapture?.(this.drag.id),this.drag=null;for(let h of this.toolButtons)h.onclick=null;for(let h of this.buttons.values())h.onclick=null;for(let h of this.branches.values())h.toggle.onclick=null;this.buttons.clear(),this.branches.clear(),this.root.remove(),Vi.get(this.host)===this&&Vi.delete(this.host),this.model=null,this.rows=[],this.onSelect=null}}};var IU=new Set(["sheet tree","sheet browser","sheet navigator","show sheet tree","open sheet tree","minimap","mini map","sheet map"]),tA=m=>IU.has(String(m||"").trim().toLowerCase().replace(/[-_]+/g," ").replace(/\s+/g," ")),Vm=class{constructor(h,p){this.project=h,this.doc=h.doc,this.ticket=0,this.loadedSource=null,this.opened=!1;let w=(S,A)=>{let T=this.doc.createElement(S);return A&&(T.textContent=A),T};this.root=w("section"),this.root.className="project-sheet-browser",this.root.hidden=!0,this.root.setAttribute("role","region"),this.root.setAttribute("aria-label","Schematic sheet browser"),this.header=w("div"),this.header.className="project-sheet-heading",this.header.append(w("strong","Schematic sheets")),this.closeButton=w("button","Close"),this.closeButton.type="button",this.closeButton.setAttribute("aria-label","Close sheet browser"),this.closeButton.onclick=()=>this.close(),this.header.append(this.closeButton),this.mount=w("div"),this.mount.className="project-sheet-mount",this.root.append(this.header,this.mount),p.append(this.root),this.tree=new dd(this.mount,{theme:h.theme,onSelect:S=>h.openFile(S.path,{pane:this.pane(),instancePath:S.instancePath})}),this.drag=null,this.down=S=>{if(S.target!==this.header||S.button!==0)return;let A=this.root.getBoundingClientRect(),T=p.getBoundingClientRect();this.drag={id:S.pointerId,x:S.clientX,y:S.clientY,left:A.left-T.left,top:A.top-T.top},this.header.setPointerCapture?.(S.pointerId),S.preventDefault()},this.move=S=>{if(!this.drag||this.drag.id!==S.pointerId)return;let A=p.getBoundingClientRect(),T=this.root.getBoundingClientRect();this.root.style.left=Math.max(0,Math.min(Math.max(0,A.width-T.width),this.drag.left+S.clientX-this.drag.x))+"px",this.root.style.top=Math.max(0,Math.min(Math.max(0,A.height-44),this.drag.top+S.clientY-this.drag.y))+"px",this.root.style.right="auto"},this.up=S=>{this.drag?.id===S.pointerId&&(this.header.releasePointerCapture?.(S.pointerId),this.drag=null)},globalThis.ResizeObserver&&(this.resize=new ResizeObserver(()=>{this.root.style.left="",this.root.style.right="8px",this.root.style.top="8px"}),this.resize.observe(p)),this.header.addEventListener("pointerdown",this.down),this.header.addEventListener("pointermove",this.move),this.header.addEventListener("pointerup",this.up),this.header.addEventListener("pointercancel",this.up)}pane(){let h=this.project.viewers.findIndex(p=>p.kind==="schematic");return h<0?this.project.activePane:h}async open(){if(this.project.disposed)return!1;if(!this.project.projectReady)throw new Error("Load a project before opening its sheets.");let h=this.project.files.filter(A=>/\.kicad_sch$/i.test(A.path));if(!h.length)throw new Error("This project has no listed schematic files.");this.opened=!0,this.root.hidden=!1,this.project.sheetButton?.setAttribute("aria-expanded","true");let p=this.project.source||this.project.viewers[0].source;if(this.loadedSource===p)return!0;this.pending?.abort();let w=new AbortController,S=++this.ticket;this.pending=w;try{let A=this.project.source?.memory?this.project.source.files:this.project.source?.files?{files:this.project.source.files,entry:h[0].path}:[{path:this.project.viewers[0].path,source:this.project.viewers[0].source}];return await this.tree.load(A,{signal:w.signal,credentials:this.project.viewers[0].credentials||"omit"}),this.project.disposed||S!==this.ticket||w.signal.aborted?!1:(this.loadedSource=p,!0)}catch(A){if(w.signal.aborted)return!1;throw A}finally{this.pending===w&&(this.pending=null)}}close(){this.opened=!1,this.root.hidden=!0,this.pending?.abort(),++this.ticket,this.project.sheetButton?.setAttribute("aria-expanded","false")}reset(){this.close(),this.loadedSource=null,this.tree.clear()}setTheme(h){this.tree.setTheme(h)}dispose(){this.close(),this.resize?.disconnect(),this.tree.dispose();for(let[h,p]of[["pointerdown",this.down],["pointermove",this.move],["pointerup",this.up],["pointercancel",this.up]])this.header.removeEventListener(h,p);this.closeButton.onclick=null,this.root.remove(),this.project=null}};Qa();var Hm=100,NU=`
:host{display:block;height:100%;font:12px/1.45 system-ui;color:#e1eaf3;--project-bar:#182330;--project-bg:#111a24;--project-line:#324254;--project-muted:#99aabd;--project-accent:#77d4df;--project-active:#23434d;--project-ink:#e1eaf3;color-scheme:dark}
:host([data-theme=light]){color:#253445;--project-bar:#fff;--project-bg:#f4f7fa;--project-line:#dbe3eb;--project-muted:#657588;--project-accent:#176b83;--project-active:#e6f3f5;--project-ink:#253445;color-scheme:light}
*{box-sizing:border-box}[hidden]{display:none!important}
select{color-scheme:dark}:host([data-theme=light]) select{color-scheme:light}select option{background:var(--project-bar);color:var(--project-ink)}button,input,select{font:inherit;color:inherit}button,select{border:1px solid var(--project-line);border-radius:6px;background:var(--project-bg);padding:6px 8px}button{cursor:pointer}button:hover{background:var(--project-active)}button:disabled{opacity:.45;cursor:default}button:focus-visible,input:focus-visible,select:focus-visible,summary:focus-visible{outline:2px solid var(--project-accent);outline-offset:2px}
.project-shell{display:flex;flex-direction:column;height:100%;min-height:0;background:var(--project-bg)}.project-toolbar{display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:8px;border-bottom:1px solid var(--project-line);background:var(--project-bar)}.project-brand{font-weight:750;letter-spacing:.03em;margin-right:auto}.project-toolbar label{display:flex;align-items:center;gap:5px}.project-toolbar button[aria-pressed=true]{background:var(--project-active);color:var(--project-accent)}
.project-body{position:relative;display:flex;flex:1;min-height:0}.project-nav{width:236px;flex:none;border-right:1px solid var(--project-line);background:var(--project-bar);display:flex;flex-direction:column;min-height:0}.project-tabs{display:flex;padding:6px;gap:4px;border-bottom:1px solid var(--project-line)}.project-tabs button{flex:1;padding:6px 4px}.project-tabs button[aria-selected=true]{background:var(--project-active);color:var(--project-accent)}.project-search{width:calc(100% - 16px);margin:8px;padding:8px;border:1px solid var(--project-line);border-radius:6px;background:var(--project-bg)}.project-count,.project-help{font-size:10px;color:var(--project-muted);padding:0 8px;margin:0 0 8px}.project-list{overflow:auto;min-height:0;flex:1;padding:0 7px 9px}.project-list button{display:block;text-align:left;width:100%;margin-bottom:4px;overflow-wrap:anywhere}.project-list small{display:block;font-size:10px;color:var(--project-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.project-list button[aria-current=true]{border-color:var(--project-accent);background:var(--project-active)}.project-list details{margin:3px 0 3px 5px}.project-list summary{color:var(--project-muted);padding:4px;cursor:pointer;overflow-wrap:anywhere}.project-list details>div{border-left:1px solid var(--project-line);padding-left:6px}
.project-layer{padding:7px;border:1px solid var(--project-line);border-radius:6px;margin-bottom:5px}.project-layer label{display:flex;align-items:center;gap:6px;overflow-wrap:anywhere}.project-layer input{flex:none}.project-layer button{margin:5px 0 0;padding:4px 6px}.project-layer small{margin-top:3px}
.project-panes{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);flex:1;min-width:0;min-height:0;gap:1px;background:var(--project-line)}.project-panes[data-layout=single]{grid-template-columns:minmax(0,1fr)}.project-pane{display:flex;flex-direction:column;min-width:0;min-height:0;background:var(--project-bg);border-top:2px solid transparent}.project-pane[data-active=true]{border-top-color:var(--project-accent)}.project-pane-heading{display:flex;align-items:center;gap:6px;padding:5px 7px;background:var(--project-bar);font-size:10px;color:var(--project-muted)}.project-pane-heading button{padding:3px 6px;white-space:nowrap}.project-path{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.project-mount{flex:1;min-height:0;min-width:0}.project-empty{padding:20px;color:var(--project-muted)}.project-status{padding:5px 9px;border-top:1px solid var(--project-line);font-size:10px;color:var(--project-muted);overflow-wrap:anywhere}.project-status[data-error=true]{color:#efb3a8}
.project-sheet-browser{position:absolute;z-index:30;top:8px;right:8px;width:min(470px,calc(100% - 16px));height:min(620px,calc(100% - 16px));min-height:180px;display:flex;flex-direction:column;background:var(--project-bar);border:1px solid var(--project-line);border-radius:8px;box-shadow:0 12px 36px #0006;overflow:hidden}.project-sheet-heading{display:flex;justify-content:space-between;gap:8px;align-items:center;padding:8px;cursor:move;touch-action:none}.project-sheet-heading strong{pointer-events:none}.project-sheet-mount{flex:1;min-height:0}
@container (max-width:850px){.project-panes{grid-template-columns:minmax(0,1fr);grid-template-rows:minmax(0,1fr) minmax(0,1fr)}.project-panes[data-layout=single]{grid-template-rows:minmax(0,1fr)}.project-nav{width:200px}.project-toolbar{gap:5px}.project-brand{font-size:11px}}
@container (max-width:580px){.project-body{position:relative}.project-nav{position:absolute;inset:0 auto 0 0;width:min(270px,calc(100% - 28px));z-index:20;box-shadow:8px 0 28px #0005}.project-toolbar{padding:6px}.project-brand{flex:1 0 100%}.project-toolbar label{font-size:10px}.project-toolbar button,.project-toolbar select{padding:5px}.project-status{max-height:56px;overflow:auto}}
`,Gm=class extends EventTarget{constructor(h,{theme:p="dark",layout:w="split",linkedSelection:S=!0,...A}={}){super();let T=typeof h=="string"?document.querySelector(h):h;if(!T?.ownerDocument||!T.append)throw new TypeError("Choose an advanced viewer container.");if(Vi.has(T))throw new Error("This container already has a viewer.");if(!["split","single"].includes(w))throw new TypeError("Choose split or single layout.");if(!["dark","light"].includes(p))throw new TypeError("Choose light or dark theme.");this.host=T,this.doc=T.ownerDocument,this.disposed=!1,this.ticket=0,this.activePane=0,this.restoreTicket=0,this.layout=w,this.linkedSelection=!!S,this.theme=p,this.files=[],this.source=null,this.tab="files",this.linkGuard=!1,this.listeners=[],this.layerControlStops=[];let H=(Q,te,he)=>{let be=this.doc.createElement(Q);return te&&(be.className=te),he!==void 0&&(be.textContent=he),be};this.make=H,this.root=H("div"),this.root.style.cssText="height:100%;min-height:0;container-type:inline-size",this.root.setAttribute("data-theme",p),this.surface=this.root.attachShadow?this.root.attachShadow({mode:"open"}):this.root;let Y=H("style","",NU),ee=H("div","project-shell");this.toolbar=H("div","project-toolbar"),this.toolbar.setAttribute("role","toolbar"),this.toolbar.setAttribute("aria-label","Project viewer controls"),this.navButton=this.button("Project navigator",()=>this.setNavigatorOpen(this.nav.hidden));let X=H("span","project-brand","KiCad WebView \xB7 Project");this.paneSelect=H("select"),this.paneSelect.setAttribute("aria-label","Active project pane");for(let Q=0;Q<2;Q++){let te=H("option","","Pane "+(Q+1));te.value=String(Q),this.paneSelect.append(te)}this.paneSelect.onchange=()=>this.setActivePane(Number(this.paneSelect.value)),this.layoutButton=this.button("Use single pane",()=>this.setLayout(this.layout==="split"?"single":"split"));let G=H("label");this.linkToggle=H("input"),this.linkToggle.type="checkbox",this.linkToggle.checked=this.linkedSelection,this.linkToggle.setAttribute("aria-label","Link saved selection"),this.linkToggle.onchange=()=>{this.linkedSelection=this.linkToggle.checked},G.append(this.linkToggle,H("span","","Link selection")),this.themeButton=this.button("Switch project theme",()=>this.setTheme(this.theme==="dark"?"light":"dark")),this.shareButton=this.button("Create view link",async()=>{let Q=await this.createViewLink(this.doc.baseURI);this.disposed||(this.viewLinkInput.value=Q,this.viewLinkInput.hidden=!1,this.viewLinkInput.focus?.(),this.viewLinkInput.select?.(),this.setStatus("View link ready \xB7 copy the selected URL. It restores the same saved project revision."))}),this.viewLinkInput=H("input"),this.viewLinkInput.type="url",this.viewLinkInput.readOnly=!0,this.viewLinkInput.hidden=!0,this.viewLinkInput.setAttribute("aria-label","Shareable project view link"),this.viewLinkInput.style.cssText="flex:1 1 100%;min-width:0;max-width:100%;padding:7px;border:1px solid var(--project-line);border-radius:6px;background:var(--project-bg)",this.sheetButton=this.button("Show sheet browser",()=>this.openSheetBrowser()),this.sheetButton.setAttribute("aria-expanded","false"),this.toolbar.append(this.sheetButton,X,this.navButton,this.paneSelect,this.layoutButton,G,this.themeButton,this.shareButton,this.viewLinkInput);let ae=H("div","project-body");this.nav=H("aside","project-nav"),this.nav.setAttribute("aria-label","Project navigator");let _e=H("div","project-tabs");_e.setAttribute("role","tablist"),_e.setAttribute("aria-label","Project sections"),this.tabButtons={};for(let Q of["files","parts","nets","layers"]){let te=this.button(Q[0].toUpperCase()+Q.slice(1),()=>this.setTab(Q));te.setAttribute("role","tab"),this.tabButtons[Q]=te,_e.append(te)}this.search=H("input","project-search"),this.search.type="search",this.search.setAttribute("aria-label","Search project files"),this.search.placeholder="Search files",this.search.oninput=()=>this.renderList(),this.count=H("p","project-count"),this.count.setAttribute("role","status"),this.list=H("div","project-list");let J=H("p","project-help","Read only. Part links use saved symbol UUIDs in the two loaded panes. Nets link between identical saved drawings; local names are not linked across sheets.");this.nav.append(_e,this.search,this.count,this.list,J),this.panes=H("div","project-panes"),this.panes.setAttribute("data-layout",w),this.paneNodes=[],this.viewers=[];try{for(let Q=0;Q<2;Q++){let te=H("section","project-pane"),he=H("div","project-pane-heading"),be=this.button("Activate pane "+(Q+1),()=>this.setActivePane(Q)),De=H("span","project-path","No drawing loaded"),Ke=H("div","project-mount");te.setAttribute("aria-label","Project pane "+(Q+1)),he.append(be,De),te.append(he,Ke),this.panes.append(te);let qe=new ko(Ke,{...A,theme:p});this.viewers.push(qe),this.paneNodes.push({pane:te,path:De,mount:Ke}),this.listen(te,"pointerdown",()=>this.setActivePane(Q)),this.listen(te,"focusin",()=>this.setActivePane(Q)),this.listen(qe,"ready",$e=>{De.textContent=qe.path||"Drawing",De.title=De.textContent,this.refresh(),this.emit("ready",{pane:Q,...$e.detail})}),this.listen(qe,"select",$e=>{this.refresh(),this.emit("select",{pane:Q,...$e.detail}),this.crossProbe(Q,$e.detail.item)}),this.listen(qe,"layerschange",()=>{Q===this.activePane&&this.tab==="layers"&&this.renderList()}),this.listen(qe,"error",$e=>{this.setStatus($e.detail?.message||"Drawing failed.",!0),this.emit("error",{pane:Q,error:$e.detail})})}this.status=H("div","project-status","Load a project manifest, repository link or local bundle."),this.status.setAttribute("role","status"),ae.append(this.nav,this.panes),this.sheetBrowser=new Vm(this,ae),ee.append(this.toolbar,ae,this.status),this.surface.append(Y,ee),T.append(this.root),Vi.set(T,this),this.setActivePane(0),this.setLayout(w),this.setTheme(p),this.setTab("files")}catch(Q){throw this.viewers.forEach(te=>te.dispose()),this.root.remove(),Q}}assertActive(){if(this.disposed)throw new Error("Advanced viewer has been disposed.")}emit(h,p){this.dispatchEvent(new CustomEvent(h,{detail:p}))}button(h,p){let w=this.make("button","",h);return w.type="button",w.setAttribute("aria-label",h),w.onclick=()=>{try{p()?.catch?.(A=>{this.disposed||this.setStatus(A.message,!0)})}catch(S){this.setStatus(S.message,!0)}},w}listen(h,p,w){h.addEventListener?.(p,w),this.listeners.push(()=>h.removeEventListener?.(p,w))}setStatus(h,p=!1){this.status&&(this.status.textContent=h,this.status.setAttribute("data-error",String(p)))}getActiveViewer(){return this.assertActive(),this.viewers[this.activePane]}setActivePane(h){if(this.assertActive(),!Number.isInteger(h)||h<0||h>1)throw new TypeError("Choose pane 0 or 1.");this.activePane=h,this.paneSelect.value=String(h);for(let p=0;p<2;p++)this.paneNodes[p].pane.setAttribute("data-active",String(p===h)),this.paneNodes[p].pane.hidden=this.layout==="single"&&p!==h;this.refresh(),this.emit("panechange",{pane:h})}setLayout(h){if(this.assertActive(),!["split","single"].includes(h))throw new TypeError("Choose split or single layout.");this.layout=h,this.panes.setAttribute("data-layout",h),this.layoutButton.textContent=h==="split"?"Single pane":"Split panes",this.layoutButton.setAttribute("aria-label",h==="split"?"Use single pane":"Use split panes"),this.layoutButton.setAttribute("aria-pressed",String(h==="split")),this.setActivePane(this.activePane)}setTheme(h){if(this.assertActive(),!["dark","light"].includes(h))throw new TypeError("Choose light or dark theme.");this.theme=h,this.root.setAttribute("data-theme",h),this.viewers.forEach(p=>p.setTheme(h)),this.sheetBrowser?.setTheme(h),this.themeButton.textContent=h==="dark"?"Light":"Dark"}openSheetBrowser(){return this.assertActive(),this.sheetBrowser.open()}closeSheetBrowser(){this.assertActive(),this.sheetBrowser.close()}setNavigatorOpen(h){this.assertActive(),this.nav.hidden=!h,this.navButton.setAttribute("aria-expanded",String(!!h))}setTab(h){if(this.assertActive(),!["files","parts","nets","layers"].includes(h))throw new TypeError("Choose Files, Parts, Nets or Layers.");this.tab=h,this.search.value="",this.search.placeholder="Search "+h,this.search.setAttribute("aria-label","Search project "+h);for(let[p,w]of Object.entries(this.tabButtons))w.setAttribute("aria-selected",String(p===h));this.renderList()}refresh(){if(this.disposed||!this.viewers.length)return;this.shareButton&&(this.shareButton.disabled=!this.projectReady),this.sheetButton&&(this.sheetButton.disabled=!this.projectReady);let p=this.viewers[0].project?.files||this.source?.files;this.files=p?[...p]:this.viewers[0].path?[{path:this.viewers[0].path}]:[],this.renderList()}renderList(){if(!this.list||!this.viewers.length||this.disposed)return;this.clearLayerControls();let h=this.viewers[this.activePane],p=(this.search.value||"").trim().toLowerCase().slice(0,200);if(this.list.replaceChildren(),tA(p)){let w=this.button("Show sheet browser",()=>this.openSheetBrowser());w.disabled=!this.projectReady,this.list.append(w),this.count.textContent="Sheet browser command";return}if(this.tab==="layers")this.renderLayers(h,p);else if(this.tab==="files"){let w=this.files.slice(0,256).filter(T=>T.path&&T.path.toLowerCase().includes(p));this.count.textContent=w.length+" files \xB7 opens in pane "+(this.activePane+1);let S=(h.getSheets?.()||[]).slice(0,256).filter(T=>[T.name,T.file].join(" ").toLowerCase().includes(p));if(S.length){let T=this.make("p","project-help","Child sheets \xB7 saved links");this.list.append(T);for(let H of S){let Y=this.button(H.name||H.file||"Child sheet",()=>this.openFile(H.path));Y.append(this.make("small","",H.file||"Missing Sheetfile")),Y.disabled=!H.path||!this.files.some(ee=>ee.path===H.path),Y.title=Y.disabled?"Referenced drawing is absent from the loaded project.":H.path,this.list.append(Y)}this.list.append(this.make("p","project-help","All project files"))}let A=new Map([["",this.list]]);for(let T of[...w].sort((H,Y)=>H.path.localeCompare(Y.path))){let H=T.path.split("/"),Y="",ee=this.list;for(let G of H.slice(0,-1)){let ae=Y?Y+"/"+G:G;if(!A.has(ae)){let _e=this.make("details"),J=this.make("summary","",G),Q=this.make("div");_e.open=!0,_e.append(J,Q),ee.append(_e),A.set(ae,Q)}ee=A.get(ae),Y=ae}let X=this.button(H.at(-1),()=>this.openFile(T.path));X.title=T.path,X.setAttribute("aria-label","Open "+T.path),X.setAttribute("aria-current",String(h.path===T.path)),X.disabled=!Ja(T.path)||/\.zip$/i.test(T.path),ee.append(X)}}else if(this.tab==="parts"){let w=h.getParts().filter(S=>[S.reference,S.value,S.footprint].join(`
`).toLowerCase().includes(p));this.count.textContent=w.length+" parts"+(w.length>Hm?" \xB7 first 100":"");for(let S of w.slice(0,Hm)){let A=this.button(S.reference||S.uuid||"Unreferenced part",()=>h.selectPart(S.id,{locate:!0}));A.append(this.make("small","",[S.value,S.footprint].filter(Boolean).join(" \xB7 "))),this.list.append(A)}}else{let w=(h.getNets?.()||[]).filter(S=>S.name.toLowerCase().includes(p));this.count.textContent=w.length+" saved nets"+(w.length>Hm?" \xB7 first 100":"");for(let S of w.slice(0,Hm)){let A=this.button(S.name,()=>h.selectNet(S.id||S.name,{locate:!1}));S.count!==void 0&&A.append(this.make("small","",S.count+" objects")),this.list.append(A)}}}clearLayerControls(){for(let h of this.layerControlStops)h();this.layerControlStops=[]}renderLayers(h,p){let w=h.getLayerState(),S=w.layers.filter(Y=>Y.toLowerCase().includes(p)),A=new Set(w.visible),T=(Y,ee)=>{let X=this.button(Y,ee);return this.layerControlStops.push(()=>{X.onclick=null}),X},H=T("Open layer controls",()=>{let Y=h.chrome?.layersMenu;Y&&!Y.hidden&&(Y.open=!0,Y.querySelector?.("summary")?.focus?.())});if(H.disabled=!w.layers.length||!h.chrome?.layersMenu||h.chrome.layersMenu.hidden,this.list.append(H),this.count.textContent=S.length+" layers \xB7 "+A.size+" visible \xB7 pane "+(this.activePane+1),!w.layers.length){this.list.append(this.make("p","project-help",h.view==="schematic"?"Layer controls are available for PCB and manufacturing views.":"Load a PCB or manufacturing drawing to inspect saved layers."));return}for(let Y of S){let ee=this.make("div","project-layer"),X=this.make("label"),G=this.make("input"),ae=this.make("small","",A.has(Y)?"Visible":"Hidden");if(G.type="checkbox",G.checked=A.has(Y),G.setAttribute("aria-label","Show "+Y),G.onchange=()=>{let _e=h.getLayerState(),J=new Set(_e.visible);G.checked?J.add(Y):J.delete(Y),h.setLayers(_e.layers.filter(Q=>J.has(Q)))},this.layerControlStops.push(()=>{G.onchange=null}),X.append(G,this.make("span","",Y)),ee.append(X,ae),h.view==="pcb"&&w.canFocus){let _e=T("Focus",()=>h.focusLayer(Y));_e.setAttribute("aria-label","Focus "+Y),_e.setAttribute("aria-pressed",String(w.focused===Y)),w.focused===Y&&(ae.textContent+=" \xB7 Focused"),ee.append(_e)}this.list.append(ee)}}async load(h,p={}){return this.loadWith("load",h,p)}async loadFiles(h,p={}){return this.loadWith("loadFiles",h,p)}async loadArchive(h,p={}){return this.loadWith("loadArchive",h,p)}async loadWith(h,p,w){this.assertActive(),this.restorePending?.abort(),++this.restoreTicket,this.restoring=!1,this.restorePending=null;let S=++this.ticket;this.loading=!0,this.projectReady=!1,this.sheetBrowser?.reset(),this.pending?.abort(),this.panePending?.forEach(H=>H?.abort()),this.pending=new AbortController;let A=this.pending,T=()=>A.abort();w.signal?.addEventListener("abort",T,{once:!0}),w.signal?.aborted&&T(),this.setStatus("Loading saved project\u2026");try{if(!await this.viewers[0][h](p,{...w,signal:A.signal})||this.disposed||S!==this.ticket)return!1;let Y=this.viewers[0];this.source=Y.project?{...Y.project,files:Y.project.files}:null,this.files=Y.project?.files||[{path:Y.path}];let ee=this.files.find(X=>Y.kind==="pcb"?/\.kicad_sch$/i.test(X.path):/\.kicad_pcb$/i.test(X.path))||this.files.find(X=>X.path!==Y.path&&Ja(X.path));return ee?await this.loadPaneFromProject(1,ee.path,{signal:A.signal}):Y.kind==="manufacturing"&&!Y.project?await this.viewers[1][h](p,{...w,signal:A.signal}):await this.loadPaneFromProject(1,Y.path,{signal:A.signal}),this.disposed||S!==this.ticket?!1:(this.projectReady=!0,this.setActivePane(0),this.refresh(),this.setStatus("Project loaded \xB7 independent cameras \xB7 read-only \xB7 no comments."),this.emit("projectready",{files:this.getFiles()}),!0)}catch(H){if(this.disposed||S!==this.ticket)return!1;throw this.setStatus(H.message,!0),H}finally{w.signal?.removeEventListener("abort",T),S===this.ticket&&(this.loading=!1)}}async loadPaneFromProject(h,p,w={}){w={textVariables:this.viewers[0].textVariables,worksheetSource:this.viewers[0].worksheetSource,...w};let S=this.viewers[h],A=this.source;if(A?.memory)return S.loadFiles(A.files,{projectSettings:A.settings,...w,file:p});if(A?.files)return S.load({files:A.files,entry:p,worksheet:A.worksheet},{...w,credentials:this.viewers[0].credentials});if(p===this.viewers[0].path)return S.loadSource(this.viewers[0].source,{...w,path:p});throw new Error("Choose a drawing from the loaded project.")}async openFile(h,{pane:p=this.activePane,signal:w,instancePath:S}={}){if(this.assertActive(),S!==void 0&&(typeof S!="string"||S.length>8192||!/^\/[^\x00-\x1f\x7f]+$/.test(S)))throw new TypeError("Choose a bounded saved sheet instance path.");if(this.restorePending?.abort(),++this.restoreTicket,this.restoring=!1,this.restorePending=null,!Number.isInteger(p)||p<0||p>1)throw new TypeError("Choose pane 0 or 1.");if(!this.files.some(Y=>Y.path===h)||!Ja(h)||/\.zip$/i.test(h))throw new Error("Choose a drawing from the loaded project.");let A=this.ticket;this.panePending||=[],this.panePending[p]?.abort();let T=new AbortController;this.panePending[p]=T;let H=()=>T.abort();w?.addEventListener("abort",H,{once:!0}),w?.aborted&&H();try{return!await this.loadPaneFromProject(p,h,{signal:T.signal,instancePath:S})||this.disposed||A!==this.ticket||this.panePending[p]!==T?!1:(this.setActivePane(p),this.refresh(),this.setStatus("Opened "+h+" in pane "+(p+1)+"."),!0)}finally{w?.removeEventListener("abort",H)}}getFiles(){return this.assertActive(),this.files.map(({path:h,url:p})=>({path:h,...p?{url:p}:{}}))}crossProbe(h,p){if(this.disposed||this.loading||this.restoring||!this.projectReady||this.linkGuard||!this.linkedSelection)return;let w=this.viewers[h],S=this.viewers[1-h];if(!(!w.source||!S.source)){this.linkGuard=!0;try{let A=Qc(w,S,p===null?null:w.getSelection?.()||p);A&&this.setStatus("Linked saved "+A+" selection in pane "+(2-h)+" \xB7 cameras stay independent.")}finally{this.linkGuard=!1}}}getViewState(){if(this.assertActive(),!this.projectReady)throw new Error("Load the project before creating a view link.");return Hv(this.viewers,{theme:this.theme,layout:this.layout,activePane:this.activePane,linkedSelection:this.linkedSelection})}async createViewLink(h=this.doc.baseURI){let p=await this.getViewState();return this.assertActive(),Wv(h,p)}async restoreViewState(h,{signal:p}={}){if(this.assertActive(),!this.projectReady)throw new Error("Load the project before restoring its view link.");let w=Vl(h);if(w.views.length!==2)throw new Error("A project view link needs two panes.");for(let X of w.views)if(!this.files.some(G=>G.path===X.path))throw new Error("View link refers to a drawing outside the loaded project.");this.restorePending?.abort();let S=new AbortController;this.restorePending=S;let A=this.restoreTicket=(this.restoreTicket||0)+1,T=this.ticket,H=()=>S.abort();p?.addEventListener("abort",H,{once:!0}),p?.aborted&&H();let Y=()=>!this.disposed&&A===this.restoreTicket&&T===this.ticket&&this.projectReady;this.restoring=!0;let ee=()=>{if(S.signal.aborted)throw new DOMException("View restoration was aborted.","AbortError");return Y()};try{return!await Gv(this.viewers,w,{signal:S.signal,current:Y,openFile:(G,ae,_e,J)=>this.loadPaneFromProject(G,ae,{signal:_e,...J})})||!ee()||w.theme&&(this.setTheme(w.theme),!ee())||w.layout&&(this.setLayout(w.layout),!ee())||w.activePane!==void 0&&(this.setActivePane(w.activePane),!ee())?!1:(w.linkedSelection!==void 0&&(this.linkedSelection=w.linkedSelection,this.linkToggle.checked=this.linkedSelection),this.setStatus("Restored linked project view \xB7 saved source hashes verified."),!0)}catch(X){if(!Y())return!1;throw this.setStatus(X.message,!0),X}finally{p?.removeEventListener("abort",H),A===this.restoreTicket&&(this.restoring=!1,this.restorePending=null)}}dispose(){if(!this.disposed){this.clearLayerControls(),this.disposed=!0,++this.ticket,this.restorePending?.abort(),this.pending?.abort(),this.panePending?.forEach(h=>h?.abort());for(let h of this.listeners)h();this.listeners=[],this.sheetBrowser?.dispose();for(let h of this.viewers)h.dispose();this.search.oninput=this.paneSelect.onchange=this.linkToggle.onchange=null,this.root.remove(),Vi.delete(this.host),this.source=null,this.files=[]}}};var LU="1.0";var Zv=class extends EventTarget{constructor(h,{viewer:p,slides:w,interval:S=5e3}={}){super();let A=typeof h=="string"?document.querySelector(h):h;if(!A?.ownerDocument||!A.append)throw new TypeError("Choose a carousel controls container.");if(!p||typeof p.setView!="function")throw new TypeError("Supply an existing KiCadViewer.");if(!Array.isArray(w)||w.length<1||w.length>100)throw new TypeError("Choose 1 to 100 presentation slides.");if(!Number.isFinite(S)||S<1e3||S>36e5)throw new TypeError("Choose an interval from 1000 to 3600000 milliseconds.");this.slides=w.map((ee,X)=>{if(!ee||typeof ee!="object"||typeof ee.label!="string"||!ee.label.trim()||ee.label.length>500)throw new TypeError("Each slide needs a label of 1 to 500 characters.");if(ee.view!==void 0&&!["pcb","schematic","3d","manufacturing"].includes(ee.view))throw new TypeError("Choose a supported slide view.");if("source"in ee&&("input"in ee||typeof ee.source!="string"))throw new TypeError("Choose either source text or a load input.");if(ee.camera&&ee.view==="3d")throw new TypeError("Programmable cameras require a 2D drawing view.");if(ee.camera3D!==void 0&&!["top","bottom","front","back","left","right","isometric"].includes(ee.camera3D))throw new TypeError("Choose a named 3D camera preset.");if(ee.camera3D!==void 0&&(ee.camera||ee.view!==void 0&&ee.view!=="3d"))throw new TypeError("3D camera presets require a 3D view without a 2D camera.");if(ee.net!==void 0&&(typeof ee.net!="string"||!ee.net||ee.net.length>1e3))throw new TypeError("Choose a saved net name.");return{...ee,options:{...ee.options},camera:ee.camera?{...ee.camera,center:{...ee.camera.center}}:void 0}}),this.viewer=p,this.host=A,this.doc=A.ownerDocument,this.interval=S,this.index=-1,this.requestedIndex=-1,this.ticket=0,this.disposed=!1,this.playing=!1,this.queue=Promise.resolve(),this.listeners=[];let T=(ee,X)=>{let G=this.doc.createElement(ee);return X!==void 0&&(G.textContent=X),G};this.root=T("section"),this.root.setAttribute("aria-label","Drawing presentation"),this.root.style.cssText="display:flex;align-items:center;flex-wrap:wrap;gap:8px;font:inherit";let H=(ee,X)=>{let G=T("button",ee);return G.type="button",G.setAttribute("aria-label",ee),G.onclick=()=>{this.pause(),Promise.resolve().then(X).catch(()=>{})},G};this.previousButton=H("Previous slide",()=>this.previous()),this.nextButton=H("Next slide",()=>this.next()),this.playButton=H("Play presentation",()=>this.play()),this.playButton.onclick=()=>{this.playing?this.pause():this.play()},this.label=T("span","Choose a slide"),this.label.setAttribute("role","status"),this.label.setAttribute("aria-live","polite"),this.label.setAttribute("aria-atomic","true"),this.root.append(this.previousButton,this.label,this.nextButton,this.playButton),A.append(this.root),this.motion=this.doc.defaultView?.matchMedia?.("(prefers-reduced-motion: reduce)");let Y=(ee,X,G)=>{ee?.addEventListener?.(X,G),this.listeners.push(()=>ee?.removeEventListener?.(X,G))};Y(this.motion,"change",()=>{this.motion.matches&&this.pause(),this.refresh()}),Y(this.doc,"visibilitychange",()=>{this.doc.hidden&&this.pause()}),Y(this.root,"focusin",()=>this.pause()),this.refresh()}assertActive(){if(this.disposed)throw new Error("Carousel has been disposed.")}emit(h,p){this.dispatchEvent(new CustomEvent(h,{detail:p}))}refresh(){this.previousButton.disabled=this.requestedIndex<=0,this.nextButton.disabled=this.requestedIndex>=this.slides.length-1,this.playButton.disabled=this.slides.length<2||!!this.motion?.matches,this.playButton.textContent=this.playing?"Pause presentation":"Play presentation",this.playButton.setAttribute("aria-label",this.playButton.textContent),this.playButton.setAttribute("aria-pressed",String(this.playing))}show(h){if(this.assertActive(),!Number.isInteger(h)||h<0||h>=this.slides.length)throw new RangeError("Choose a slide index in the presentation.");let p=++this.ticket;this.requestedIndex=h,this.pending?.abort(),clearTimeout(this.timer),this.refresh();let w=()=>!this.disposed&&p===this.ticket,S=async()=>{if(!w())return!1;let T=this.slides[h],H=new AbortController;this.pending=H,this.root.setAttribute("aria-busy","true");try{let Y;if("input"in T?Y=await this.viewer.load(T.input,{...T.options,view:T.view,signal:H.signal}):"source"in T&&(Y=await this.viewer.loadSource(T.source,{...T.options,view:T.view,signal:H.signal})),!w()||Y===!1||T.view!==void 0&&this.viewer.view!==T.view&&(Y=await this.viewer.setView(T.view),!w()||Y===!1))return!1;if(T.camera&&this.viewer.setCamera(T.camera),T.camera3D!==void 0&&this.viewer.setCamera3D(T.camera3D),T.clearSelection&&this.viewer.clearSelection(),T.net!==void 0&&!this.viewer.selectNet(T.net))throw new Error("Saved net is absent from this drawing: "+T.net);return w()?(this.index=h,this.label.textContent=h+1+" / "+this.slides.length+" \xB7 "+T.label,this.emit("slidechange",{index:h,label:T.label}),!0):!1}catch(Y){if(!w()||H.signal.aborted)return!1;throw this.pause(),this.label.textContent="Unable to show "+T.label+": "+Y.message,this.emit("error",{index:h,error:Y}),Y}finally{w()&&(this.pending=null,this.root.setAttribute("aria-busy","false"),this.schedule())}},A=this.queue.then(S);return this.queue=A.catch(()=>{}),A}next(){return this.assertActive(),this.show(Math.min(this.slides.length-1,this.requestedIndex+1))}previous(){return this.assertActive(),this.show(Math.max(0,this.requestedIndex-1))}play(){return this.assertActive(),this.motion?.matches||this.doc.hidden||this.slides.length<2?!1:(this.playing=!0,this.refresh(),this.requestedIndex<0?this.show(0).catch(()=>{}):this.queue.then(()=>this.schedule()),!0)}schedule(){clearTimeout(this.timer),!this.disposed&&this.playing&&(this.timer=setTimeout(()=>{!this.disposed&&this.playing&&this.show((this.requestedIndex+1)%this.slides.length).catch(()=>{})},this.interval))}pause(){this.disposed||(this.playing=!1,clearTimeout(this.timer),this.refresh())}dispose(){this.disposed||(this.pause(),this.disposed=!0,++this.ticket,this.pending?.abort(),this.listeners.forEach(h=>h()),this.listeners=[],this.previousButton.onclick=this.nextButton.onclick=this.playButton.onclick=null,this.root.remove())}};Qu();ov();iv();var kU=Object.freeze(["realistic","layers","translucent"]);function rA(m){if(!kU.includes(m))throw new TypeError("Choose realistic, layers or translucent appearance.");return m}var OU=64*1024*1024,$v=m=>String(m).replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;"),Jv=m=>JSON.stringify(m).replaceAll("<","\\u003c");function DU(m){let h="";for(let p=0;p<m.length;p+=8192)h+=String.fromCharCode(...m.subarray(p,p+8192));return btoa(h)}function UU({viewerScript:m,licenseText:h,files:p,title:w="Interactive design",view:S,theme:A="dark",highlightStyle:T="dim",highlightColor:H="source",appearance:Y="realistic"}={}){if(typeof m!="string"||!m.trim()||m.length>8*1024*1024)throw new TypeError("Supply the full classic viewer script (up to 8 MiB).");if(typeof h!="string"||!h.trim()||h.length>1024*1024)throw new TypeError("Include the viewer license and dependency notices.");if(!Array.isArray(p)||!p.length||p.length>256)throw new TypeError("Choose 1 to 256 files, or one project ZIP.");if(!["dark","light"].includes(A)||S!==void 0&&!["pcb","schematic","3d","manufacturing"].includes(S))throw new TypeError("Choose a supported theme and view.");let ee=ed(T,H);rA(Y);let X=new Set,G=0,ae=p.map(he=>{let be=he?.path;if(typeof be!="string"||be.length>1024||!be||be.includes("\\")||be.startsWith("/")||/^[a-z]+:/i.test(be)||be.split("/").some(De=>!De||De==="."||De==="..")||X.has(be))throw new TypeError("Choose unique relative project file paths.");if(X.add(be),!(he.bytes instanceof Uint8Array)||!he.bytes.length)throw new TypeError("Each file needs nonempty Uint8Array bytes.");if(G+=he.bytes.length,G>OU)throw new RangeError("HTML export is limited to 64 MiB of input files.");return{path:be,base64:DU(he.bytes)}}),_e=ae.some(he=>/\.zip$/i.test(he.path));if(_e&&ae.length!==1)throw new TypeError("Export a ZIP alone, or choose individual project files.");let J={theme:A,inspectOnSelect:!1,highlightStyle:ee.mode,highlightColor:ee.color,appearance:Y},Q={...S?{view:S}:{}},te=m.replace(/<\/script/gi,"<\\/script");return`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; worker-src blob:; connect-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'"><title>${$v(w)}</title><style>*{box-sizing:border-box}html,body{margin:0;height:100%;font:14px system-ui;background:#111a24;color:#e1eaf3}body{display:flex;flex-direction:column}header{padding:8px 12px;border-bottom:1px solid #324254;display:flex;align-items:center;gap:8px;flex-wrap:wrap}h1{margin:0;flex:1;font-size:15px}button{font:inherit;min-height:44px;background:#182330;color:#e1eaf3;border:1px solid #52748a;border-radius:6px;padding:5px 10px}#viewer{flex:1;min-height:240px}#status{margin:0;padding:4px 12px;font-size:11px}dialog{max-width:min(700px,95vw);max-height:80dvh;background:#182330;color:#e1eaf3;border:1px solid #52748a;overflow:auto}pre{white-space:pre-wrap;overflow-wrap:anywhere;font:11px/1.5 monospace}</style></head><body><header><h1>${$v(w)}</h1><button id="notices">License &amp; source</button></header><div id="viewer" aria-label="Interactive design viewer"></div><p id="status" role="status">Opening bundled design\u2026</p><dialog id="license"><button id="close">Close</button><p>Design files are bundled in this document. No external network access is enabled. Models must be included in the project; unresolved models use labelled proxies.</p><pre>${$v(h)}</pre></dialog><script>${te}<\/script><script>
const data=${Jv(ae)};const files=data.map(file=>({path:file.path,bytes:Uint8Array.from(atob(file.base64),c=>c.charCodeAt(0))}));
const viewer=new KiCadWebView.Viewer('#viewer',${Jv(J)});const status=document.querySelector('#status');
document.querySelector('#notices').onclick=()=>document.querySelector('#license').showModal();document.querySelector('#close').onclick=()=>document.querySelector('#license').close();
viewer.addEventListener('error',event=>status.textContent=event.detail?.message||'Unable to load design.');
${_e?"viewer.loadArchive(files[0].bytes,":"viewer.loadFiles(files,"}${Jv(Q)}).then(()=>status.textContent='Read-only \xB7 bundled design \xB7 no external network access').catch(error=>status.textContent=error.message);
window.addEventListener('pagehide',()=>viewer.dispose(),{once:true});
<\/script></body></html>`}var v8=Vn(Qv(),1),x8=Vn(iA(),1),ex=globalThis.KiCadAnalysisData,tx=globalThis.KiCadAnalysisSpatial,nA=64*1024*1024,aA=64,oA=4e6,FU=m=>typeof m=="string"&&/^[a-f0-9]{64}$/i.test(m);function zU(m){let h=0,p=0,w=/(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/y,S=()=>{throw new TypeError("Invalid, duplicate-key or over-limit JSON result.")},A=()=>{for(;h<m.length&&/[\x20\t\r\n]/.test(m[h]);)h++},T=()=>{let Y=h++;for(;h<m.length;){let ee=m[h++];if(ee==='"')try{return JSON.parse(m.slice(Y,h))}catch{return S()}if(ee==="\\"){if(h>=m.length)return S();let X=m[h++];if(X==="u"){if(!/^[0-9a-fA-F]{4}$/.test(m.slice(h,h+4)))return S();h+=4}else if(!'"\\/bfnrt'.includes(X))return S()}else if(ee.charCodeAt(0)<32)return S()}return S()};function H(Y){if(Y>aA||++p>oA)return S();A();let ee=m[h];if(ee==='"'){T();return}if(ee==="{"){h++,A();let G=new Set;if(m[h]==="}"){h++;return}for(;;){if(A(),m[h]!=='"')return S();let ae=T();if(G.has(ae)||(G.add(ae),A(),m[h++]!==":"))return S();H(Y+1),A();let _e=m[h++];if(_e==="}")return;if(_e!==",")return S()}}if(ee==="["){if(h++,A(),m[h]==="]"){h++;return}for(;;){H(Y+1),A();let G=m[h++];if(G==="]")return;if(G!==",")return S()}}w.lastIndex=h;let X=w.exec(m)?.[0];if(!X||X!=="true"&&X!=="false"&&X!=="null"&&!Number.isFinite(Number(X)))return S();h+=X.length}return H(0),A(),h!==m.length?S():JSON.parse(m)}function BU(m){if(typeof m=="string"){if(new TextEncoder().encode(m).length>nA)throw new RangeError("Result exceeds 64 MiB.");return zU(m.replace(/^\uFEFF/,""))}let h=new WeakSet,p=0;function w(A,T){if(T>aA||++p>oA)throw new RangeError("Result exceeds depth or work limit.");if(A===null||typeof A=="string"||typeof A=="boolean"||typeof A=="number"&&Number.isFinite(A))return;if(!A||typeof A!="object"||h.has(A))throw new TypeError("Result must be acyclic JSON data.");if(!Array.isArray(A)&&Object.getPrototypeOf(A)!==Object.prototype&&Object.getPrototypeOf(A)!==null)throw new TypeError("Result must use plain JSON objects.");h.add(A);let H=Object.getOwnPropertyDescriptors(A);for(let[Y,ee]of Object.entries(H))if(!(Array.isArray(A)&&Y==="length")){if(!ee.enumerable||!("value"in ee))throw new TypeError("Result must contain only JSON data properties.");w(ee.value,T+1)}if(Object.getOwnPropertySymbols(A).length)throw new TypeError("Result must not contain symbol keys.");if(Array.isArray(A)&&Object.keys(A).length!==A.length)throw new TypeError("Sparse arrays are not JSON results.");h.delete(A)}w(m,0);let S=JSON.stringify(m);if(new TextEncoder().encode(S).length>nA)throw new RangeError("Result exceeds 64 MiB.");return JSON.parse(S)}function lA(m,h=new WeakSet){if(!m||typeof m!="object"||h.has(m))return m;h.add(m);for(let p of Object.values(m))lA(p,h);return Object.freeze(m)}function jU(m){if(!m||typeof m!="object"||Array.isArray(m)||typeof m.schema=="string"&&/setup/i.test(m.schema))return!1;let h=m.pocket_kivi_export,p=m.wayricad_saved_result;if(h&&h.schema!=="wayricad.pocket-kivi-export/v1")throw new TypeError("Unsupported portable result metadata.");if(p&&(p.schema!=="wayricad.project-result/v1"||!["quick-pi","quick-si","quick-therm","quick-emerge"].includes(p.plugin)))throw new TypeError("Unsupported project result metadata.");return!!(m.mesh&&m.result||m.schema==="wayricad.quick-si/v1"&&(m.path||m.eye)||m.quick_therm&&(m.board_thermal_view||m.thermal_network)||p&&m.result)}function rx(m,{path:h="wayricad-results.json"}={}){if(typeof h!="string"||h.length>4096||!h.toLowerCase().endsWith(".json"))throw new TypeError("Choose a JSON result path.");let p=BU(m);if(!jU(p))throw new TypeError("Unsupported WayriCAD result or setup file.");let w=ex.parseJSONValue(p,h),S=tx.sourceBindings(p),A={portable:p.pocket_kivi_export??null,library:p.wayricad_saved_result??null,libraryIntegrity:"unverified"};return lA({raw:p,report:w,sourceBindings:S,path:h,metadata:A})}function ix(m,h){if(!FU(h)||!m?.sourceBindings?.length||m.metadata?.library||m.metadata?.portable&&m.metadata.portable.source_state!=="saved")return"unverified";let p=new Set(m.sourceBindings.map(w=>w.sha256));return p.size!==1?"unverified":p.has(h.toLowerCase())?"matching":"stale"}var nx=(m,h)=>ex.frameValues(m,h),pd=(m,h,p,w)=>ex.probe(m,h,p,w),sx=(m,h,p)=>tx.pointHistory(m,h,p),sA=m=>Array.isArray(m)&&m.length>=2&&m.every((h,p)=>typeof h=="number"&&Number.isFinite(h)&&(!p||(m[1]>m[0]?h>m[p-1]:h<m[p-1]))),Ym=m=>m?.type==="heatmap"&&(!sA(m.x)||!sA(m.y))?null:tx.toSurface(m);Om();var VU=m=>mh(m.values);function HU(m){let h=1/0,p=1/0,w=-1/0,S=-1/0;for(let A of m.points)h=Math.min(h,A[0]),w=Math.max(w,A[0]),p=Math.min(p,A[1]),S=Math.max(S,A[1]);return![h,p,w,S].every(Number.isFinite)||w<=h||S<=p?null:{x0:h,y0:p,x1:w,y1:S}}function cA(m,{maxSize:h=768,maxPixelTests:p=16e6,range:w,palette:S="wayricad"}={}){if(!Number.isSafeInteger(h)||h<2||h>1024||!Number.isSafeInteger(p)||p<1||p>32e6)throw new RangeError("Invalid field preview budget.");if(w&&(!Array.isArray(w)||w.length!==2||!w.every(Number.isFinite)||w[1]<=w[0]))throw new RangeError("Invalid fixed field range.");let A=fh(S),T=HU(m),H=w||VU(m);if(!T||!H)return null;let Y=T.x1-T.x0,ee=T.y1-T.y0;if(!Number.isFinite(Y+ee))throw new RangeError("Field extent exceeds the preview range.");let X=Math.max(2,Math.round(h*Y/Math.max(Y,ee))),G=Math.max(2,Math.round(h*ee/Math.max(Y,ee))),ae=new Uint8ClampedArray(X*G*4),_e=Array.from({length:256},(he,be)=>km(be,[0,255],A)),J=0,Q=0,te=0;for(let he=0;he<m.triangles.length;he++){let be=m.triangles[he],De=be.map($=>m.points[$]),Ke=m.nodal?be.map($=>m.values[$]):[m.values[he]];if(Ke.some($=>!Number.isFinite($))){te++;continue}let qe=De.map($=>[($[0]-T.x0)/Y*X,($[1]-T.y0)/ee*G]),[$e,Xe,ve]=qe,Ee=(Xe[1]-ve[1])*($e[0]-ve[0])+(ve[0]-Xe[0])*($e[1]-ve[1]);if(!Number.isFinite(Ee)||Math.abs(Ee)<1e-14){te++;continue}let me=Math.max(0,Math.floor(Math.min($e[0],Xe[0],ve[0]))),N=Math.min(X-1,Math.ceil(Math.max($e[0],Xe[0],ve[0]))),re=Math.max(0,Math.floor(Math.min($e[1],Xe[1],ve[1]))),R=Math.min(G-1,Math.ceil(Math.max($e[1],Xe[1],ve[1])));if(J+=(N-me+1)*(R-re+1),J>p)throw new RangeError("Field exceeds the bounded 2D raster preview budget. Use a smaller result or 3D; full data is retained.");for(let $=re;$<=R;$++)for(let V=me;V<=N;V++){let O=V+.5,C=$+.5,j=((Xe[1]-ve[1])*(O-ve[0])+(ve[0]-Xe[0])*(C-ve[1]))/Ee,B=((ve[1]-$e[1])*(O-ve[0])+($e[0]-ve[0])*(C-ve[1]))/Ee,W=1-j-B;if(j<-1e-10||B<-1e-10||W<-1e-10)continue;let K=m.nodal?j*Ke[0]+B*Ke[1]+W*Ke[2]:Ke[0],ge=_e[Math.max(0,Math.min(255,Math.round(Ov(K,H)*255)))],Ne=($*X+V)*4;ae[Ne]=ge[0],ae[Ne+1]=ge[1],ae[Ne+2]=ge[2],ae[Ne+3]=255}Q++}return{bounds:T,range:H,palette:S,width:X,height:G,pixels:ae,drawn:Q,omitted:te,pixelTests:J}}function hA(m,h,{maxPoints:p=1e5}={}){let w=[],S=0,A=0,T=1/0,H=-1/0,Y=1/0,ee=-1/0;for(let[G,ae]of(m.series||[]).entries()){if(!h.has(G))continue;A+=ae.points.length;let _e=Math.min(ae.points.length,Math.max(0,p-S)),J=ae.points.slice(0,_e);S+=_e;for(let Q of J)Number.isFinite(Q.x)&&(T=Math.min(T,Q.x),H=Math.max(H,Q.x)),Number.isFinite(Q.y)&&(Y=Math.min(Y,Q.y),ee=Math.max(ee,Q.y));w.push({index:G,name:ae.name,points:J})}let X=(G,ae)=>G===ae?[G-.5*Math.max(1,Math.abs(G)),ae+.5*Math.max(1,Math.abs(ae))]:[G,ae];return{series:w,shown:S,total:A,limited:S<A,bounds:[T,H,Y,ee].every(Number.isFinite)?{x:X(T,H),y:X(Y,ee)}:null}}function uA(m,{raster:h,surface:p,range:w,allowed:S,layer:A,probe:T=()=>null,onProbe:H=()=>{},onState:Y=()=>{},opacity:ee=()=>.65,palette:X=()=>"wayricad"}){let G=m.host.ownerDocument.createElement("canvas");G.setAttribute("aria-hidden","true"),G.style.cssText="position:absolute;inset:0;width:100%;height:100%;pointer-events:none;z-index:2";let ae=Symbol("WayriCAD saved field"),_e,J=null,Q=!1,te=null,he=null,be=null,De={placed:!1,reason:"No registered field."},Ke=null,qe=R=>{De=R,Y({...De})},$e=R=>{R?.setAnalysisOverlay?.(null,{owner:ae}),te=he=be=null},Xe=()=>{let R=T(),$=p();if(!R||!$||!Number.isFinite(R.x)||!Number.isFinite(R.y))return[];let V=Number.isFinite(R.z)?R.z:$.points?.[0]?.[2];return Number.isFinite(V)?[{x:R.x,y:R.y,z:V,label:""}]:[]};function ve(){if(J=null,Q)return;let R=m.renderer;_e!==R&&(_e?.removeEventListener?.("kicad:viewframe",Ee),$e(_e),_e=R,_e?.addEventListener?.("kicad:viewframe",Ee));let $=p(),V=A(),O=m.getLayers?.(),C=S()&&$&&(!V||!O||O.includes(V))&&(!V||(m.view==="3d"?m.getLayerState?.().visible?.includes(V)!==!1:m.renderer?.visibleLayers?.has(V)!==!1));if(G.hidden=!0,m.view==="3d"){if(!C||!_e?.setAnalysisOverlay){$e(_e),qe({placed:!1,reason:C?"This renderer cannot register saved fields.":"Field disabled, hidden layer or unmatched source."});return}try{let ke=w(),Me=X();if(te!==$||he!==ke||be!==Me){let Ce=_e.setAnalysisOverlay($,{owner:ae,range:ke,palette:Me,throughBoard:!0,layer:V});if(!Ce.placed){$e(_e),qe(Ce);return}te=$,he=ke,be=Me,qe({...Ce,layer:V,view:"3d",throughBoard:!0})}_e.setAnalysisOpacity?.(ee(),{owner:ae}),_e.setAnalysisProbes?.(Xe(),{owner:ae})}catch(ke){$e(_e),qe({placed:!1,reason:ke.message})}return}$e(_e);let j=m.view==="pcb"&&_e?.viewport?.camera;if(!C||!j){qe({placed:!1,reason:"Field disabled, hidden layer or unmatched source."});return}let B=h();if(!B){qe({placed:!1,reason:"No finite saved field coverage."});return}G.hidden=!1;let W=Math.min(2,globalThis.devicePixelRatio||1),K=Math.max(1,Math.round(j.width*W)),ge=Math.max(1,Math.round(j.height*W));(G.width!==K||G.height!==ge)&&(G.width=K,G.height=ge);let Ne=G.getContext("2d");Ne.setTransform(1,0,0,1,0,0),Ne.clearRect(0,0,K,ge);let ne=j.world_to_screen({x:B.bounds.x0,y:B.bounds.y0}),we=j.world_to_screen({x:B.bounds.x1,y:B.bounds.y1});Ne.setTransform(W,0,0,W,0,0),Ne.save(),Ne.globalAlpha=ee(),Ne.translate(ne.x,ne.y),Ne.scale((we.x-ne.x)/B.width,(we.y-ne.y)/B.height),Ne.drawImage(B.canvas,0,0),Ne.restore();let xe=T();if(xe&&Number.isFinite(xe.x)&&Number.isFinite(xe.y)){let ke=j.world_to_screen(xe);Ne.beginPath(),Ne.arc(ke.x,ke.y,7,0,2*Math.PI),Ne.strokeStyle="#fff",Ne.lineWidth=3,Ne.stroke(),Ne.strokeStyle="#073e49",Ne.lineWidth=1,Ne.stroke()}qe({placed:!0,layer:V,view:"pcb",throughBoard:!1})}function Ee(){Q||(G.parentNode!==m.stage&&m.stage.append(G),J===null&&(J=requestAnimationFrame(ve)))}function me(R){Ke=R.button===0?{x:R.clientX,y:R.clientY,id:R.pointerId}:null}function N(R){let $=Ke;if(Ke=null,!$||$.id!==R.pointerId||R.button!==0||Math.hypot($.x-R.clientX,$.y-R.clientY)>5||m.view!=="pcb"||!S())return;let V=m.renderer?.viewport?.camera;if(!V)return;let O=m.stage.getBoundingClientRect(),C=V.world_to_screen({x:0,y:0}),j=V.world_to_screen({x:1,y:1});j.x===C.x||j.y===C.y||H((R.clientX-O.left-C.x)/(j.x-C.x),(R.clientY-O.top-C.y)/(j.y-C.y))}let re=["ready","viewchange","camerachange","layerschange"];for(let R of re)m.addEventListener(R,Ee);return m.stage.addEventListener("pointerdown",me),m.stage.addEventListener("pointerup",N),Ee(),{sync:Ee,ownsProbe(R){return!Q&&S()&&m.view==="3d"&&_e===m.renderer&&te===p()&&R?.overlayOwner===ae},getState(){return{...De}},dispose(){if(!Q){Q=!0,J!==null&&cancelAnimationFrame(J),$e(_e),_e?.removeEventListener?.("kicad:viewframe",Ee);for(let R of re)m.removeEventListener(R,Ee);m.stage.removeEventListener("pointerdown",me),m.stage.removeEventListener("pointerup",N),G.remove(),G.width=G.height=1}}}}Om();od();Am();function ax(m){let h=m?.raw,p=h?.schema==="wayricad.quick-si/v1"?h.path:null,w=p?.net_name||(h?.mesh&&h?.result?h.request?.net_name:null),S=typeof w=="string"&&w.length>0&&w.length<=1e3?w:null,A=[...new Set((Array.isArray(p?.segments)?p.segments:[]).map(T=>T?.item_uuid).filter(T=>typeof T=="string"&&T.length>0&&T.length<=240))];return Object.freeze({netName:S,objectIds:Object.freeze(A)})}Ul();var Gs=m=>Number.isFinite(m)?Number(m.toPrecision(6)).toString():"missing",_h=(m,h=500)=>typeof m=="string"?m.slice(0,h)+(m.length>h?" \u2026 [full text retained]":""):m===null||typeof m=="number"||typeof m=="boolean"?m:"[structured data retained]";function GU(m){let h=m.metadata.portable,p=h?Object.fromEntries(["schema","tool","version","source_state","coordinate_frame","zBasis"].map(w=>[w,_h(h[w])])):null;if(p&&h.units&&typeof h.units=="object"){p.units={};let w=0;for(let S in h.units){if(++w>32)break;Object.defineProperty(p.units,S.slice(0,80),{enumerable:!0,value:_h(h.units[S],80)})}}return{producer:p,projectRecord:m.metadata.library?{schema:_h(m.metadata.library.schema),plugin:_h(m.metadata.library.plugin),identity:"unverified; original record retained"}:null,sourceBindings:m.sourceBindings.slice(0,32).map(w=>({path:_h(w.path,200),sha256:w.sha256})),notes:m.report.warnings.slice(0,24).map(w=>_h(w)),display:"No solver execution. Missing values stay missing. Grid cells follow saved center spacing and are not clipped to board/copper boundaries. Full source data remains downloadable."}}var qm=["#58d8de","#f2c66d","#b59af5","#ff8f9b","#87cc8f","#9cbeff"],WU=".kw-results{--bg:#14212c;--panel:#1b2d3b;--ink:#edf4f8;--muted:#b8c8d5;--line:#3d5668;--accent:#69dce3;color:var(--ink);background:var(--bg);border:1px solid var(--line);border-radius:10px;padding:12px;font:13px/1.5 system-ui;min-width:0;color-scheme:dark}.kw-results[data-theme=light]{--bg:#fff;--panel:#eef4f8;--ink:#152534;--muted:#40566a;--line:#aebdca;--accent:#00727d;color-scheme:light}.kw-results *{box-sizing:border-box}.kw-results button,.kw-results select,.kw-results input{font:inherit;color:var(--ink);background:var(--panel);border:1px solid var(--line);border-radius:5px;padding:7px;min-width:0;max-width:100%;min-height:38px}.kw-results button{cursor:pointer}.kw-results button:disabled{opacity:.55;cursor:default}.kw-results :focus-visible{outline:2px solid var(--accent);outline-offset:2px}.kw-results label{display:flex;align-items:center;gap:6px;min-width:0}.kw-result-tools{display:flex;flex-wrap:wrap;gap:8px;align-items:center}.kw-result-tools>select{flex:1 1 220px}.kw-results p{margin:7px 0;overflow-wrap:anywhere}.kw-result-status{color:var(--accent);font-weight:650}.kw-result-small{color:var(--muted);font-size:12px}.kw-result-viewport{position:relative;height:clamp(260px,48vh,500px);min-height:240px;margin:10px 0;overflow:hidden;border:1px solid var(--line);border-radius:6px;background:var(--panel)}.kw-result-viewport>canvas,.kw-result-viewport>.kw-result-three{position:absolute;inset:0;width:100%;height:100%}.kw-result-series{display:flex;flex-wrap:wrap;gap:6px 14px;max-height:160px;overflow:auto}.kw-result-series label{min-height:38px;overflow-wrap:anywhere;white-space:normal}.kw-result-series input{min-height:0}.kw-results details{border-top:1px solid var(--line);padding-top:8px;margin-top:10px}.kw-results summary{cursor:pointer;padding:6px 0;font-weight:600}.kw-results pre{white-space:pre-wrap;overflow-wrap:anywhere;max-height:240px;overflow:auto;background:var(--panel);padding:8px}.kw-result-data{display:grid;gap:4px;max-height:260px;overflow:auto;margin-top:8px}.kw-result-data button{text-align:left;white-space:normal;overflow-wrap:anywhere}.kw-result-data-path{overflow-wrap:anywhere}.kw-result-controls{display:flex;flex-wrap:wrap;gap:8px;align-items:center}.kw-result-controls input[type=range]{flex:1 1 140px}.kw-results [hidden]{display:none!important}@media(pointer:coarse){.kw-results button,.kw-results select,.kw-result-series label{min-height:44px}}",ox=class extends EventTarget{constructor(h,{theme:p="dark",boardViewer:w=null,palette:S="wayricad"}={}){if(super(),fh(S),!["light","dark"].includes(p))throw new TypeError("Choose light or dark theme.");let A=typeof h=="string"?globalThis.document?.querySelector(h):h;if(!A?.ownerDocument)throw new TypeError("Choose a results mount element.");if(Vi.has(A))throw new Error("This container already has a viewer.");this.host=A,this.doc=A.ownerDocument,this.theme=p,this.ticket=0,this.plotTicket=0,this.model=null,this.mode="2d",this.palette=S,this.opacity=.65,this.overlayWanted=!1,this.sourceState="unverified",this.sourceSnapshot=null,this.selected=new Set,this.stops=[],this.make=(Q,te)=>{let he=this.doc.createElement(Q);return te!==void 0&&(he.textContent=String(te)),he};let T=this.make;this.root=T("section"),this.root.className="kw-results",this.root.dataset.theme=p,this.root.setAttribute("aria-label","WayriCAD saved results");let H=T("style",WU),Y=T("strong","WayriCAD \xB7 saved results"),ee=T("div");ee.className="kw-result-tools",this.plotSelect=T("select"),this.plotSelect.setAttribute("aria-label","Saved result plot"),this.viewSelect=T("select"),this.viewSelect.setAttribute("aria-label","Result view");for(let[Q,te]of[["2d","2D field / graph"],["3d","3D saved field"]]){let he=T("option",te);he.value=Q,this.viewSelect.append(he)}this.sourceButton=this.button("Highlight saved net",()=>this.highlightSource()),this.routeButton=this.button("Locate saved route",()=>this.locateSource()),this.sourceButton.disabled=this.routeButton.disabled=!0,this.fitButton=this.button("Fit result",()=>this.scene?.fit()),this.downloadButton=this.button("Download full JSON",()=>this.download()),this.layerSelect=T("select"),this.layerSelect.setAttribute("aria-label","Saved result layer"),this.layerSelect.disabled=!0,this.paletteSelect=T("select"),this.paletteSelect.setAttribute("aria-label","Saved field palette");for(let[Q,te]of[["wayricad","WayriCAD"],["viridis","Viridis (4 stops)"],["inferno","Inferno (4 stops)"],["grayscale","Grayscale"]]){let he=T("option",te);he.value=Q,this.paletteSelect.append(he)}this.paletteSelect.value=S,this.paletteSelect.disabled=!0,this.paletteSelect.onchange=()=>{try{this.setPalette(this.paletteSelect.value)}catch(Q){this.paletteSelect.value=this.palette,this.fail(Q)}},ee.append(this.plotSelect,this.layerSelect,this.viewSelect,this.paletteSelect,this.fitButton,this.sourceButton,this.routeButton,this.downloadButton),this.status=T("p","Open a saved WayriCAD result JSON."),this.status.className="kw-result-status",this.status.setAttribute("role","status"),this.sourceNote=T("p","No PCB registration. Independent result plots do not establish engineering validity."),this.sourceNote.className="kw-result-small",this.viewport=T("div"),this.viewport.className="kw-result-viewport",this.canvas=T("canvas"),this.canvas.setAttribute("role","img"),this.canvas.setAttribute("aria-label","Saved numerical result plot; use the probe readout for values"),this.threeHost=T("div"),this.threeHost.className="kw-result-three",this.threeHost.hidden=!0,this.viewport.append(this.canvas,this.threeHost),this.legend=T("p"),this.legend.className="kw-result-small",this.colorBar=T("div"),this.colorBar.setAttribute("role","img"),this.colorBar.style.cssText="height:12px;max-width:480px;border:1px solid var(--line);border-radius:4px;margin-block:8px",this.colorBar.hidden=!0,this.boardStatus=T("p"),this.boardStatus.className="kw-result-small",this.boardStatus.setAttribute("role","status"),this.probe=T("output","Click the plot to probe retained values."),this.probe.setAttribute("aria-live","polite"),this.historyButton=this.button("Plot probe history",()=>this.showHistory()),this.historyButton.hidden=!0,this.frameRow=T("label","Saved frame"),this.frameRow.className="kw-result-controls",this.frame=T("input"),this.frame.type="range",this.frame.min="0",this.frame.step="1",this.frame.setAttribute("aria-label","Saved thermal frame"),this.frameTime=T("span"),this.frameRow.append(this.frame,this.frameTime),this.frameRow.hidden=!0,this.series=T("div"),this.series.className="kw-result-series",this.series.setAttribute("aria-label","Visible saved series"),this.seriesMore=this.button("More series",()=>{this.seriesPage=(this.seriesPage||0)+1,this.updateSeries()});let X=T("div");X.className="kw-result-controls",this.overlayInput=T("input"),this.overlayInput.type="checkbox",this.overlayInput.setAttribute("aria-label","Show result on matching PCB");let G=T("label");G.append(this.overlayInput,T("span","Show on matching PCB")),this.alpha=T("input"),this.alpha.type="range",this.alpha.min="0",this.alpha.max="100",this.alpha.value="65",this.alpha.setAttribute("aria-label","Saved field opacity"),X.append(G,this.alpha);let ae=T("details"),_e=T("summary","Producer, assumptions & display limits");this.metadata=T("pre"),ae.append(_e,this.metadata);let J=T("details");J.append(T("summary","Complete numerical data")),this.dataPath=T("p"),this.dataPath.className="kw-result-data-path",this.dataList=T("div"),this.dataList.className="kw-result-data",J.append(this.dataPath,this.dataList),this.root.append(H,Y,ee,this.status,this.sourceNote,this.viewport,this.colorBar,this.legend,this.probe,this.historyButton,this.frameRow,this.series,this.seriesMore,X,ae,J),A.append(this.root),Vi.set(A,this),this.plotSelect.onchange=()=>this.setPlot(Number(this.plotSelect.value)),this.viewSelect.onchange=()=>{this.setView(this.viewSelect.value).catch(Q=>this.fail(Q))},this.frame.oninput=()=>{try{this.setFrame(Number(this.frame.value))}catch(Q){this.frame.value=String(this.plot?.frameIndex||0),this.fail(Q)}},this.alpha.oninput=()=>this.setOpacity(Number(this.alpha.value)/100),this.layerSelect.onchange=()=>this.setLayer(this.layerSelect.value),this.overlayInput.onchange=()=>this.setBoardOverlay(this.overlayInput.checked),this.canvas.onpointerup=Q=>this.probeAt(Q),this.plotSelect.disabled=this.viewSelect.disabled=this.downloadButton.disabled=this.fitButton.disabled=this.overlayInput.disabled=this.alpha.disabled=!0,this.seriesMore.hidden=!0,this.observer=typeof ResizeObserver=="function"?new ResizeObserver(()=>this.invalidate()):null,this.observer?.observe(this.viewport),this.visible=!0,this.intersection=typeof IntersectionObserver=="function"?new IntersectionObserver(Q=>{this.visible=Q.some(te=>te.isIntersecting),this.visible&&this.invalidate()}):null,this.intersection?.observe(this.root),this.visibility=()=>{this.doc.hidden||this.invalidate()},this.doc.addEventListener?.("visibilitychange",this.visibility),this.root.append(this.boardStatus),this.attachBoard(w)}button(h,p){let w=this.make("button",h);return w.type="button",w.onclick=()=>{try{p()}catch(S){this.fail(S)}},w}assertActive(){if(this.disposed)throw new Error("Results viewer is disposed.")}emit(h,p){this.dispatchEvent(new CustomEvent(h,{detail:p}))}fail(h){this.disposed||(this.status.textContent=h.message,this.emit("error",{message:h.message}))}beginLoad(h){this.assertActive(),h?.throwIfAborted(),this.downloadController?.abort();let p=this.downloadController=new AbortController,w=++this.ticket,S=()=>p.abort(h.reason);return h?.addEventListener("abort",S,{once:!0}),{ticket:w,controller:p,current:()=>!this.disposed&&this.ticket===w,check:()=>{h?.throwIfAborted(),p.signal.throwIfAborted()},cleanup:()=>h?.removeEventListener("abort",S)}}async commitResult(h,p,w){w.check();let S=rx(h,{path:p}),A=await this.assessSource(S);return w.current()?(w.check(),this.scene?.dispose(),this.scene=null,this.boardLayer?.dispose(),this.boardLayer=null,this.model=S,this.downloadButton.disabled=!1,this.mode="2d",this.plotSelect.replaceChildren(),this.sourceLinks=ax(S),S.report.plots.forEach((T,H)=>{let Y=this.make("option",T.title);Y.value=String(H),this.plotSelect.append(Y)}),this.metadata.textContent=JSON.stringify(GU(S),null,2),this.rawPath=[],this.rawPage=0,this.showRaw(),this.setPlot(0),this.applyAssessment(A),this.emit("ready",{path:p,plots:S.report.plots.length,sourceState:this.sourceState}),!0):!1}async load(h,{path:p="wayricad-results.json",signal:w}={}){let S=this.beginLoad(w);try{return await this.commitResult(h,p,S)}catch(A){if(!S.current()&&!w?.aborted)return!1;throw A}finally{S.cleanup()}}async loadURL(h,{signal:p,credentials:w="omit",path:S}={}){let A=this.beginLoad(p);try{let T=new URL(h,this.doc.baseURI),H=await eo(T.href,{signal:A.controller.signal,credentials:w,limit:64*1024*1024});return A.current()?await this.commitResult(H,S||T.pathname.split("/").at(-1)||"wayricad-results.json",A):!1}catch(T){if(!A.current()&&!p?.aborted)return!1;throw T}finally{A.cleanup()}}getResults(){return this.assertActive(),this.model}getSourceState(){return this.assertActive(),this.sourceState}getView(){return this.assertActive(),this.mode}getPalette(){return this.assertActive(),this.palette}setPalette(h){if(this.assertActive(),fh(h),this.palette===h)return h;if(this.scene){if(typeof this.scene.setPalette!="function")throw new Error("Use a matching library distribution to change 3D palettes.");this.scene.setPalette(h),this.scene.setProbes?.(this.probePins())}return this.palette=h,this.paletteSelect.value=h,this.cache=null,this.updateColorBar(),this.boardLayer?.sync(),this.invalidate(),this.emit("palettechange",{palette:h}),h}updateColorBar(){let h=this.colorRange;this.colorBar.hidden=!this.surface||!h,h&&(this.colorBar.style.background="linear-gradient(to right,"+fh(this.palette).map(p=>"rgb("+p.join(",")+")").join(",")+")",this.colorBar.setAttribute("aria-label",this.palette+" palette, "+Gs(h[0])+" to "+Gs(h[1])+" "+(this.plot?.unit||"")+". Missing values are transparent."))}getResultLayers(){return this.assertActive(),[...new Set((this.model?.report.plots||[]).map(h=>h.layerName).filter(Boolean))]}setLayer(h){this.assertActive();let p=this.model?.report.plots||[],w=this.plot?.title?.replace(/ · [^·]+$/,""),S=p.map((T,H)=>({p:T,i:H})).filter(({p:T})=>T.layerName===h),A=S.find(({p:T})=>T.type===this.plot?.type&&T.title.replace(/ · [^·]+$/,"")===w)||S[0];if(!A)throw new RangeError("Choose a saved result layer.");return this.setPlot(A.i)}setBoardOverlay(h){if(this.assertActive(),typeof h!="boolean")throw new TypeError("Choose true or false for the board overlay.");return this.overlayWanted=h&&this.sourceReady()&&!!this.surface&&this.model?.metadata.portable?.coordinate_frame==="KiCad PCB XY in mm",this.overlayInput.checked=this.overlayWanted,this.boardLayer?.sync(),this.overlayWanted}getBoardOverlayState(){return this.assertActive(),this.boardLayer?.getState()||{placed:!1,reason:"No matching board overlay."}}getRenderStats(){return this.assertActive(),{view:this.mode,palette:this.palette,sourceState:this.sourceState,preview:this.cache?{width:this.cache.width,height:this.cache.height,pixelTests:this.cache.pixelTests,range:[...this.cache.range],drawn:this.cache.drawn,omitted:this.cache.omitted}:null,scene:this.scene?.getRenderStats()||null,boardOverlay:this.getBoardOverlayState()}}setPlot(h){if(this.assertActive(),!this.model)return!1;let p=this.model.report.plots[h];if(!p){if(this.model.report.plots.length)throw new RangeError("Choose a saved plot.");return this.plot=null,this.surface=null,this.paletteSelect.disabled=!0,this.colorBar.hidden=!0,this.plotSelect.disabled=this.viewSelect.disabled=this.fitButton.disabled=!0,this.series.replaceChildren(),this.legend.textContent="",this.frameRow.hidden=!0,this.historyButton.hidden=!0,this.status.textContent="No supported plot; complete numerical data is available below.",this.invalidate(),!1}return this.plotSelect.disabled=this.viewSelect.disabled=!1,this.plotTicket++,this.scene?.dispose(),this.scene=null,this.mode="2d",this.plotIndex=h,this.plot=p,this.plotSelect.value=String(h),this.viewSelect.value="2d",this.cache=null,this.lastProbe=null,this.historyButton.hidden=!0,this.historyButton.textContent="Plot probe history",this.historySource=null,this.seriesPage=0,this.colorRange=this.rangeForPlot(p),this.selected=new Set((p.series||[]).slice(0,/eye/i.test(p.title)?32:4).map((w,S)=>S)),this.updatePlot(),this.updateSeries(),this.status.textContent=p.title,this.emit("plotchange",{index:h,title:p.title}),!0}updatePlot(h){let p=this.getResultLayers();this.layerSelect.replaceChildren(...p.map(w=>{let S=this.make("option",w);return S.value=w,S})),this.layerSelect.disabled=!p.length,this.layerSelect.value=this.plot?.layerName||"",this.fitButton.disabled=this.mode!=="3d",this.viewSelect.value=this.mode,this.surface=h===void 0?Ym(this.plot):h,this.paletteSelect.disabled=!this.surface,this.updateColorBar(),this.frameRow.hidden=!this.plot?.frames,this.frame.max=String(Math.max(0,(this.plot?.frames?.length||1)-1)),this.frame.value=String(this.plot?.frameIndex||0),this.frameTime.textContent=this.plot?.frames?Gs(this.plot.frames[this.plot.frameIndex||0]?.time_s)+" s \xB7 "+(Number(this.frame.value)+1)+"/"+this.plot.frames.length:"",this.viewSelect.options[1].disabled=!this.surface?.zKnown,this.alpha.disabled=!this.surface,this.threeHost.hidden=this.mode!=="3d",this.canvas.hidden=this.mode==="3d",this.overlayInput.disabled=this.sourceState!=="matching"||!this.surface||this.model?.metadata.portable?.coordinate_frame!=="KiCad PCB XY in mm",this.overlayInput.checked=!this.overlayInput.disabled&&this.overlayWanted,this.invalidate(),this.boardLayer?.sync()}rangeForPlot(h){if(h?.frames&&h.cells&&Number.isSafeInteger(h.layerIndex)){let p=h.cells.length,w=h.layerIndex*p;function*S(){for(let A of h.frames)for(let T=0;T<p;T++)yield A.temperatures_c?.[w+T]}return mh(S())}if(h?.type==="mesh-field")return mh(h.values);if(h?.type==="heatmap"){function*p(){for(let w of h.values)yield*w}return mh(p())}return null}setFrame(h){if(this.assertActive(),!this.plot?.frames||!Number.isSafeInteger(h)||h<0||h>=this.plot.frames.length)throw new RangeError("Choose a saved thermal frame.");let p={...this.plot,frameIndex:h,values:nx(this.plot,h)},w=Ym(p);if(this.scene)try{this.scene.setSurface(w)}catch(S){if(!["NO_SAVED_FIELD_VALUES","SAVED_Z_REQUIRED"].includes(S.code))throw S;this.scene.dispose(),this.scene=null,this.mode="2d",this.status.textContent="Saved frame has no supported 3D field; showing its 2D data."}this.plot=p,this.cache=null,this.updatePlot(w),this.lastProbe&&this.showProbe(pd(this.plot,this.lastProbe.x,this.lastProbe.y)),this.emit("framechange",{index:h,time:this.plot.frames[h].time_s})}async setView(h){if(this.assertActive(),!["2d","3d"].includes(h))throw new TypeError("Choose 2d or 3d results.");let p=++this.plotTicket;if(h==="2d")return this.scene?.dispose(),this.scene=null,this.mode=h,this.viewSelect.value=h,this.updatePlot(),h;if(!this.surface?.zKnown)throw new Error("This field has no explicit saved elevation. Use its 2D plot.");let w=this.surface,S=await Promise.resolve().then(()=>(Tv(),Av)),A=await S.loadThree();if(this.disposed||p!==this.plotTicket||w!==this.surface)return!1;if(typeof A.mountSavedResult3D!="function")throw new Error("This renderer does not support saved-result 3D. Use the matching library distribution.");let T=A.mountSavedResult3D(this.threeHost,w,{dark:this.theme==="dark",palette:this.palette,range:this.colorRange||void 0,coordinateUnit:this.model.metadata.portable?.coordinate_frame==="KiCad PCB XY in mm"?"mm":"source units",onProbe:H=>this.showProbe(H),onDiagnostics:H=>{this.disposed||(this.legend.textContent=H.join(" "))}});if(this.disposed||p!==this.plotTicket)return T.dispose(),!1;if(T.unavailable)throw T.dispose(),new Error(T.diagnostic?.message||T.diagnostic||"Saved field 3D is unavailable.");return this.scene?.dispose(),this.scene=T,T.setOpacity(this.opacity),T.setProbes?.(this.probePins()),this.mode="3d",this.viewSelect.value="3d",this.updatePlot(),h}setTheme(h){if(this.assertActive(),!["light","dark"].includes(h))throw new TypeError("Choose light or dark theme.");this.theme=h,this.root.dataset.theme=h,this.scene?.setTheme(h==="dark"),this.invalidate()}setOpacity(h){if(this.assertActive(),!Number.isFinite(h)||h<0||h>1)throw new RangeError("Opacity must be 0\u20131.");return this.opacity=h,this.alpha.value=String(Math.round(h*100)),this.scene?.setOpacity(h),this.boardLayer?.sync(),this.invalidate(),h}attachBoard(h){if(this.assertActive(),this.boardLayer?.dispose(),this.boardLayer=null,this.stopBoard?.(),this.boardViewer=h,this.sourceHashCache=null,this.sourceSnapshot=null,this.sourceState="unverified",h){let p=()=>{this.checkSource().catch(A=>this.fail(A))};h.addEventListener("ready",p);let w=A=>this.receiveSourceSelection(A.detail),S=A=>{let T=A.detail?.probe;if(this.sourceReady()&&this.overlayInput.checked&&this.boardLayer?.ownsProbe(T)&&[T.x,T.y,T.z,T.value].every(Number.isFinite)){let{overlayOwner:H,...Y}=T;this.showProbe(Y)}};h.addEventListener("select",w),h.addEventListener("analysisprobe",S),this.stopBoard=()=>{h.removeEventListener("ready",p),h.removeEventListener("select",w),h.removeEventListener("analysisprobe",S)}}else this.stopBoard=null;this.model&&this.checkSource().catch(p=>this.fail(p))}sourceReady(){return this.sourceState==="matching"&&this.boardViewer?.source===this.sourceSnapshot&&!this.boardViewer?.disposed}highlightSource(){if(this.assertActive(),!this.sourceReady()||!this.sourceLinks?.netName)return!1;let h=this.boardViewer.getNets().filter(p=>p.name===this.sourceLinks.netName);return h.length===1?this.boardViewer.selectNet(h[0].id,{locate:!0}):!1}locateSource(){if(this.assertActive(),!this.sourceReady())return!1;for(let h of this.sourceLinks?.objectIds||[])if(this.boardViewer.selectObject(h,{locate:!0}))return!0;return!1}probeSourcePoint(h,p){!this.sourceReady()||!this.surface||this.showProbe(pd(this.plot,h,p))}receiveSourceSelection(h){if(!this.sourceReady()||!this.model)return;let p=this.boardViewer?.getSelectionPosition?.();p&&(!this.overlayInput.checked&&p.layer&&p.layer!==this.plot?.layerName&&this.getResultLayers().includes(p.layer)&&this.setLayer(p.layer),this.probeSourcePoint(p.x,p.y));let w=h?.item||{},S=!!(this.sourceLinks?.objectIds.includes(w.uuid||w.id)||this.sourceLinks?.netName&&w.netName===this.sourceLinks.netName);this.viewport.style.outline=S?"2px solid var(--accent)":"",S&&(this.status.textContent=(this.plot?.title||"Saved result")+" \xB7 source selection matched",this.emit("sourceselection",{matched:!0,netName:w.netName||null,objectId:w.uuid||w.id||null}))}async assessSource(h){let p=this.boardViewer,w=p?.source;if(!h||p?.kind!=="pcb"||typeof w!="string")return{state:"unverified",source:null,viewer:p};if(!globalThis.crypto?.subtle)return{state:"unverified",source:w,viewer:p,reason:"PCB registration requires HTTPS or localhost; independent saved results remain available."};(this.sourceHashCache?.viewer!==p||this.sourceHashCache?.source!==w)&&(this.sourceHashCache={viewer:p,source:w,promise:Dm(w)});let S=await this.sourceHashCache.promise;return{state:p.source===w?ix(h,S):"unverified",source:w,viewer:p}}applyAssessment(h){this.boardLayer?.dispose(),this.boardLayer=null,this.overlayInput.checked=this.overlayWanted,this.sourceState=h.viewer===this.boardViewer&&h.viewer?.source===h.source?h.state:"unverified",this.sourceSnapshot=this.sourceState==="matching"?h.source:null,this.sourceButton.disabled=this.sourceState!=="matching"||!this.sourceLinks?.netName,this.routeButton.disabled=this.sourceState!=="matching"||!this.sourceLinks?.objectIds?.length,this.sourceNote.textContent=this.sourceState==="matching"?"Matching saved PCB bytes \xB7 result provenance and solver applicability remain producer claims.":this.sourceState==="stale"?"Stale result \xB7 loaded PCB hash differs. Board overlay is disabled.":h.reason||"Unverified PCB association \xB7 board overlay is disabled.",this.sourceState==="matching"&&(this.boardLayer=uA(this.boardViewer,{surface:()=>this.surface,range:()=>this.colorRange,palette:()=>this.palette,probe:()=>this.lastProbe,onProbe:(p,w)=>this.probeSourcePoint(p,w),onState:p=>{this.boardStatus.textContent=p.placed?p.view==="3d"?"Registered on 3D PCB \xB7 "+(p.layer||"saved elevation")+" \xB7 visible through board and components":"Registered on PCB \xB7 "+(p.layer||"saved XY field"):p.reason},raster:()=>{try{return this.getRaster()}catch(p){return this.fail(p),null}},allowed:()=>!this.disposed&&this.overlayInput.checked&&this.model?.metadata.portable?.coordinate_frame==="KiCad PCB XY in mm"&&this.boardViewer?.source===this.sourceSnapshot&&this.sourceState==="matching",layer:()=>this.plot?.layerName,opacity:()=>this.opacity})),this.updatePlotIfLoaded(),this.emit("sourcechange",{state:this.sourceState})}async checkSource(){let h=this.model,p=this.ticket,w=this.sourceTicket=(this.sourceTicket||0)+1;this.boardViewer?.source!==this.sourceSnapshot&&(this.overlayWanted=!1),this.sourceState="unverified",this.sourceSnapshot=null,this.boardLayer?.dispose(),this.boardLayer=null,this.overlayInput.checked=!1,this.overlayInput.disabled=!0,this.sourceButton.disabled=this.routeButton.disabled=!0,this.sourceNote.textContent="Unverified PCB association \xB7 independent saved results only.";let S=await this.assessSource(h);return this.disposed||this.model!==h||this.ticket!==p||this.sourceTicket!==w?"unverified":(this.applyAssessment(S),this.sourceState)}updatePlotIfLoaded(){this.plot&&this.updatePlot(this.surface)}getRaster(){if(!this.surface)return null;if(this.cache)return this.cache;let h=cA(this.surface,{range:this.colorRange||void 0,palette:this.palette});if(!h)return null;let p=this.make("canvas");p.width=h.width,p.height=h.height;let w=p.getContext("2d"),S=w.createImageData(h.width,h.height);return S.data.set(h.pixels),w.putImageData(S,0,0),this.cache={...h,canvas:p},this.cache}invalidate(){this.disposed||this.frameRequest!==void 0||!this.visible||this.doc.hidden||(this.frameRequest=requestAnimationFrame(()=>{this.frameRequest=void 0;try{!this.disposed&&this.visible&&!this.doc.hidden&&this.draw()}catch(h){this.fail(h)}}))}draw(){if(this.mode==="3d")return;let h=this.viewport.getBoundingClientRect(),p=Math.max(1,h.width),w=Math.max(1,h.height),S=Math.min(2,globalThis.devicePixelRatio||1);this.canvas.width=Math.max(1,Math.round(p*S)),this.canvas.height=Math.max(1,Math.round(w*S));let A=this.canvas.getContext("2d");if(A.setTransform(S,0,0,S,0,0),A.fillStyle=this.theme==="dark"?"#1b2d3b":"#eef4f8",A.fillRect(0,0,p,w),this.mapping=null,!this.plot)return;if(this.surface){let Q=this.getRaster();if(!Q){this.legend.textContent="No finite saved field coverage.";return}let te=Q.bounds,he=Math.min((p-44)/(te.x1-te.x0),(w-44)/(te.y1-te.y0)),be=(te.x1-te.x0)*he,De=(te.y1-te.y0)*he,Ke=(p-be)/2,qe=(w-De)/2;if(A.globalAlpha=this.opacity,A.drawImage(Q.canvas,Ke,qe,be,De),A.globalAlpha=1,this.lastProbe&&Number.isFinite(this.lastProbe.x)&&Number.isFinite(this.lastProbe.y)){let $e=Ke+(this.lastProbe.x-te.x0)*he,Xe=qe+(this.lastProbe.y-te.y0)*he;A.beginPath(),A.arc($e,Xe,6,0,Math.PI*2),A.strokeStyle="#fff",A.lineWidth=3,A.stroke(),A.strokeStyle="#073e49",A.lineWidth=1,A.stroke()}this.mapping={x:Ke,y:qe,width:be,height:De,bounds:te,field:!0},this.legend.textContent=Gs(Q.range[0])+" \u2013 "+Gs(Q.range[1])+" "+(this.plot.unit||"")+" \xB7 "+Q.drawn+" supplied triangles \xB7 "+Q.omitted+" missing/degenerate triangles omitted. Transparent areas have no drawn data. Grid boundary cells are not clipped to board cutouts.";return}if(!this.plot.series){this.legend.textContent="No supported spatial geometry. Inspect complete numerical data.";return}let T=hA(this.plot,this.selected);if(this.chartData=T,!T.bounds){this.legend.textContent="No finite selected samples.";return}let{x:[H,Y],y:[ee,X]}=T.bounds,G=60,ae=18,_e=Math.max(1,p-78),J=Math.max(1,w-62);A.strokeStyle=this.theme==="dark"?"#7891a3":"#5a7083",A.beginPath(),A.moveTo(G,ae),A.lineTo(G,ae+J),A.lineTo(G+_e,ae+J),A.stroke();for(let Q of T.series){A.strokeStyle=qm[Q.index%qm.length],A.lineWidth=1.4,A.beginPath();let te=!1;for(let he of Q.points){if(!Number.isFinite(he.x)||!Number.isFinite(he.y)){te=!1;continue}let be=G+(he.x-H)/(Y-H)*_e,De=ae+J-(he.y-ee)/(X-ee)*J;te?A.lineTo(be,De):(A.moveTo(be,De),te=!0)}if(A.stroke(),Q.points.length===1&&Number.isFinite(Q.points[0].y)){let he=Q.points[0];A.fillStyle=A.strokeStyle,A.fillRect(G+(he.x-H)/(Y-H)*_e-2,ae+J-(he.y-ee)/(X-ee)*J-2,4,4)}}A.fillStyle=this.theme==="dark"?"#edf4f8":"#152534",A.font="11px system-ui",A.fillText(Gs(X),4,ae+10),A.fillText(Gs(ee),4,ae+J),A.fillText(Gs(H),G,ae+J+17),A.textAlign="right",A.fillText(Gs(Y),G+_e,ae+J+17),A.textAlign="center",A.fillText(this.plot.xLabel||"Saved axis",G+_e/2,w-7),A.textAlign="left",this.mapping={x:G,y:ae,width:_e,height:J,bounds:{x0:H,x1:Y,y0:ee,y1:X},field:!1},this.legend.textContent=T.series.length+" of "+this.plot.series.length+" saved series selected \xB7 "+T.shown+" of "+T.total+" selected saved samples shown"+(T.limited?" \xB7 DISPLAY LIMIT: remaining samples are retained in the full JSON.":" \xB7 missing values break curves; repeated timestamps are retained.")}updateSeries(){this.series.replaceChildren();let h=this.plot?.series||[],p=(this.seriesPage||0)*20;for(let w=p;w<Math.min(h.length,p+20);w++){let S=this.make("label"),A=this.make("input");A.type="checkbox",A.checked=this.selected.has(w),A.onchange=()=>{A.checked?this.selected.add(w):this.selected.delete(w),this.invalidate()},S.append(A,this.make("span",h[w].name)),S.style.borderBottom="2px solid "+qm[w%qm.length],this.series.append(S)}if(p>0){let w=this.button("Previous series",()=>{this.seriesPage--,this.updateSeries()});this.series.append(w)}this.seriesMore.hidden=p+20>=h.length}probeAt(h){if(!this.mapping||!this.plot)return;let p=this.canvas.getBoundingClientRect(),w=this.mapping,S=h.clientX-p.left,A=h.clientY-p.top;if(S<w.x||S>w.x+w.width||A<w.y||A>w.y+w.height)return;let T=w.bounds.x0+(S-w.x)/w.width*(w.bounds.x1-w.bounds.x0),H=w.field?w.bounds.y0+(A-w.y)/w.height*(w.bounds.y1-w.bounds.y0):w.bounds.y1-(A-w.y)/w.height*(w.bounds.y1-w.bounds.y0),Y=[...this.selected][0];if(this.showProbe(pd(this.plot,T,H,this.plot.series?.[Y]?.name)),this.sourceReady()&&this.sourceLinks?.netName){let ee=this.boardViewer.getNets().filter(X=>X.name===this.sourceLinks.netName);ee.length===1&&this.boardViewer.selectNet(ee[0].id,{locate:!1})}}probePins(){let h=this.lastProbe;if(!h||!this.surface||!Number.isFinite(h.x)||!Number.isFinite(h.y))return[];let p=Number.isFinite(h.z)?h.z:this.surface.points[0]?.[2];return Number.isFinite(p)?[{x:h.x,y:h.y,z:p}]:[]}showProbe(h){this.lastProbe=h,this.scene?.setProbes?.(this.probePins()),this.boardLayer?.sync(),this.invalidate(),this.probe.textContent=h?(h.name||this.plot?.title||"Saved field")+" \xB7 "+Gs(h.value)+" "+(h.unit||"")+" \xB7 x "+Gs(h.x)+(h.y!==void 0?", y "+Gs(h.y):"")+" \xB7 "+(h.method||"Saved field"):"No saved value at this position.",this.historyButton.hidden=!h||!this.plot?.frames||!Number.isFinite(h.y),this.emit("probe",{...h})}showHistory(){if(this.historySource){this.plot=this.historySource,this.historySource=null,this.cache=null,this.colorRange=this.rangeForPlot(this.plot),this.lastProbe=null,this.historyButton.hidden=!0,this.historyButton.textContent="Plot probe history",this.selected=new Set,this.updatePlot(),this.updateSeries(),this.status.textContent=this.plot.title;return}if(!this.lastProbe)return;let h=sx(this.plot,this.lastProbe.x,this.lastProbe.y);h&&(this.scene?.dispose(),this.scene=null,this.historySource=this.plot,this.mode="2d",this.viewSelect.value="2d",this.plot=h,this.surface=null,this.colorRange=null,this.cache=null,this.selected=new Set([0]),this.updatePlot(),this.updateSeries(),this.historyButton.hidden=!1,this.historyButton.textContent="Return to saved field",this.status.textContent=h.title)}showRaw(){if(this.dataList.replaceChildren(),!this.model)return;let h=this.model.raw;for(let T of this.rawPath)h=h?.[T];if(this.dataPath.textContent="root"+this.rawPath.map(T=>"["+JSON.stringify(String(T).slice(0,120))+"]").join(""),this.rawPath.length&&this.dataList.append(this.button("Up one level",()=>{this.rawPath.pop(),this.rawPage=0,this.showRaw()})),h===null||typeof h!="object"){if(typeof h=="string"){let T=(this.rawPage||0)*4096;this.dataList.append(this.make("pre",h.slice(T,T+4096))),T&&this.dataList.append(this.button("Previous text block",()=>{this.rawPage--,this.showRaw()})),T+4096<h.length&&this.dataList.append(this.button("Next text block",()=>{this.rawPage++,this.showRaw()})),this.dataList.append(this.make("small",Math.min(T+4096,h.length)+" of "+h.length+" characters"))}else this.dataList.append(this.make("pre",JSON.stringify(h)));return}let p=Array.isArray(h),w=p?null:Object.keys(h),S=p?h.length:w.length,A=(this.rawPage||0)*100;for(let T=A;T<Math.min(S,A+100);T++){let H=p?String(T):w[T],Y=h[H],ee=String(H).slice(0,120)+": "+(Y&&typeof Y=="object"?Array.isArray(Y)?"["+Y.length+" saved entries]":"{structured fields}":typeof Y=="string"?JSON.stringify(Y.slice(0,180))+(Y.length>180?" \u2026":""):JSON.stringify(Y));this.dataList.append(this.button(ee,()=>{this.rawPath.push(H),this.rawPage=0,this.showRaw()}))}A&&this.dataList.append(this.button("Previous entries",()=>{this.rawPage--,this.showRaw()})),A+100<S&&this.dataList.append(this.button("Next entries",()=>{this.rawPage++,this.showRaw()})),this.dataList.append(this.make("small",Math.min(A+100,S)+" of "+S+" entries \xB7 full arrays retained."))}download(){if(this.assertActive(),!this.model)return;let h=URL.createObjectURL(new Blob([JSON.stringify(this.model.raw)+`
`],{type:"application/json"})),p=this.make("a");p.href=h,p.download="wayricad-results.json",p.click(),setTimeout(()=>URL.revokeObjectURL(h),0)}clear(){this.assertActive(),this.ticket++,this.plotTicket++,this.downloadController?.abort(),this.scene?.dispose(),this.scene=null,this.boardLayer?.dispose(),this.boardLayer=null,this.model=this.plot=this.surface=this.cache=this.sourceSnapshot=this.historySource=this.sourceHashCache=null,this.paletteSelect.disabled=!0,this.colorBar.hidden=!0,this.plotSelect.disabled=this.viewSelect.disabled=this.downloadButton.disabled=this.fitButton.disabled=!0,this.plotSelect.replaceChildren(),this.series.replaceChildren(),this.dataList.replaceChildren(),this.metadata.textContent="",this.status.textContent="No saved result loaded.",this.sourceState="unverified",this.sourceLinks=null,this.sourceButton.disabled=this.routeButton.disabled=!0,this.sourceNote.textContent="No PCB registration. Independent saved results only.",this.threeHost.hidden=!0,this.canvas.hidden=!1,this.frameRow.hidden=!0,this.historyButton.hidden=!0,this.legend.textContent="",this.probe.textContent="",this.overlayWanted=!1,this.overlayInput.checked=!1,this.overlayInput.disabled=!0,this.boardStatus.textContent="",this.layerSelect.replaceChildren(),this.layerSelect.disabled=!0,this.mode="2d",this.invalidate()}dispose(){this.disposed||(this.clear(),this.disposed=!0,this.frameRequest!==void 0&&cancelAnimationFrame(this.frameRequest),this.observer?.disconnect(),this.intersection?.disconnect(),this.doc.removeEventListener?.("visibilitychange",this.visibility),this.stopBoard?.(),this.paletteSelect.onchange=null,this.canvas.width=this.canvas.height=1,this.root.remove(),Vi.get(this.host)===this&&Vi.delete(this.host),this.boardViewer=null)}};Bl();var B8=Vn(pA(),1),XU=globalThis.KiCadDesignDiff,lx=globalThis.KiCadBomAnalytics,YU=sa,qU=1e5,KU=64,ZU=32*1024*1024,mA=new WeakSet,Ms=m=>m&&typeof m=="object"&&!Array.isArray(m)?m.quoted:m,fd=m=>Array.isArray(m)?String(Ms(m[0])):"",Hl=(m,h)=>Array.isArray(m)?m.filter(p=>fd(p)===h):[],$m=(m,h)=>Hl(m,h)[0],Zm=(m,h)=>Ms($m(m,h)?.[1]);function gA(m,h){if(typeof m!="string")throw new TypeError("Source must be KiCad text.");if(new TextEncoder().encode(m).length>YU)throw new Error("Source exceeds 256 MiB.");if(typeof h!="string"||!h||h.length>1024||/[\x00-\x1f\x7f]/.test(h))throw new TypeError("A source path of at most 1024 characters without control characters is required.");let p=XU.parse(m),w=fd(p);if(!["kicad_pcb","kicad_sch"].includes(w))throw new Error("Expected a saved KiCad PCB or schematic.");let S=0;for(let A of p)if(Array.isArray(A)&&(S++,fd(A)==="footprint"&&(S+=Hl(A,"pad").length),fd(A)==="zone"&&(S+=Hl(A,"polygon").length+Hl(A,"filled_polygon").length),S>qU))throw new Error("Source exceeds the 100,000-object analytics limit.");return{ast:p,root:w}}function cx(m){if(m&&typeof m=="object"&&!Object.isFrozen(m)){for(let h of Object.values(m))cx(h);Object.freeze(m)}return m}function fA(m,h){let p=$m(m,h);if(!p)return null;if(p.length===1)return!0;let w=String(Ms(p[1])).toLowerCase();return["yes","true","1"].includes(w)?!0:["no","false","0"].includes(w)?!1:null}function $U(m,h,p,w){let S=fd(m),A={},T=Hl(m,"property");for(let ae of T){if(ae.length<3)continue;let _e=String(Ms(ae[1]));["Reference","Value","Footprint"].includes(_e)&&(A[_e]=String(Ms(ae[2])))}for(let ae of T){if(ae.length<3)continue;let _e=String(Ms(ae[1]));if(!Object.hasOwn(A,_e)){if(Object.keys(A).length>=KU){w.add("Part properties limited to 64 saved fields.");continue}Object.defineProperty(A,_e,{value:String(Ms(ae[2])),enumerable:!0,writable:!0,configurable:!0})}}if(S==="footprint")for(let[ae,_e]of[["reference","Reference"],["value","Value"]]){let J=Hl(m,"fp_text").find(Q=>Ms(Q[1])===ae);!Object.hasOwn(A,_e)&&J?.length>=3&&(A[_e]=String(Ms(J[2])))}let H=S==="symbol"?Zm(m,"lib_id"):Ms(m[1]);H!==void 0&&!Object.hasOwn(A,"Library ID")&&(A["Library ID"]=String(H));let Y=$m(m,"attr")?.slice(1).map(Ms).map(String)||[],ee=ae=>["yes","true","1","dnp","dni","do not populate","do not install"].includes(String(ae??"").trim().toLowerCase()),X=T.some(ae=>["dnp","do not populate","dni","do not install"].includes(String(Ms(ae[1])).trim().toLowerCase())&&ee(Ms(ae[2]))),G=Zm(m,"uuid")??Zm(m,"tstamp")??null;return{id:G?`${h}#${String(G)}`:`${h}#object-${p}`,uuid:G===null?null:String(G),kind:S,path:h,reference:A.Reference||null,properties:A,populated:!(fA(m,"dnp")===!0||Y.includes("dnp")||X),excludeFromBom:fA(m,"in_bom")===!1||Y.includes("exclude_from_bom")}}function hx(m,{path:h="board.kicad_pcb"}={}){let{ast:p,root:w}=gA(m,h);if(w!=="kicad_pcb")throw new Error("Board analytics requires a saved PCB.");let S=lx.board(m),A=Zm($m(p,"general"),"thickness");return A!==void 0&&(!Number.isFinite(Number(A))||Number(A)<=0)&&(S.boardThicknessMm=null,S.warnings.push("Invalid or nonpositive saved board thickness omitted.")),cx({path:h,sourceKind:"pcb",...S})}function ux(m,{path:h="drawing.kicad_pcb"}={}){let{ast:p,root:w}=gA(m,h),S=new Set,T=Hl(p,w==="kicad_pcb"?"footprint":"symbol").map((ee,X)=>$U(ee,h,X+1,S));if(w==="kicad_pcb"){let ee=new Map;for(let X of T)X.uuid&&ee.set(X.uuid,(ee.get(X.uuid)||0)+1);T.forEach((X,G)=>{if(X.uuid&&ee.get(X.uuid)>1){for(X.savedUUID=X.uuid,X.uuid=null,X.id=h+"#object-"+(G+1);ee.has(X.id);)X.id+="#";S.add("Duplicate saved PCB footprint UUIDs are ambiguous; affected parts cannot be selected by UUID.")}})}let H=lx.bom(T),Y=cx({path:h,sourceKind:w==="kicad_pcb"?"pcb":"schematic",...H,warnings:[...S],limits:"BOM counts saved file/reference identities; reused sheet instances are not expanded. Source is limited to 256 MiB and 100,000 objects; part properties are limited to 64 saved fields. CSV export is limited to 32 MiB UTF-8."});return mA.add(Y),Y}function dx(m){if(!m||!mA.has(m))throw new TypeError("Expected a report returned by buildBOM.");let h=new TextEncoder,p=0,w=S=>{p+=S.length*2+S.length-1+2;for(let A of S){let T=String(A??"");p+=h.encode(T).length,/^[\s]*[=+@-]/.test(T)&&p++;for(let H=0;H<T.length;H++)T[H]==='"'&&p++;if(p>ZU)throw new Error("BOM CSV exceeds 32 MiB UTF-8.")}};w(["Reference","Value","Footprint","Population","File"]);for(let S of m.groups)for(let A of S.parts)w([A.reference||"",S.value,S.footprint,S.populated?"Fitted":"DNP",A.path]);return lx.csv(m)}Ul();var Ea=(m,h=180)=>{let p=String(m??"");return p.length>h?p.slice(0,h)+"\u2026":p},md=(m,h=3)=>Number.isFinite(m)?Number(m.toFixed(h)).toString():"Not available",JU=".kw-bom{--bg:#14212c;--panel:#1b2d3b;--ink:#edf4f8;--muted:#b8c8d5;--line:#3d5668;--accent:#69dce3;background:var(--bg);color:var(--ink);border:1px solid var(--line);border-radius:10px;padding:12px;font:13px/1.5 system-ui;min-width:0;color-scheme:dark}.kw-bom[data-theme=light]{--bg:#fff;--panel:#eef4f8;--ink:#152534;--muted:#40566a;--line:#aebdca;--accent:#00727d;color-scheme:light}.kw-bom *{box-sizing:border-box}.kw-bom button,.kw-bom input{font:inherit;color:var(--ink);background:var(--panel);border:1px solid var(--line);border-radius:5px;padding:8px;min-height:40px;min-width:0;max-width:100%}.kw-bom button{cursor:pointer}.kw-bom button:disabled{opacity:.5;cursor:default}.kw-bom button[aria-pressed=true],.kw-bom .kw-bom-selected{border-color:var(--accent);box-shadow:inset 3px 0 var(--accent)}.kw-bom :focus-visible{outline:2px solid var(--accent);outline-offset:2px}.kw-bom-tools{display:flex;flex-wrap:wrap;gap:8px;align-items:center}.kw-bom-tools input[type=search]{flex:1 1 180px}.kw-bom label{display:flex;align-items:center;gap:6px}.kw-bom label input{min-height:0}.kw-bom p{overflow-wrap:anywhere;margin:8px 0}.kw-bom-small{color:var(--muted);font-size:12px}.kw-bom-list{display:grid;gap:7px;margin:12px 0;max-height:520px;overflow:auto;overscroll-behavior:contain}.kw-bom-row{padding:10px;border:1px solid var(--line);border-radius:6px;overflow-wrap:anywhere;background:var(--panel)}.kw-bom-row.kw-bom-hover{border-color:#d9902c;box-shadow:inset 3px 0 #d9902c}.kw-bom-row button{width:100%;text-align:left}.kw-bom-members{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px}.kw-bom-members button{width:auto;max-width:100%}.kw-bom-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:8px}.kw-bom-grid>div{padding:10px;background:var(--panel);border:1px solid var(--line);border-radius:6px}.kw-bom [hidden]{display:none!important}.kw-bom details{border-top:1px solid var(--line);padding-top:8px;margin-top:12px}.kw-bom summary{cursor:pointer;min-height:40px}.kw-bom pre{white-space:pre-wrap;overflow-wrap:anywhere;max-height:250px;overflow:auto;background:var(--panel);padding:10px}@media(pointer:coarse){.kw-bom button,.kw-bom input,.kw-bom summary{min-height:44px}}",px=class extends EventTarget{constructor(h,{viewer:p=null,theme:w="dark"}={}){if(super(),!["light","dark"].includes(w))throw new TypeError("Choose light or dark theme.");let S=typeof h=="string"?globalThis.document?.querySelector(h):h;if(!S?.ownerDocument)throw new TypeError("Choose a BOM mount element.");if(Vi.has(S))throw new Error("This container already has a viewer.");this.host=S,this.doc=S.ownerDocument,this.theme=w,this.mode="parts",this.query="",this.grouped=!0,this.page=0,this.report=null,this.stats=null,this.source=null,this.path=null,this.selectedUUID=null,this.disposed=!1,this.make=(G,ae)=>{let _e=this.doc.createElement(G);return ae!==void 0&&(_e.textContent=String(ae)),_e};let A=this.make;this.root=A("section"),this.root.className="kw-bom",this.root.dataset.theme=w,this.root.setAttribute("aria-label","Saved BOM and board data");let T=A("style",JU),H=A("div");H.className="kw-bom-tools",this.partsButton=this.button("BOM",()=>this.setMode("parts")),this.boardButton=this.button("Board data",()=>this.setMode("board")),this.downloadButton=this.button("Export full BOM CSV",()=>this.downloadCSV()),H.append(A("strong","Saved design data"),this.partsButton,this.boardButton,this.downloadButton),this.status=A("p","Load a saved KiCad PCB or schematic."),this.status.setAttribute("role","status"),this.summary=A("p"),this.filters=A("div"),this.filters.className="kw-bom-tools",this.search=A("input"),this.search.type="search",this.search.maxLength=200,this.search.placeholder="Reference, value or footprint",this.search.setAttribute("aria-label","Find an eligible BOM part"),this.search.oninput=()=>this.setQuery(this.search.value);let Y=A("label","Group equal value / footprint / population");this.groupInput=A("input"),this.groupInput.type="checkbox",this.groupInput.checked=!0,this.groupInput.onchange=()=>this.setGrouped(this.groupInput.checked),Y.append(this.groupInput),this.filters.append(this.search,Y),this.count=A("p"),this.count.className="kw-bom-small",this.list=A("div"),this.list.className="kw-bom-list",this.list.setAttribute("aria-label","Saved data rows"),this.pages=A("div"),this.pages.className="kw-bom-tools",this.previous=this.button("Previous rows",()=>{this.page--,this.render()}),this.next=this.button("Next rows",()=>{this.page++,this.render()}),this.pageText=A("span"),this.pages.append(this.previous,this.pageText,this.next);let ee=A("details"),X=A("summary","Source and interpretation limits");this.limits=A("p"),this.warnings=A("pre"),ee.append(X,this.limits,this.warnings),this.root.append(T,H,this.status,this.summary,this.filters,this.count,this.list,this.pages,ee),this.host.append(this.root),Vi.set(S,this),this.attachViewer(p),this.render()}button(h,p){let w=this.make("button",h);return w.type="button",w.onclick=()=>{try{p()}catch(S){this.fail(S)}},w}active(){if(this.disposed)throw new Error("BOM viewer is disposed.")}emit(h,p){this.dispatchEvent(new CustomEvent(h,{detail:p}))}fail(h){this.disposed||(this.status.textContent=h.message,this.emit("error",{message:h.message}))}sourceReady(){return!!(this.viewer&&!this.viewer.disposed&&this.viewer.source===this.source&&this.viewer.path===this.path)}attachViewer(h){if(this.active(),h&&(!h.addEventListener||!h.removeEventListener||typeof h.selectPart!="function"))throw new TypeError("Attach a native KiCad viewer.");if(this.stopViewer?.(),this.selectedUUID=null,this.hoveredUUID=null,this.viewer=h,h){let p=()=>{if(!this.disposed){this.markDrawingHover(null);try{if(typeof h.source!="string"||!["pcb","schematic"].includes(h.kind)){this.clear();return}h.source!==this.source||h.path!==this.path?this.loadSource(h.source,{path:h.path}):(this.status.textContent=this.bindingLabel(),this.render())}catch(A){this.fail(A),this.render()}}},w=()=>{let A=this.sourceReady()?h.getSelection?.():null;this.selectedUUID=A?.ownerUuid??A?.uuid??null,this.mode==="parts"&&this.render()};h.addEventListener("ready",p),h.addEventListener("select",w);let S=h.subscribePartHover?.(A=>this.markDrawingHover(this.sourceReady()?A:null));this.stopViewer=()=>{S?.(),h.hoverBomParts?.([]),h.removeEventListener("ready",p),h.removeEventListener("select",w)},h.source&&p()}else this.stopViewer=null;this.report&&(this.status.textContent=this.bindingLabel(),this.render())}markDrawingHover(h){if(this.hoveredUUID!==h){this.hoveredUUID=h;for(let[p,w]of this.visibleRows||[])p.classList.toggle("kw-bom-hover",!!(h&&w.has(h)))}}hoverParts(h){this.sourceReady()&&this.viewer.hoverBomParts?.(h.slice(0,50).map(p=>p.uuid).filter(p=>p&&this.uuidCounts.get(p)===1))}bindingLabel(){return Ea(this.path,240)+" \xB7 "+(this.sourceReady()?"Linked to the same saved source.":"Independent saved-source summary; selection links disabled.")}loadSource(h,{path:p="drawing.kicad_pcb"}={}){this.active();let w=ux(h,{path:p});this.source=h,this.path=p,this.report=w,this.stats=null,this.page=0,this.selectedUUID=null;let S=A=>[A.reference,A.properties?.Value,A.properties?.Footprint,A.properties?.["Library ID"]].join(" ").toLowerCase();this.partRows=w.groups.flatMap(A=>A.parts.map(T=>({group:A,parts:[T],search:S(T)}))),this.groupRows=w.groups.map(A=>({group:A,parts:A.parts,search:A.parts.map(S).join(" ")})),this.uuidCounts=new Map;for(let A of w.parts)A.uuid&&this.uuidCounts.set(A.uuid,(this.uuidCounts.get(A.uuid)||0)+1);return w.sourceKind!=="pcb"&&(this.mode="parts"),this.status.textContent=this.bindingLabel(),this.render(),this.emit("ready",{path:p,kind:w.sourceKind,total:w.total,groups:w.groups.length}),!0}getBOM(){return this.active(),this.report}getBoardStatistics(){return this.active(),this.report?.sourceKind!=="pcb"?null:(this.stats||(this.stats=hx(this.source,{path:this.path})),this.stats)}setMode(h){if(this.active(),!["parts","board"].includes(h))throw new TypeError("Choose parts or board.");return h==="board"&&this.report?.sourceKind!=="pcb"?!1:(this.mode=h,this.page=0,this.render(),!0)}setQuery(h){if(this.active(),typeof h!="string"||h.length>200)throw new TypeError("Search text is limited to 200 characters.");this.query=h,this.search.value=h,this.page=0,this.render()}setGrouped(h){if(this.active(),typeof h!="boolean")throw new TypeError("Choose true or false for grouped rows.");this.grouped=h,this.groupInput.checked=h,this.page=0,this.render()}setTheme(h){if(this.active(),!["light","dark"].includes(h))throw new TypeError("Choose light or dark theme.");this.theme=h,this.root.dataset.theme=h}selectPart(h){if(this.active(),!this.sourceReady()||!h.uuid||this.uuidCounts.get(h.uuid)!==1)return!1;let p=this.viewer.selectPart(h.uuid,{locate:!0});return p&&this.emit("select",{uuid:h.uuid,reference:h.reference,path:this.path}),p}render(){if(this.disposed)return;let h=this.make;if(this.viewer?.hoverBomParts?.([]),this.visibleRows=new Map,this.list.replaceChildren(),this.partsButton.setAttribute("aria-pressed",String(this.mode==="parts")),this.boardButton.setAttribute("aria-pressed",String(this.mode==="board")),this.boardButton.disabled=this.report?.sourceKind!=="pcb",this.downloadButton.disabled=!this.report,this.filters.hidden=this.mode!=="parts",this.pages.hidden=this.mode!=="parts"||!this.report,!this.report){this.summary.textContent="",this.count.textContent="",this.limits.textContent="Read-only saved-source data. No edits, solver runs or manufacturing checks.",this.warnings.textContent="";return}let p=this.report;if(this.summary.textContent=p.total+" saved parts \xB7 "+p.fitted+" fitted \xB7 "+p.dnp+" DNP \xB7 "+p.excluded+" excluded from BOM",this.limits.textContent=p.limits,this.warnings.textContent=p.warnings.slice(0,24).map(T=>Ea(T,500)).join(`
`),this.mode==="board"){try{this.renderBoard(this.getBoardStatistics())}catch(T){this.fail(T)}return}let w=this.query.trim().toLowerCase(),S=(this.grouped?this.groupRows:this.partRows).filter(T=>!w||T.search.includes(w)),A=Math.max(1,Math.ceil(S.length/50));this.page=Math.max(0,Math.min(this.page,A-1)),this.previous.disabled=this.page===0,this.next.disabled=this.page+1>=A,this.pageText.textContent=this.page+1+" / "+A,this.count.textContent=S.length+" matching "+(this.grouped?"groups":"parts")+" \xB7 up to 50 rows per page. Group quantities include the whole matching group. Excluded parts are omitted; CSV exports every eligible saved part, including DNP, regardless of this filter.";for(let T of S.slice(this.page*50,this.page*50+50)){let H=h("div");H.className="kw-bom-row",this.selectedUUID&&T.parts.some(_e=>_e.uuid===this.selectedUUID)&&(H.className+=" kw-bom-selected");let Y=T.group;H.append(h("strong",Ea(Y.value||"No saved value")+" \xB7 "+T.parts.length+" \xD7 "+(Y.populated?"Fitted":"DNP")),h("p",Ea(Y.footprint||"No saved footprint",240)));let ee=new Set(T.parts.map(_e=>_e.uuid).filter(_e=>_e&&this.uuidCounts.get(_e)===1));this.visibleRows.set(H,ee),this.hoveredUUID&&ee.has(this.hoveredUUID)&&(H.className+=" kw-bom-hover"),H.onpointerenter=_e=>{_e.pointerType!=="touch"&&this.hoverParts(T.parts)},H.onpointerleave=()=>this.hoverParts([]);let X=h("div");X.className="kw-bom-members";let G=0,ae=()=>{X.replaceChildren();for(let _e of T.parts.slice(G*25,G*25+25)){let J=this.button("Select "+Ea(_e.reference||"unnamed",80),()=>this.selectPart(_e));J.disabled=!this.sourceReady()||!_e.uuid||this.uuidCounts.get(_e.uuid)!==1,J.onpointerenter=Q=>{Q.pointerType!=="touch"&&this.hoverParts([_e])},J.onpointerleave=()=>this.hoverParts(T.parts),X.append(J)}G&&X.append(this.button("Previous parts",()=>{G--,ae()})),(G+1)*25<T.parts.length&&X.append(this.button("More parts",()=>{G++,ae()}))};if(T.parts.length>1){let _e=h("details");_e.append(h("summary",Ea(T.parts.slice(0,8).map(J=>J.reference||"?").join(", "),160)+(T.parts.length>8?" \u2026":"")+" \xB7 select a saved part"),X),_e.ontoggle=()=>{_e.open&&ae()},H.append(_e)}else ae(),H.append(X);this.list.append(H)}S.length||this.list.append(h("p","No eligible saved BOM parts match this filter."))}renderBoard(h){let p=this.make,w=p("div");w.className="kw-bom-grid";for(let[X,G]of[["Footprints",h.footprints],["Pads",h.pads],["Drilled pads",h.drilledPads],["Vias",h.vias],["Saved track length (mm)",md(h.totalTrackLengthMm)],["Saved thickness (mm)",md(h.boardThicknessMm)]]){let ae=p("div");ae.append(p("small",X),p("p",G)),w.append(ae)}this.list.append(w),this.count.textContent="Saved geometry summary \xB7 no DRC, copper union, zone refill or placement certification.",this.limits.textContent=h.limits,this.warnings.textContent=h.warnings.slice(0,24).map(X=>Ea(X,500)).join(`
`);let S=p("details");S.append(p("summary","Track length by saved net \xB7 "+h.netTracks.length+" entries"));let A=0,T=p("div");T.className="kw-bom-members";let H=()=>{let X=this.sourceReady()?this.viewer.getNets():[];T.replaceChildren();for(let G of h.netTracks.slice(A*50,A*50+50)){let ae=String(G.code)==="0"||G.code==="name:"?[]:X.filter(J=>J.id===this.path+"/net:"+G.code),_e=this.button(Ea(G.name,120)+" \xB7 "+md(G.lengthMm)+" mm",()=>{this.sourceReady()&&ae.length===1&&this.viewer.selectNet(ae[0].id,{locate:!0})});_e.disabled=ae.length!==1,T.append(_e)}A&&T.append(this.button("Previous nets",()=>{A--,H()})),(A+1)*50<h.netTracks.length&&T.append(this.button("More nets",()=>{A++,H()}))};S.ontoggle=()=>{S.open&&H()},S.append(T),this.list.append(S);let Y=p("details");Y.append(p("summary","Track length by saved layer \xB7 "+h.layerTracks.length+" entries"));for(let X of h.layerTracks.slice(0,256))Y.append(p("p",Ea(X.layer,120)+" \xB7 "+md(X.lengthMm)+" mm"));h.layerTracks.length>256&&Y.append(p("p","First 256 layers shown; complete data is available through getBoardStatistics().")),this.list.append(Y);let ee=p("details");ee.append(p("summary","Saved zone polygon sums \xB7 "+h.zones.length+" zones")),ee.append(p("p","Polygon sums count overlaps repeatedly and do not subtract holes. Invalid polygons are omitted; these are not copper-union areas."));for(let X of h.zones.slice(0,100))ee.append(p("p",Ea(X.name,120)+" \xB7 "+md(X.fillAreaMm2)+" mm\xB2 counted saved fill"+(X.valid?"":" \xB7 incomplete/invalid polygons omitted")));h.zones.length>100&&ee.append(p("p","First 100 zones shown; complete data is available through getBoardStatistics().")),this.list.append(ee)}exportCSV(){if(this.active(),!this.report)throw new Error("Load saved BOM data first.");return dx(this.report)}downloadCSV(){let h=this.exportCSV(),p=URL.createObjectURL(new Blob([h],{type:"text/csv;charset=utf-8"})),w=this.make("a");w.href=p,w.download="saved-bom.csv",w.click(),setTimeout(()=>URL.revokeObjectURL(p),0)}clear(){this.active(),this.source=null,this.path=null,this.report=this.stats=null,this.groupRows=this.partRows=null,this.uuidCounts?.clear(),this.selectedUUID=null,this.status.textContent="No saved BOM loaded.",this.render()}dispose(){this.disposed||(this.disposed=!0,this.stopViewer?.(),this.stopViewer=null,this.visibleRows?.clear(),this.list.replaceChildren(),this.root.replaceChildren(),this.uuidCounts?.clear(),this.root.remove(),this.source=null,this.report=this.stats=this.groupRows=this.partRows=this.viewer=null,this.search.oninput=this.groupInput.onchange=null,Vi.delete(this.host))}};export{Gm as AdvancedKiCadViewer,Bv as AltiumViewer,px as BOMViewer,av as DemoController,LU as EMBED_API_VERSION,ko as KiCadViewer,dd as ProjectTree,Gm as ProjectViewer,ko as Viewer,Zv as ViewerCarousel,Fm as ViewerInset,ox as WayriCADResultsViewer,Dm as analysisSourceHash,hx as analyzeBoard,dx as bomToCSV,ux as buildBOM,hd as buildProjectHierarchy,Hv as captureViewState,ix as classifyWayriCADSource,UU as createStandaloneHTML,Wv as createViewLink,Ym as createWayriCADSurface,nx as getWayriCADFrame,sx as getWayriCADPointHistory,ax as getWayriCADSourceLinks,eA as hierarchyToSVG,MD as linkViewers,qv as loadProjectHierarchy,RM as parseAnalysis,pv as parseManufacturing,EU as parseViewLink,rx as parseWayriCADResults,pd as probeWayriCADPlot,jl as readZip,DM as registerKiCadViewer,Gv as restoreViewState,Vl as validateViewState};
/*! KiCad WebView 1.2.1 | Copyright (c) 2026 wayri | SPDX-License-Identifier: MPL-2.0 | Source: https://github.com/wayri/kicad-webview/tree/v1.2.1 | Keep LICENSE and THIRD-PARTY-NOTICES.md; bundled dependencies retain their licenses. */