@wayrisignals/kicad-webview
Version:
Interactive KiCad schematic, PCB and 3D viewer for the web, with Gerber, Excellon, linked views and offline HTML exports
4,900 lines • 1.41 MB
JavaScript
/*! 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 cN=Object.create;var fg=Object.defineProperty;var uN=Object.getOwnPropertyDescriptor;var hN=Object.getOwnPropertyNames;var dN=Object.getPrototypeOf,pN=Object.prototype.hasOwnProperty;var r1=(ye=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(ye,{get:(Z,xe)=>(typeof require<"u"?require:Z)[xe]}):ye)(function(ye){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+ye+'" is not supported')});var fN=(ye,Z)=>()=>(ye&&(Z=ye(ye=0)),Z);var Zd=(ye,Z)=>()=>(Z||ye((Z={exports:{}}).exports,Z),Z.exports),mN=(ye,Z)=>{for(var xe in Z)fg(ye,xe,{get:Z[xe],enumerable:!0})},gN=(ye,Z,xe,Re)=>{if(Z&&typeof Z=="object"||typeof Z=="function")for(let Ne of hN(Z))!pN.call(ye,Ne)&&Ne!==xe&&fg(ye,Ne,{get:()=>Z[Ne],enumerable:!(Re=uN(Z,Ne))||Re.enumerable});return ye};var mg=(ye,Z,xe)=>(xe=ye!=null?cN(dN(ye)):{},gN(Z||!ye||!ye.__esModule?fg(xe,"default",{value:ye,enumerable:!0}):xe,ye));var gg=Zd((jN,Qd)=>{(ye=>{"use strict";let Ae=ge=>/\.(wbk|raw|csv|tsv|html?|json|txt)$/i.test(ge),Ee=ge=>typeof ge=="number"?Number.isFinite(ge)?ge:null:typeof ge=="string"&&/^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/.test(ge.trim())&&Number.isFinite(Number(ge))?Number(ge):null;function Kt(ge,ve){let Je=[],Ze=[],Ke="",De=!1,We=0,rt=()=>{if(Ze.length>=257||Ze.length===256&&Ke!=="")throw Error("Too many data columns.");if(++We>4e6)throw Error("Too many CSV cells; split the exported data.");Ze.push(Ke),Ke=""},Be=()=>{if(rt(),Ze.some(Le=>Le.trim())){if(Je.length>=2e5)throw Error("Too many data rows; split this export into smaller files.");Je.push(Ze)}Ze=[]};for(let Le=0;Le<ge.length;Le++){let Qe=ge[Le];Qe==='"'?De&&ge[Le+1]==='"'?(Ke+='"',Le++):De=!De:Qe===ve&&!De?rt():(Qe===`
`||Qe==="\r")&&!De?(Qe==="\r"&&ge[Le+1]===`
`&&Le++,Be()):Ke+=Qe}if(De)throw Error("Incomplete quoted CSV field.");return(Ke||Ze.length)&&Be(),Je}function er(ge,ve=64){let Je=ge.columns.map((De,We)=>We).filter(De=>ge.rows.some(We=>Ee(We[De])!==null));if(Je.length<2)return null;let Ze=Je[0],Ke=Je.slice(1,ve+1).map(De=>({name:ge.columns[De],points:ge.rows.map(We=>({x:Ee(We[Ze]),y:Ee(We[De])})).filter(We=>We.x!==null).map(We=>({...We,y:We.y===null?NaN:We.y}))})).filter(De=>De.points.length);return Ke.length?{title:ge.title,xLabel:ge.columns[Ze],series:Ke}:null}function Qt(ge,ve){let Je=ge.split(/\r?\n/,1)[0],Ze=/\.tsv$/i.test(ve)?" ":Je.includes(";")?";":Je.includes(" ")?" ":",",Ke=Kt(ge,Ze);if(!Ke.length)throw Error("The data file is empty.");for(;Ke[0].length>1&&Ke.every(Be=>Be.at(-1)==="");)for(let Be of Ke)Be.pop();let De=Ke.shift().map((Be,Le)=>Be.trim()||"Column "+(Le+1));if(De.length>256)throw Error("Too many data columns.");if(Ke.some(Be=>Be.length!==De.length))throw Error("CSV rows have different column counts.");if(Ke.length*De.length>4e6)throw Error("Too many CSV cells; split the exported data.");let We={title:ve.split("/").at(-1),columns:De,rows:Ke},rt=er(We,256);if(rt)for(let Be of rt.series)Be.signal=Ct(Be.name);return{kind:"Simulation / tabular data",tables:[We],plots:rt?[rt]:[],fields:[],warnings:rt?[]:["No pair of numeric columns was found for a graph."]}}function fr(ge){let ve=[],Je=0,Ze=(Be,Le,Qe,ht)=>{if(ve.length>=64||!Array.isArray(Le)||Le.length>2e5||!Le.length)return;let bt=Qe.slice(0,Be==="Illustrative eye diagram"?512:64).filter(et=>Array.isArray(et.values)&&et.values.length===Le.length).map(et=>({name:et.name,points:Le.map((dt,St)=>({x:Ee(dt),y:Ee(et.values[St])})).filter(dt=>dt.x!==null).map(dt=>({...dt,y:dt.y===null?NaN:dt.y}))}));bt.length&&ve.push({title:Be,xLabel:ht,series:bt})},Ke=(Be,Le,Qe)=>{if(!Be||typeof Be!="object"||Qe>18||++Je>12e3||ve.length>=64)return;if(Array.isArray(Be)){for(let et of Be.slice(0,100))et&&typeof et=="object"&&!Array.isArray(et)&&Ke(et,Le,Qe+1);return}if(Array.isArray(Be.times_s)){Ze(Le||"Transient",Be.times_s,Object.entries(Be).filter(([et,dt])=>Array.isArray(dt)&&/_V$|_A$/.test(et)).map(([et,dt])=>({name:et,values:dt})),"Time (s)");for(let et of[...Array.isArray(Be.loads)?Be.loads:[],...Array.isArray(Be.components)?Be.components:[],...Array.isArray(Be.thermal_nodes)?Be.thermal_nodes:[]])et&&typeof et=="object"&&Ze((Le||"Transient")+" \xB7 "+(et.reference||et.name||et.label||et.id||"component"),Be.times_s,Object.entries(et).filter(([dt,St])=>Array.isArray(St)&&/_V$|_A$|temperature_c|power_W/.test(dt)).map(([dt,St])=>({name:dt,values:St})),"Time (s)")}if(Array.isArray(Be.history)&&Be.history.length&&Be.history.length<=2e5&&Be.history.some(et=>Ee(et?.time_s)!==null)){let et=Be.history,dt=et.map(be=>be?.time_s),St=[...new Set(et.flatMap(be=>Array.isArray(be?.boards)?be.boards.map((Oe,Me)=>Oe?.name??String(Me)):[]))].slice(0,32);for(let be of St){if(ve.length>=64)break;let Oe=et.map(ft=>(Array.isArray(ft?.boards)?ft.boards:[]).find((it,_t)=>(it?.name??String(_t))===be)),Me=[...new Set(Oe.flatMap(ft=>ft?.temperatures_c&&typeof ft.temperatures_c=="object"?Object.keys(ft.temperatures_c):[]))].slice(0,60);Ze("Saved thermal transient \xB7 "+be,dt,[...Me.map(ft=>({name:ft+" (\xB0C)",values:Oe.map(it=>it?.temperatures_c?.[ft])})),...["inlet_air_c","outlet_air_c"].filter(ft=>Oe.some(it=>Ee(it?.[ft])!==null)).map(ft=>({name:ft+" (\xB0C)",values:Oe.map(it=>it?.[ft])}))],"Time (s)");let nt=["power_w","air_heat_w","fixture_heat_w","stored_heat_w","energy_residual_w"].filter(ft=>Oe.some(it=>Ee(it?.[ft])!==null));nt.length&&ve.length<64&&Ze("Saved thermal power \xB7 "+be,dt,nt.map(ft=>({name:ft+" (W)",values:Oe.map(it=>it?.[ft])})),"Time (s)")}}let ht=Be.spatial_index,bt=Be.frames;if(ht&&Array.isArray(bt)&&bt.length&&bt.length<=2e5&&Array.isArray(ht.x_centers_mm)&&Array.isArray(ht.y_centers_mm)&&Array.isArray(ht.cells)&&Array.isArray(ht.layers)){let et=ht.x_centers_mm.map(Ee),dt=ht.y_centers_mm.map(Ee),St=ht.cells,be=ht.layers;if(et.length&&dt.length&&et.length*dt.length<=1e6&&et.every(Me=>Me!==null)&&dt.every(Me=>Me!==null)&&St.length&&St.length<=1e6&&be.length&&be.length<=64&&ht.active_cells_per_layer===St.length&&St.every(Me=>Array.isArray(Me)&&Me.length===2&&Me.every(Number.isSafeInteger)&&Me[0]>=0&&Me[0]<et.length&&Me[1]>=0&&Me[1]<dt.length)&&new Set(St.map(Me=>Me.join(","))).size===St.length&&bt.every(Me=>Ee(Me?.time_s)!==null&&Array.isArray(Me.temperatures_c)&&Me.temperatures_c.length>=St.length*be.length)&&et.length*dt.length*be.length<=1e6)for(let Me=0;Me<be.length&&ve.length<64;Me++){let nt={type:"heatmap",title:"Saved thermal transient field \xB7 "+(be[Me]?.name||be[Me]?.id||Me),x:et,y:dt,cells:St,frames:bt,layerIndex:Me,frameIndex:bt.length-1,unit:"\xB0C",layerName:be[Me]?.name,layerZmm:Ee(be[Me]?.z_mm),zBasis:"front-depth"};nt.values=Nt(nt,nt.frameIndex),ve.push(nt)}}if(Array.isArray(Be.time_ui)&&Array.isArray(Be.traces_v)&&Ze("Illustrative eye diagram",Be.time_ui,Be.traces_v.slice(0,512).map((et,dt)=>({name:"Trace "+(dt+1)+" (V)",values:et})),"Time (UI)"),Array.isArray(Be.time_ns)&&Array.isArray(Be.voltage_v)&&Ze("Saved step response",Be.time_ns,[{name:"Voltage (V)",values:Be.voltage_v}],"Time (ns)"),Array.isArray(Be.segments)&&Le.endsWith("path")){let et=0,dt=[],St=[];for(let be of Be.segments){let Oe=Ee(be?.length_mm);if(Oe===null||Oe<0){dt.push({x:et,y:NaN}),St.push({x:et,y:NaN});continue}let Me=et+Oe/2;dt.push({x:Me,y:Ee(be.impedance_ohm)??NaN}),St.push({x:Me,y:Ee(be.screening_z0_ohm)??NaN}),et+=Oe}dt.length&&ve.push({title:"Saved route impedance",xLabel:"Distance along path (mm)",series:[{name:"Reference-covered impedance (\u03A9)",points:dt},{name:"Ideal continuous-plane screening (\u03A9)",points:St}]})}if(Array.isArray(Be.x_centers_mm)&&Array.isArray(Be.y_centers_mm)&&Array.isArray(Be.values_c)){let et=Be.x_centers_mm.map(Ee),dt=Be.y_centers_mm.map(Ee),St=Be.values_c.map(be=>Array.isArray(be)?be.map(Ee):be);et.length&&dt.length&&et.length*dt.length<=1e6&&et.every(be=>Ee(be)!==null)&&dt.every(be=>Ee(be)!==null)&&St.length===dt.length&&St.every(be=>Array.isArray(be)&&be.length===et.length)&&ve.push({type:"heatmap",title:Le.includes("board_thermal_view")?"Illustrative junction interpolation"+(Le.endsWith(".top")?" \xB7 top":Le.endsWith(".bottom")?" \xB7 bottom":""):"Saved board temperature field",x:et,y:dt,values:St,unit:"\xB0C",label:Le})}for(let et of["rows","samples"])if(Array.isArray(Be[et])&&Be[et].length){let dt=Be[et].filter(be=>be&&typeof be=="object"&&!Array.isArray(be)),St=["frequency_mhz","frequency_Hz","time_s"].find(be=>dt.some(Oe=>Ee(Oe?.[be])!==null));if(St){let be=[...new Set(dt.flatMap(Oe=>Object.keys(Oe)))].filter(Oe=>Oe!==St&&dt.some(Me=>Ee(Me?.[Oe])!==null));Ze(Le,dt.map(Oe=>Oe[St]),be.slice(0,32).map(Oe=>({name:Oe,values:dt.map(Me=>Me[Oe])})),St)}}for(let[et,dt]of Object.entries(Be))["values_c","points_mm","triangles","vertices","faces","traces_v","frames","spatial_index","history"].includes(et)||Ke(dt,Le?Le+"."+et:et,Qe+1)};Ke(ge,"",0);let De=ge?.mesh,We=ge?.result;if(Array.isArray(De?.points_mm)&&Array.isArray(De?.triangles)&&De.points_mm.length<=2e5&&De.triangles.length<=2e5&&De.points_mm.every(Be=>Array.isArray(Be)&&(Be.length===2||Be.length===3)&&Be.slice(0,2).every(Le=>Ee(Le)!==null))&&De.triangles.every(Be=>Array.isArray(Be)&&Be.length===3&&Be.every(Le=>Number.isSafeInteger(Le)&&Le>=0&&Le<De.points_mm.length))){let Be=De.points_mm.map(Qe=>Qe.map(Ee)),Le=(Qe,ht,bt,et)=>{if(!Array.isArray(ht)||ht.length!==(bt?De.points_mm.length:De.triangles.length))return;let dt=Array.isArray(De.triangle_layer)&&De.triangle_layer.length===De.triangles.length?[...new Set(De.triangle_layer.map(String))].slice(0,64):[null];for(let St of dt){if(ve.length>=64)break;let be=De.triangles.map((Me,nt)=>nt).filter(Me=>St===null||String(De.triangle_layer[Me])===St),Oe=(Array.isArray(ge.geometry?.layers)?ge.geometry.layers:[]).find(Me=>String(Me?.id)===St)?.name||St;ve.push({type:"mesh-field",title:Qe+(Oe?" \xB7 "+Oe:""),points:Be,triangles:be.map(Me=>De.triangles[Me]),values:bt?ht:be.map(Me=>ht[Me]),nodal:bt,unit:et,layerName:Oe,zBasis:typeof ge.geometry?.z_convention=="string"&&ge.geometry.z_convention.includes("positive Z down from the top copper surface")?"front-depth":void 0})}};Le("Saved nodal potential",We?.potential_V,!0,"V"),Le("Saved cell power",We?.cell_power_W,!1,"W"),Array.isArray(We?.cell_J_A_mm2)&&Le("Saved current density magnitude",We.cell_J_A_mm2.map(Qe=>{if(!Array.isArray(Qe)||![2,3].includes(Qe.length)||!Qe.every(bt=>typeof bt=="number"&&Number.isFinite(bt)))return null;let ht=Math.hypot(...Qe);return Number.isFinite(ht)?ht:null}),!1,"A/mm\xB2")}let rt=ge?.bodies;if(Array.isArray(rt)){let Be=rt.filter(Le=>Array.isArray(Le?.mesh?.vertices)&&Array.isArray(Le.mesh?.faces)&&Le.mesh.vertices.length<=2e5&&Le.mesh.faces.length<=1e5&&Le.mesh.vertices.every(Qe=>Array.isArray(Qe)&&Qe.length===3&&Qe.every(ht=>Ee(ht)!==null))&&Le.mesh.faces.every(Qe=>Array.isArray(Qe)&&Qe.length===3&&Qe.every(ht=>Number.isSafeInteger(ht)&&ht>=0&&ht<Le.mesh.vertices.length)));Be.length&&ve.push({type:"mechanical",title:"Saved mechanical meshes",bodies:Be.slice(0,100).map(Le=>({...Le,mesh:{...Le.mesh,vertices:Le.mesh.vertices.map(Qe=>Qe.map(Ee))}})),unit:"mm"})}return ve}function rr(ge){if(!ge||typeof ge!="object"||Array.isArray(ge)||typeof ge.schema!="string"||!/^kicad_monkey\.(design|netlist)\./.test(ge.schema))return null;if(!["kicad_monkey.design.a0","kicad_monkey.netlist.a0"].includes(ge.schema))throw Error("Unsupported KiCad Monkey export schema: "+ge.schema.slice(0,100));let ve=()=>{throw Error("Invalid KiCad Monkey a0 report. Expected saved components, nets and terminals.")},Je=Qe=>Qe&&typeof Qe=="object"&&!Array.isArray(Qe),Ze=(Qe,ht,bt=!1)=>{let et=Qe[ht];return et===void 0&&!bt?"":((typeof et!="string"||et.length>16384||bt&&!et)&&ve(),et)};if((ge.generator!=="kicad_monkey"||!Array.isArray(ge.components)||!Array.isArray(ge.nets))&&ve(),ge.components.length>2e4||ge.nets.length>2e4)throw Error("KiCad Monkey report exceeds 20,000 components or nets. Split the export.");let Ke=0,De=()=>{if(++Ke>2e5)throw Error("KiCad Monkey report exceeds 200,000 table rows. Split the export.")},We={title:"Components",columns:["Designator","Value","Footprint","Library reference","Description","Sheet"],rows:[]},rt={title:"Component properties",columns:["Designator","Property","Value"],rows:[]};for(let Qe of ge.components){Je(Qe)||ve();let ht=Ze(Qe,"designator",!0);if(De(),Qe.hierarchy!==void 0&&!Je(Qe.hierarchy)&&ve(),We.rows.push([ht,Ze(Qe,"value"),Ze(Qe,"footprint"),Ze(Qe,"library_ref"),Ze(Qe,"description"),Qe.hierarchy?Ze(Qe.hierarchy,"sheet_path"):""]),Qe.parameters!==void 0){Je(Qe.parameters)||ve();for(let bt of Object.keys(Qe.parameters))De(),bt.length>16384&&ve(),rt.rows.push([ht,bt,Ze(Qe.parameters,bt)])}}let Be={title:"Nets",columns:["Name","Net class","Source sheets","Terminal count"],rows:[]},Le={title:"Net terminals",columns:["Net","Designator","Pin","Pin name","Pin type"],rows:[]};for(let Qe of ge.nets){(!Je(Qe)||!Array.isArray(Qe.terminals))&&ve();let ht=Ze(Qe,"name");if(De(),Qe.terminals.length>2e5-Ke)throw Error("KiCad Monkey report exceeds 200,000 table rows. Split the export.");let bt="";if(Qe.source_sheets!==void 0&&((!Array.isArray(Qe.source_sheets)||Qe.source_sheets.length>1e3||Qe.source_sheets.some(et=>typeof et!="string"||et.length>16384))&&ve(),bt=Qe.source_sheets.join(" \xB7 "),bt.length>16384))throw Error("KiCad Monkey net sheet list exceeds the display budget.");Be.rows.push([ht,Ze(Qe,"net_class"),bt,Qe.terminals.length]);for(let et of Qe.terminals)De(),Je(et)||ve(),Le.rows.push([ht,Ze(et,"designator",!0),Ze(et,"pin",!0),Ze(et,"pin_name"),Ze(et,"pin_type")])}return{kind:"KiCad Monkey saved "+(ge.schema.includes(".design.")?"design":"netlist"),tables:[We,Be,Le,rt].filter(Qe=>Qe.rows.length),plots:[],fields:[{path:"Export schema",value:ge.schema},{path:"Generator",value:ge.generator},{path:"Components",value:ge.components.length},{path:"Nets",value:ge.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:ge}}function Ye(ge,ve){let Je=rr(ge);if(Je)return Je;let Ze={kind:/\.wbk$/i.test(ve)?"KiCad simulation workbook":"Saved analysis report",tables:[],plots:[],fields:[],warnings:[]},Ke=0,De=0,We=(rt,Be,Le)=>{if(++Ke>4e3||Le>32)return;if(rt===null||typeof rt!="object"){Ze.fields.push({path:Be,value:rt});return}if(Array.isArray(rt)){if(rt.length>2e5)throw Error("Too many analysis rows.");if(rt.length&&rt.every(bt=>bt&&typeof bt=="object"&&!Array.isArray(bt))){let bt=[...new Set(rt.slice(0,100).flatMap(et=>Object.keys(et).filter(dt=>et[dt]===null||typeof et[dt]!="object")))].slice(0,128);if(bt.length){if((De+=bt.length*rt.length)>4e6)throw Error("Too many analysis table cells; split this export into smaller files.");let et={title:Be,columns:bt,rows:rt.map(dt=>bt.map(St=>dt[St]??""))};Ze.tables.push(et)}}for(let bt=0;bt<Math.min(rt.length,100);bt++)We(rt[bt],Be+"["+bt+"]",Le+1);return}let Qe=rt.x||rt.frequency_hz||rt.time_s,ht=rt.y||rt.values;Array.isArray(Qe)&&Array.isArray(ht)&&Qe.length===ht.length&&Qe.length&&Qe.every(bt=>Ee(bt)!==null)&&ht.every(bt=>Ee(bt)!==null)&&Ze.plots.push({title:Be,xLabel:rt.x_label||rt.xLabel||(rt.frequency_hz?"Frequency (Hz)":rt.time_s?"Time (s)":"x"),series:[{name:rt.name||rt.y_label||rt.yLabel||Be,points:Qe.map((bt,et)=>({x:Ee(bt),y:Ee(ht[et])}))}]});for(let[bt,et]of Object.entries(rt).sort(([dt],[St])=>(/schema|sha|source|status|coverage|findings|checks|assumptions|limit|warning/.test(dt)?-1:/mesh|values|samples|points|traces|bodies|field/.test(dt)?1:0)-(/schema|sha|source|status|coverage|findings|checks|assumptions|limit|warning/.test(St)?-1:/mesh|values|samples|points|traces|bodies|field/.test(St)?1:0)))We(et,Be?Be+"."+bt:bt,Le+1)};return Ze.savedSource=ge,Ze.plots=fr(ge),We(ge,"",0),Ke>4e3&&Ze.warnings.push("Property preview limited to 4000 fields; full source remains available."),/\.wbk$/i.test(ve)&&(Ze.plots=[],Ze.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.")),Ze}function Ct(ge,ve){let Je=/^v\(([^(),]+)\)(\d+)?$/i.exec(ge),Ze=/^i\(([^(),]+)\)$/i.exec(ge);return Je&&(!ve||ve==="voltage")?{expression:ge,quantity:"voltage",unit:"V",net:Je[1],...Je[2]?{run:Je[2]}:{}}:Ze&&(!ve||ve==="current")?{expression:ge,quantity:"current",unit:"A",device:Ze[1]}:ve==="voltage"&&!/[(),\s]/.test(ge)?{expression:ge,quantity:ve,unit:"V",net:ge}:{expression:ge,quantity:ve||null,unit:{time:"s",frequency:"Hz",current:"A",voltage:"V"}[ve]||null}}function*It(ge,ve=0,Je=ge.length){for(;ve<Je;){let Ze=ge.indexOf(`
`,ve);(Ze<0||Ze>Je)&&(Ze=Je);let Ke=ge.slice(ve,Ze).trim();ve=Ze+1,Ke&&(yield Ke)}}function wt(ge){if(/(?:^|\n)Binary:/i.test(ge))throw Error("Binary SPICE raw data is not supported. Export ASCII raw data or KiCad CSV.");let ve=ge.search(/^Variables:[ \t]*\r?$/im),Je=ge.search(/^Values:[ \t]*\r?$/im);if(ve<0||Je<=ve)throw Error("Expected an ASCII SPICE raw file with Variables and Values sections.");if(ve>1024*1024||Je-ve>1024*1024)throw Error("SPICE header exceeds the 1 MiB metadata budget.");let Ze=ge.slice(0,ve),Ke=Oe=>{let Me=[...Ze.matchAll(new RegExp("^"+Oe+":[ \\t]*(.*)\\r?$","gim"))];if(Me.length!==1)throw Error("Missing or duplicate SPICE "+Oe+" header.");return Me[0][1].trim()},De=[Ke("No\\. Variables"),Ke("No\\. Points")],We=Number(De[0]),rt=Number(De[1]),Be=Ke("Flags").toLowerCase().split(/\s+/),Le=Be.includes("complex");if(Be.length!==1||!["real","complex"].includes(Be[0]))throw Error("Unsupported SPICE flags; export one padded real or complex plot.");if(!De.every(Oe=>/^\d+$/.test(Oe))||!We||We>256||!Number.isSafeInteger(rt)||rt<1||rt>2e5||rt*We*(Le?2:1)>4e6)throw Error("Invalid or excessive SPICE dimensions.");let Qe=[];for(let Oe of It(ge,ge.indexOf(`
`,ve)+1,Je)){let Me=Oe.match(/^(\d+)\s+(\S+)\s+(\S+)(?:\s+(.*))?$/);if(Qe.length>=We||!Me||Number(Me[1])!==Qe.length)throw Error("Invalid SPICE variable declaration or index.");if(/\bdims=/.test(Me[4]||""))throw Error("Variable-specific SPICE dimensions are not supported.");Qe.push({name:Me[2],unit:Me[3],attributes:Me[4]||"",signal:Ct(Me[2],Me[3])})}if(We!==Qe.length||new Set(Qe.map(Oe=>Oe.name)).size!==We)throw Error("Invalid or duplicate SPICE variables.");let ht=It(ge,ge.indexOf(`
`,Je)+1),bt=[];for(let Oe=0;Oe<rt;Oe++){let Me=[];for(let nt=0;nt<We;nt++){let ft=ht.next();if(ft.done)throw Error("Incomplete SPICE raw samples.");let it=ft.value;if(nt===0){let Rt=it.match(/^(\d+)\s+(.*)$/);if(!Rt||Number(Rt[1])!==Oe)throw Error("Invalid SPICE sample index.");it=Rt[2]}let _t=it.split(",").map(Ee);if(_t.some(Rt=>Rt===null)||_t.length!==(Le?2:1))throw Error("Invalid SPICE sample value.");if(nt===0&&Le&&_t[1]!==0)throw Error("Complex SPICE sweep axes are not supported; their imaginary values cannot be discarded.");nt===0?Me.push(_t[0]):Me.push(..._t)}bt.push(Me)}if(!ht.next().done)throw Error("Incomplete SPICE raw samples or trailing concatenated plots.");let et=[Qe[0].name+" ("+Qe[0].unit+")",...Qe.slice(1).flatMap(Oe=>Le?[Oe.name+" real ("+Oe.unit+")",Oe.name+" imaginary ("+Oe.unit+")"]:[Oe.name+" ("+Oe.unit+")"])],dt={title:"SPICE waveform samples",columns:et,rows:bt},St=[];for(let Oe=1;Oe<We;Oe++)for(let Me=0;Me<(Le?2:1);Me++){let nt=1+(Oe-1)*(Le?2:1)+Me;St.push({name:et[nt],signal:{...Qe[Oe].signal,component:Le&&Me?"imaginary":"real"},points:bt.map(ft=>({x:ft[0],y:ft[nt]}))})}let be=[];for(let Oe of It(Ze)){if(be.length>=4e3)throw Error("Too many SPICE metadata fields.");let Me=Oe.indexOf(":");be.push({path:Me<0?"Header":Oe.slice(0,Me),value:Me<0?Oe:Oe.slice(Me+1).trim()})}return{kind:"ASCII SPICE simulation",tables:[dt],plots:St.length?[{title:be.find(Oe=>Oe.path.toLowerCase()==="plotname")?.value||dt.title,xLabel:et[0],series:St}]:[],fields:be,warnings:Le?["Complex traces are displayed as real and imaginary components in their saved units."]:[]}}function at(ge){let ve="",Je=!1,Ze=!1;for(let Ke=0;Ke<ge.length;Ke++){let De=ge[Ke];if(Je){ve+=De,Ze?Ze=!1:De==="\\"?Ze=!0:De==='"'&&(Je=!1);continue}if(De==='"')Je=!0,ve+=De;else if(De==="/"&&ge[Ke+1]==="/"){for(;Ke<ge.length&&ge[Ke]!==`
`;)Ke++;ve+=`
`}else if(De==="/"&&ge[Ke+1]==="*"){let We=ge.indexOf("*/",Ke+2);if(We<0)throw Error("Incomplete workbook comment.");Ke=We+1,ve+=" "}else ve+=De}return ve}function zt(ge){if(ge.trimStart().startsWith("{"))return JSON.parse(at(ge));let ve=ge.replace(/\r/g,"").split(`
`),Je=0,Ze=()=>{if(Je>=ve.length)throw Error("Incomplete legacy KiCad workbook.");return ve[Je++]},Ke=()=>{let Le=Number(Ze());if(!Number.isInteger(Le)||Le<0||Le>1e4)throw Error("Invalid legacy workbook count.");return Le},De=1;if(/^version\s+\d+$/i.test(ve[0])&&(De=Number(Ze().split(/\s+/)[1])),De<1||De>5)throw Error("Unsupported legacy workbook version.");let We=[];for(let Le=0,Qe=Ke();Le<Qe;Le++){let ht={simulation_type:Ke(),command:Ze(),traces:[],measurements:[]};for(let bt=0,et=Ke();bt<et;bt++)ht.traces.push({trace_type:Ke(),signal:Ze(),parameters:Ze()});if(De>4)for(let bt=0,et=Ke();bt<et;bt++)ht.measurements.push({expression:Ze(),format:Ze()});We.push(ht)}let rt=[];if(Je<ve.length&&ve[Je].trim())for(let Le=0,Qe=Ke();Le<Qe;Le++)rt.push(Ze());let Be=De>=5&&Je<ve.length?Ze():"";return{version:De,tabs:We,user_defined_signals:rt,last_sch_text_sim_command:Be}}function Ot(ge,ve){if(typeof ve!="string"||new TextEncoder().encode(ve).length>67108864)throw Error("Analysis file exceeds the 64 MiB viewer budget.");ve=ve.replace(/^\uFEFF/,"");let Je;if(/\.(csv|tsv)$/i.test(ge))Je=Qt(ve,ge);else if(/\.raw$/i.test(ge))Je=wt(ve);else if(/\.(json|wbk)$/i.test(ge))try{Je=Ye(/\.wbk$/i.test(ge)?zt(ve):JSON.parse(ve),ge)}catch(Ze){throw Ze instanceof SyntaxError?Error("Unsupported or incomplete JSON workbook/report."):Ze}else if(/\.html?$/i.test(ge))Je={kind:"Saved HTML report",fields:[],tables:[],plots:[],warnings:["Report scripts and external resources are never executed."],html:ve};else if(/\.txt$/i.test(ge))Je={kind:"Saved text report",fields:[{path:"Report text",value:ve.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{...Je,path:ge,title:ge.split("/").at(-1)}}function Nt(ge,ve){let Je=ge.frames?.[ve];if(!Je||!Number.isSafeInteger(ve))return null;let Ze=ge.y.map(()=>ge.x.map(()=>null));return ge.cells.forEach(([Ke,De],We)=>{Ze[De][Ke]=Ee(Je.temperatures_c[ge.layerIndex*ge.cells.length+We])}),Ze}function Xt(ge,ve){let Je=ge[ve],Ze=ge[ve-1],Ke=ge[ve+1];if(ge.length===1)return[Je-.5,Je+.5];let De=Ze===void 0?Je+(Je-Ke)/2:(Ze+Je)/2,We=Ke===void 0?Je+(Je-Ze)/2:(Ke+Je)/2;return[Math.min(De,We),Math.max(De,We)]}function sr(ge,ve,Je,Ze){if(!Number.isFinite(ve)||!ge)return null;if(ge.series){let Ke=ge.series.find(Le=>Le.name===Ze)||ge.series[0];if(!Ke)return null;let De=null,We=1/0,rt=1/0,Be=-1/0;for(let Le of Ke.points){if(!Number.isFinite(Le.x))continue;rt=Math.min(rt,Le.x),Be=Math.max(Be,Le.x);let Qe=Math.abs(Le.x-ve);Qe<We&&(De=Le,We=Qe)}return!De||ve<rt||ve>Be?null:{x:De.x,value:Ee(De.y),name:Ke.name,axis:ge.xLabel,method:"Nearest saved sample"}}if(!Number.isFinite(Je))return null;if(ge.type==="heatmap"){let Ke=(rt,Be)=>{let Le=-1,Qe=1/0;for(let ht=0;ht<rt.length;ht++){let[bt,et]=Xt(rt,ht);Be>=bt&&Be<=et&&Math.abs(rt[ht]-Be)<Qe&&(Le=ht,Qe=Math.abs(rt[ht]-Be))}return Le},De=Ke(ge.x,ve),We=Ke(ge.y,Je);return De<0||We<0?null:{x:ge.x[De],y:ge.y[We],value:Ee(ge.values[We][De]),name:ge.title,unit:ge.unit,method:"Saved cell center"}}if(ge.type==="mesh-field")for(let Ke=0;Ke<ge.triangles.length;Ke++){let De=ge.triangles[Ke],[We,rt,Be]=De.map(be=>ge.points[be]),Le=(rt[1]-Be[1])*(We[0]-Be[0])+(Be[0]-rt[0])*(We[1]-Be[1]);if(Math.abs(Le)<1e-14)continue;let Qe=((rt[1]-Be[1])*(ve-Be[0])+(Be[0]-rt[0])*(Je-Be[1]))/Le,ht=((Be[1]-We[1])*(ve-Be[0])+(We[0]-Be[0])*(Je-Be[1]))/Le,bt=1-Qe-ht;if(Math.min(Qe,ht,bt)<-1e-9)continue;let et=ge.nodal?De.map(be=>Ee(ge.values[be])):[Ee(ge.values[Ke])],dt=et.some(be=>be===null)?null:ge.nodal?et[0]*Qe+et[1]*ht+et[2]*bt:et[0],St=[We,rt,Be].every(be=>Number.isFinite(be[2]))?We[2]*Qe+rt[2]*ht+Be[2]*bt:void 0;return{x:ve,y:Je,...St===void 0?{}:{z:St},value:dt,name:ge.title,unit:ge.unit,method:ge.nodal?"Interpolated saved nodes":"Saved cell value"}}return null}function Et(ge,ve){return!ge||!ve||ge.name!==ve.name||ge.unit!==ve.unit||ge.axis!==ve.axis?null:{dx:ve.x-ge.x,...Number.isFinite(ge.y)&&Number.isFinite(ve.y)?{dy:ve.y-ge.y,distance:Math.hypot(ve.x-ge.x,ve.y-ge.y)}:{},delta:ge.value===null||ve.value===null?null:ve.value-ge.value}}let Lt={parse:Ot,parseJSONValue:Ye,candidate:Ae,numeric:Ee,delimited:Kt,tablePlot:er,cellBounds:Xt,frameValues:Nt,probe:sr,probeDifference:Et,MAX_BYTES:67108864};ye.KiCadAnalysisData=Lt,typeof Qd=="object"&&Qd.exports&&(Qd.exports=Lt)})(globalThis)});var i1=Zd((XN,Jd)=>{(ye=>{"use strict";let Ne=Ye=>typeof Ye=="number"&&Number.isFinite(Ye)?Ye:null,Ae=Ye=>Array.isArray(Ye)&&Ye.length>=2&&Ye.slice(0,2).every(Ct=>Ne(Ct)!==null)?{x:Ye[0],y:Ye[1]}:null,Ee=()=>ye.KiCadAnalysisData||(typeof r1=="function"?gg():null);function Kt(Ye){if(!Ye)return null;let Ct={unit:Ye.unit||"",title:Ye.title||"",layer:Ye.layerName,zBasis:Ye.zBasis,points:[],triangles:[],values:[],nodal:!1,zKnown:!1};if(Ye.type==="mesh-field")return!Array.isArray(Ye.points)||!Ye.points.length||Ye.points.length>4e5||!Array.isArray(Ye.triangles)||Ye.triangles.length>2e5||!Array.isArray(Ye.values)||Ye.values.length!==(Ye.nodal?Ye.points.length:Ye.triangles.length)||!Ye.points.every(at=>Ae(at)&&(!(at.length>2)||Ne(at[2])!==null))||!Ye.triangles.every(at=>Array.isArray(at)&&at.length===3&&at.every(zt=>Number.isSafeInteger(zt)&&zt>=0&&zt<Ye.points.length))?null:(Ct.points=Ye.points.map(at=>[at[0],at[1],at.length>2?at[2]:Ne(Ye.layerZmm)??0]),Ct.triangles=Ye.triangles.map(at=>at.slice()),Ct.values=Ye.values.map(Ne),Ct.nodal=!!Ye.nodal,Ct.zKnown=Ye.points.every(at=>at.length>2)||Ne(Ye.layerZmm)!==null,Ct);if(Ye.type!=="heatmap"||!Array.isArray(Ye.x)||!Array.isArray(Ye.y)||!Ye.x.length||!Ye.y.length||Ye.x.length*Ye.y.length>1e6||!Ye.x.every(at=>Ne(at)!==null)||!Ye.y.every(at=>Ne(at)!==null)||!Array.isArray(Ye.values)||Ye.values.length!==Ye.y.length||!Ye.values.every(at=>Array.isArray(at)&&at.length===Ye.x.length))return null;let It=Ee()?.cellBounds;if(!It)return null;let wt=Ne(Ye.layerZmm)??0;Ct.zKnown=Ne(Ye.layerZmm)!==null;for(let at=0;at<Ye.y.length;at++)for(let zt=0;zt<Ye.x.length;zt++){let Ot=Ne(Ye.values[at][zt]);if(Ot===null)continue;if(Ct.triangles.length+2>2e5)return null;let[Nt,Xt]=It(Ye.x,zt),[sr,Et]=It(Ye.y,at),Lt=Ct.points.length;Ct.points.push([Nt,sr,wt],[Xt,sr,wt],[Xt,Et,wt],[Nt,Et,wt]),Ct.triangles.push([Lt,Lt+1,Lt+2],[Lt,Lt+2,Lt+3]),Ct.values.push(Ot,Ot)}return Ct}function er(Ye){let Ct=[],It=0,wt=0,at=new WeakSet,zt=(Et,Lt)=>{if(Ct.length>=1e4||!Array.isArray(Et)||Et.length<3||Et.length>5e4||It+Et.length>2e5)return;let ge=Et.map(Ae);ge.some(ve=>!ve)||(It+=ge.length,Ct.push({type:"polygon",kind:"saved-context",points:ge,color:Lt,width:.12,stroke:!0}))},Ot=(Et,Lt)=>Array.isArray(Et)?Et.slice(0,Lt):[],Nt=(Et,Lt)=>{if(Array.isArray(Et)){zt(Et,Lt);return}if(!(!Et||typeof Et!="object")){zt(Et.outer||Et.outer_mm,Lt);for(let ge of Ot(Et.holes||Et.holes_mm,1e3))zt(ge,Lt)}},Xt=Et=>{for(let Lt of(Array.isArray(Et.outline)?Et.outline:[]).slice(0,1e3))Nt(Lt,"#a5b6bc");for(let Lt of Ot(Et.layers,64))for(let ge of Ot(Lt?.polygons||Lt?.polygons_mm,1e4))Nt(ge,"#5f8079");for(let Lt of(Array.isArray(Et.polygons)?Et.polygons:[]).slice(0,1e4))Nt(Lt,"#5f8079");for(let Lt of Ot(Et.tracks,1e4)){let ge=Ae(Lt?.start_mm||Lt?.start),ve=Ae(Lt?.end_mm||Lt?.end);ge&&ve&&Ct.length<1e4&&Ct.push({type:"line",kind:"saved-context",points:[ge,ve],width:Math.min(10,Math.max(.12,Ne(Lt.width_mm)??.12)),color:"#5f8079"})}for(let Lt of Ot(Et.components,1e3)){let ge=Lt?.bbox_mm||Lt?.source_bbox_mm;Array.isArray(ge)&&ge.length===4&&ge.every(ve=>Ne(ve)!==null)&&zt([[ge[0],ge[1]],[ge[2],ge[1]],[ge[2],ge[3]],[ge[0],ge[3]]],"#8296ac")}},sr=(Et,Lt)=>{if(!(!Et||typeof Et!="object"||Lt>12||++wt>4e3||at.has(Et)||Array.isArray(Et))){at.add(Et),Xt(Et);for(let ge of["geometry","thermal_geometry","board_thermal_view","thermal_network","top","bottom","view","coupled","baseline","result"])sr(Et[ge],Lt+1)}};return sr(Ye,0),Ct}function Qt(Ye){let Ct=[],It=new Set,wt=0,at=(Ot,Nt)=>{if(typeof Ot!="string"||Ot.length>4096||/[\x00-\x1f]/.test(Ot)||!/\.kicad_pcb$/i.test(Ot)||typeof Nt!="string"||!/^\w{64}$/.test(Nt)||!/^[a-f0-9]{64}$/i.test(Nt))return;let Xt=Nt.toLowerCase(),sr=Ot+`
`+Xt;!It.has(sr)&&Ct.length<32&&(It.add(sr),Ct.push({path:Ot,sha256:Xt}))},zt=(Ot,Nt)=>{if(!(!Ot||typeof Ot!="object"||Array.isArray(Ot)||Nt>12||++wt>4e3)){at(Ot.source_path,Ot.source_sha256),at(Ot.board_path,Ot.source_sha256),at(Ot.request?.board_path,Ot.source_sha256);for(let Xt of["geometry","thermal_geometry","baseline","coupled","result","report","thermal_network","electrical","thermal"])zt(Ot[Xt],Nt+1)}};return zt(Ye,0),Ct}function fr(Ye,Ct,It){if(Ye?.type!=="heatmap"||!Array.isArray(Ye.frames)||!Ye.frames.length||Ye.frames.length>2e5||!Array.isArray(Ye.cells)||!Array.isArray(Ye.x)||!Array.isArray(Ye.y)||!Number.isSafeInteger(Ye.layerIndex)||Ye.layerIndex<0)return null;let at=Ee()?.probe(Ye,Ct,It);if(!at)return null;let zt=Ye.x.indexOf(at.x),Ot=Ye.y.indexOf(at.y),Nt=Ye.cells.findIndex(sr=>sr[0]===zt&&sr[1]===Ot);if(Nt<0)return null;let Xt=Ye.frames.filter(sr=>Ne(sr?.time_s)!==null).map(sr=>({x:sr.time_s,y:Ne(sr.temperatures_c?.[Ye.layerIndex*Ye.cells.length+Nt])??NaN}));return Xt.length?{title:Ye.title+" \xB7 probe ("+at.x+", "+at.y+" mm)",xLabel:"Time (s)",series:[{name:(Ye.title||"Saved temperature")+" ("+(Ye.unit||"\xB0C")+")",points:Xt}]}:null}let rr={toSurface:Kt,contextGeometry:er,sourceBindings:Qt,pointHistory:fr,MAX_TRIANGLES:2e5};ye.KiCadAnalysisSpatial=rr,typeof Jd=="object"&&Jd.exports&&(Jd.exports=rr)})(globalThis)});var v1=Zd((TL,ep)=>{(ye=>{"use strict";let Ne=It=>({quoted:String(It??"")}),Ae=It=>{let wt=Number(It);if(!Number.isFinite(wt)||Math.abs(wt)>1e8)throw Error("Invalid legacy schematic coordinate.");return Math.round(wt*.0254*1e8)/1e8},Ee=It=>[...It.matchAll(/"((?:\\.|[^"\\])*)"|([^\s]+)/g)].map(wt=>wt[1]!==void 0?wt[1].replace(/\\(["\\])/g,"$1"):wt[2]),Kt=(It,wt,at=0)=>["at",Ae(It),Ae(wt),at],er=(It=50,wt=!1)=>["effects",["font",["size",Ae(It),Ae(It)]],...wt?["hide"]:[]];function Qt(It){if(typeof It!="string"||new TextEncoder().encode(It).length>8388608)throw Error("Legacy schematic/library exceeds its size limit.");let wt=It.replace(/^\uFEFF/,"").split(/\r?\n/);if(wt.length>15e4)throw Error("Legacy schematic/library exceeds its line limit.");return wt}function fr(It,wt,at){let zt,Ot=1,Nt=!1,Xt=!1,sr=0,Et=[];for(let Lt=wt;Lt<at;Lt++){let ge=It[Lt].trim();if(!ge)continue;if(ge==="EndData"&&Nt&&!Xt){Xt=!0;continue}if(Nt&&!Xt){if(!/^[0-9a-f]{2}(?:\s+[0-9a-f]{2})*$/i.test(ge))throw Error("Invalid saved bitmap bytes.");let Ke=ge.match(/[0-9a-f]{2}/gi);if(sr+=Ke.length,sr>4*1024*1024)throw Error("Saved bitmap exceeds its 4 MiB limit.");for(let De=0;De<Ke.length;De+=8192)Et.push(String.fromCharCode(...Ke.slice(De,De+8192).map(We=>parseInt(We,16))));continue}let[ve,Je,Ze]=Ee(ge);ve==="Pos"&&Je!==void 0&&Ze!==void 0&&(zt=Kt(Je,Ze)),ve==="Scale"&&Je!==void 0&&(Ot=Number(Je)),ve==="Data"&&!Nt&&(Nt=!0)}if(!zt||!Et.length||!Xt||!Number.isFinite(Ot)||Ot<=0)throw Error("Invalid saved bitmap placement or data.");return["image",zt,["scale",Ot],["uuid",Ne("legacy-bitmap-"+wt)],["data",Ne(btoa(Et.join("")))]]}function rr(It,wt){let at=new Map,zt=0;if(!Array.isArray(It))return at;if(It.length>16)throw Error("Too many legacy symbol libraries.");for(let Ot of It){let Nt=typeof Ot=="string"?Ot:Ot?.content;if(typeof Nt!="string")continue;if(zt+=Nt.length,zt>16*1024*1024)throw Error("Legacy symbol libraries exceed their combined limit.");let Xt=null,sr=[],Et=!1,Lt=new Map;for(let ge of Qt(Nt)){let ve=Ee(ge),Je=ve[0];if(!Je||Je[0]==="#")continue;if(Je==="DEF"){Xt=ve,sr=[],Lt=new Map;continue}if(!Xt)continue;if(Je==="ALIAS"){sr.push(...ve.slice(1));continue}if(Je==="DRAW"){Et=!0;continue}if(Je==="ENDDRAW"){Et=!1;continue}if(Je==="ENDDEF"){let We=Xt[1],rt=["symbol",Ne(We),...Xt[9]==="P"?[["power"]]:[],...Xt[5]==="N"?[["pin_numbers","hide"]]:[],...Xt[6]==="N"?[["pin_names","hide"]]:[],...Lt.values()];for(let Be of[We,...sr])at.has(Be)||at.set(Be,rt);Xt=null;continue}if(!Et)continue;let Ze=(We,rt,Be)=>{let Le=We+"_"+rt;Lt.has(Le)||Lt.set(Le,["symbol",Ne(Xt[1]+"_"+Le)]),Lt.get(Le).push(Be)},Ke=We=>["stroke",["width",Math.max(Ae(We||6),.01)]],De=We=>["fill",["type",We==="F"?"outline":We==="f"?"background":"none"]];if(Je==="S")Ze(ve[5],ve[6],["rectangle",["start",Ae(ve[1]),Ae(ve[2])],["end",Ae(ve[3]),Ae(ve[4])],Ke(ve[7]),De(ve[8])]);else if(Je==="C")Ze(ve[4],ve[5],["circle",["center",Ae(ve[1]),Ae(ve[2])],["radius",Ae(ve[3])],Ke(ve[6]),De(ve[7])]);else if(Je==="P"){let We=Number(ve[1]);if(!Number.isInteger(We)||We<2||We>1e4||ve.length<5+2*We)throw Error("Invalid legacy library polyline.");Ze(ve[2],ve[3],["polyline",["pts",...Array.from({length:We},(rt,Be)=>["xy",Ae(ve[5+Be*2]),Ae(ve[6+Be*2])])],Ke(ve[4]),De(ve[5+We*2])])}else if(Je==="A"){let We=Ae(ve[1]),rt=Ae(ve[2]),Be=Ae(ve[3]),Le=Number(ve[4])*Math.PI/1800,ht=Number(ve[5])*Math.PI/1800-Le;for(;ht<0;)ht+=Math.PI*2;let bt=et=>[We+Be*Math.cos(et),rt+Be*Math.sin(et)];Ze(ve[6],ve[7],["arc",["start",...bt(Le)],["mid",...bt(Le+ht/2)],["end",...bt(Le+ht)],Ke(ve[8]),De(ve[9])])}else if(Je==="X"){let We={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"},rt={R:0,U:90,L:180,D:270}[ve[6]],Be={"":"line",I:"inverted",C:"clock",CI:"inverted_clock",L:"input_low",CL:"clock_low",V:"output_low",F:"edge_clock_high",X:"non_logic"},Le=ve[12]||"",Qe=Le.includes("N"),ht=Be[Le.replace(/N/g,"")];if(rt===void 0||!ht){wt("Unsupported legacy pin orientation/style omitted: "+ve[1]);continue}Ze(ve[9],ve[10],["pin",We[ve[11]]||"unspecified",ht,Kt(ve[3],ve[4],rt),["length",Ae(ve[5])],["name",Ne(ve[1]),er(ve[8])],["number",Ne(ve[2]),er(ve[7])],...Qe?["hide"]:[]])}else wt(Je==="T"?"Legacy library text is omitted; convert a copy in KiCad for complete typography.":"Unsupported legacy library graphic "+Je+" omitted.")}}return at}function Ye(It,wt={}){let at=Qt(It);if(!/^EESchema Schematic File Version [24]\b/.test(at[0]))throw Error("Only legacy Eeschema v2/v4 schematics are supported.");let zt=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."]),Ot=ve=>{zt.size<200&&zt.add(ve)},Nt=rr(wt.libraries,Ot),Xt=["kicad_sch",["version",Number(at[0].match(/\d+$/)[0])],["legacy_source",Ne(at[0])]],sr=["lib_symbols"],Et=[],Lt=(ve,Je,Ze,Ke,De=50,We=!1,rt=0)=>["property",Ne(ve),Ne(Je),Kt(Ze,Ke,rt),er(De,We)];function ge(ve,Je){let Ze=[],Ke=ve;for(;Ke<at.length&&at[Ke]!==Je;Ke++)Ze.push(Ee(at[Ke]));if(Ke===at.length)throw Error("Incomplete legacy schematic "+Je+" block.");return{records:Ze,end:Ke}}for(let ve=1;ve<at.length;ve++){let Je=Ee(at[ve]),Ze=Je[0];if(!(!Ze||Ze[0]==="#")){if(Ze==="$Descr"){Xt.push(["paper",Ne(Je[1])]);continue}if(/^Comment[1-9]$/.test(Ze)){let Ke=Xt.find(De=>Array.isArray(De)&&De[0]==="title_block");Ke||(Ke=["title_block"],Xt.push(Ke)),Ke.push(["comment",Number(Ze.slice(7)),Ne(Je[1])]);continue}if(["Title","Date","Rev","Comp"].includes(Ze)){let Ke=Xt.find(De=>Array.isArray(De)&&De[0]==="title_block");Ke||(Ke=["title_block"],Xt.push(Ke)),Ke.push([{Title:"title",Date:"date",Rev:"rev",Comp:"company"}[Ze],Ne(Je[1])]);continue}if(Ze==="Wire"||Ze==="Entry"){let Ke=Ee(at[++ve]||"");if(Ke.length!==4)throw Error("Invalid legacy wire record.");if(Ze==="Entry"){Ot("Legacy bus-entry geometry omitted.");continue}Xt.push([Je[1]==="Bus"?"bus":"wire",["pts",["xy",Ae(Ke[0]),Ae(Ke[1])],["xy",Ae(Ke[2]),Ae(Ke[3])]]]);continue}if(Ze==="Connection"||Ze==="NoConn"){Xt.push([Ze==="Connection"?"junction":"no_connect",Kt(Je[2],Je[3])]);continue}if(Ze==="Text"){let Ke=at[++ve]??"",De={Label:"label",GLabel:"global_label",HLabel:"hierarchical_label",Notes:"text"}[Je[1]];if(!De){Ot("Unsupported legacy text record "+Je[1]+" omitted.");continue}let We=[0,90,180,270],rt=We[Number(Je[4])];if(rt===void 0){Ot("Unsupported legacy text orientation omitted.");continue}let Be={Input:"input",Output:"output",BiDi:"bidirectional",TriState:"tri_state",UnSpc:"passive"}[Je[6]];!["text","label"].includes(De)&&!Be&&Ot("Unknown legacy label shape "+Je[6]+"; passive outline used."),Xt.push([De,Ne(Ke.replace(/\\n/g,`
`)),Kt(Je[2],Je[3],rt),er(Je[5]),...De==="text"||De==="label"?[]:[["shape",Be||"passive"]]]);continue}if(Ze==="$Sheet"){let Ke=ge(ve+1,"$EndSheet");ve=Ke.end;let De=Ke.records,We=De.find(Le=>Le[0]==="S"),rt=De.find(Le=>Le[0]==="U");if(!We)throw Error("Legacy sheet has no bounds.");let Be=["sheet",Kt(We[1],We[2]),["size",Ae(We[3]),Ae(We[4])],["uuid",Ne(rt?.[1]||"legacy-sheet-"+ve)]];for(let Le of De.filter(Qe=>/^F\d+$/.test(Qe[0])))if(Le[0]==="F0"||Le[0]==="F1")Be.push(Lt(Le[0]==="F0"?"Sheetname":"Sheetfile",Le[1],We[1],We[2],Le[2]));else{let Qe=Le[3],ht={L:180,R:0,U:90,D:270}[Qe];Be.push(["pin",Ne(Le[1]),{I:"input",O:"output",B:"bidirectional",T:"tri_state",U:"passive"}[Le[2]]||"passive",Kt(Le[4],Le[5],ht??0),er(Le[6])])}Xt.push(Be);continue}if(Ze==="$Comp"){let Ke=ge(ve+1,"$EndComp");ve=Ke.end;let De=Ke.records,We=De.find(dt=>dt[0]==="L"),rt=De.find(dt=>dt[0]==="U"),Be=De.find(dt=>dt[0]==="P");if(!We||!Be)throw Error("Incomplete legacy component.");let Le=We[1],Qe=De.find(dt=>dt.length===4&&dt.every(St=>/^-?\d+$/.test(St)))?.map(Number)||[1,0,0,-1],ht=null;for(let dt of[0,90,180,270])for(let St of["","x","y"]){let be=dt*Math.PI/180,Oe=Math.round(Math.cos(be)),Me=Math.round(Math.sin(be)),nt=St==="y"?-1:1,ft=St==="x"?-1:1,it=[nt*Oe,-nt*Me,-ft*Me,-ft*Oe];Qe.every((_t,Rt)=>_t===it[Rt])&&(ht={angle:dt,mirror:St})}if(!ht){Ot("Legacy component "+Le+" has an unsupported orientation and is omitted.");continue}let bt=["symbol",["lib_id",Ne(Le)],Kt(Be[1],Be[2],ht.angle),["unit",Number(rt?.[1]||1)],["convert",Number(rt?.[2]||1)],["uuid",Ne(rt?.[3]||"legacy-component-"+ve)],...ht.mirror?[["mirror",ht.mirror]]:[]];for(let dt of De.filter(St=>St[0]==="F")){let St=["Reference","Value","Footprint","Datasheet"][Number(dt[1])]||dt[11]||"Field"+dt[1];bt.push(Lt(St,dt[2],dt[4],dt[5],dt[6],dt[7]!=="0000",(((dt[3]==="V"?90:0)-ht.angle)%180+180)%180))}let et=Nt.get(Le)||Nt.get(Le.split(":").pop());et?Et.includes(Le)||(sr.push(["symbol",Ne(Le),...et.slice(2)]),Et.push(Le)):Ot("Missing saved legacy library definition for "+Le+": symbol body and pins omitted; fields remain visible."),Xt.push(bt);continue}if(Ze==="$Bitmap"){let Ke=at.indexOf("$EndBitmap",ve+1);if(Ke<0){Ot("Legacy bitmap omitted: missing block terminator.");break}try{Xt.push(fr(at,ve+1,Ke))}catch(De){Ot("Legacy bitmap omitted: "+De.message)}ve=Ke}}}if(!at.some(ve=>ve==="$EndSCHEMATC"))throw Error("Incomplete legacy schematic terminator.");return Xt.push(sr,...[...zt].map(ve=>["legacy_diagnostic",Ne(ve)])),Xt}function Ct(It){let wt=Qt(It),at=[],zt=!1;for(let Ot of wt)if(Ot==="$Sheet")zt=!0;else if(Ot==="$EndSheet")zt=!1;else if(zt){let Nt=Ee(Ot);Nt[0]==="F1"&&at.push(Nt[1])}return at}ye.KiCadLegacy={parse:Ye,sheetFiles:Ct},typeof ep=="object"&&ep.exports&&(ep.exports=ye.KiCadLegacy)})(globalThis)});var b1=Zd((x1,dl)=>{(ye=>{"use strict";let xe=()=>268435456,er=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"]),Qt=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"]),fr=new Set(["uuid","tstamp","filled_polygon","fill_segments"]),rr=/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?$/;function Ye(be){if(typeof be!="string")throw new TypeError("KiCad source must be a string.");if(!/[^\x00-\x7f]/.test(be))return be.length;let Oe=be.length;for(let Me=0;Me<be.length;Me++){let nt=be.charCodeAt(Me);if(!(nt<128)){if(nt<2048){Oe++;continue}if(nt>=55296&&nt<=56319&&Me+1<be.length){let ft=be.charCodeAt(Me+1);if(ft>=56320&&ft<=57343){Oe+=2,Me++;continue}}Oe+=2}}return Oe}let Ct=be=>be===32||be>=9&&be<=13||be>127&&/\s/.test(String.fromCharCode(be));function It(be){if(!Array.isArray(be)||be.length!==4||be.some(_t=>!_t||!Number.isFinite(_t.x)||!Number.isFinite(_t.y)))throw Error("Bezier requires four finite control points.");let Oe=[{...be[0]}],Me=[be],nt=.005**2,ft=(_t,Rt,Ft)=>{let Zt=Ft.x-Rt.x,or=Ft.y-Rt.y,lr=Zt*Zt+or*or,gr=lr?Math.max(0,Math.min(1,((_t.x-Rt.x)*Zt+(_t.y-Rt.y)*or)/lr)):0;return(_t.x-Rt.x-gr*Zt)**2+(_t.y-Rt.y-gr*or)**2},it=(_t,Rt)=>({x:_t.x/2+Rt.x/2,y:_t.y/2+Rt.y/2});for(;Me.length;){let[_t,Rt,Ft,Zt]=Me.pop();if(Math.max(ft(Rt,_t,Zt),ft(Ft,_t,Zt))<=nt){if(Oe.length>=2049)throw Error("Bezier exceeds the bounded tessellation budget.");Oe.push({...Zt})}else{let or=it(_t,Rt),lr=it(Rt,Ft),gr=it(Ft,Zt),cr=it(or,lr),Gt=it(lr,gr),Er=it(cr,Gt);if(Me.length>32||[or,lr,gr,cr,Gt,Er].some(Xr=>!Number.isFinite(Xr.x)||!Number.isFinite(Xr.y)))throw Error("Bezier exceeds the bounded tessellation budget.");Me.push([Er,Gt,gr,Zt],[_t,or,cr,Er])}}return Oe}let wt=new Set(["version","generator","generator_version","uuid","paper","title_block","property","sheet","symbol","footprint","module","sheet_instances","legacy_source","legacy_diagnostic"]),at=new Set([...wt,"embedded_files"]),zt=new Set(["property","uuid","path","instances"]);function Ot(be,Oe={}){if(typeof be!="string")throw new TypeError("KiCad source must be a string.");if(/^\s*PCBNEW-BOARD/.test(be))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(be)){let lr=ye.KiCadLegacy||(typeof dl=="object"&&dl.exports?v1():null);if(!lr)throw Error("Legacy schematic adapter is unavailable; reload the extension.");return lr.parse(be,Oe)}if(be.length>268435456||be.length>268435456/3&&Ye(be)>268435456)throw new Error("KiCad file exceeds browser parser size limits.");let Me=[],nt=[],ft=/\(xy[ \t]+([-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?)[ \t]+([-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?)[ \t]*\)/y,it=0,_t=0,Rt=0,Ft=()=>Me.length===3&&Me[0][0]==="kicad_pcb"&&Me[1][0]==="zone"&&Me[2][0]==="filled_polygon";function Zt(lr){let gr=lr+4,cr=0,Gt=new Float64Array(128);for(;gr<be.length;){for(;Ct(be.charCodeAt(gr));)gr++;if(be.charCodeAt(gr)===41)return cr<6?null:(_t+=1+cr*2,or(["pts",cr===Gt.length?Gt:Gt.slice(0,cr)]),gr+1);ft.lastIndex=gr;let Er=ft.exec(be);if(!Er)return null;let Xr=Number(Er[1]),Ti=Number(Er[2]);if(!Number.isFinite(Xr)||!Number.isFinite(Ti))throw new Error("Invalid numeric KiCad value.");if(_t+6+cr*2>12e6)throw new Error("KiCad file has too many S-expression nodes.");if(cr===Gt.length){let Ta=new Float64Array(Gt.length*2);Ta.set(Gt),Gt=Ta}Gt[cr++]=Xr,Gt[cr++]=Ti,gr=ft.lastIndex}return null}let or=lr=>{if(++_t>12e6)throw new Error("KiCad file has too many S-expression nodes.");Rt||(Me.at(-1)||nt).push(lr)};for(;it<be.length;){let lr=be[it];if(Ct(be.charCodeAt(it))){it++;continue}if((lr==="<"||lr===">")&&/^(?:<{7,}|>{7,})(?:\s|$)/.test(be.slice(it,it+120)))throw new Error("Unresolved Git merge conflict at line "+be.slice(0,it).split(`
`).length+". Resolve the conflict in a separate copy before viewing.");if(lr===";"){for(;it<be.length&&be[it]!==`
`;)it++;continue}if(lr==="("){if(Me.length>=96)throw new Error("KiCad S-expression is too deep.");if(Oe.compactCopper&&!Oe.metadataOnly&&be.startsWith("(pts",it)&&Ct(be.charCodeAt(it+4))&&Ft()){let Er=Zt(it);if(Er!==null){it=Er;continue}}if(!Oe.metadataOnly&&Me.length&&be.startsWith("(xy",it)){ft.lastIndex=it;let Er=ft.exec(be);if(Er){let Xr=Number(Er[1]),Ti=Number(Er[2]);if(!Number.isFinite(Xr)||!Number.isFinite(Ti))throw new Error("Invalid numeric KiCad value.");_t+=3,or(["xy",Xr,Ti]),it=ft.lastIndex;continue}}if(Oe.metadataOnly&&!Rt){let Er=null;if(Me.length===1?Er=Oe.includeEmbeddedFonts?at:wt:Me.length===2&&["symbol","footprint","module"].includes(Me.at(-1)?.[0])?Er=zt:Me.at(-1)?.[0]==="property"&&(Er=new Set),Er){let Xr=it+1;for(;Xr<be.length&&Ct(be.charCodeAt(Xr));)Xr++;let Ti=Xr;for(;Ti<be.length&&!Ct(be.charCodeAt(Ti))&&!["(",")",";"].includes(be[Ti]);)Ti++;Er.has(be.slice(Xr,Ti))||(Rt=Me.length+1)}}let Gt=[];or(Gt),Me.push(Gt),it++;continue}if(lr===")"){if(!Me.length)throw new Error("Unexpected closing parenthesis in KiCad file.");let Gt=Me.pop();if(!Rt&&Gt.length>0&&Gt.length<=4){let Er=Gt.slice(),Xr=Me.at(-1)||nt;Xr[Xr.length-1]=Er}Rt&&Me.length<Rt&&(Rt=0),it++;continue}if(!Me.length)throw new Error("Expected a KiCad S-expression.");if(lr==='"'){let Gt=null,Er=++it,Xr=!1,Ti="";for(;it<be.length;){let Ta=be[it++];if(Ta==='"'){if(Xr=!0,!Rt){let fn=be.slice(Er,it-1);Gt?(Gt.push(fn),Ti=Gt.join("")):Ti=fn}break}if(Ta==="\\"){if(it>=be.length)throw new Error("Unterminated KiCad escape sequence.");let fn=be[it++];if(!Rt){Gt??=[],Gt.push(be.slice(Er,it-2));let gl={n:`
`,r:"\r",t:" ",'"':'"',"\\":"\\"}[fn];Gt.push(gl===void 0?"\\"+fn:gl)}Er=it}}if(!Xr)throw new Error("Unterminated quoted KiCad string.");or(Rt?null:{quoted:Ti});continue}let gr=it;for(;it<be.length;){let Gt=be.charCodeAt(it);if(Gt===40||Gt===41||Gt===59||Gt===34||Ct(Gt))break;it++}if(gr===it)throw new Error("Unexpected KiCad source character.");if(Rt){or(null);continue}let cr=be.slice(gr,it);if(rr.test(cr)){let Gt=Number(cr);if(!Number.isFinite(Gt))throw new Error("Invalid numeric KiCad value.");or(Gt)}else or(cr==="xy"?"xy":cr)}if(Me.length||nt.length!==1||!Array.isArray(nt[0]))throw new Error("Incomplete KiCad S-expression.");return nt[0]}let Nt=be=>be&&typeof be=="object"&&!Array.isArray(be)?be.quoted:be,Xt=be=>Array.isArray(be)?String(Nt(be[0])):"",sr=(be,Oe)=>be.filter(Me=>Array.isArray(Me)&&Xt(Me)===Oe),Et=(be,Oe)=>be.find(Me=>Array.isArray(Me)&&Xt(Me)===Oe),Lt=(be,Oe)=>Nt(Et(be,Oe)?.[1]);function ge(be){let Oe=Et(be,"polyline"),Me=Oe&&Et(Oe,"pts");if(!Me||Me.length<4||Me.length>4097)return null;let nt=[];for(let _t of Me.slice(1)){let Rt=Nt(_t?.[1]),Ft=Nt(_t?.[2]);if(!Array.isArray(_t)||Xt(_t)!=="xy"||!Number.isFinite(Rt)||!Number.isFinite(Ft))return null;let Zt=nt.at(-1);(Zt?.x!==Rt||Zt.y!==Ft)&&nt.push({x:Rt,y:Ft})}if(nt[0].x===nt.at(-1).x&&nt[0].y===nt.at(-1).y&&nt.pop(),nt.length<3)return null;let ft=nt[0],it=0;for(let _t=1;_t<nt.length-1;_t++){let Rt=nt[_t],Ft=nt[_t+1];it+=(Rt.x-ft.x)*(Ft.y-ft.y)-(Rt.y-ft.y)*(Ft.x-ft.x)}return Number.isFinite(it)&&it!==0?nt:null}function ve(be){for(let Oe of["at","start","center","end","xy"]){let Me=Et(be,Oe);if(Me&&Number.isFinite(Nt(Me[1]))&&Number.isFinite(Nt(Me[2])))return{x:Nt(Me[1]),y:Nt(Me[2])}}for(let Oe of["pts","polygon"]){let Me=Et(be,Oe),nt=Me&&Et(Oe==="polygon"&&Et(Me,"pts")||Me,"xy");if(nt&&Number.isFinite(Nt(nt[1]))&&Number.isFinite(Nt(nt[2])))return{x:Nt(nt[1]),y:Nt(nt[2])}}return null}function Je(be,Oe){let Me=[];for(let _t of sr(be,"property"))_t.length>=3&&Me.push([String(Nt(_t[1])),String(Nt(_t[2]))]);if(Oe==="footprint")for(let[_t,Rt]of[["reference","Reference"],["value","Value"]]){let Ft=sr(be,"fp_text").find(Zt=>Nt(Zt[1])===_t);Ft&&Ft.length>=3&&!Me.some(([Zt])=>Zt===Rt)&&Me.push([Rt,String(Nt(Ft[2]))])}for(let _t of["lib_id","layer","width","drill","size","unit"]){let Rt=Et(be,_t);Rt&&Me.push([_t,Rt.slice(1).map(Nt).join(", ")])}let nt=Et(be,"layers");nt&&Me.push(["Layers",nt.slice(1).map(Nt).join(", ")]);let ft=Et(be,"net");ft&&Me.push(["Net",String(Nt(ft[2]??ft[1]))]);let it=Et(be,"at");return it&&Number.isFinite(Nt(it[3]))&&Me.push(["Angle",String(Nt(it[3]))]),["label","global_label","hierarchical_label","text","gr_text","gr_text_box"].includes(Oe)&&Me.push(["Text",String(Nt(be[1]??""))]),Oe==="pad"&&(Me.push(["Number",String(Nt(be[1]??""))]),Me.push(["Type",String(Nt(be[2]??""))]),Me.push(["Shape",String(Nt(be[3]??""))])),Object.fromEntries(Me)}function Ze(be){return Array.isArray(be)?be.filter(Oe=>!Array.isArray(Oe)||!fr.has(Xt(Oe))).map(Ze):be&&typeof be=="object"?["quoted",be.quoted]:be}function Ke(be){let Oe=2166136261;for(let Me=0;Me<be.length;Me++)Oe=Math.imul(Oe^be.charCodeAt(Me),16777619);return(Oe>>>0).toString(16).padStart(8,"0")}function De(be,Oe,Me,nt){let ft=Lt(be,"uuid")??Lt(be,"tstamp")??(Oe==="rule_area"&&Et(be,"polyline")?Lt(Et(be,"polyline"),"uuid"):void 0);if(ft!=null&&String(ft))return{key:`uuid:${ft}`,uuid:String(ft)};let it=Oe==="pad"?Me.Number:Oe==="sheet"?Me.Sheetfile:Oe==="symbol"||Oe==="footprint"?Me.Reference:void 0;return{key:it?`fallback:${String(it)}`:`fallback:${Ke(typeof nt=="function"?nt():nt)}`,uuid:null}}function We(be,Oe,Me,nt){return Oe==="pad"?`${nt||"Footprint"} pad ${Me.Number||""}`.trim():Me.Reference||Me.Sheetname||Me["Sheet name"]||Me.Text||(Oe==="footprint"?String(Nt(be[1]??"Footprint")):Oe==="symbol"?Me.lib_id||"symbol":Oe==="netclass_flag"||Oe==="directive_label"?"Directive label":Oe==="rule_area"?"Rule area":Oe.replace(/_/g," "))}function rt(be,Oe){if(!be||!Oe?.position)return null;let Me=Number(Nt(Et(Oe.form,"at")?.[3]??0)),nt=(Number.isFinite(Me)?Me:0)*Math.PI/180,ft=Math.cos(nt),it=Math.sin(nt),_t=Oe.position.x+be.x*ft+be.y*it,Rt=Oe.position.y-be.x*it+be.y*ft,Ft=Zt=>Math.round(Zt*1e6)/1e6;return{x:Ft(_t),y:Ft(Rt)}}function Be(be,Oe,Me=null,nt=null,ft=!1){let it=Xt(Oe),_t=Je(Oe,it),Rt=ve(it==="rule_area"&&Et(Oe,"polyline")||Oe),Ft=it==="pad"?rt(Rt,Me):Rt,Zt,or=()=>Zt??=JSON.stringify([Ze(Oe),Ft,typeof nt=="function"?nt():nt]);ft||(_t["Source fingerprint"]=Ke(or()));let lr=De(Oe,it,_t,or),cr=`${Me?`${Me.scope}/`:`${be}/`}${it}:${lr.key}`,Gt=We(Oe,it,_t,Me?.label);return{key:cr,scope:cr,signature:ft?null:or(),metadata:{uuid:lr.uuid,position:Ft,properties:_t},path:be,kind:it,label:Gt,form:Oe}}function Le(be,Oe,Me=null,{forConnectivity:nt=!1,parseOnly:ft=!1,compactCopper:it=!1}={},_t){let Rt=_t||Ot(Oe,{compactCopper:it});Me?.(Rt);let Ft=Xt(Rt);if(Ft!=="kicad_sch"&&Ft!=="kicad_pcb")throw new Error("Expected a KiCad schematic or board.");if(ft)return[];let Zt=Ft==="kicad_sch"?er:Qt,or=new Map;if(Ft==="kicad_sch"){let gr=Et(Rt,"lib_symbols");if(gr)for(let cr of sr(gr,"symbol")){let Gt=Nt(cr[1]);typeof Gt=="string"&&or.set(Gt,nt?cr:JSON.stringify(Ze(cr)))}}let lr=[];for(let gr of Rt){if(!Array.isArray(gr)||!Zt.has(Xt(gr)))continue;let cr=Xt(gr)==="symbol"?or.get(String(Lt(gr,"lib_name")??Lt(gr,"lib_id"))):null,Gt=Be(be,gr,null,nt&&cr?()=>JSON.stringify(Ze(cr)):cr,nt);if(lr.push(Gt),Ft==="kicad_pcb"&&Gt.kind==="footprint")for(let Er of sr(gr,"pad"))lr.push(Be(be,Er,{form:gr,position:Gt.metadata.position,scope:Gt.scope,label:Gt.label},null,nt))}return lr}function Qe(be,Oe={}){return Ot(be,{...Oe,metadataOnly:!0}).filter((nt,ft)=>ft===0||Array.isArray(nt)&&(Oe.includeEmbeddedFonts?at:wt).has(nt[0])).map(nt=>Array.isArray(nt)&&["symbol","footprint","module"].includes(nt[0])?nt.filter((ft,it)=>it===0||Array.isArray(ft)&&zt.has(ft[0])):nt)}let ht=new WeakMap;function bt(be,{forConnectivity:Oe=!1,compactCopper:Me=!1}={}){let nt=new Map,ft=dt(be,(_t,Rt)=>nt.set(_t.path,Rt),null,{forConnectivity:Oe,parseOnly:Oe,compactCopper:Oe&&Me}),it=Object.freeze({});return ht.set(it,{files:be.map(_t=>({path:_t.path,content:_t.content})),parsed:nt,records:Oe?null:ft,forConnectivity:Oe}),it}function et(be,Oe,Me){let nt=ht.get(be);if(!nt||!nt.parsed.has(Oe))throw new Error("Prepared KiCad file is unavailable.");if(Me!==void 0&&!nt.files.some(ft=>ft.path===Oe&&ft.content===Me))throw new Error("Prepared KiCad file differs from source.");return nt.parsed.get(Oe)}function dt(be,Oe=null,Me=null,{forConnectivity:nt=!1,parseOnly:ft=!1,compactCopper:it=!1}={}){if(Me){let Zt=ht.get(Me);if(!Zt||!Array.isArray(be)||be.length!==Zt.files.length||be.some((or,lr)=>or?.path!==Zt.files[lr].path||or?.content!==Zt.files[lr].content))throw new Error("Prepared KiCad project differs from source.");if(Zt.forConnectivity!==nt||!Zt.records){let or=[];for(let lr of be)for(let gr of Le(lr.path,lr.content,cr=>Oe?.(lr,cr),{forConnectivity:nt},Zt.parsed.get(lr.path)))or.push(gr);return or}for(let or of be)Oe?.(or,Zt.parsed.get(or.path));return Zt.records.map(or=>({...or}))}if(!Array.isArray(be)||be.length>128)throw new Error("Too many KiCad files to compare.");let _t=new Set,Rt=[],Ft=0;for(let Zt of be){if(!Zt||typeof Zt.path!="string"||typeof Zt.content!="string"||!/\.kicad_(?:sch|pcb)$/i.test(Zt.path)||_t.has(Zt.path))throw new Error("Invalid or duplicate KiCad file entry.");_t.add(Zt.path);let or=Ye(Zt.content);if(Ft+=or,or>268435456||Ft>536870912)throw new Error("KiCad project exceeds browser comparison size limits.");for(let lr of Le(Zt.path,Zt.content,gr=>Oe?.(Zt,gr),{forConnectivity:nt,parseOnly:ft,compactCopper:it}))Rt.push(lr)}return Rt}function St(be,Oe){let Me=dt(be),nt=dt(Oe),ft=new Map;for(let Ft of Me)ft.has(Ft.key)||ft.set(Ft.key,{before:[],after:[]}),ft.get(Ft.key).before.push(Ft);for(let Ft of nt)ft.has(Ft.key)||ft.set(Ft.key,{before:[],after:[]}),ft.get(Ft.key).after.push(Ft);let it=[],_t={added:0,removed:0,modified:0},Rt=(Ft,Zt,or,lr,gr)=>{it.push({id:gr,path:Ft.path,kind:Ft.kind,label:Ft.label,status:Zt,before:or?.metadata??null,after:lr?.metadata??null}),_t[Zt]++};for(let[Ft,Zt]of ft){let or=[...Zt.before],lr=[...Zt.after];for(let cr=or.length-1;cr>=0;cr--){let Gt=lr.findIndex(Er=>Er.signature===or[cr].signature);Gt>=0&&(or.splice(cr,1),lr.splice(Gt,1))}or.sort((cr,Gt)=>cr.signature.localeCompare(Gt.signature)),lr.sort((cr,Gt)=>cr.signature.localeCompare(Gt.signature));let gr=Math.max(or.length,lr.length);for(let cr=0;cr<gr;cr++){let Gt=or[cr]||null,Er=lr[cr]||null;Rt(Er||Gt,Gt&&Er?"modified":Gt?"removed":"added",Gt,Er,gr>1?`${Ft}#${cr+1}`:Ft)}}return it.sort((Ft,Zt)=>Ft.path.localeCompare(Zt.path)||Ft.id.localeCompare(Zt.id)||Ft.status.localeCompare(Zt.status)),{changes:it,counts:_t}}ye.KiCadDesignDiff={compareProjects:St,projectObjects:dt,parse:Ot,parseMetadata:Qe,sourceByteLimit:xe,sourceByteLength:Ye,prepareProject:bt,preparedFile:et,cubicBezierPoints:It,MAX_FILES:128,MAX_FILE_BYTES:268435456,MAX_PROJECT_BYTES:536870912,MAX_RENDER_PRIMITIVES:15e5,ruleAreaPoints:ge},typeof dl=="object"&&dl.exports&&(dl.exports=ye.KiCadDesignDiff)})(typeof globalThis=="object"?globalThis:x1)});var r_={};mN(r_,{loadThree:()=>DN});function DN(){return Promise.resolve(ON)}var ON,i_=fN(()=>{ON=(()=>{var ye=Object.create,Z=Object.defineProperty,xe=Object.getOwnPropertyDescriptor,Re=Object.getOwnPropertyNames,Ne=Object.getPrototypeOf,Ae=Object.prototype.hasOwnProperty,Ee=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Kt=(e,t)=>{for(var r in t)Z(e,r,{get:t[r],enumerable:!0})},er=(e,t,r,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Re(t))!Ae.call(e,n)&&n!==r&&Z(e,n,{get:()=>t[n],enumerable:!(i=xe(t,n))||i.enumerable});return e},Qt=(e,t,r)=>(r=e!=null?ye(Ne(e)):{},er(t||!e||!e.__esModule?Z(r,"default",{value:e,enumerable:!0}):r,e)),fr=e=>er(Z({},"__esModule",{value:!0}),e),rr=Ee((e,t)=>{(r=>{"use strict";let i=f=>({quoted:String(f??"")}),n=f=>{let y=Number(f);if(!Number.isFinite(y)||Math.abs(y)>1e8)throw Error("Invalid legacy schematic coordinate.");return Math.round(y*.0254*1e8)/1e8},a=f=>[...f.matchAll(/"((?:\\.|[^"\\])*)"|([^\s]+)/g)].map(y=>y[1]!==void 0?y[1].replace(/\\(["\\])/g,"$1"):y[2]),s=(f,y,g=0)=>["at",n(f),n(y),g],o=(f=50,y=!1)=>["effects",["font",["size",n(f),n(f)]],...y?["hide"]:[]];function l(f){if(typeof f!="string"||new TextEncoder().encode(f).length>8388608)throw Error("Legacy schematic/library exceeds its size limit.");let y=f.replace(/^\uFEFF/,"").split(/\r?\n/);if(y.length>15e4)throw Error("Legacy schematic/library exceeds its line limit.");return y}function c(f,y,g){let p,m=1,v=!1,x=!1,b=0,_=[];for(let M=y;M<g;M++){let C=f[M].trim();if(!C)continue;if(C==="EndData"&&v&&!x){x=!0;continue}if(v&&!x){if(!/^[0-9a-f]{2}(?:\s+[0-9a-f]{2})*$/i.test(C))throw Error("Invalid saved bitmap bytes.");let P=C.match(/[0-9a-f]{2}/gi);if(b+=P.length,b>4*1024*1024)throw Error("Saved bitmap exceeds its 4 MiB limit.");for(let N=0;N<P.length;N+=8192)_.push(String.fromCharCode(...P.slice(N,N+8192).map(D=>parseInt(D,16))));continue}let[S,w,E]=a(C);S==="Pos"&&w!==void 0&&E!==void 0&&(p=s(w,E)),S==="Scale"&&w!==void 0&&(m=Number(w)),S==="Data"&&!v&&(v=!0)}if(!p||!_.length||!x||!Number.isFinite(m)||m<=0)throw Error("Invalid saved bitmap placement or data.");return["image",p,["scale",m],["uuid",i("legacy-bitmap-"+y)],["data",i(btoa(_.join("")))]]}function u(f,y){let g=new Map,p=0;if(!Array.isArray(f))return g;if(f.length>16)throw Error("Too many legacy symbol libraries.");for(let m of f){let v=typeof m=="string"?m:m?.content;if(typeof v!="string")continue;if(p+=v.length,p>16*1024*1024)throw Error("Legacy symbol libraries exceed their combined limit.");let x=null,b=[],_=!1,M=new Map;for(let C of l(v)){let S=a(C),w=S[0];if(!w||w[0]==="#")continue;if(w==="DEF"){x=S,b=[],M=new Map;continue}if(!x)continue;if(w==="ALIAS"){b.push(...S.slice(1));continue}if(w==="DRAW"){_=!0;continue}if(w==="ENDDRAW"){_=!1;continue}if(w==="ENDDEF"){let D=x[1],B=["symbol",i(D),...x[9]==="P"?[["power"]]:[],...x[5]==="N"?[["pin_numbers","hide"]]:[],...x[6]==="N"?[["pin_names","hide"]]:[],...M.values()];for(let J of[D,...b])g.has(J)||g.set(J,B);x=null;continue}if(!_)continue;let E=(D,B,J)=>{let Q=D+"_"+B;M.has(Q)||M.set(Q,["symbol",i(x[1]+"_"+Q)]),M.get(Q).push(J)},P=D=>["stroke",["width",Math.max(n(D||6),.01)]],N=D=>["fill",["type",D==="F"?"outline":D==="f"?"background":"none"]];if(w==="S")E(S[5],S[6],["rectangle",["start",n(S[1]),n(S[2])],["end",n(S[3]),n(S[4])],P(S[7]),N(S[8])]);else if(w==="C")E(S[4],S[5],["circle",["center",n(S[1]),n(S[2])],["radius",n(S[3])],P(S[6]),N(S[7])]);else if(w==="P"){let D=Number(S[1]);if(!Number.isInteger(D)||D<2||D>1e4||S.length<5+2*D)throw Error("Invalid legacy library polyline.");E(S[2],S[3],["polyline",["pts",...Array.from({length:D},(B,J)=>["xy",n(S[5+J*2]),n(S[6+J*2])])],P(S[4]),N(S[5+D*2])])}else if(w==="A"){let D=n(S[1]),B=n(S[2]),J=n(S[3]),Q=Number(S[4])*Math.PI/1800,j=Number(S[5])*Math.PI/1800-Q;for(;j<0;)j+=Math.PI*2;let k=H=>[D+J*Math.cos(H),B+J*Math.sin(H)];E(S[6],S[7],["arc",["start",...k(Q)],["mid",...k(Q+j/2)],["end",...k(Q+j)],P(S[8]),N(S[9])])}else if(w==="X"){let D={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"},B={R:0,U:90,L:180,D:270}[S[6]],J={"":"line",I:"inverted",C:"clock",CI:"inverted_clock",L:"input_low",CL:"clock_low",V:"output_low",F:"edge_clock_high",X:"non_logic"},Q=S[12]||"",j=Q.includes("N"),k=J[Q.replace(/N/g,"")];if(B===void 0||!k){y("Unsupported legacy pin orientation/style omitted: "+S[1]);continue}E(S[9],S[10],["pin",D[S[11]]||"unspecified",k,s(S[3],S[4],B),["length",n(S[5])],["name",i(S[1]),o(S[8])],["number",i(S[2]),o(S[7])],...j?["hide"]:[]])}else y(w==="T"?"Legacy library text is omitted; convert a copy in KiCad for complete typography.":"Unsupported legacy library graphic "+w+" omitted.")}}return g}function h(f,y={}){let g=l(f);if(!/^EESchema Schematic File Version [24]\b/.test(g[0]))throw Error("Only legacy Eeschema v2/v4 schematics are supported.");let p=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."]),m=S=>{p.size<200&&p.add(S)},v=u(y.libraries,m),x=["kicad_sch",["version",Number(g[0].match(/\d+$/)[0])],["legacy_source",i(g[0])]],b=["lib_symbols"],_=[],M=(S,w,E,P,N=50,D=!1,B=0)=>["property",i(S),i(w),s(E,P,B),o(N,D)];function C(S,w){let E=[],P=S;for(;P<g.length&&g[P]!==w;P++)E.push(a(g[P]));if(P===g.length)throw Error("Incomplete legacy schematic "+w+" block.");return{records:E,end:P}}for(let S=1;S<g.length;S++){let w=a(g[S]),E=w[0];if(!(!E||E[0]==="#")){if(E==="$Descr"){x.push(["paper",i(w[1])]);continue}if(/^Comment[1-9]$/.test(E)){let P=x.find(N=>Array.isArray(N)&&N[0]==="title_block");P||(P=["title_block"],x.push(P)),P.push(["comment",Number(E.slice(7)),i(w[1])]);continue}if(["Title","Date","Rev","Comp"].includes(E)){let P=x.find(N=>Array.isArray(N)&&N[0]==="title_block");P||(P=["title_block"],x.push(P)),P.push([{Title:"title",Date:"date",Rev:"rev",Comp:"company"}[E],i(w[1])]);continue}if(E==="Wire"||E==="Entry"){let P=a(g[++S]||"");if(P.length!==4)throw Error("Invalid legacy wire record.");if(E==="Entry"){m("Legacy bus-entry geometry omitted.");continue}x.push([w[1]==="Bus"?"bus":"wire",["pts",["xy",n(P[0]),n(P[1])],["xy",n(P[2]),n(P[3])]]]);continue}if(E==="Connection"||E==="NoConn"){x.push([E==="Connection"?"junction":"no_connect",s(w[2],w[3])]);continue}if(E==="Text"){let P=g[++S]??"",N={Label:"label",GLabel:"global_label",HLabel:"hierarchical_label",Notes:"text"}[w[1]];if(!N){m("Unsupported legacy text record "+w[1]+" omitted.");continue}let D=[0,90,180,270],B=D[Number(w[4])];if(B===void 0){m("Unsupported legacy text orientation omitted.");continue}let J={Input:"input",Output:"output",BiDi:"bidirectional",TriState:"tri_state",UnSpc:"passive"}[w[6]];!["text","label"].includes(N)&&!J&&m("Unknown legacy label shape "+w[6]+"; passive outline used."),x.push([N,i(P.replace(/\\n/g,`
`)),s(w[2],w[3],B),o(w[5]),...N==="text"||N==="label"?[]:[["shape",J||"passive"]]]);continue}if(E==="$Sheet"){let P=C(S+1,"$EndSheet");S=P.end;let N=P.records,D=N.find(Q=>Q[0]==="S"),B=N.find(Q=>Q[0]==="U");if(!D)throw Error("Legacy sheet has no bounds.");let J=["sheet",s(D[1],D[2]),["size",n(D[3]),n(D[4])],["uuid",i(B?.[1]||"legacy-sheet-"+S)]];for(let Q of N.filter(j=>/^F\d+$/.test(j[0])))if(Q[0]==="F0"||Q[0]==="F1")J.push(M(Q[0]==="F0"?"Sheetname":"Sheetfile",Q[1],D[1],D[2],Q[2]));else{let j=Q[3],k={L:180,R:0,U:90,D:270}[j];J.push(["pin",i(Q[1]),{I:"input",O:"output",B:"bidirectional",T:"tri_state",U:"passive"}[Q[2]]||"passive",s(Q[4],Q[5],k??0),o(Q[6])])}x.push(J);continue}if(E==="$Comp"){let P=C(S+1,"$EndComp");S=P.end;let N=P.records,D=N.find(X=>X[0]==="L"),B=N.find(X=>X[0]==="U"),J=N.find(X=>X[0]==="P");if(!D||!J)throw Error("Incomplete legacy component.");let Q=D[1],j=N.find(X=>X.length===4&&X.every(W=>/^-?\d+$/.test(W)))?.map(Number)||[1,0,0,-1],k=null;for(let X of[0,90,180,270])for(let W of["","x","y"]){let $=X*Math.PI/180,G=Math.round(Math.cos($)),T=Math.round(Math.sin($)),I=W==="y"?-1:1,V=W==="x"?-1:1,K=[I*G,-I*T,-V*T,-V*G];j.every((ie,le)=>ie===K[le])&&(k={angle:X,mirror:W})}if(!k){m("Legacy component "+Q+" has an unsupported orientation and is omitted.");continue}let H=["symbol",["lib_id",i(Q)],s(J[1],J[2],k.angle),["unit",Number(B?.[1]||1)],["convert",Number(B?.[2]||1)],["uuid",i(B?.[3]||"legacy-component-"+S)],...k.mirror?[["mirror",k.mirror]]:[]];for(let X of N.filter(W=>W[0]==="F")){let W=["Reference","Value","Footprint","Datasheet"][Number(X[1])]||X[11]||"Field"+X[1];H.push(M(W,X[2],X[4],X[5],X[6],X[7]!=="0000",(((X[3]==="V"?90:0)-k.angle)%180+180)%180))}let U=v.get(Q)||v.get(Q.split(":").pop());U?_.includes(Q)||(b.push(["symbol",i(Q),...U.slice(2)]),_.push(Q)):m("Missing saved legacy library definition for "+Q+": symbol body and pins omitted; fields remain visible."),x.push(H);continue}if(E==="$Bitmap"){let P=g.indexOf("$EndBitmap",S+1);if(P<0){m("Legacy bitmap omitted: missing block terminator.");break}try{x.push(c(g,S+1,P))}catch(N){m("Legacy bitmap omitted: "+N.message)}S=P}}}if(!g.some(S=>S==="$EndSCHEMATC"))throw Error("Incomplete legacy schematic terminator.");return x.push(b,...[...p].map(S=>["legacy_diagnostic",i(S)])),x}function d(f){let y=l(f),g=[],p=!1;for(let m of y)if(m==="$Sheet")p=!0;else if(m==="$EndSheet")p=!1;else if(p){let v=a(m);v[0]==="F1"&&g.push(v[1])}return g}r.KiCadLegacy={parse:h,sheetFiles:d},typeof t=="object"&&t.exports&&(t.exports=r.KiCadLegacy)})(globalThis)}),Ye=Ee((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"]),a=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"]),s=new Set(["uuid","tstamp","filled_polygon","fill_segments"]),o=/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?$/;function l(U){if(typeof U!="string")throw new TypeError("KiCad source must be a string.");if(!/[^\x00-\x7f]/.test(U))return U.length;let X=U.length;for(let W=0;W<U.length;W++){let $=U.charCodeAt(W);if(!($<128)){if($<2048){X++;continue}if($>=55296&&$<=56319&&W+1<U.length){let G=U.charCodeAt(W+1);if(G>=56320&&G<=57343){X+=2,W++;continue}}X+=2}}return X}let c=U=>U===32||U>=9&&U<=13||U>127&&/\s/.test(String.fromCharCode(U));function u(U){if(!Array.isArray(U)||U.length!==4||U.some(I=>!I||!Number.isFinite(I.x)||!Number.isFinite(I.y)))throw Error("Bezier requires four finite control points.");let X=[{...U[0]}],W=[U],$=.005**2,G=(I,V,K)=>{let ie=K.x-V.x,le=K.y-V.y,ae=ie*ie+le*le,de=ae?Math.max(0,Math.min(1,((I.x-V.x)*ie+(I.y-V.y)*le)/ae)):0;return(I.x-V.x-de*ie)**2+(I.y-V.y-de*le)**2},T=(I,V)=>({x:I.x/2+V.x/2,y:I.y/2+V.y/2});for(;W.length;){let[I,V,K,ie]=W.pop();if(Math.max(G(V,I,ie),G(K,I,ie))<=$){if(X.length>=2049)throw Error("Bezier exceeds the bounded tessellation budget.");X.push({...ie})}else{let le=T(I,V),ae=T(V,K),de=T(K,ie),z=T(le,ae),me=T(ae,de),we=T(z,me);if(W.length>32||[le,ae,de,z,me,we].some(He=>!Number.isFinite(He.x)||!Number.isFinite(He.y)))throw Error("Bezier exceeds the bounded tessellation budget.");W.push([we,me,de,ie],[I,le,z,we])}}return X}let h=new Set(["version","generator","generator_version","uuid","paper","title_block","property","sheet","symbol","footprint","module","sheet_instances","legacy_source","legacy_diagnostic"]),d=new Set([...h,"embedded_files"]),f=new Set(["property","uuid","path","instances"]);function y(U,X={}){if(typeof U!="string")throw new TypeError("KiCad source must be a string.");if(/^\s*PCBNEW-BOARD/.test(U))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(U)){let ae=r.KiCadLegacy||(typeof t=="object"&&t.exports?rr():null);if(!ae)throw Error("Legacy schematic adapter is unavailable; reload the extension.");return ae.parse(U,X)}if(U.length>268435456||U.length>268435456/3&&l(U)>268435456)throw new Error("KiCad file exceeds browser parser size limits.");let W=[],$=[],G=/\(xy[ \t]+([-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?)[ \t]+([-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?)[ \t]*\)/y,T=0,I=0,V=0,K=()=>W.length===3&&W[0][0]==="kicad_pcb"&&W[1][0]==="zone"&&W[2][0]==="filled_polygon";function ie(ae){let de=ae+4,z=0,me=new Float64Array(128);for(;de<U.length;){for(;c(U.charCodeAt(de));)de++;if(U.charCodeAt(de)===41)return z<6?null:(I+=1+z*2,le(["pts",z===me.length?me:me.slice(0,z)]),de+1);G.lastIndex=de;let we=G.exec(U);if(!we)return null;let He=Number(we[1]),ne=Number(we[2]);if(!Number.isFinite(He)||!Number.isFinite(ne))throw new Error("Invalid numeric KiCad value.");if(I+6+z*2>12e6)throw new Error("KiCad file has too many S-expression nodes.");if(z===me.length){let _e=new Float64Array(me.length*2);_e.set(me),me=_e}me[z++]=He,me[z++]=ne,de=G.lastIndex}return null}let le=ae=>{if(++I>12e6)throw new Error("KiCad file has too many S-expression nodes.");V||(W.at(-1)||$).push(ae)};for(;T<U.length;){let ae=U[T];if(c(U.charCodeAt(T))){T++;continue}if((ae==="<"||ae===">")&&/^(?:<{7,}|>{7,})(?:\s|$)/.test(U.slice(T,T+120)))throw new Error("Unresolved Git merge conflict at line "+U.slice(0,T).split(`
`).length+". Resolve the conflict in a separate copy before viewing.");if(ae===";"){for(;T<U.length&&U[T]!==`
`;)T++;continue}if(ae==="("){if(W.length>=96)throw new Error("KiCad S-expression is too deep.");if(X.compactCopper&&!X.metadataOnly&&U.startsWith("(pts",T)&&c(U.charCodeAt(T+4))&&K()){let we=ie(T);if(we!==null){T=we;continue}}if(!X.metadataOnly&&W.length&&U.startsWith("(xy",T)){G.lastIndex=T;let we=G.exec(U);if(we){let He=Number(we[1]),ne=Number(we[2]);if(!Number.isFinite(He)||!Number.isFinite(ne))throw new Error("Invalid numeric KiCad value.");I+=3,le(["xy",He,ne]),T=G.lastIndex;continue}}if(X.metadataOnly&&!V){let we=null;if(W.length===1?we=X.includeEmbeddedFonts?d:h:W.length===2&&["symbol","footprint","module"].includes(W.at(-1)?.[0])?we=f:W.at(-1)?.[0]==="property"&&(we=new Set),we){let He=T+1;for(;He<U.length&&c(U.charCodeAt(He));)He++;let ne=He;for(;ne<U.length&&!c(U.charCodeAt(ne))&&!["(",")",";"].includes(U[ne]);)ne++;we.has(U.slice(He,ne))||(V=W.length+1)}}let me=[];le(me),W.push(me),T++;continue}if(ae===")"){if(!W.length)throw new Error("Unexpected closing parenthesis in KiCad file.");let me=W.pop();if(!V&&me.length>0&&me.length<=4){let we=me.slice(),He=W.at(-1)||$;He[He.length-1]=we}V&&W.length<V&&(V=0),T++;continue}if(!W.length)throw new Error("Expected a KiCad S-expression.");if(ae==='"'){let me=null,we=++T,He=!1,ne="";for(;T<U.length;){let _e=U[T++];if(_e==='"'){if(He=!0,!V){let oe=U.slice(we,T-1);me?(me.push(oe),ne=me.join("")):ne=oe}break}if(_e==="\\"){if(T>=U.length)throw new Error("Unterminated KiCad escape sequence.");let oe=U[T++];if(!V){me??=[],me.push(U.slice(we,T-2));let ce={n:`
`,r:"\r",t:" ",'"':'"',"\\":"\\"}[oe];me.push(ce===void 0?"\\"+oe:ce)}we=T}}if(!He)throw new Error("Unterminated quoted KiCad string.");le(V?null:{quoted:ne});continue}let de=T;for(;T<U.length;){let me=U.charCodeAt(T);if(me===40||me===41||me===59||me===34||c(me))break;T++}if(de===T)throw new Error("Unexpected KiCad source character.");if(V){le(null);continue}let z=U.slice(de,T);if(o.test(z)){let me=Number(z);if(!Number.isFinite(me))throw new Error("Invalid numeric KiCad value.");le(me)}else le(z==="xy"?"xy":z)}if(W.length||$.length!==1||!Array.isArray($[0]))throw new Error("Incomplete KiCad S-expression.");return $[0]}let g=U=>U&&typeof U=="object"&&!Array.isArray(U)?U.quoted:U,p=U=>Array.isArray(U)?String(g(U[0])):"",m=(U,X)=>U.filter(W=>Array.isArray(W)&&p(W)===X),v=(U,X)=>U.find(W=>Array.isArray(W)&&p(W)===X),x=(U,X)=>g(v(U,X)?.[1]);function b(U){let X=v(U,"polyline"),W=X&&v(X,"pts");if(!W||W.length<4||W.length>4097)return null;let $=[];for(let I of W.slice(1)){let V=g(I?.[1]),K=g(I?.[2]);if(!Array.isArray(I)||p(I)!=="xy"||!Number.isFinite(V)||!Number.isFinite(K))return null;let ie=$.at(-1);(ie?.x!==V||ie.y!==K)&&$.push({x:V,y:K})}if($[0].x===$.at(-1).x&&$[0].y===$.at(-1).y&&$.pop(),$.length<3)return null;let G=$[0],T=0;for(let I=1;I<$.length-1;I++){let V=$[I],K=$[I+1];T+=(V.x-G.x)*(K.y-G.y)-(V.y-G.y)*(K.x-G.x)}return Number.isFinite(T)&&T!==0?$:null}function _(U){for(let X of["at","start","center","end","xy"]){let W=v(U,X);if(W&&Number.isFinite(g(W[1]))&&Number.isFinite(g(W[2])))return{x:g(W[1]),y:g(W[2])}}for(let X of["pts","polygon"]){let W=v(U,X),$=W&&v(X==="polygon"&&v(W,"pts")||W,"xy");if($&&Number.isFinite(g($[1]))&&Number.isFinite(g($[2])))return{x:g($[1]),y:g($[2])}}return null}function M(U,X){let W=[];for(let I of m(U,"property"))I.length>=3&&W.push([String(g(I[1])),String(g(I[2]))]);if(X==="footprint")for(let[I,V]of[["reference","Reference"],["value","Value"]]){let K=m(U,"fp_text").find(ie=>g(ie[1])===I);K&&K.length>=3&&!W.some(([ie])=>ie===V)&&W.push([V,String(g(K[2]))])}for(let I of["lib_id","layer","width","drill","size","unit"]){let V=v(U,I);V&&W.push([I,V.slice(1).map(g).join(", ")])}let $=v(U,"layers");$&&W.push(["Layers",$.slice(1).map(g).join(", ")]);let G=v(U,"net");G&&W.push(["Net",String(g(G[2]??G[1]))]);let T=v(U,"at");return T&&Number.isFinite(g(T[3]))&&W.push(["Angle",String(g(T[3]))]),["label","global_label","hierarchical_label","text","gr_text","gr_text_box"].includes(X)&&W.push(["Text",String(g(U[1]??""))]),X==="pad"&&(W.push(["Number",String(g(U[1]??""))]),W.push(["Type",String(g(U[2]??""))]),W.push(["Shape",String(g(U[3]??""))])),Object.fromEntries(W)}function C(U){return Array.isArray(U)?U.filter(X=>!Array.isArray(X)||!s.has(p(X))).map(C):U&&typeof U=="object"?["quoted",U.quoted]:U}function S(U){let X=2166136261;for(let W=0;W<U.length;W++)X=Math.imul(X^U.charCodeAt(W),16777619);return(X>>>0).toString(16).padStart(8,"0")}function w(U,X,W,$){let G=x(U,"uuid")??x(U,"tstamp")??(X==="rule_area"&&v(U,"polyline")?x(v(U,"polyline"),"uuid"):void 0);if(G!=null&&String(G))return{key:`uuid:${G}`,uuid:String(G)};let T=X==="pad"?W.Number:X==="sheet"?W.Sheetfile:X==="symbol"||X==="footprint"?W.Reference:void 0;return{key:T?`fallback:${String(T)}`:`fallback:${S(typeof $=="function"?$():$)}`,uuid:null}}function E(U,X,W,$){return X==="pad"?`${$||"Footprint"} pad ${W.Number||""}`.trim():W.Reference||W.Sheetname||W["Sheet name"]||W.Text||(X==="footprint"?String(g(U[1]??"Footprint")):X==="symbol"?W.lib_id||"symbol":X==="netclass_flag"||X==="directive_label"?"Directive label":X==="rule_area"?"Rule area":X.replace(/_/g," "))}function P(U,X){if(!U||!X?.position)return null;let W=Number(g(v(X.form,"at")?.[3]??0)),$=(Number.isFinite(W)?W:0)*Math.PI/180,G=Math.cos($),T=Math.sin($),I=X.position.x+U.x*G+U.y*T,V=X.position.y-U.x*T+U.y*G,K=ie=>Math.round(ie*1e6)/1e6;return{x:K(I),y:K(V)}}function N(U,X,W=null,$=null,G=!1){let T=p(X),I=M(X,T),V=_(T==="rule_area"&&v(X,"polyline")||X),K=T==="pad"?P(V,W):V,ie,le=()=>ie??=JSON.stringify([C(X),K,typeof $=="function"?$():$]);G||(I["Source fingerprint"]=S(le()));let ae=w(X,T,I,le),de=`${W?`${W.scope}/`:`${U}/`}${T}:${ae.key}`,z=E(X,T,I,W?.label);return{key:de,scope:de,signature:G?null:le(),metadata:{uuid:ae.uuid,position:K,properties:I},path:U,kind:T,label:z,form:X}}function D(U,X,W=null,{forConnectivity:$=!1,parseOnly:G=!1,compactCopper:T=!1}={},I){let V=I||y(X,{compactCopper:T});W?.(V);let K=p(V);if(K!=="kicad_sch"&&K!=="kicad_pcb")throw new Error("Expected a KiCad schematic or board.");if(G)return[];let ie=K==="kicad_sch"?n:a,le=new Map;if(K==="kicad_sch"){let de=v(V,"lib_symbols");if(de)for(let z of m(de,"symbol")){let me=g(z[1]);typeof me=="string"&&le.set(me,$?z:JSON.stringify(C(z)))}}let ae=[];for(let de of V){if(!Array.isArray(de)||!ie.has(p(de)))continue;let z=p(de)==="symbol"?le.get(String(x(de,"lib_name")??x(de,"lib_id"))):null,me=N(U,de,null,$&&z?()=>JSON.stringify(C(z)):z,$);if(ae.push(me),K==="kicad_pcb"&&me.kind==="footprint")for(let we of m(de,"pad"))ae.push(N(U,we,{form:de,position:me.metadata.position,scope:me.scope,label:me.label},null,$))}return ae}function B(U,X={}){return y(U,{...X,metadataOnly:!0}).filter((W,$)=>$===0||Array.isArray(W)&&(X.includeEmbeddedFonts?d:h).has(W[0])).map(W=>Array.isArray(W)&&["symbol","footprint","module"].includes(W[0])?W.filter(($,G)=>G===0||Array.isArray($)&&f.has($[0])):W)}let J=new WeakMap;function Q(U,{forConnectivity:X=!1,compactCopper:W=!1}={}){let $=new Map,G=k(U,(I,V)=>$.set(I.path,V),null,{forConnectivity:X,parseOnly:X,compactCopper:X&&W}),T=Object.freeze({});return J.set(T,{files:U.map(I=>({path:I.path,content:I.content})),parsed:$,records:X?null:G,forConnectivity:X}),T}function j(U,X,W){let $=J.get(U);if(!$||!$.parsed.has(X))throw new Error("Prepared KiCad file is unavailable.");if(W!==void 0&&!$.files.some(G=>G.path===X&&G.content===W))throw new Error("Prepared KiCad file differs from source.");return $.parsed.get(X)}function k(U,X=null,W=null,{forConnectivity:$=!1,parseOnly:G=!1,compactCopper:T=!1}={}){if(W){let ie=J.get(W);if(!ie||!Array.isArray(U)||U.length!==ie.files.length||U.some((le,ae)=>le?.path!==ie.files[ae].path||le?.content!==ie.files[ae].content))throw new Error("Prepared KiCad project differs from source.");if(ie.forConnectivity!==$||!ie.records){let le=[];for(let ae of U)for(let de of D(ae.path,ae.content,z=>X?.(ae,z),{forConnectivity:$},ie.parsed.get(ae.path)))le.push(de);return le}for(let le of U)X?.(le,ie.parsed.get(le.path));return ie.records.map(le=>({...le}))}if(!Array.isArray(U)||U.length>128)throw new Error("Too many KiCad files to compare.");let I=new Set,V=[],K=0;for(let ie of U){if(!ie||typeof ie.path!="string"||typeof ie.content!="string"||!/\.kicad_(?:sch|pcb)$/i.test(ie.path)||I.has(ie.path))throw new Error("Invalid or duplicate KiCad file entry.");I.add(ie.path);let le=l(ie.content);if(K+=le,le>268435456||K>536870912)throw new Error("KiCad project exceeds browser comparison size limits.");for(let ae of D(ie.path,ie.content,de=>X?.(ie,de),{forConnectivity:$,parseOnly:G,compactCopper:T}))V.push(ae)}return V}function H(U,X){let W=k(U),$=k(X),G=new Map;for(let K of W)G.has(K.key)||G.set(K.key,{before:[],after:[]}),G.get(K.key).before.push(K);for(let K of $)G.has(K.key)||G.set(K.key,{before:[],after:[]}),G.get(K.key).after.push(K);let T=[],I={added:0,removed:0,modified:0},V=(K,ie,le,ae,de)=>{T.push({id:de,path:K.path,kind:K.kind,label:K.label,status:ie,before:le?.metadata??null,after:ae?.metadata??null}),I[ie]++};for(let[K,ie]of G){let le=[...ie.before],ae=[...ie.after];for(let z=le.length-1;z>=0;z--){let me=ae.findIndex(we=>we.signature===le[z].signature);me>=0&&(le.splice(z,1),ae.splice(me,1))}le.sort((z,me)=>z.signature.localeCompare(me.signature)),ae.sort((z,me)=>z.signature.localeCompare(me.signature));let de=Math.max(le.length,ae.length);for(let z=0;z<de;z++){let me=le[z]||null,we=ae[z]||null;V(we||me,me&&we?"modified":me?"removed":"added",me,we,de>1?`${K}#${z+1}`:K)}}return T.sort((K,ie)=>K.path.localeCompare(ie.path)||K.id.localeCompare(ie.id)||K.status.localeCompare(ie.status)),{changes:T,counts:I}}r.KiCadDesignDiff={compareProjects:H,projectObjects:k,parse:y,parseMetadata:B,sourceByteLimit:i,sourceByteLength:l,prepareProject:Q,preparedFile:j,cubicBezierPoints:u,MAX_FILES:128,MAX_FILE_BYTES:268435456,MAX_PROJECT_BYTES:536870912,MAX_RENDER_PRIMITIVES:15e5,ruleAreaPoints:b},typeof t=="object"&&t.exports&&(t.exports=r.KiCadDesignDiff)})(typeof globalThis=="object"?globalThis:e)}),Ct=Ee((e,t)=>{(r=>{"use strict";let i=p=>p&&typeof p=="object"&&!Array.isArray(p)?p.quoted:p,n=p=>Array.isArray(p)?String(i(p[0])):"",a=(p,m)=>Array.isArray(p)?p.filter(v=>Array.isArray(v)&&n(v)===m):[],s=(p,m)=>a(p,m)[0],o=(p,m)=>i(s(p,m)?.[1]),l=(p,m)=>typeof i(p)=="number"&&Number.isFinite(i(p))?i(p):m,c=(p,m,v)=>{let x=s(s(p,m),"xyz");return x?[l(x[1],NaN),l(x[2],NaN),l(x[3],NaN)]:[...v]},u=p=>typeof p=="string"&&p.length>0&&p.length<=500&&!/[\\\u0000-\u001f\u007f?%]/.test(p)&&!/^[a-z][a-z\d+.-]*:/i.test(p)&&!p.startsWith("/");function h(p,m){if(typeof m=="string"&&(m=m.replace(/\\/g,"/")),!u(p)||!/\.kicad_pcb$/i.test(p)||!u(m))return null;let v=p.split("/");if(v.some(M=>!M||M==="."||M===".."))return null;let x=m.replace(/^(?:\$\{KIPRJMOD\}|\$\(KIPRJMOD\))\//,"");if(x.includes("$(")||x.includes("${")||x.includes("}"))return null;let b=v.slice(0,-1);for(let M of x.split("/"))if(!(!M||M==="."))if(M===".."){if(!b.length)return null;b.pop()}else b.push(M);let _=b.join("/");return _.length<=500&&u(_)?_:null}function d(p){if(n(p)!=="kicad_pcb")throw new Error("Expected a saved KiCad PCB.");let m=new Set(["at","layer","uuid","tstamp","model","embedded_files"]),v=["kicad_pcb"];for(let x of p){if(n(x)==="embedded_files"&&v.push(x),n(x)!=="footprint")continue;let b=["footprint"];if(v.push(b),!!x.some(_=>n(_)==="model"))for(let _ of x){let M=n(_);m.has(M)?b.push(_):(M==="property"&&i(_[1])==="Reference"||M==="fp_text"&&i(_[1])==="reference")&&b.push(_.slice(0,3))}}return v}function f(p,m,v=r.KiCadDesignDiff?.parse,x=[]){if(typeof v!="function")throw new Error("KiCad S-expression parser is unavailable.");return y(v(p),m,x)}function y(p,m,v=[]){if(n(p)!=="kicad_pcb")throw new Error("Expected a saved KiCad PCB.");let x=[],b=[],_=N=>{b.length<48&&b.push(N)},M=Array.isArray(v)?v.slice(0,2e3).filter(N=>u(N)&&N.split("/").every(D=>D&&D!=="."&&D!=="..")):[];function C(N,D){let B=h(m,N),J=/^(?:\$\{(?:KICAD\d+_3DMODEL_DIR|KISYS3DMOD)\}|\$\((?:KICAD\d+_3DMODEL_DIR|KISYS3DMOD)\))[\\/]/,Q=typeof N=="string"&&J.test(N)?N.replace(J,"").replace(/\\/g,"/"):null,j=B||Q;if(B&&(!M.length||M.includes(B)))return B;if(Array.isArray(v)&&v.length>=2e3)return B||_(`${D}: model discovery is incomplete; library recovery is unavailable: ${String(N).slice(0,100)}`),B;if(B){let k=M.filter(H=>H.toLowerCase()===B.toLowerCase());if(k.length===1)return _(`${D}: model path casing corrected to ${k[0]}`),k[0];if(k.length>1)return _(`${D}: model path casing is ambiguous: ${B}`),null}if(j&&u(j)&&j.split("/").every(k=>k&&k!=="."&&k!=="..")){let k=Q?M.filter(U=>U===Q||U.endsWith("/"+Q)):[];if(k.length===1)return k[0];if(k.length>1)return _(`${D}: model library path matches multiple repository files: ${Q}`),null;if(Q){let U=Q.toLowerCase(),X=M.filter(W=>W.toLowerCase()===U||W.toLowerCase().endsWith("/"+U));if(X.length===1)return _(`${D}: model path casing corrected to ${X[0]}`),X[0];if(X.length>1)return _(`${D}: model path casing is ambiguous: ${Q}`),null}let H=j.replace(/\.(?:step|stp|wrl|vrml)$/i,"");if(H!==j){let U=M.filter(X=>{let W=X.replace(/\.(?:step|stp|wrl|vrml)$/i,"");return W!==X&&(W.toLowerCase()===H.toLowerCase()||Q&&W.toLowerCase().endsWith("/"+H.toLowerCase()))});if(U.length===1)return _(`${D}: using repository model alternative ${U[0]} for ${N}`),U[0];if(U.length>1)return _(`${D}: model alternatives are ambiguous: ${j}`),null}}return B||(!Q||!u(Q)||Q.split("/").some(k=>!k||k==="."||k==="..")||_(`${D}: library model is not included in this project: ${Q}. Include the model files with the project to load them offline or in the browser.`),null)}function S(N){let D=new Map;for(let B of a(s(N,"embedded_files"),"file")){let J=o(B,"name");if(!(!u(J)||J.split("/").some(Q=>!Q||Q==="."||Q===".."))){if(D.has(J)){D.set(J,null),_(`Duplicate embedded model name: ${J}`);continue}D.set(J,B)}}return D}let w=S(p),E=new WeakMap;function P(N){if(!N)return null;if(E.has(N))return E.get(N);let D=s(N,"data"),B=0;for(let j=1;j<(D?.length||0)&&B<=11200002;j++)B+=String(i(D[j])).length;let J=B&&B<=11200002?D.slice(1).map(i).join(""):"",Q=J.startsWith("|")&&J.endsWith("|")?{base64:J.slice(1,-1),checksum:String(o(N,"checksum")||"")}:null;return E.set(N,Q),Q}for(let[N,D]of a(p,"footprint").entries()){let B=a(D,"model");if(!B.length)continue;let J=a(D,"property").find(T=>i(T[1])==="Reference"),Q=a(D,"fp_text").find(T=>i(T[1])==="reference"),j=String(i(J?.[2])||i(Q?.[2])||`REF${N+1}`),k=o(D,"uuid")||o(D,"tstamp")||`component-${j}`,H=s(D,"at"),U=l(H?.[1],NaN),X=l(H?.[2],NaN),W=l(H?.[3],0),$=String(o(D,"layer")||"F.Cu");if(![U,X,W].every(Number.isFinite)||!["F.Cu","B.Cu"].includes($)){_(`${j}: footprint placement or side is unsupported.`);continue}let G;for(let T of B){if(x.length>=2048)return _("Only the first 2048 footprint model references are loaded."),{models:x,diagnostics:b};let I=i(T[1]),V=typeof I=="string"&&I.startsWith("kicad-embed://")?I.slice(14):null;V!==null&&(G??=S(D));let K=V!==null?P(G.has(V)?G.get(V):w.get(V)):null;if(V!==null&&!K){_(`${j}: embedded model is missing or ambiguous: ${V}`);continue}let ie=V!==null?I:C(I,j);if(!ie){_(`${j}: model path is not a repository-relative file: ${String(I).slice(0,100)}`);continue}let le=/\.([a-z\d]+)$/i.exec(ie)?.[1]?.toLowerCase();if(!["wrl","vrml","glb","step","stp"].includes(le)){_(`${j}: ${le==="step"||le==="stp"?"STEP":"model format"} is not supported in the browser: ${ie}`);continue}let ae=s(T,"hide");if(ae&&i(ae[1])!=="no"&&i(ae[1])!==!1)continue;let de=c(T,"offset",[0,0,0]),z=c(T,"scale",[1,1,1]),me=c(T,"rotate",[0,0,0]);if(de.some(we=>!Number.isFinite(we)||Math.abs(we)>1e4)||z.some(we=>!Number.isFinite(we)||we<=0||we>1e3)||me.some(we=>!Number.isFinite(we)||Math.abs(we)>3600)){_(`${j}: model transform is invalid: ${ie}`);continue}x.push({path:ie,format:le,footprintId:String(k),reference:j,footprint:{x:U,y:X,angle:W,layer:$},offset:de,scale:z,rotate:me,...K?{embeddedAsset:K,assetKey:`embedded:${G.has(V)?N:"board"}:${V}`}:{}})}}return{models:x,diagnostics:b}}function g(p,m,v,x){let b=p.footprint.layer==="B.Cu",_=p.footprint.angle*Math.PI/180,[M,C,S]=p.offset,w=b?-C:C,E=["glb","step","stp"].includes(p.format)?1:2.54;return{position:[p.footprint.x-m+M*Math.cos(_)-w*Math.sin(_),v-p.footprint.y+M*Math.sin(_)+w*Math.cos(_),(b?-1:1)*(x/2+S)],footprintAngle:_,modelRotation:[(b?180:0)-p.rotate[0],(b?1:-1)*p.rotate[1],(b?1:-1)*p.rotate[2]].map(P=>P*Math.PI/180),scale:p.scale.map(P=>P*E)}}r.KiCadRepoModels={collect:f,collectParsed:y,modelSource:d,resolveModelPath:h,modelPose:g},typeof t=="object"&&t.exports&&(t.exports=r.KiCadRepoModels)})(typeof globalThis=="object"?globalThis:e)}),It=Ee((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,a=Uint16Array,s=Int16Array,o=Uint32Array,l=Int32Array,c=function(k,H,U){if(n.prototype.slice)return n.prototype.slice.call(k,H,U);(H==null||H<0)&&(H=0),(U==null||U>k.length)&&(U=k.length);var X=new n(U-H);return X.set(k.subarray(H,U)),X},u=function(k,H,U,X){if(n.prototype.fill)return n.prototype.fill.call(k,H,U,X);for((U==null||U<0)&&(U=0),(X==null||X>k.length)&&(X=k.length);U<X;++U)k[U]=H;return k},h=function(k,H,U,X){if(n.prototype.copyWithin)return n.prototype.copyWithin.call(k,H,U,X);for((U==null||U<0)&&(U=0),(X==null||X>k.length)&&(X=k.length);U<X;)k[H++]=k[U++]};r.ZstdErrorCode={InvalidData:0,WindowSizeTooLarge:1,InvalidBlockType:2,FSEAccuracyTooHigh:3,DistanceTooFarBack:4,UnexpectedEOF:5};var d=["invalid zstd data","window size too large (>2046MB)","invalid block type","FSE accuracy too high","match distance too far back","unexpected EOF"],f=function(k,H,U){var X=Error(H||d[k]);if(X.code=k,Error.captureStackTrace&&Error.captureStackTrace(X,f),!U)throw X;return X},y=function(k,H,U){for(var X=0,W=0;X<U;++X)W|=k[H++]<<(X<<3);return W},g=function(k,H){return(k[H]|k[H+1]<<8|k[H+2]<<16|k[H+3]<<24)>>>0},p=function(k,H){var U=k[0]|k[1]<<8|k[2]<<16;if(U==3126568&&k[3]==253){var X=k[4],W=X>>5&1,$=X>>2&1,G=3&X,T=X>>6;8&X&&f(0);var I=6-W,V=G==3?4:G,K=y(k,I,V),ie=T?1<<T:W,le=y(k,I+=V,ie)+(T==1&&256),ae=le;if(!W){var de=1<<10+(k[5]>>3);ae=de+(de>>3)*(7&k[5])}ae>2145386496&&f(1);var z=new n((H==1?le||ae:H?0:ae)+12);return z[0]=1,z[4]=4,z[8]=8,{b:I+ie,y:0,l:0,d:K,w:H&&H!=1?H:z.subarray(12),e:ae,o:new l(z.buffer,0,3),u:le,c:$,m:Math.min(131072,ae)}}if((U>>4|k[3]<<20)==25481893)return g(k,4)+8;f(0)},m=function(k){for(var H=0;1<<H<=k;++H);return H-1},v=function(k,H,U){var X=4+(H<<3),W=5+(15&k[H]);W>U&&f(3);for(var $=1<<W,G=$,T=-1,I=-1,V=-1,K=$,ie=new i(512+($<<2)),le=new s(ie,0,256),ae=new a(ie,0,256),de=new a(ie,512,$),z=512+($<<1),me=new n(ie,z,$),we=new n(ie,z+$);T<255&&G>0;){var He=m(G+1),ne=X>>3,_e=(1<<He+1)-1,oe=(k[ne]|k[ne+1]<<8|k[ne+2]<<16)>>(7&X)&_e,ce=(1<<He)-1,L=_e-G-1,A=oe&ce;if(A<L?(X+=He,oe=A):(X+=He+1,oe>ce&&(oe-=L)),le[++T]=--oe,oe==-1?(G+=oe,me[--K]=T):G-=oe,!oe)do{var O=X>>3;I=(k[O]|k[O+1]<<8)>>(7&X)&3,X+=2,T+=I}while(I==3)}(T>255||G)&&f(0);for(var F=0,Y=($>>1)+($>>3)+3,re=$-1,ue=0;ue<=T;++ue){var se=le[ue];if(se<1)ae[ue]=-se;else for(V=0;V<se;++V){me[F]=ue;do F=F+Y&re;while(F>=K)}}for(F&&f(0),V=0;V<$;++V){var pe=ae[me[V]]++,Pe=we[V]=W-m(pe);de[V]=(pe<<Pe)-$}return[X+7>>3,{b:W,s:me,n:we,t:de}]},x=function(k,H){var U=0,X=-1,W=new n(292),$=k[H],G=W.subarray(0,256),T=W.subarray(256,268),I=new a(W.buffer,268);if($<128){var V=v(k,H+1,6),K=V[1],ie=V[0]<<3,le=k[H+=$];le||f(0);for(var ae=0,de=0,z=K.b,me=z,we=(++H<<3)-8+m(le);!((we-=z)<ie);){var He=we>>3;if(G[++X]=K.s[ae+=(k[He]|k[He+1]<<8)>>(7&we)&(1<<z)-1],(we-=me)<ie)break;G[++X]=K.s[de+=(k[He=we>>3]|k[He+1]<<8)>>(7&we)&(1<<me)-1],z=K.n[ae],ae=K.t[ae],me=K.n[de],de=K.t[de]}++X>255&&f(0)}else{for(X=$-127;U<X;U+=2){var ne=k[++H];G[U]=ne>>4,G[U+1]=15&ne}++H}var _e=0;for(U=0;U<X;++U)(A=G[U])>11&&f(0),_e+=A&&1<<A-1;var oe=m(_e)+1,ce=1<<oe,L=ce-_e;for(L&L-1&&f(0),G[X++]=m(L)+1,U=0;U<X;++U){var A;++T[G[U]=(A=G[U])&&oe+1-A]}var O=new n(ce<<1),F=O.subarray(0,ce),Y=O.subarray(ce);for(I[oe]=0,U=oe;U>0;--U){var re=I[U];u(Y,U,re,I[U-1]=re+T[U]*(1<<oe-U))}for(I[0]!=ce&&f(0),U=0;U<X;++U){var ue=G[U];if(ue){var se=I[ue];u(F,U,se,I[ue]=se+(1<<oe-ue))}}return[H,{n:Y,b:oe,s:F}]},b=v(new n([81,16,99,140,49,198,24,99,12,33,196,24,99,102,102,134,70,146,4]),0,6)[1],_=v(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],M=v(new n([32,132,16,66,102,70,68,68,68,68,36,73,2]),0,5)[1],C=function(k,H){for(var U=k.length,X=new l(U),W=0;W<U;++W)X[W]=H,H+=1<<k[W];return X},S=new n(new l([0,0,0,0,16843009,50528770,134678020,202050057,269422093]).buffer,0,36),w=C(S,0),E=new n(new l([0,0,0,0,0,0,0,0,16843009,50528770,117769220,185207048,252579084,16]).buffer,0,53),P=C(E,3),N=function(k,H,U){var X=k.length,W=H.length,$=k[X-1],G=(1<<U.b)-1,T=-U.b;$||f(0);for(var I=0,V=U.b,K=(X<<3)-8+m($)-V,ie=-1;K>T&&ie<W;){var le=K>>3;H[++ie]=U.s[I=(I<<V|(k[le]|k[le+1]<<8|k[le+2]<<16)>>(7&K))&G],K-=V=U.n[I]}K==T&&ie+1==W||f(0)},D=function(k,H,U){var X=6,W=H.length+3>>2,$=W<<1,G=W+$;N(k.subarray(X,X+=k[0]|k[1]<<8),H.subarray(0,W),U),N(k.subarray(X,X+=k[2]|k[3]<<8),H.subarray(W,$),U),N(k.subarray(X,X+=k[4]|k[5]<<8),H.subarray($,G),U),N(k.subarray(X),H.subarray(G),U)},B=function(k,H,U){var X,W=H.b,$=k[W],G=$>>1&3;H.l=1&$;var T=$>>3|k[W+1]<<5|k[W+2]<<13,I=(W+=3)+T;if(G==1)return W>=k.length?void 0:(H.b=W+1,U?(u(U,k[W],H.y,H.y+=T),U):u(new n(T),k[W]));if(!(I>k.length)){if(G==0)return H.b=I,U?(U.set(k.subarray(W,I),H.y),H.y+=T,U):c(k,W,I);if(G==2){var V=k[W],K=3&V,ie=V>>2&3,le=V>>4,ae=0,de=0;K<2?1&ie?le|=k[++W]<<4|(2&ie&&k[++W]<<12):le=V>>3:(de=ie,ie<2?(le|=(63&k[++W])<<4,ae=k[W]>>6|k[++W]<<2):ie==2?(le|=k[++W]<<4|(3&k[++W])<<12,ae=k[W]>>2|k[++W]<<6):(le|=k[++W]<<4|(63&k[++W])<<12,ae=k[W]>>6|k[++W]<<2|k[++W]<<10)),++W;var z=U?U.subarray(H.y,H.y+H.m):new n(H.m),me=z.length-le;if(K==0)z.set(k.subarray(W,W+=le),me);else if(K==1)u(z,k[W++],me);else{var we=H.h;if(K==2){var He=x(k,W);ae+=W-(W=He[0]),H.h=we=He[1]}else we||f(0);(de?D:N)(k.subarray(W,W+=ae),z.subarray(me),we)}var ne=k[W++];if(ne){ne==255?ne=32512+(k[W++]|k[W++]<<8):ne>127&&(ne=ne-128<<8|k[W++]);var _e=k[W++];3&_e&&f(0);for(var oe=[_,M,b],ce=2;ce>-1;--ce){var L=_e>>2+(ce<<1)&3;if(L==1){var A=new n([0,0,k[W++]]);oe[ce]={s:A.subarray(2,3),n:A.subarray(0,1),t:new a(A.buffer,0,1),b:0}}else L==2?(W=(X=v(k,W,9-(1&ce)))[0],oe[ce]=X[1]):L==3&&(H.t||f(0),oe[ce]=H.t[ce])}var O=H.t=oe,F=O[0],Y=O[1],re=O[2],ue=k[I-1];ue||f(0);var se=(I<<3)-8+m(ue)-re.b,pe=se>>3,Pe=0,Ce=(k[pe]|k[pe+1]<<8)>>(7&se)&(1<<re.b)-1,je=(k[pe=(se-=Y.b)>>3]|k[pe+1]<<8)>>(7&se)&(1<<Y.b)-1,st=(k[pe=(se-=F.b)>>3]|k[pe+1]<<8)>>(7&se)&(1<<F.b)-1;for(++ne;--ne;){var Pt=re.s[Ce],ut=re.n[Ce],ot=F.s[st],tt=F.n[st],Ht=Y.s[je],fe=Y.n[je],qe=1<<Ht,Ue=qe+((k[pe=(se-=Ht)>>3]|k[pe+1]<<8|k[pe+2]<<16|k[pe+3]<<24)>>>(7&se)&qe-1);pe=(se-=E[ot])>>3;var Ie=P[ot]+((k[pe]|k[pe+1]<<8|k[pe+2]<<16)>>(7&se)&(1<<E[ot])-1);pe=(se-=S[Pt])>>3;var mt=w[Pt]+((k[pe]|k[pe+1]<<8|k[pe+2]<<16)>>(7&se)&(1<<S[Pt])-1);if(pe=(se-=ut)>>3,Ce=re.t[Ce]+((k[pe]|k[pe+1]<<8)>>(7&se)&(1<<ut)-1),pe=(se-=tt)>>3,st=F.t[st]+((k[pe]|k[pe+1]<<8)>>(7&se)&(1<<tt)-1),pe=(se-=fe)>>3,je=Y.t[je]+((k[pe]|k[pe+1]<<8)>>(7&se)&(1<<fe)-1),Ue>3)H.o[2]=H.o[1],H.o[1]=H.o[0],H.o[0]=Ue-=3;else{var lt=Ue-(mt!=0);lt?(Ue=lt==3?H.o[0]-1:H.o[lt],lt>1&&(H.o[2]=H.o[1]),H.o[1]=H.o[0],H.o[0]=Ue):Ue=H.o[0]}for(ce=0;ce<mt;++ce)z[Pe+ce]=z[me+ce];me+=mt;var Ut=(Pe+=mt)-Ue;if(Ut<0){var xt=-Ut,Dt=H.e+Ut;for(xt>Ie&&(xt=Ie),ce=0;ce<xt;++ce)z[Pe+ce]=H.w[Dt+ce];Pe+=xt,Ie-=xt,Ut=0}for(ce=0;ce<Ie;++ce)z[Pe+ce]=z[Ut+ce];Pe+=Ie}if(Pe!=me)for(;me<z.length;)z[Pe++]=z[me++];else Pe=z.length;U?H.y+=Pe:z=c(z,0,Pe)}else if(U){if(H.y+=le,me)for(ce=0;ce<le;++ce)z[ce]=z[me+ce]}else me&&(z=c(z,me));return H.b=I,z}f(2)}},J=function(k,H){if(k.length==1)return k[0];for(var U=new n(H),X=0,W=0;X<k.length;++X){var $=k[X];U.set($,W),W+=$.length}return U};function Q(k,H){for(var U=[],X=+!H,W=0,$=0;k.length;){var G=p(k,X||H);if(typeof G=="object"){for(X?(H=null,G.w.length==G.u&&(U.push(H=G.w),$+=G.u)):(U.push(H),G.e=0);!G.l;){var T=B(k,G,H);T||f(5),H?G.e=G.y:(U.push(T),$+=T.length,h(G.w,0,T.length),G.w.set(T,G.w.length-T.length))}W=G.b+4*G.c}else W=G;k=k.subarray(W)}return J(U,$)}r.decompress=Q;var j=(function(){function k(H){this.ondata=H,this.c=[],this.l=0,this.z=0}return k.prototype.push=function(H,U){if(typeof this.s=="number"){var X=Math.min(H.length,this.s);H=H.subarray(X),this.s-=X}var W=H.length+this.l;if(!this.s){if(U){if(!W)return void this.ondata(new n(0),!0);W<5&&f(5)}else if(W<18)return this.c.push(H),void(this.l=W);if(this.l&&(this.c.push(H),H=J(this.c,W),this.c=[],this.l=0),typeof(this.s=p(H))=="number")return this.push(H,U)}if(typeof this.s!="number"){if(W<(this.z||3))return U&&f(5),this.c.push(H),void(this.l=W);if(this.l&&(this.c.push(H),H=J(this.c,W),this.c=[],this.l=0),!this.z&&W<(this.z=2&H[this.s.b]?4:3+(H[this.s.b]>>3|H[this.s.b+1]<<5|H[this.s.b+2]<<13)))return U&&f(5),this.c.push(H),void(this.l=W);for(this.z=0;;){var $=B(H,this.s);if(!$){U&&f(5);var G=H.subarray(this.s.b);return this.s.b=0,this.c.push(G),void(this.l+=G.length)}if(this.ondata($,!1),h(this.s.w,0,$.length),this.s.w.set($,this.s.w.length-$.length),this.s.l){var T=H.subarray(this.s.b);return this.s=4*this.s.c,void this.push(T,U)}}}else U&&f(5)},k})();return r.Decompress=j,r})}),wt=Ee((e,t)=>{(r=>{"use strict";function i(h,{maxBytes:d=8388608,padded:f=!1,host:y=r}={}){if(!Number.isSafeInteger(d)||d<0||d>8388608||typeof h!="string"||h.length>112e5)throw Error("Invalid or oversized model base64.");let g=h.length,p=h.endsWith("==")?2:h.endsWith("=")?1:0;if(g%4===1||(p||f)&&g%4!==0)throw Error("Invalid model base64 padding.");let m=g-p;for(let M=0;M<m;M++){let C=h.charCodeAt(M);if(!(C>=65&&C<=90||C>=97&&C<=122||C>=48&&C<=57||C===43||C===47))throw Error("Invalid model base64.")}let v=Math.floor(g*3/4)-p;if(v>d)throw Error("Model base64 exceeds its decoded byte limit.");let x=y.Uint8Array?.fromBase64;if(typeof x=="function")return x.call(y.Uint8Array,h);let b=y.atob(h),_=new Uint8Array(v);for(let M=0;M<v;M++)_[M]=b.charCodeAt(M);return _}function n(h,d=!1){let f=(1n<<64n)-1n,y=0x87c37b91114253d5n,g=0x4cf5ad432745937fn,p=(w,E)=>(w<<E|w>>64n-E)&f,m=(w,E)=>{let P=0n;for(let N=0;N<E;N++)P|=BigInt(h[w+N]||0)<<BigInt(N*8);return P},v=w=>(w^=w>>33n,w=w*0xff51afd7ed558ccdn&f,w^=w>>33n,w=w*0xc4ceb9fe1a85ec53n&f,w^w>>33n),x=0xabba2345n,b=x,_=new DataView(h.buffer,h.byteOffset,h.byteLength),M=h.length-h.length%16;for(let w=0;w<M;w+=16){let E=_.getBigUint64(w,!0),P=_.getBigUint64(w+8,!0);E=p(E*y&f,31n)*g&f,x^=E,x=(p(x,27n)+b)*5n+0x52dce729n&f,P=p(P*g&f,33n)*y&f,b^=P,b=(p(b,31n)+x)*5n+0x38495ab5n&f}let C=d?Math.ceil(h.length/4)*4:h.length,S=C%16;return S>8&&(b^=p(m(M+8,S-8)*g&f,33n)*y&f),S&&(x^=p(m(M,Math.min(8,S))*y&f,31n)*g&f),x^=BigInt(C),b^=BigInt(C),x=x+b&f,b=b+x&f,x=v(x),b=v(b),x=x+b&f,b=b+x&f,x.toString(16).padStart(16,"0")+b.toString(16).padStart(16,"0")}function a(h){let d=new DataView(h.buffer,h.byteOffset,h.byteLength);if(h.length<6||d.getUint32(0,!0)!==4247762216)throw Error("Embedded model is not Zstandard.");let f=h[4],y=!!(f&32),g=f>>>6;if(f&24)throw Error("Unsupported Zstandard frame flags.");let p=5;if(!y){let b=h[p++];if(2**(10+(b>>>3))*(1+(b&7)/8)>8388608)throw Error("Embedded model window exceeds 8 MiB.")}if([0,1,2,4][f&3])throw Error("Embedded model requires a Zstandard dictionary.");let m=g?[0,2,4,8][g]:y?1:0;if(!m||p+m>h.length)throw Error("Embedded model has no bounded content size.");let v=0;for(let b=0;b<m;b++)v+=h[p++]*2**(8*b);if(g===1&&(v+=256),!Number.isSafeInteger(v)||v<=0||v>8388608)throw Error("Embedded model exceeds 8 MiB.");let x=!1;for(;!x;){if(p+3>h.length)throw Error("Truncated embedded model block.");let b=h[p]|h[p+1]<<8|h[p+2]<<16;p+=3,x=!!(b&1);let _=b>>>1&3,M=b>>>3;if(_===3||M>131072)throw Error("Invalid embedded model block.");if(p+=_===1?1:M,p>h.length)throw Error("Truncated embedded model block.")}if(f&4&&(p+=4),p!==h.length)throw Error("Embedded model has trailing or missing frame data.");return v}async function s(h,d=r.fzstd?.decompress,f=8388608){let y=h?.base64,g=i(y,{padded:!0});if(g.length>8388608)throw Error("Compressed embedded model exceeds 8 MiB.");let p=a(g);if(p>f)throw Error("Embedded asset exceeds its allocation budget.");if(typeof d!="function")throw Error("Embedded model decoder unavailable.");let m=d(g,new Uint8Array(p));if(!(m instanceof Uint8Array)||m.length!==p)throw Error("Embedded model size mismatch.");if(/^[a-f0-9]{64}$/i.test(h.checksum||"")){let v=new Uint8Array(await r.crypto.subtle.digest("SHA-256",m));if(Array.from(v,x=>x.toString(16).padStart(2,"0")).join("")!==h.checksum.toLowerCase())throw Error("Embedded model checksum mismatch.")}else if(/^[a-f0-9]{32}$/i.test(h.checksum||"")){let v=h.checksum.toLowerCase();if(n(m)!==v&&n(m,!0)!==v)throw Error("Embedded model checksum mismatch.")}else throw Error("Embedded model checksum is missing or unsupported.");return m}function o(h){let d=new DataView(h.buffer,h.byteOffset,h.byteLength),f=new Set;if(d.byteLength<12||![65536,1330926671,1953658213].includes(d.getUint32(0)))return f;let y=d.getUint16(4);if(y>256||12+y*16>d.byteLength)return f;for(let g=12;g<12+y*16;g+=16){if(d.getUint32(g)!==1851878757)continue;let p=d.getUint32(g+8),m=d.getUint32(g+12);if(m<6||p+m>d.byteLength)break;let v=d.getUint16(p+2),x=p+d.getUint16(p+4);if(v>2048||x<p+6+v*12||x>p+m)break;let b=new TextDecoder("utf-16be");for(let _=0;_<v;_++){let M=p+6+_*12,C=d.getUint16(M),S=d.getUint16(M+6);if(![0,3].includes(C)||![1,4,6,16].includes(S))continue;let w=d.getUint16(M+8),E=x+d.getUint16(M+10);if(!w||w>512||w%2||E+w>p+m)continue;let P=b.decode(h.subarray(E,E+w)).trim().toLowerCase();P&&!P.includes("\0")&&f.add(P)}break}return f}function l(h){let d=new DataView(h.buffer,h.byteOffset,h.byteLength),f=d.getUint16(4);for(let y=12;y<12+f*16;y+=16){if(d.getUint32(y)!==1751474532)continue;let g=d.getUint32(y+8),p=d.getUint32(y+12);if(p<46||g+p>h.length)break;let m=d.getUint16(g+44);return{weight:m&1?"bold":"normal",style:m&2?"italic":"normal"}}return{weight:"normal",style:"normal"}}let c=0;function u(h,d,f,y,g=r,p){if(!h?.length||!d.size||typeof g.FontFace!="function"||!g.document?.fonts)return null;let m=++c,v=new Map,x=[],b=new Set,_=g.document.fonts,M=!1,C=8*1024*1024,S;async function w(){for(let E of h){if(await new Promise(P=>setTimeout(P,0)),M||C<=0)return;try{if(S??=p?await p():g.fzstd?.decompress,M)return;let P=await s(E,S,Math.min(C,2*1024*1024));if(M)return;C-=P.length;let N=[...o(P)].filter(B=>d.has(B));if(!N.length)continue;let D=l(P);for(let B of N){let J=JSON.stringify([B,D.weight,D.style]);if(b.has(J))continue;let Q=v.get(B)||"kivi-embedded-"+m+"-"+v.size,j=await new g.FontFace(Q,P,D).load();if(M)return;_.add(j),x.push(j),b.add(J),v.set(B,Q)}}catch(P){M||y?.(E.name,P.message)}}!M&&x.length&&f()}return w(),{family(E){return typeof E=="string"?v.get(E.trim().toLowerCase()):void 0},dispose(){M=!0;for(let E of x)_.delete(E);x.length=0,v.clear()}}}r.KiCadEmbeddedFonts={mount:u,fontNames:o},r.KiCadEmbeddedModels={decode:s,decodeBase64:i,frameSize:a,murmur:n,MAX_BYTES:8388608,fontNames:o,mountFonts:u},typeof t=="object"&&t.exports&&(t.exports=r.KiCadEmbeddedModels)})(typeof globalThis=="object"?globalThis:e)}),at=Ee((e,t)=>{(r=>{"use strict";function i(s){if(s?.success!==!0||!Array.isArray(s.meshes)||!s.meshes.length||s.meshes.length>512)throw new Error("STEP did not produce a supported mesh.");let o=0,l=0,c=0;return s.meshes.map((u,h)=>{let d=u.attributes?.position?.array,f=u.index?.array,y=u.attributes?.normal?.array;if(!Array.isArray(d)||d.length%3||!d.length||!Array.isArray(f)||f.length%3||!f.length)throw new Error("STEP returned invalid mesh arrays.");if(o+=d.length/3,l+=f.length/3,o>5e5||l>5e5)throw new Error("STEP tessellation exceeds 500,000 vertices or triangles.");if(d.some(E=>!Number.isFinite(E)||Math.abs(E)>1e6)||f.some(E=>!Number.isSafeInteger(E)||E<0||E>=d.length/3))throw new Error("STEP mesh coordinates or indices are invalid.");if(y&&(!Array.isArray(y)||y.length!==d.length||y.some(E=>!Number.isFinite(E))))throw new Error("STEP returned invalid mesh normals.");let g=Array.isArray(u.color)&&u.color.length===3&&u.color.every(E=>Number.isFinite(E)&&E>=0&&E<=1)?u.color:[.65,.68,.7],p=u.brep_faces;if(p!==void 0&&(!Array.isArray(p)||p.length>f.length/3))throw new Error("STEP returned invalid face ranges.");let m=[g],v=new Map([[JSON.stringify(g),0]]),x=new Uint8Array(f.length/3).fill(255),b=Math.min(8,1024-c-(s.meshes.length-h-1));for(let E of p||[]){let P=E?.first,N=E?.last;if(!Number.isSafeInteger(P)||!Number.isSafeInteger(N)||P<0||N<P||N>=x.length)throw new Error("STEP returned invalid face ranges.");let D=Array.isArray(E.color)&&E.color.length===3&&E.color.every(Q=>Number.isFinite(Q)&&Q>=0&&Q<=1),B=D?JSON.stringify(E.color):null,J=D?v.get(B):0;if(J===void 0){if(m.length>=b)throw new Error("STEP face colours exceed the bounded material budget.");J=m.length,m.push(E.color),v.set(B,J)}for(let Q=P;Q<=N;Q++){if(x[Q]!==255)throw new Error("STEP returned overlapping face ranges.");x[Q]=J}}let _=new Uint32Array(m.length);for(let E=0;E<x.length;E++)x[E]===255&&(x[E]=0),_[x[E]]+=3;let M=[],C=new Uint32Array(m.length),S=0;for(let E=0;E<m.length;E++)C[E]=S,_[E]&&(M.push({start:S,count:_[E],color:m[E]}),S+=_[E]);c+=M.length;let w=new Uint32Array(f.length);for(let E=0;E<x.length;E++){let P=C[x[E]];C[x[E]]+=3,w[P]=f[E*3],w[P+1]=f[E*3+1],w[P+2]=f[E*3+2]}return{positions:new Float32Array(d),normals:y?new Float32Array(y):null,index:w,color:g,groups:M}})}async function n(s,o=r.Worker,l=r,c){let u=await l.fetch(s,{credentials:"omit",redirect:"error",signal:c});if(!u.ok)throw new Error("Bundled STEP worker could not be read.");let h=await u.arrayBuffer();if(h.byteLength>256*1024)throw new Error("Bundled STEP worker exceeds 256 KiB.");let d=l.URL.createObjectURL(new l.Blob([h],{type:"text/javascript"}));try{return new o(d)}finally{l.URL.revokeObjectURL(d)}}class a{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=(g,p)=>{clearTimeout(d),this.pending=null,this.worker&&(this.worker.onmessage=this.worker.onerror=null),g?c(g):l(p)},h=g=>{this.worker?.terminate(),this.worker=null,this.initialized=!1,u(new Error(g))},d,f=this.initialized,y=(g,p)=>{clearTimeout(d),d=setTimeout(()=>h(p),g)};y(this.initialized?3e4:6e4,this.initialized?"STEP conversion timed out after 30 seconds.":"STEP initialization timed out after 60 seconds."),this.pending=()=>h("STEP decoder is closed."),this.worker.onmessage=g=>{if(g.data?.stage==="kernel-ready"){f||(f=!0,this.initialized=!0,y(3e4,"STEP conversion timed out after 30 seconds."));return}this.initialized=g.data?.ok===!0,this.initialized?u(null,g.data.meshes):u(new Error(g.data?.error||"STEP conversion failed."))},this.worker.onerror=()=>h("STEP worker failed.");try{let g=o.slice();this.worker.postMessage({bytes:g,reportStages:!0,...this.wasmUrl?{wasmUrl:this.wasmUrl}:{}},[g.buffer])}catch{h("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:a,bundledWorker:n},typeof t=="object"&&t.exports&&(t.exports=r.KiCadStepDecoder)})(typeof globalThis=="object"?globalThis:e)}),zt=Ee((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 d of Object.values(i))Object.freeze(d);Object.freeze(i);let n=d=>i[String(d)]?.[0]||"#c2c2c2",a=d=>i[String(d)]?.[1]??1,s=d=>{let f=n(d),y=a(d);return y===1?f:`rgba(${parseInt(f.slice(1,3),16)},${parseInt(f.slice(3,5),16)},${parseInt(f.slice(5,7),16)},${y})`},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(d,f=!0){let y=(f?o:l)[String(d)]||n(d),g=a(d);return g===1?y:`rgba(${parseInt(y.slice(1,3),16)},${parseInt(y.slice(3,5),16)},${parseInt(y.slice(5,7),16)},${g})`}function u(d){let f=String(d||"").toLowerCase(),y=/bottom|\bbot\b/.test(f),g=y?"B.":"F.";if(/drill|plated/.test(f))return null;if(/outline|profile/.test(f))return"Edge.Cuts";if(/copper/.test(f)){if(/inner|inr/.test(f)){let p=/copper,\s*l(\d+),\s*inr/.exec(f),m=/inner copper\s*(\d+)/.exec(f),v=p?Number(p[1])-1:m?Number(m[1]):0;return v>=1&&v<=30?"In"+v+".Cu":null}return g+"Cu"}return/mask/.test(f)?g+"Mask":/silk|legend/.test(f)?g+"SilkS":/paste/.test(f)?g+"Paste":null}let h=Object.freeze({entries:i,hexFor:n,opacityFor:a,colorFor:s,reviewColorFor:c,fabricationLayer:u});r.KiCadLayerColors=h,typeof t=="object"&&t.exports&&(t.exports=h)})(globalThis)}),Ot={};Kt(Ot,{mountBoard3D:()=>zI,mountResultScene:()=>uI,mountSavedResult3D:()=>gI,objectVisibilityPolicy:()=>Hm});function Nt(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,a){if(t.has(n))return r++,t.get(n);let s=a();return t.size<e?t.set(n,s):i++,s},clear(){t.clear()},stats(){return{entries:t.size,hits:r,uncached:i}}}}function Xt(e,t=r=>r.assetKey||r.path){let r=new Map,i=new Map;for(let n of e){let a=t(n);r.set(a,(r.get(a)||0)+1)}return{get(n,a){let s=t(n);return i.has(s)||i.set(s,Promise.resolve().then(a)),i.get(s)},isLastUse(n){return r.get(t(n))===1},release(n){let a=t(n),s=(r.get(a)||0)-1;s>0?r.set(a,s):(r.delete(a),i.delete(a))},clear(){r.clear(),i.clear()},stats:()=>({templates:i.size,remainingAssets:r.size})}}var sr={5120:1,5121:1,5122:2,5123:2,5125:4,5126:4},Et={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Lt=(e,t)=>{if(!Number.isSafeInteger(e)||e<0)throw Error("Invalid GLB "+t+".");return e},ge=e=>{throw Object.assign(Error("Linked model "+e+" exceeds its decoded memory budget; saved footprint proxies and identities are retained."),{code:"MODEL_ALLOCATION_BUDGET"})},ve="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Je(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,a=i.length-n,s=i.endsWith("==")?2:i.endsWith("=")?1:0;if(a%4||a<4)throw Error("Invalid embedded image base64.");for(let o=n;o<i.length-s;o++)if(ve.indexOf(i[o])<0)throw Error("Invalid embedded image base64.");return{length:a*3/4-s,at(o){let l=Math.floor(o/3)*4+n,c=o%3,u=ve.indexOf(i[l+c]),h=ve.indexOf(i[l+c+1]);return c===0?(u<<2|h>>4)&255:c===1?(u<<4|h>>2)&255:(u<<6|h)&255}}}function Ze(e){let t=e.length,r=e.at,i=a=>r(a)*256+r(a+1),n=a=>r(a)*16777216+r(a+1)*65536+r(a+2)*256+r(a+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 a=n(16),s=n(20);if(!a||!s)throw Error("Invalid embedded PNG dimensions.");return{width:a,height:s}}if(t>=4&&r(0)===255&&r(1)===216){let a=2;for(;a<t;){if(r(a++)!==255)throw Error("Invalid embedded JPEG marker.");for(;a<t&&r(a)===255;)a++;if(a>=t)break;let s=r(a++);if(s===0||s===218||s===217)break;if(s===1||s>=208&&s<=216)continue;if(a+2>t)break;let o=i(a);if(o<2||a+o>t)throw Error("Invalid embedded JPEG segment.");if(s>=192&&s<=207&&![196,200,204].includes(s)){if(o<8)throw Error("Invalid embedded JPEG frame.");let l=i(a+3),c=i(a+5),u=r(a+7);if(!c||!l||!u||o<8+3*u)throw Error("Invalid embedded JPEG dimensions.");return{width:c,height:l}}a+=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 Ke(e,t,r,{maxAccessorBytes:i=67108864,maxTextureBytes:n=33554432,maxTextureDimension:a=8192}={}){for(let[g,p]of[[i,"accessor budget"],[n,"texture budget"],[a,"texture dimension"]])if(!Number.isSafeInteger(g)||g<1)throw TypeError("Invalid GLB "+p+".");let s=null,o=r;for(;o<t.length;){if(o+8>t.length)throw Error("Truncated GLB chunk.");let g=new DataView(t.buffer,t.byteOffset+o,8),p=g.getUint32(0,!0),m=g.getUint32(4,!0);if(o+=8,p>t.length-o)throw Error("Truncated GLB chunk.");if(m===5130562){if(s)throw Error("Duplicate GLB binary chunk.");s=t.subarray(o,o+p)}o+=p}let l=e.buffers||[],c=e.bufferViews||[];function u(g){Lt(g,"buffer view index");let p=c[g];if(!p)throw Error("GLB references an invalid buffer view.");let m=l[Lt(p.buffer,"buffer index")];if(!m)throw Error("GLB references an invalid buffer.");let v=Lt(p.byteOffset??0,"buffer offset"),x=Lt(p.byteLength,"buffer length"),b=Lt(m.byteLength,"buffer length");if(!Number.isSafeInteger(v+x)||v+x>b)throw Error("GLB buffer view exceeds its declared buffer.");if(!m.uri&&(!s||b>s.length))throw Error("GLB buffer exceeds its binary chunk.");return{view:p,start:v,length:x,buffer:m}}let h=g=>{let{buffer:p,start:m,length:v}=u(g);if(p.uri)throw Error("Embedded image buffer uses an unsupported nested data URI.");return s.subarray(m,m+v)},d=0;for(let g=0;g<c.length;g++)d+=u(g).length,(!Number.isSafeInteger(d)||d>i+n)&&ge("buffer view expansion");let f=0;for(let g of e.accessors||[]){let p=Lt(g.count,"accessor count"),m=sr[g.componentType],v=Et[g.type];if(!p||!Number.isInteger(g.componentType)||!m||!Object.hasOwn(sr,g.componentType)||!v||!Object.hasOwn(Et,g.type))throw Error("Invalid GLB accessor component type, shape or count.");let x=g.type.startsWith("MAT")?Number(g.type.at(-1)):1,b=v/x,_=x>1?x*Math.ceil(b*m/4)*4:v*m,M=_,C=Lt(g.byteOffset??0,"accessor offset");if(C%m)throw Error("Misaligned GLB accessor offset.");if(g.bufferView!==void 0){let w=u(g.bufferView);if(M=w.view.byteStride??_,!Number.isSafeInteger(M)||M<_||M%m||w.view.byteStride!==void 0&&(M<4||M>252||M%4))throw Error("Invalid GLB accessor stride.");let E=(p-1)*M+_;if(!Number.isSafeInteger(E)||C+E>w.length)throw Error("GLB accessor exceeds its buffer view.")}else if(C)throw Error("GLB accessor without a buffer view has an offset.");let S=p*M;if(g.sparse){let w=g.sparse,E=Lt(w.count,"sparse count"),P=sr[w.indices?.componentType];if(!E||E>p||![5121,5123,5125].includes(w.indices?.componentType)||!w.values)throw Error("Invalid GLB sparse accessor.");for(let[N,D,B]of[[w.indices,E*P,P],[w.values,E*_,m]]){let J=u(N.bufferView),Q=Lt(N.byteOffset??0,"sparse offset");if(Q%B||Q+D>J.length)throw Error("GLB sparse accessor exceeds its buffer view.")}S+=p*v*m}f+=S,(!Number.isSafeInteger(f)||f>i)&&ge("accessor expansion")}let y=0;for(let g of e.images||[]){let{width:p,height:m}=Ze(Je(g,h));(p>a||m>a)&&ge("image dimensions"),y+=Math.ceil(p*m*4*4/3),(!Number.isSafeInteger(y)||y>n)&&ge("image pixels")}return{accessorBytes:f,textureBytes:y}}var De=(e,t)=>e||t>512?1:3,We=()=>Object.assign(Error("Linked model graph exceeds the bounded assembly node budget; saved footprint proxies and identities are retained."),{code:"MODEL_GRAPH_BUDGET"});function rt(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 a(s){if(t.has(s))return t.get(s);let o=[s],l=0;for(;o.length;){let c=o.pop();if(++l>e)throw We();for(let u of c.children||[]){if(l+o.length>=e)throw We();o.push(u)}}return t.set(s,l),l}return{limit:e,checkTemplate(s,o=0){try{let l=a(s);if(r+l+o>e)throw We();return l}catch(l){throw l.code==="MODEL_GRAPH_BUDGET"&&i++,l}},rejectPreflight(){i++},admit(s,o,l){let c=a(s)+o;if(r+c>e)throw n++,We();let u=l();return r+=c,u},stats:()=>({limit:e,admittedNodes:r,rejectedTemplates:i,rejectedOccurrences:n})}}function Be(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 a=JSON.parse(new TextDecoder().decode(e.subarray(20,20+n)));for(let h of[a.buffers||[],a.images||[]])for(let d of h)if(d.uri&&!/^data:/i.test(d.uri))throw Error("GLB has an external dependency or invalid header");Ke(a,e,20+n,r);let s=a.nodes||[],o=a.scenes||[],l=a.meshes||[],c=o.length;if(s.length>t||c>t)throw We();let u=[];for(let h of o){for(let d of h.nodes||[]){if(c+u.length>=t)throw We();u.push(d)}for(;u.length;){let d=u.pop(),f=s[d];if(!Number.isInteger(d)||!f)throw Error("GLB references an invalid node.");let y=1;if(f.mesh!==void 0){let g=l[f.mesh];if(!g||!Array.isArray(g.primitives))throw Error("GLB references an invalid mesh.");g.primitives.length>1&&(y+=g.primitives.length)}if(f.camera!==void 0&&y++,f.extensions?.KHR_lights_punctual&&(y+=2),c+=y,c>t)throw We();for(let g of f.children||[]){if(c+u.length>=t)throw We();u.push(g)}}}return c}var Le={};Kt(Le,{ACESFilmicToneMapping:()=>lu,AddEquation:()=>Gt,AddOperation:()=>Gg,AdditiveAnimationBlendMode:()=>xp,AdditiveBlending:()=>or,AgXToneMapping:()=>op,AlphaFormat:()=>pp,AlwaysCompare:()=>i0,AlwaysDepth:()=>ru,AlwaysStencilFunc:()=>_p,AmbientLight:()=>kf,AnimationAction:()=>iv,AnimationClip:()=>Lo,AnimationLoader:()=>xE,AnimationMixer:()=>XE,AnimationObjectGroup:()=>WE,AnimationUtils:()=>mE,ArcCurve:()=>ey,ArrayCamera:()=>Qy,ArrowHelper:()=>fM,AttachedBindMode:()=>cp,Audio:()=>ev,AudioAnalyser:()=>OE,AudioContext:()=>Uf,AudioListener:()=>IE,AudioLoader:()=>CE,AxesHelper:()=>mM,BackSide:()=>_t,BasicDepthPacking:()=>qg,BasicShadowMap:()=>Oe,BatchedMesh:()=>Y0,Bone:()=>vh,BooleanKeyframeTrack:()=>ys,Box2:()=>eM,Box3:()=>Yr,Box3Helper:()=>dM,BoxGeometry:()=>da,BoxHelper:()=>hM,BufferAttribute:()=>Mr,BufferGeometry:()=>ar,BufferGeometryLoader:()=>jy,ByteType:()=>up,Cache:()=>ga,Camera:()=>hh,CameraHelper:()=>uM,CanvasTexture:()=>Lh,CapsuleGeometry:()=>sy,CatmullRomCurve3:()=>ty,CineonToneMapping:()=>sp,CircleGeometry:()=>oy,ClampToEdgeWrapping:()=>Ri,Clock:()=>Ff,Color:()=>yt,ColorKeyframeTrack:()=>Rf,ColorManagement:()=>_r,CompressedArrayTexture:()=>Fw,CompressedCubeTexture:()=>Bw,CompressedTexture:()=>Nh,CompressedTextureLoader:()=>bE,ConeGeometry:()=>gf,ConstantAlphaFactor:()=>Fg,ConstantColorFactor:()=>kg,Controls:()=>mv,CubeCamera:()=>R0,CubeReflectionMapping:()=>ta,CubeRefractionMapping:()=>Aa,CubeTexture:()=>Ul,CubeTextureLoader:()=>_E,CubeUVReflectionMapping:()=>Js,CubicBezierCurve:()=>uf,CubicBezierCurve3:()=>iy,CubicInterpolant:()=>Ny,CullFaceBack:()=>dt,CullFaceFront:()=>St,CullFaceFrontBack:()=>be,CullFaceNone:()=>et,Curve:()=>On,CurvePath:()=>ay,CustomBlending:()=>cr,CustomToneMapping:()=>Vg,CylinderGeometry:()=>Zl,Cylindrical:()=>JE,Data3DTexture:()=>Ap,DataArrayTexture:()=>Yu,DataTexture:()=>sn,DataTextureLoader:()=>wE,DataUtils:()=>pw,DecrementStencilOp:()=>f_,DecrementWrapStencilOp:()=>g_,DefaultLoadingManager:()=>Dy,DepthFormat:()=>es,DepthStencilFormat:()=>Ra,DepthTexture:()=>Oh,DetachedBindMode:()=>Hg,DirectionalLight:()=>Xh,DirectionalLightHelper:()=>cM,DiscreteInterpolant:()=>Ly,DodecahedronGeometry:()=>ly,DoubleSide:()=>Rt,DstAlphaFactor:()=>$c,DstColorFactor:()=>eu,DynamicCopyUsage:()=>P_,DynamicDrawUsage:()=>n0,DynamicReadUsage:()=>A_,EdgesGeometry:()=>Ql,EllipseCurve:()=>Dh,EqualCompare:()=>$g,EqualDepth:()=>nu,EqualStencilFunc:()=>b_,EquirectangularReflectionMapping:()=>vl,EquirectangularRefractionMapping:()=>xl,Euler:()=>Nn,EventDispatcher:()=>Wn,ExtrudeGeometry:()=>Wh,FileLoader:()=>bn,Float16BufferAttribute:()=>xw,Float32BufferAttribute:()=>Mt,FloatType:()=>Xi,Fog:()=>N0,FogExp2:()=>I0,FramebufferTexture:()=>Uw,FrontSide:()=>it,Frustum:()=>Wl,GLBufferAttribute:()=>QE,GLSL1:()=>N_,GLSL3:()=>Ep,GreaterCompare:()=>e0,GreaterDepth:()=>su,GreaterEqualCompare:()=>r0,GreaterEqualDepth:()=>au,GreaterEqualStencilFunc:()=>M_,GreaterStencilFunc:()=>w_,GridHelper:()=>oM,Group:()=>jr,HalfFloatType:()=>yn,HemisphereLight:()=>ky,HemisphereLightHelper:()=>sM,IcosahedronGeometry:()=>my,ImageBitmapLoader:()=>qy,ImageLoader:()=>tc,ImageUtils:()=>h0,IncrementStencilOp:()=>p_,IncrementWrapStencilOp:()=>m_,InstancedBufferAttribute:()=>hs,InstancedBufferGeometry:()=>Wy,InstancedInterleavedBuffer:()=>ZE,InstancedMesh:()=>bh,Int16BufferAttribute:()=>yw,Int32BufferAttribute:()=>vw,Int8BufferAttribute:()=>fw,IntType:()=>hu,InterleavedBuffer:()=>Fl,InterleavedBufferAttribute:()=>wo,Interpolant:()=>No,InterpolateDiscrete:()=>ro,InterpolateLinear:()=>io,InterpolateSmooth:()=>Hu,InvertStencilOp:()=>y_,KeepStencilOp:()=>is,KeyframeTrack:()=>Dn,LOD:()=>U0,LatheGeometry:()=>mf,Layers:()=>eh,LessCompare:()=>Jg,LessDepth:()=>iu,LessEqualCompare:()=>wp,LessEqualDepth:()=>Ja,LessEqualStencilFunc:()=>__,LessStencilFunc:()=>x_,Light:()=>Fa,LightProbe:()=>Vy,Line:()=>jn,Line3:()=>tM,LineBasicMaterial:()=>ri,LineCurve:()=>hf,LineCurve3:()=>ny,LineDashedMaterial:()=>Ry,LineLoop:()=>Ch,LineSegments:()=>Fi,LinearFilter:()=>Zr,LinearInterpolant:()=>Cf,LinearMipMapLinearFilter:()=>o_,LinearMipMapNearestFilter:()=>s_,LinearMipmapLinearFilter:()=>mn,LinearMipmapNearestFilter:()=>eo,LinearSRGBColorSpace:()=>Oi,LinearToneMapping:()=>np,LinearTransfer:()=>Al,Loader:()=>fi,LoaderUtils:()=>va,LoadingManager:()=>Pf,LoopOnce:()=>Wg,LoopPingPong:()=>Xg,LoopRepeat:()=>jg,LuminanceAlphaFormat:()=>gp,LuminanceFormat:()=>mp,MOUSE:()=>ht,Material:()=>xi,MaterialLoader:()=>Hy,MathUtils:()=>Xu,Matrix2:()=>$E,Matrix3:()=>xr,Matrix4:()=>Jt,MaxEquation:()=>Ta,Mesh:()=>hr,MeshBasicMaterial:()=>ti,MeshDepthMaterial:()=>Mf,MeshDistanceMaterial:()=>Sf,MeshLambertMaterial:()=>Ay,MeshMatcapMaterial:()=>Cy,MeshNormalMaterial:()=>Ef,MeshPhongMaterial:()=>wf,MeshPhysicalMaterial:()=>on,MeshStandardMaterial:()=>Ki,MeshToonMaterial:()=>Ty,MinEquation:()=>Ti,MirroredRepeatWrapping:()=>$s,MixOperation:()=>zg,MultiplyBlending:()=>gr,MultiplyOperation:()=>yl,NearestFilter:()=>Kr,NearestMipMapLinearFilter:()=>a_,NearestMipMapNearestFilter:()=>n_,NearestMipmapLinearFilter:()=>$a,NearestMipmapNearestFilter:()=>uu,NeutralToneMapping:()=>lp,NeverCompare:()=>Qg,NeverDepth:()=>tu,NeverStencilFunc:()=>v_,NoBlending:()=>Ft,NoColorSpace:()=>ia,NoToneMapping:()=>ea,NormalAnimationBlendMode:()=>Wu,NormalBlending:()=>Zt,NotEqualCompare:()=>t0,NotEqualDepth:()=>ou,NotEqualStencilFunc:()=>E_,NumberKeyframeTrack:()=>vs,Object3D:()=>Ar,ObjectLoader:()=>TE,ObjectSpaceNormalMap:()=>Zg,OctahedronGeometry:()=>bf,OneFactor:()=>gl,OneMinusConstantAlphaFactor:()=>Bg,OneMinusConstantColorFactor:()=>Ug,OneMinusDstAlphaFactor:()=>Lg,OneMinusDstColorFactor:()=>Og,OneMinusSrcAlphaFactor:()=>Jc,OneMinusSrcColorFactor:()=>Ng,OrthographicCamera:()=>Oo,PCFShadowMap:()=>Me,PCFSoftShadowMap:()=>nt,PMREMGenerator:()=>td,Path:()=>Co,PerspectiveCamera:()=>li,Plane:()=>pa,PlaneGeometry:()=>Io,PlaneHelper:()=>pM,PointLight:()=>jh,PointLightHelper:()=>nM,Points:()=>Ih,PointsMaterial:()=>Yl,PolarGridHelper:()=>lM,PolyhedronGeometry:()=>Ro,PositionalAudio:()=>LE,PropertyBinding:()=>Vr,PropertyMixer:()=>rv,QuadraticBezierCurve:()=>df,QuadraticBezierCurve3:()=>pf,Quaternion:()=>di,QuaternionKeyframeTrack:()=>xs,QuaternionLinearInterpolant:()=>Oy,RED_GREEN_RGTC2_Format:()=>Gu,RED_RGTC1_Format:()=>vp,REVISION:()=>Qe,RGBADepthPacking:()=>Kg,RGBAFormat:()=>Li,RGBAIntegerFormat:()=>gu,RGBA_ASTC_10x10_Format:()=>Du,RGBA_ASTC_10x5_Format:()=>Nu,RGBA_ASTC_10x6_Format:()=>Lu,RGBA_ASTC_10x8_Format:()=>Ou,RGBA_ASTC_12x10_Format:()=>ku,RGBA_ASTC_12x12_Format:()=>Uu,RGBA_ASTC_4x4_Format:()=>Mu,RGBA_ASTC_5x4_Format:()=>Su,RGBA_ASTC_5x5_Format:()=>Tu,RGBA_ASTC_6x5_Format:()=>Au,RGBA_ASTC_6x6_Format:()=>Cu,RGBA_ASTC_8x5_Format:()=>Ru,RGBA_ASTC_8x6_Format:()=>Pu,RGBA_ASTC_8x8_Format:()=>Iu,RGBA_BPTC_Format:()=>Sl,RGBA_ETC2_EAC_Format:()=>Eu,RGBA_PVRTC_2BPPV1_Format:()=>bu,RGBA_PVRTC_4BPPV1_Format:()=>xu,RGBA_S3TC_DXT1_Format:()=>wl,RGBA_S3TC_DXT3_Format:()=>El,RGBA_S3TC_DXT5_Format:()=>Ml,RGBDepthPacking:()=>c_,RGBFormat:()=>fp,RGBIntegerFormat:()=>l_,RGB_BPTC_SIGNED_Format:()=>Fu,RGB_BPTC_UNSIGNED_Format:()=>Bu,RGB_ETC1_Format:()=>_u,RGB_ETC2_Format:()=>wu,RGB_PVRTC_2BPPV1_Format:()=>vu,RGB_PVRTC_4BPPV1_Format:()=>yu,RGB_S3TC_DXT1_Format:()=>_l,RGDepthPacking:()=>u_,RGFormat:()=>yp,RGIntegerFormat:()=>mu,RawShaderMaterial:()=>_f,Ray:()=>ls,Raycaster:()=>ic,RectAreaLight:()=>zy,RedFormat:()=>fu,RedIntegerFormat:()=>bl,ReinhardToneMapping:()=>ap,RenderTarget:()=>d0,RepeatWrapping:()=>Ni,ReplaceStencilOp:()=>d_,ReverseSubtractEquation:()=>Xr,RingGeometry:()=>gy,SIGNED_RED_GREEN_RGTC2_Format:()=>Vu,SIGNED_RED_RGTC1_Format:()=>zu,SRGBColorSpace:()=>Pr,SRGBTransfer:()=>kr,Scene:()=>us,ShaderChunk:()=>br,ShaderLib:()=>kn,ShaderMaterial:()=>oi,ShadowMaterial:()=>Sy,Shape:()=>fa,ShapeGeometry:()=>yy,ShapePath:()=>gM,ShapeUtils:()=>ma,ShortType:()=>hp,Skeleton:()=>Jp,SkeletonHelper:()=>iM,SkinnedMesh:()=>Qp,Source:()=>as,Sphere:()=>si,SphereGeometry:()=>Ua,Spherical:()=>Vf,SphericalHarmonics3:()=>Gy,SplineCurve:()=>ff,SpotLight:()=>Of,SpotLightHelper:()=>rM,Sprite:()=>qp,SpriteMaterial:()=>dh,SrcAlphaFactor:()=>Qc,SrcAlphaSaturateFactor:()=>Dg,SrcColorFactor:()=>Ig,StaticCopyUsage:()=>R_,StaticDrawUsage:()=>Cl,StaticReadUsage:()=>T_,StereoCamera:()=>RE,StreamCopyUsage:()=>I_,StreamDrawUsage:()=>S_,StreamReadUsage:()=>C_,StringKeyframeTrack:()=>bs,SubtractEquation:()=>Er,SubtractiveBlending:()=>lr,TOUCH:()=>bt,TangentSpaceNormalMap:()=>Pa,TetrahedronGeometry:()=>vy,Texture:()=>ei,TextureLoader:()=>If,TextureUtils:()=>_M,TorusGeometry:()=>xy,TorusKnotGeometry:()=>by,Triangle:()=>ua,TriangleFanDrawMode:()=>ju,TriangleStripDrawMode:()=>bp,TrianglesDrawMode:()=>Yg,TubeGeometry:()=>_y,UVMapping:()=>cu,Uint16BufferAttribute:()=>Hp,Uint32BufferAttribute:()=>Wp,Uint8BufferAttribute:()=>mw,Uint8ClampedBufferAttribute:()=>gw,Uniform:()=>YE,UniformsGroup:()=>KE,UniformsLib:()=>kt,UniformsUtils:()=>xn,UnsignedByteType:()=>gn,UnsignedInt248Type:()=>Ca,UnsignedInt5999Type:()=>dp,UnsignedIntType:()=>ra,UnsignedShort4444Type:()=>du,UnsignedShort5551Type:()=>pu,UnsignedShortType:()=>to,VSMShadowMap:()=>ft,Vector2:()=>Xe,Vector3:()=>ee,Vector4:()=>Nr,VectorKeyframeTrack:()=>_s,VideoTexture:()=>kw,WebGL3DRenderTarget:()=>iw,WebGLArrayRenderTarget:()=>rw,WebGLCoordinateSystem:()=>Hn,WebGLCubeRenderTarget:()=>P0,WebGLMultipleRenderTargets:()=>wM,WebGLRenderTarget:()=>Pi,WebGLRenderer:()=>sd,WebGLUtils:()=>Wv,WebGPUCoordinateSystem:()=>Rl,WireframeGeometry:()=>wy,WrapAroundEnding:()=>Tl,ZeroCurvatureEnding:()=>ts,ZeroFactor:()=>fn,ZeroSlopeEnding:()=>rs,ZeroStencilOp:()=>h_,createCanvasElement:()=>o0});var Qe="171",ht={LEFT:0,MIDDLE:1,RIGHT:2,ROTATE:0,DOLLY:1,PAN:2},bt={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},et=0,dt=1,St=2,be=3,Oe=0,Me=1,nt=2,ft=3,it=0,_t=1,Rt=2,Ft=0,Zt=1,or=2,lr=3,gr=4,cr=5,Gt=100,Er=101,Xr=102,Ti=103,Ta=104,fn=200,gl=201,Ig=202,Ng=203,Qc=204,Jc=205,$c=206,Lg=207,eu=208,Og=209,Dg=210,kg=211,Ug=212,Fg=213,Bg=214,tu=0,ru=1,iu=2,Ja=3,nu=4,au=5,su=6,ou=7,yl=0,zg=1,Gg=2,ea=0,np=1,ap=2,sp=3,lu=4,Vg=5,op=6,lp=7,cp="attached",Hg="detached",cu=300,ta=301,Aa=302,vl=303,xl=304,Js=306,Ni=1e3,Ri=1001,$s=1002,Kr=1003,uu=1004,n_=1004,$a=1005,a_=1005,Zr=1006,eo=1007,s_=1007,mn=1008,o_=1008,gn=1009,up=1010,hp=1011,to=1012,hu=1013,ra=1014,Xi=1015,yn=1016,du=1017,pu=1018,Ca=1020,dp=35902,pp=1021,fp=1022,Li=1023,mp=1024,gp=1025,es=1026,Ra=1027,fu=1028,bl=1029,yp=1030,mu=1031,l_=1032,gu=1033,_l=33776,wl=33777,El=33778,Ml=33779,yu=35840,vu=35841,xu=35842,bu=35843,_u=36196,wu=37492,Eu=37496,Mu=37808,Su=37809,Tu=37810,Au=37811,Cu=37812,Ru=37813,Pu=37814,Iu=37815,Nu=37816,Lu=37817,Ou=37818,Du=37819,ku=37820,Uu=37821,Sl=36492,Fu=36494,Bu=36495,vp=36283,zu=36284,Gu=36285,Vu=36286,Wg=2200,jg=2201,Xg=2202,ro=2300,io=2301,Hu=2302,ts=2400,rs=2401,Tl=2402,Wu=2500,xp=2501,Yg=0,bp=1,ju=2,qg=3200,Kg=3201,c_=3202,u_=3203,Pa=0,Zg=1,ia="",Pr="srgb",Oi="srgb-linear",Al="linear",kr="srgb",h_=0,is=7680,d_=7681,p_=7682,f_=7683,m_=34055,g_=34056,y_=5386,v_=512,x_=513,b_=514,__=515,w_=516,E_=517,M_=518,_p=519,Qg=512,Jg=513,$g=514,wp=515,e0=516,t0=517,r0=518,i0=519,Cl=35044,n0=35048,S_=35040,T_=35045,A_=35049,C_=35041,R_=35046,P_=35050,I_=35042,N_="100",Ep="300 es",Hn=2e3,Rl=2001,Wn=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}}},Di=["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"],a0=1234567,ns=Math.PI/180,no=180/Math.PI;function rn(){let e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,r=Math.random()*4294967295|0,i=Math.random()*4294967295|0;return(Di[e&255]+Di[e>>8&255]+Di[e>>16&255]+Di[e>>24&255]+"-"+Di[t&255]+Di[t>>8&255]+"-"+Di[t>>16&15|64]+Di[t>>24&255]+"-"+Di[r&63|128]+Di[r>>8&255]+"-"+Di[r>>16&255]+Di[r>>24&255]+Di[i&255]+Di[i>>8&255]+Di[i>>16&255]+Di[i>>24&255]).toLowerCase()}function mr(e,t,r){return Math.max(t,Math.min(r,e))}function Mp(e,t){return(e%t+t)%t}function L_(e,t,r,i,n){return i+(e-t)*(n-i)/(r-t)}function O_(e,t,r){return e!==t?(r-e)/(t-e):0}function Pl(e,t,r){return(1-r)*e+r*t}function D_(e,t,r,i){return Pl(e,t,1-Math.exp(-r*i))}function k_(e,t=1){return t-Math.abs(Mp(e,t*2)-t)}function U_(e,t,r){return e<=t?0:e>=r?1:(e=(e-t)/(r-t),e*e*(3-2*e))}function F_(e,t,r){return e<=t?0:e>=r?1:(e=(e-t)/(r-t),e*e*e*(e*(e*6-15)+10))}function B_(e,t){return e+Math.floor(Math.random()*(t-e+1))}function z_(e,t){return e+Math.random()*(t-e)}function G_(e){return e*(.5-Math.random())}function V_(e){e!==void 0&&(a0=e);let t=a0+=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 H_(e){return e*ns}function W_(e){return e*no}function j_(e){return(e&e-1)===0&&e!==0}function X_(e){return Math.pow(2,Math.ceil(Math.log(e)/Math.LN2))}function Y_(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))}function q_(e,t,r,i,n){let a=Math.cos,s=Math.sin,o=a(r/2),l=s(r/2),c=a((t+i)/2),u=s((t+i)/2),h=a((t-i)/2),d=s((t-i)/2),f=a((i-t)/2),y=s((i-t)/2);switch(n){case"XYX":e.set(o*u,l*h,l*d,o*c);break;case"YZY":e.set(l*d,o*u,l*h,o*c);break;case"ZXZ":e.set(l*h,l*d,o*u,o*c);break;case"XZX":e.set(o*u,l*y,l*f,o*c);break;case"YXY":e.set(l*f,o*u,l*y,o*c);break;case"ZYZ":e.set(l*y,l*f,o*u,o*c);break;default:console.warn("THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+n)}}function Vi(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 yr(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 Xu={DEG2RAD:ns,RAD2DEG:no,generateUUID:rn,clamp:mr,euclideanModulo:Mp,mapLinear:L_,inverseLerp:O_,lerp:Pl,damp:D_,pingpong:k_,smoothstep:U_,smootherstep:F_,randInt:B_,randFloat:z_,randFloatSpread:G_,seededRandom:V_,degToRad:H_,radToDeg:W_,isPowerOfTwo:j_,ceilPowerOfTwo:X_,floorPowerOfTwo:Y_,setQuaternionFromProperEuler:q_,normalize:yr,denormalize:Vi},Xe=class E1{constructor(t=0,r=0){E1.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=mr(this.x,t.x,r.x),this.y=mr(this.y,t.y,r.y),this}clampScalar(t,r){return this.x=mr(this.x,t,r),this.y=mr(this.y,t,r),this}clampLength(t,r){let i=this.length();return this.divideScalar(i||1).multiplyScalar(mr(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(mr(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),a=this.x-t.x,s=this.y-t.y;return this.x=a*i-s*n+t.x,this.y=a*n+s*i+t.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},xr=class M1{constructor(t,r,i,n,a,s,o,l,c){M1.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],t!==void 0&&this.set(t,r,i,n,a,s,o,l,c)}set(t,r,i,n,a,s,o,l,c){let u=this.elements;return u[0]=t,u[1]=n,u[2]=o,u[3]=r,u[4]=a,u[5]=l,u[6]=i,u[7]=s,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,a=this.elements,s=i[0],o=i[3],l=i[6],c=i[1],u=i[4],h=i[7],d=i[2],f=i[5],y=i[8],g=n[0],p=n[3],m=n[6],v=n[1],x=n[4],b=n[7],_=n[2],M=n[5],C=n[8];return a[0]=s*g+o*v+l*_,a[3]=s*p+o*x+l*M,a[6]=s*m+o*b+l*C,a[1]=c*g+u*v+h*_,a[4]=c*p+u*x+h*M,a[7]=c*m+u*b+h*C,a[2]=d*g+f*v+y*_,a[5]=d*p+f*x+y*M,a[8]=d*m+f*b+y*C,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],a=t[3],s=t[4],o=t[5],l=t[6],c=t[7],u=t[8];return r*s*u-r*o*c-i*a*u+i*o*l+n*a*c-n*s*l}invert(){let t=this.elements,r=t[0],i=t[1],n=t[2],a=t[3],s=t[4],o=t[5],l=t[6],c=t[7],u=t[8],h=u*s-o*c,d=o*l-u*a,f=c*a-s*l,y=r*h+i*d+n*f;if(y===0)return this.set(0,0,0,0,0,0,0,0,0);let g=1/y;return t[0]=h*g,t[1]=(n*c-u*i)*g,t[2]=(o*i-n*s)*g,t[3]=d*g,t[4]=(u*r-n*l)*g,t[5]=(n*a-o*r)*g,t[6]=f*g,t[7]=(i*l-c*r)*g,t[8]=(s*r-i*a)*g,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,a,s,o){let l=Math.cos(a),c=Math.sin(a);return this.set(i*l,i*c,-i*(l*s+c*o)+s+t,-n*c,n*l,-n*(-c*s+l*o)+o+r,0,0,1),this}scale(t,r){return this.premultiply(Sp.makeScale(t,r)),this}rotate(t){return this.premultiply(Sp.makeRotation(-t)),this}translate(t,r){return this.premultiply(Sp.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)}},Sp=new xr;function s0(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}var K_={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function ao(e,t){return new K_[e](t)}function Il(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}function o0(){let e=Il("canvas");return e.style.display="block",e}var l0={};function so(e){e in l0||(l0[e]=!0,console.warn(e))}function Z_(e,t,r){return new Promise(function(i,n){function a(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:n();break;case e.TIMEOUT_EXPIRED:setTimeout(a,r);break;default:i()}}setTimeout(a,r)})}function Q_(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 J_(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 c0=new xr().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),u0=new xr().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function $_(){let e={enabled:!0,workingColorSpace:Oi,spaces:{},convert:function(n,a,s){return this.enabled===!1||a===s||!a||!s||(this.spaces[a].transfer===kr&&(n.r=na(n.r),n.g=na(n.g),n.b=na(n.b)),this.spaces[a].primaries!==this.spaces[s].primaries&&(n.applyMatrix3(this.spaces[a].toXYZ),n.applyMatrix3(this.spaces[s].fromXYZ)),this.spaces[s].transfer===kr&&(n.r=oo(n.r),n.g=oo(n.g),n.b=oo(n.b))),n},fromWorkingColorSpace:function(n,a){return this.convert(n,this.workingColorSpace,a)},toWorkingColorSpace:function(n,a){return this.convert(n,a,this.workingColorSpace)},getPrimaries:function(n){return this.spaces[n].primaries},getTransfer:function(n){return n===ia?Al:this.spaces[n].transfer},getLuminanceCoefficients:function(n,a=this.workingColorSpace){return n.fromArray(this.spaces[a].luminanceCoefficients)},define:function(n){Object.assign(this.spaces,n)},_getMatrix:function(n,a,s){return n.copy(this.spaces[a].toXYZ).multiply(this.spaces[s].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({[Oi]:{primaries:t,whitePoint:i,transfer:Al,toXYZ:c0,fromXYZ:u0,luminanceCoefficients:r,workingColorSpaceConfig:{unpackColorSpace:Pr},outputColorSpaceConfig:{drawingBufferColorSpace:Pr}},[Pr]:{primaries:t,whitePoint:i,transfer:kr,toXYZ:c0,fromXYZ:u0,luminanceCoefficients:r,outputColorSpaceConfig:{drawingBufferColorSpace:Pr}}}),e}var _r=$_();function na(e){return e<.04045?e*.0773993808:Math.pow(e*.9478672986+.0521327014,2.4)}function oo(e){return e<.0031308?e*12.92:1.055*Math.pow(e,.41666)-.055}var lo,h0=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{lo===void 0&&(lo=Il("canvas")),lo.width=e.width,lo.height=e.height;let r=lo.getContext("2d");e instanceof ImageData?r.putImageData(e,0,0):r.drawImage(e,0,0,e.width,e.height),t=lo}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=Il("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 a=0;a<n.length;a++)n[a]=na(n[a]/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(na(t[r]/255)*255):t[r]=na(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}},ew=0,as=class{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:ew++}),this.uuid=rn(),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 a=0,s=i.length;a<s;a++)i[a].isDataTexture?n.push(Tp(i[a].image)):n.push(Tp(i[a]))}else n=Tp(i);r.url=n}return t||(e.images[this.uuid]=r),r}};function Tp(e){return typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap?h0.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 tw=0,ei=class tp extends Wn{constructor(t=tp.DEFAULT_IMAGE,r=tp.DEFAULT_MAPPING,i=Ri,n=Ri,a=Zr,s=mn,o=Li,l=gn,c=tp.DEFAULT_ANISOTROPY,u=ia){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:tw++}),this.uuid=rn(),this.name="",this.source=new as(t),this.mipmaps=[],this.mapping=r,this.channel=0,this.wrapS=i,this.wrapT=n,this.magFilter=a,this.minFilter=s,this.anisotropy=c,this.format=o,this.internalFormat=null,this.type=l,this.offset=new Xe(0,0),this.repeat=new Xe(1,1),this.center=new Xe(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new xr,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!==cu)return t;if(t.applyMatrix3(this.matrix),t.x<0||t.x>1)switch(this.wrapS){case Ni:t.x=t.x-Math.floor(t.x);break;case Ri:t.x=t.x<0?0:1;break;case $s: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 Ni:t.y=t.y-Math.floor(t.y);break;case Ri:t.y=t.y<0?0:1;break;case $s: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++}};ei.DEFAULT_IMAGE=null,ei.DEFAULT_MAPPING=cu,ei.DEFAULT_ANISOTROPY=1;var Nr=class S1{constructor(t=0,r=0,i=0,n=1){S1.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,a=this.w,s=t.elements;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.w=s[3]*r+s[7]*i+s[11]*n+s[15]*a,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,a,s=t.elements,o=s[0],l=s[4],c=s[8],u=s[1],h=s[5],d=s[9],f=s[2],y=s[6],g=s[10];if(Math.abs(l-u)<.01&&Math.abs(c-f)<.01&&Math.abs(d-y)<.01){if(Math.abs(l+u)<.1&&Math.abs(c+f)<.1&&Math.abs(d+y)<.1&&Math.abs(o+h+g-3)<.1)return this.set(1,0,0,0),this;r=Math.PI;let m=(o+1)/2,v=(h+1)/2,x=(g+1)/2,b=(l+u)/4,_=(c+f)/4,M=(d+y)/4;return m>v&&m>x?m<.01?(i=0,n=.707106781,a=.707106781):(i=Math.sqrt(m),n=b/i,a=_/i):v>x?v<.01?(i=.707106781,n=0,a=.707106781):(n=Math.sqrt(v),i=b/n,a=M/n):x<.01?(i=.707106781,n=.707106781,a=0):(a=Math.sqrt(x),i=_/a,n=M/a),this.set(i,n,a,r),this}let p=Math.sqrt((y-d)*(y-d)+(c-f)*(c-f)+(u-l)*(u-l));return Math.abs(p)<.001&&(p=1),this.x=(y-d)/p,this.y=(c-f)/p,this.z=(u-l)/p,this.w=Math.acos((o+h+g-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=mr(this.x,t.x,r.x),this.y=mr(this.y,t.y,r.y),this.z=mr(this.z,t.z,r.z),this.w=mr(this.w,t.w,r.w),this}clampScalar(t,r){return this.x=mr(this.x,t,r),this.y=mr(this.y,t,r),this.z=mr(this.z,t,r),this.w=mr(this.w,t,r),this}clampLength(t,r){let i=this.length();return this.divideScalar(i||1).multiplyScalar(mr(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}},d0=class extends Wn{constructor(e=1,t=1,r={}){super(),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=1,this.scissor=new Nr(0,0,e,t),this.scissorTest=!1,this.viewport=new Nr(0,0,e,t);let i={width:e,height:t,depth:1};r=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Zr,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1},r);let n=new ei(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 a=r.count;for(let s=0;s<a;s++)this.textures[s]=n.clone(),this.textures[s].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 as(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"})}},Pi=class extends d0{constructor(e=1,t=1,r={}){super(e,t,r),this.isWebGLRenderTarget=!0}},Yu=class extends ei{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=Kr,this.minFilter=Kr,this.wrapR=Ri,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},rw=class extends Pi{constructor(e=1,t=1,r=1,i={}){super(e,t,i),this.isWebGLArrayRenderTarget=!0,this.depth=r,this.texture=new Yu(null,e,t,r),this.texture.isRenderTargetTexture=!0}},Ap=class extends ei{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=Kr,this.minFilter=Kr,this.wrapR=Ri,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},iw=class extends Pi{constructor(e=1,t=1,r=1,i={}){super(e,t,i),this.isWebGL3DRenderTarget=!0,this.depth=r,this.texture=new Ap(null,e,t,r),this.texture.isRenderTargetTexture=!0}},di=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,a,s){let o=r[i+0],l=r[i+1],c=r[i+2],u=r[i+3],h=n[a+0],d=n[a+1],f=n[a+2],y=n[a+3];if(s===0){e[t+0]=o,e[t+1]=l,e[t+2]=c,e[t+3]=u;return}if(s===1){e[t+0]=h,e[t+1]=d,e[t+2]=f,e[t+3]=y;return}if(u!==y||o!==h||l!==d||c!==f){let g=1-s,p=o*h+l*d+c*f+u*y,m=p>=0?1:-1,v=1-p*p;if(v>Number.EPSILON){let b=Math.sqrt(v),_=Math.atan2(b,p*m);g=Math.sin(g*_)/b,s=Math.sin(s*_)/b}let x=s*m;if(o=o*g+h*x,l=l*g+d*x,c=c*g+f*x,u=u*g+y*x,g===1-s){let b=1/Math.sqrt(o*o+l*l+c*c+u*u);o*=b,l*=b,c*=b,u*=b}}e[t]=o,e[t+1]=l,e[t+2]=c,e[t+3]=u}static multiplyQuaternionsFlat(e,t,r,i,n,a){let s=r[i],o=r[i+1],l=r[i+2],c=r[i+3],u=n[a],h=n[a+1],d=n[a+2],f=n[a+3];return e[t]=s*f+c*u+o*d-l*h,e[t+1]=o*f+c*h+l*u-s*d,e[t+2]=l*f+c*d+s*h-o*u,e[t+3]=c*f-s*u-o*h-l*d,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,a=e._order,s=Math.cos,o=Math.sin,l=s(r/2),c=s(i/2),u=s(n/2),h=o(r/2),d=o(i/2),f=o(n/2);switch(a){case"XYZ":this._x=h*c*u+l*d*f,this._y=l*d*u-h*c*f,this._z=l*c*f+h*d*u,this._w=l*c*u-h*d*f;break;case"YXZ":this._x=h*c*u+l*d*f,this._y=l*d*u-h*c*f,this._z=l*c*f-h*d*u,this._w=l*c*u+h*d*f;break;case"ZXY":this._x=h*c*u-l*d*f,this._y=l*d*u+h*c*f,this._z=l*c*f+h*d*u,this._w=l*c*u-h*d*f;break;case"ZYX":this._x=h*c*u-l*d*f,this._y=l*d*u+h*c*f,this._z=l*c*f-h*d*u,this._w=l*c*u+h*d*f;break;case"YZX":this._x=h*c*u+l*d*f,this._y=l*d*u+h*c*f,this._z=l*c*f-h*d*u,this._w=l*c*u-h*d*f;break;case"XZY":this._x=h*c*u-l*d*f,this._y=l*d*u-h*c*f,this._z=l*c*f+h*d*u,this._w=l*c*u+h*d*f;break;default:console.warn("THREE.Quaternion: .setFromEuler() encountered an unknown order: "+a)}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],a=t[1],s=t[5],o=t[9],l=t[2],c=t[6],u=t[10],h=r+s+u;if(h>0){let d=.5/Math.sqrt(h+1);this._w=.25/d,this._x=(c-o)*d,this._y=(n-l)*d,this._z=(a-i)*d}else if(r>s&&r>u){let d=2*Math.sqrt(1+r-s-u);this._w=(c-o)/d,this._x=.25*d,this._y=(i+a)/d,this._z=(n+l)/d}else if(s>u){let d=2*Math.sqrt(1+s-r-u);this._w=(n-l)/d,this._x=(i+a)/d,this._y=.25*d,this._z=(o+c)/d}else{let d=2*Math.sqrt(1+u-r-s);this._w=(a-i)/d,this._x=(n+l)/d,this._y=(o+c)/d,this._z=.25*d}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(mr(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,a=e._w,s=t._x,o=t._y,l=t._z,c=t._w;return this._x=r*c+a*s+i*l-n*o,this._y=i*c+a*o+n*s-r*l,this._z=n*c+a*l+r*o-i*s,this._w=a*c-r*s-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,a=this._w,s=a*e._w+r*e._x+i*e._y+n*e._z;if(s<0?(this._w=-e._w,this._x=-e._x,this._y=-e._y,this._z=-e._z,s=-s):this.copy(e),s>=1)return this._w=a,this._x=r,this._y=i,this._z=n,this;let o=1-s*s;if(o<=Number.EPSILON){let d=1-t;return this._w=d*a+t*this._w,this._x=d*r+t*this._x,this._y=d*i+t*this._y,this._z=d*n+t*this._z,this.normalize(),this}let l=Math.sqrt(o),c=Math.atan2(l,s),u=Math.sin((1-t)*c)/l,h=Math.sin(t*c)/l;return this._w=a*u+this._w*h,this._x=r*u+this._x*h,this._y=i*u+this._y*h,this._z=n*u+this._z*h,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}},ee=class T1{constructor(t=0,r=0,i=0){T1.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(p0.setFromEuler(t))}applyAxisAngle(t,r){return this.applyQuaternion(p0.setFromAxisAngle(t,r))}applyMatrix3(t){let r=this.x,i=this.y,n=this.z,a=t.elements;return this.x=a[0]*r+a[3]*i+a[6]*n,this.y=a[1]*r+a[4]*i+a[7]*n,this.z=a[2]*r+a[5]*i+a[8]*n,this}applyNormalMatrix(t){return this.applyMatrix3(t).normalize()}applyMatrix4(t){let r=this.x,i=this.y,n=this.z,a=t.elements,s=1/(a[3]*r+a[7]*i+a[11]*n+a[15]);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}applyQuaternion(t){let r=this.x,i=this.y,n=this.z,a=t.x,s=t.y,o=t.z,l=t.w,c=2*(s*n-o*i),u=2*(o*r-a*n),h=2*(a*i-s*r);return this.x=r+l*c+s*h-o*u,this.y=i+l*u+o*c-a*h,this.z=n+l*h+a*u-s*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,a=t.elements;return this.x=a[0]*r+a[4]*i+a[8]*n,this.y=a[1]*r+a[5]*i+a[9]*n,this.z=a[2]*r+a[6]*i+a[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=mr(this.x,t.x,r.x),this.y=mr(this.y,t.y,r.y),this.z=mr(this.z,t.z,r.z),this}clampScalar(t,r){return this.x=mr(this.x,t,r),this.y=mr(this.y,t,r),this.z=mr(this.z,t,r),this}clampLength(t,r){let i=this.length();return this.divideScalar(i||1).multiplyScalar(mr(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,a=t.z,s=r.x,o=r.y,l=r.z;return this.x=n*l-a*o,this.y=a*s-i*l,this.z=i*o-n*s,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 Cp.copy(this).projectOnVector(t),this.sub(Cp)}reflect(t){return this.sub(Cp.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(mr(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}},Cp=new ee,p0=new di,Yr=class{constructor(e=new ee(1/0,1/0,1/0),t=new ee(-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(Pn.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,r=e.count;t<r;t++)this.expandByPoint(Pn.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=Pn.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 a=0,s=n.count;a<s;a++)e.isMesh===!0?e.getVertexPosition(a,Pn):Pn.fromBufferAttribute(n,a),Pn.applyMatrix4(e.matrixWorld),this.expandByPoint(Pn);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),qu.copy(e.boundingBox)):(r.boundingBox===null&&r.computeBoundingBox(),qu.copy(r.boundingBox)),qu.applyMatrix4(e.matrixWorld),this.union(qu)}let i=e.children;for(let n=0,a=i.length;n<a;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,Pn),Pn.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(Nl),Ku.subVectors(this.max,Nl),co.subVectors(e.a,Nl),uo.subVectors(e.b,Nl),ho.subVectors(e.c,Nl),Ia.subVectors(uo,co),Na.subVectors(ho,uo),ss.subVectors(co,ho);let t=[0,-Ia.z,Ia.y,0,-Na.z,Na.y,0,-ss.z,ss.y,Ia.z,0,-Ia.x,Na.z,0,-Na.x,ss.z,0,-ss.x,-Ia.y,Ia.x,0,-Na.y,Na.x,0,-ss.y,ss.x,0];return!Rp(t,co,uo,ho,Ku)||(t=[1,0,0,0,1,0,0,0,1],!Rp(t,co,uo,ho,Ku))?!1:(Zu.crossVectors(Ia,Na),t=[Zu.x,Zu.y,Zu.z],Rp(t,co,uo,ho,Ku))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Pn).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Pn).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:(aa[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),aa[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),aa[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),aa[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),aa[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),aa[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),aa[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),aa[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(aa),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)}},aa=[new ee,new ee,new ee,new ee,new ee,new ee,new ee,new ee],Pn=new ee,qu=new Yr,co=new ee,uo=new ee,ho=new ee,Ia=new ee,Na=new ee,ss=new ee,Nl=new ee,Ku=new ee,Zu=new ee,os=new ee;function Rp(e,t,r,i,n){for(let a=0,s=e.length-3;a<=s;a+=3){os.fromArray(e,a);let o=n.x*Math.abs(os.x)+n.y*Math.abs(os.y)+n.z*Math.abs(os.z),l=t.dot(os),c=r.dot(os),u=i.dot(os);if(Math.max(-Math.max(l,c,u),Math.min(l,c,u))>o)return!1}return!0}var nw=new Yr,Ll=new ee,Pp=new ee,si=class{constructor(e=new ee,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):nw.setFromPoints(e).getCenter(r);let i=0;for(let n=0,a=e.length;n<a;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;Ll.subVectors(e,this.center);let t=Ll.lengthSq();if(t>this.radius*this.radius){let r=Math.sqrt(t),i=(r-this.radius)*.5;this.center.addScaledVector(Ll,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):(Pp.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Ll.copy(e.center).add(Pp)),this.expandByPoint(Ll.copy(e.center).sub(Pp))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}},sa=new ee,Ip=new ee,Qu=new ee,La=new ee,Np=new ee,Ju=new ee,Lp=new ee,ls=class{constructor(e=new ee,t=new ee(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,sa)),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=sa.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(sa.copy(this.origin).addScaledVector(this.direction,t),sa.distanceToSquared(e))}distanceSqToSegment(e,t,r,i){Ip.copy(e).add(t).multiplyScalar(.5),Qu.copy(t).sub(e).normalize(),La.copy(this.origin).sub(Ip);let n=e.distanceTo(t)*.5,a=-this.direction.dot(Qu),s=La.dot(this.direction),o=-La.dot(Qu),l=La.lengthSq(),c=Math.abs(1-a*a),u,h,d,f;if(c>0)if(u=a*o-s,h=a*s-o,f=n*c,u>=0)if(h>=-f)if(h<=f){let y=1/c;u*=y,h*=y,d=u*(u+a*h+2*s)+h*(a*u+h+2*o)+l}else h=n,u=Math.max(0,-(a*h+s)),d=-u*u+h*(h+2*o)+l;else h=-n,u=Math.max(0,-(a*h+s)),d=-u*u+h*(h+2*o)+l;else h<=-f?(u=Math.max(0,-(-a*n+s)),h=u>0?-n:Math.min(Math.max(-n,-o),n),d=-u*u+h*(h+2*o)+l):h<=f?(u=0,h=Math.min(Math.max(-n,-o),n),d=h*(h+2*o)+l):(u=Math.max(0,-(a*n+s)),h=u>0?n:Math.min(Math.max(-n,-o),n),d=-u*u+h*(h+2*o)+l);else h=a>0?-n:n,u=Math.max(0,-(a*h+s)),d=-u*u+h*(h+2*o)+l;return r&&r.copy(this.origin).addScaledVector(this.direction,u),i&&i.copy(Ip).addScaledVector(Qu,h),d}intersectSphere(e,t){sa.subVectors(e.center,this.origin);let r=sa.dot(this.direction),i=sa.dot(sa)-r*r,n=e.radius*e.radius;if(i>n)return null;let a=Math.sqrt(n-i),s=r-a,o=r+a;return o<0?null:s<0?this.at(o,t):this.at(s,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,a,s,o,l=1/this.direction.x,c=1/this.direction.y,u=1/this.direction.z,h=this.origin;return l>=0?(r=(e.min.x-h.x)*l,i=(e.max.x-h.x)*l):(r=(e.max.x-h.x)*l,i=(e.min.x-h.x)*l),c>=0?(n=(e.min.y-h.y)*c,a=(e.max.y-h.y)*c):(n=(e.max.y-h.y)*c,a=(e.min.y-h.y)*c),r>a||n>i||((n>r||isNaN(r))&&(r=n),(a<i||isNaN(i))&&(i=a),u>=0?(s=(e.min.z-h.z)*u,o=(e.max.z-h.z)*u):(s=(e.max.z-h.z)*u,o=(e.min.z-h.z)*u),r>o||s>i)||((s>r||r!==r)&&(r=s),(o<i||i!==i)&&(i=o),i<0)?null:this.at(r>=0?r:i,t)}intersectsBox(e){return this.intersectBox(e,sa)!==null}intersectTriangle(e,t,r,i,n){Np.subVectors(t,e),Ju.subVectors(r,e),Lp.crossVectors(Np,Ju);let a=this.direction.dot(Lp),s;if(a>0){if(i)return null;s=1}else if(a<0)s=-1,a=-a;else return null;La.subVectors(this.origin,e);let o=s*this.direction.dot(Ju.crossVectors(La,Ju));if(o<0)return null;let l=s*this.direction.dot(Np.cross(La));if(l<0||o+l>a)return null;let c=-s*La.dot(Lp);return c<0?null:this.at(c/a,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)}},Jt=class Rg{constructor(t,r,i,n,a,s,o,l,c,u,h,d,f,y,g,p){Rg.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,a,s,o,l,c,u,h,d,f,y,g,p)}set(t,r,i,n,a,s,o,l,c,u,h,d,f,y,g,p){let m=this.elements;return m[0]=t,m[4]=r,m[8]=i,m[12]=n,m[1]=a,m[5]=s,m[9]=o,m[13]=l,m[2]=c,m[6]=u,m[10]=h,m[14]=d,m[3]=f,m[7]=y,m[11]=g,m[15]=p,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 Rg().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/po.setFromMatrixColumn(t,0).length(),a=1/po.setFromMatrixColumn(t,1).length(),s=1/po.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]*a,r[5]=i[5]*a,r[6]=i[6]*a,r[7]=0,r[8]=i[8]*s,r[9]=i[9]*s,r[10]=i[10]*s,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,a=t.z,s=Math.cos(i),o=Math.sin(i),l=Math.cos(n),c=Math.sin(n),u=Math.cos(a),h=Math.sin(a);if(t.order==="XYZ"){let d=s*u,f=s*h,y=o*u,g=o*h;r[0]=l*u,r[4]=-l*h,r[8]=c,r[1]=f+y*c,r[5]=d-g*c,r[9]=-o*l,r[2]=g-d*c,r[6]=y+f*c,r[10]=s*l}else if(t.order==="YXZ"){let d=l*u,f=l*h,y=c*u,g=c*h;r[0]=d+g*o,r[4]=y*o-f,r[8]=s*c,r[1]=s*h,r[5]=s*u,r[9]=-o,r[2]=f*o-y,r[6]=g+d*o,r[10]=s*l}else if(t.order==="ZXY"){let d=l*u,f=l*h,y=c*u,g=c*h;r[0]=d-g*o,r[4]=-s*h,r[8]=y+f*o,r[1]=f+y*o,r[5]=s*u,r[9]=g-d*o,r[2]=-s*c,r[6]=o,r[10]=s*l}else if(t.order==="ZYX"){let d=s*u,f=s*h,y=o*u,g=o*h;r[0]=l*u,r[4]=y*c-f,r[8]=d*c+g,r[1]=l*h,r[5]=g*c+d,r[9]=f*c-y,r[2]=-c,r[6]=o*l,r[10]=s*l}else if(t.order==="YZX"){let d=s*l,f=s*c,y=o*l,g=o*c;r[0]=l*u,r[4]=g-d*h,r[8]=y*h+f,r[1]=h,r[5]=s*u,r[9]=-o*u,r[2]=-c*u,r[6]=f*h+y,r[10]=d-g*h}else if(t.order==="XZY"){let d=s*l,f=s*c,y=o*l,g=o*c;r[0]=l*u,r[4]=-h,r[8]=c*u,r[1]=d*h+g,r[5]=s*u,r[9]=f*h-y,r[2]=y*h-f,r[6]=o*u,r[10]=g*h+d}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(aw,t,sw)}lookAt(t,r,i){let n=this.elements;return nn.subVectors(t,r),nn.lengthSq()===0&&(nn.z=1),nn.normalize(),Oa.crossVectors(i,nn),Oa.lengthSq()===0&&(Math.abs(i.z)===1?nn.x+=1e-4:nn.z+=1e-4,nn.normalize(),Oa.crossVectors(i,nn)),Oa.normalize(),$u.crossVectors(nn,Oa),n[0]=Oa.x,n[4]=$u.x,n[8]=nn.x,n[1]=Oa.y,n[5]=$u.y,n[9]=nn.y,n[2]=Oa.z,n[6]=$u.z,n[10]=nn.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,a=this.elements,s=i[0],o=i[4],l=i[8],c=i[12],u=i[1],h=i[5],d=i[9],f=i[13],y=i[2],g=i[6],p=i[10],m=i[14],v=i[3],x=i[7],b=i[11],_=i[15],M=n[0],C=n[4],S=n[8],w=n[12],E=n[1],P=n[5],N=n[9],D=n[13],B=n[2],J=n[6],Q=n[10],j=n[14],k=n[3],H=n[7],U=n[11],X=n[15];return a[0]=s*M+o*E+l*B+c*k,a[4]=s*C+o*P+l*J+c*H,a[8]=s*S+o*N+l*Q+c*U,a[12]=s*w+o*D+l*j+c*X,a[1]=u*M+h*E+d*B+f*k,a[5]=u*C+h*P+d*J+f*H,a[9]=u*S+h*N+d*Q+f*U,a[13]=u*w+h*D+d*j+f*X,a[2]=y*M+g*E+p*B+m*k,a[6]=y*C+g*P+p*J+m*H,a[10]=y*S+g*N+p*Q+m*U,a[14]=y*w+g*D+p*j+m*X,a[3]=v*M+x*E+b*B+_*k,a[7]=v*C+x*P+b*J+_*H,a[11]=v*S+x*N+b*Q+_*U,a[15]=v*w+x*D+b*j+_*X,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],a=t[12],s=t[1],o=t[5],l=t[9],c=t[13],u=t[2],h=t[6],d=t[10],f=t[14],y=t[3],g=t[7],p=t[11],m=t[15];return y*(+a*l*h-n*c*h-a*o*d+i*c*d+n*o*f-i*l*f)+g*(+r*l*f-r*c*d+a*s*d-n*s*f+n*c*u-a*l*u)+p*(+r*c*h-r*o*f-a*s*h+i*s*f+a*o*u-i*c*u)+m*(-n*o*u-r*l*h+r*o*d+n*s*h-i*s*d+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],a=t[3],s=t[4],o=t[5],l=t[6],c=t[7],u=t[8],h=t[9],d=t[10],f=t[11],y=t[12],g=t[13],p=t[14],m=t[15],v=h*p*c-g*d*c+g*l*f-o*p*f-h*l*m+o*d*m,x=y*d*c-u*p*c-y*l*f+s*p*f+u*l*m-s*d*m,b=u*g*c-y*h*c+y*o*f-s*g*f-u*o*m+s*h*m,_=y*h*l-u*g*l-y*o*d+s*g*d+u*o*p-s*h*p,M=r*v+i*x+n*b+a*_;if(M===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);let C=1/M;return t[0]=v*C,t[1]=(g*d*a-h*p*a-g*n*f+i*p*f+h*n*m-i*d*m)*C,t[2]=(o*p*a-g*l*a+g*n*c-i*p*c-o*n*m+i*l*m)*C,t[3]=(h*l*a-o*d*a-h*n*c+i*d*c+o*n*f-i*l*f)*C,t[4]=x*C,t[5]=(u*p*a-y*d*a+y*n*f-r*p*f-u*n*m+r*d*m)*C,t[6]=(y*l*a-s*p*a-y*n*c+r*p*c+s*n*m-r*l*m)*C,t[7]=(s*d*a-u*l*a+u*n*c-r*d*c-s*n*f+r*l*f)*C,t[8]=b*C,t[9]=(y*h*a-u*g*a-y*i*f+r*g*f+u*i*m-r*h*m)*C,t[10]=(s*g*a-y*o*a+y*i*c-r*g*c-s*i*m+r*o*m)*C,t[11]=(u*o*a-s*h*a-u*i*c+r*h*c+s*i*f-r*o*f)*C,t[12]=_*C,t[13]=(u*g*n-y*h*n+y*i*d-r*g*d-u*i*p+r*h*p)*C,t[14]=(y*o*n-s*g*n-y*i*l+r*g*l+s*i*p-r*o*p)*C,t[15]=(s*h*n-u*o*n+u*i*l-r*h*l-s*i*d+r*o*d)*C,this}scale(t){let r=this.elements,i=t.x,n=t.y,a=t.z;return r[0]*=i,r[4]*=n,r[8]*=a,r[1]*=i,r[5]*=n,r[9]*=a,r[2]*=i,r[6]*=n,r[10]*=a,r[3]*=i,r[7]*=n,r[11]*=a,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),a=1-i,s=t.x,o=t.y,l=t.z,c=a*s,u=a*o;return this.set(c*s+i,c*o-n*l,c*l+n*o,0,c*o+n*l,u*o+i,u*l-n*s,0,c*l-n*o,u*l+n*s,a*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,a,s){return this.set(1,i,a,0,t,1,s,0,r,n,1,0,0,0,0,1),this}compose(t,r,i){let n=this.elements,a=r._x,s=r._y,o=r._z,l=r._w,c=a+a,u=s+s,h=o+o,d=a*c,f=a*u,y=a*h,g=s*u,p=s*h,m=o*h,v=l*c,x=l*u,b=l*h,_=i.x,M=i.y,C=i.z;return n[0]=(1-(g+m))*_,n[1]=(f+b)*_,n[2]=(y-x)*_,n[3]=0,n[4]=(f-b)*M,n[5]=(1-(d+m))*M,n[6]=(p+v)*M,n[7]=0,n[8]=(y+x)*C,n[9]=(p-v)*C,n[10]=(1-(d+g))*C,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,a=po.set(n[0],n[1],n[2]).length(),s=po.set(n[4],n[5],n[6]).length(),o=po.set(n[8],n[9],n[10]).length();this.determinant()<0&&(a=-a),t.x=n[12],t.y=n[13],t.z=n[14],In.copy(this);let l=1/a,c=1/s,u=1/o;return In.elements[0]*=l,In.elements[1]*=l,In.elements[2]*=l,In.elements[4]*=c,In.elements[5]*=c,In.elements[6]*=c,In.elements[8]*=u,In.elements[9]*=u,In.elements[10]*=u,r.setFromRotationMatrix(In),i.x=a,i.y=s,i.z=o,this}makePerspective(t,r,i,n,a,s,o=Hn){let l=this.elements,c=2*a/(r-t),u=2*a/(i-n),h=(r+t)/(r-t),d=(i+n)/(i-n),f,y;if(o===Hn)f=-(s+a)/(s-a),y=-2*s*a/(s-a);else if(o===Rl)f=-s/(s-a),y=-s*a/(s-a);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);return l[0]=c,l[4]=0,l[8]=h,l[12]=0,l[1]=0,l[5]=u,l[9]=d,l[13]=0,l[2]=0,l[6]=0,l[10]=f,l[14]=y,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(t,r,i,n,a,s,o=Hn){let l=this.elements,c=1/(r-t),u=1/(i-n),h=1/(s-a),d=(r+t)*c,f=(i+n)*u,y,g;if(o===Hn)y=(s+a)*h,g=-2*h;else if(o===Rl)y=a*h,g=-1*h;else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);return l[0]=2*c,l[4]=0,l[8]=0,l[12]=-d,l[1]=0,l[5]=2*u,l[9]=0,l[13]=-f,l[2]=0,l[6]=0,l[10]=g,l[14]=-y,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}},po=new ee,In=new Jt,aw=new ee(0,0,0),sw=new ee(1,1,1),Oa=new ee,$u=new ee,nn=new ee,f0=new Jt,m0=new di,Nn=class A1{constructor(t=0,r=0,i=0,n=A1.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,a=n[0],s=n[4],o=n[8],l=n[1],c=n[5],u=n[9],h=n[2],d=n[6],f=n[10];switch(r){case"XYZ":this._y=Math.asin(mr(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-u,f),this._z=Math.atan2(-s,a)):(this._x=Math.atan2(d,c),this._z=0);break;case"YXZ":this._x=Math.asin(-mr(u,-1,1)),Math.abs(u)<.9999999?(this._y=Math.atan2(o,f),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-h,a),this._z=0);break;case"ZXY":this._x=Math.asin(mr(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-h,f),this._z=Math.atan2(-s,c)):(this._y=0,this._z=Math.atan2(l,a));break;case"ZYX":this._y=Math.asin(-mr(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(d,f),this._z=Math.atan2(l,a)):(this._x=0,this._z=Math.atan2(-s,c));break;case"YZX":this._z=Math.asin(mr(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-u,c),this._y=Math.atan2(-h,a)):(this._x=0,this._y=Math.atan2(o,f));break;case"XZY":this._z=Math.asin(-mr(s,-1,1)),Math.abs(s)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(o,a)):(this._x=Math.atan2(-u,f),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 f0.makeRotationFromQuaternion(t),this.setFromRotationMatrix(f0,r,i)}setFromVector3(t,r=this._order){return this.set(t.x,t.y,t.z,r)}reorder(t){return m0.setFromEuler(this),this.setFromQuaternion(m0,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}};Nn.DEFAULT_ORDER="XYZ";var eh=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}},ow=0,g0=new ee,fo=new di,oa=new Jt,th=new ee,Ol=new ee,lw=new ee,cw=new di,y0=new ee(1,0,0),v0=new ee(0,1,0),x0=new ee(0,0,1),b0={type:"added"},uw={type:"removed"},mo={type:"childadded",child:null},Op={type:"childremoved",child:null},Ar=class rp extends Wn{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:ow++}),this.uuid=rn(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=rp.DEFAULT_UP.clone();let t=new ee,r=new Nn,i=new di,n=new ee(1,1,1);function a(){i.setFromEuler(r,!1)}function s(){r.setFromQuaternion(i,void 0,!1)}r._onChange(a),i._onChange(s),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 Jt},normalMatrix:{value:new xr}}),this.matrix=new Jt,this.matrixWorld=new Jt,this.matrixAutoUpdate=rp.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=rp.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new eh,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 fo.setFromAxisAngle(t,r),this.quaternion.multiply(fo),this}rotateOnWorldAxis(t,r){return fo.setFromAxisAngle(t,r),this.quaternion.premultiply(fo),this}rotateX(t){return this.rotateOnAxis(y0,t)}rotateY(t){return this.rotateOnAxis(v0,t)}rotateZ(t){return this.rotateOnAxis(x0,t)}translateOnAxis(t,r){return g0.copy(t).applyQuaternion(this.quaternion),this.position.add(g0.multiplyScalar(r)),this}translateX(t){return this.translateOnAxis(y0,t)}translateY(t){return this.translateOnAxis(v0,t)}translateZ(t){return this.translateOnAxis(x0,t)}localToWorld(t){return this.updateWorldMatrix(!0,!1),t.applyMatrix4(this.matrixWorld)}worldToLocal(t){return this.updateWorldMatrix(!0,!1),t.applyMatrix4(oa.copy(this.matrixWorld).invert())}lookAt(t,r,i){t.isVector3?th.copy(t):th.set(t,r,i);let n=this.parent;this.updateWorldMatrix(!0,!1),Ol.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?oa.lookAt(Ol,th,this.up):oa.lookAt(th,Ol,this.up),this.quaternion.setFromRotationMatrix(oa),n&&(oa.extractRotation(n.matrixWorld),fo.setFromRotationMatrix(oa),this.quaternion.premultiply(fo.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(b0),mo.child=t,this.dispatchEvent(mo),mo.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(uw),Op.child=t,this.dispatchEvent(Op),Op.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),oa.copy(this.matrixWorld).invert(),t.parent!==null&&(t.parent.updateWorldMatrix(!0,!1),oa.multiply(t.parent.matrixWorld)),t.applyMatrix4(oa),t.removeFromParent(),t.parent=this,this.children.push(t),t.updateWorldMatrix(!1,!0),t.dispatchEvent(b0),mo.child=t,this.dispatchEvent(mo),mo.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 a=this.children[i].getObjectByProperty(t,r);if(a!==void 0)return a}}getObjectsByProperty(t,r,i=[]){this[t]===r&&i.push(this);let n=this.children;for(let a=0,s=n.length;a<s;a++)n[a].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(Ol,t,lw),t}getWorldScale(t){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Ol,cw,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 a=0,s=n.length;a<s;a++)n[a].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 a(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=a(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 h=l[c];a(t.shapes,h)}else a(t.shapes,l)}}if(this.isSkinnedMesh&&(n.bindMode=this.bindMode,n.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(a(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(a(t.materials,this.material[l]));n.material=o}else n.material=a(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(a(t.animations,l))}}if(r){let o=s(t.geometries),l=s(t.materials),c=s(t.textures),u=s(t.images),h=s(t.shapes),d=s(t.skeletons),f=s(t.animations),y=s(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),h.length>0&&(i.shapes=h),d.length>0&&(i.skeletons=d),f.length>0&&(i.animations=f),y.length>0&&(i.nodes=y)}return i.object=n,i;function s(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}};Ar.DEFAULT_UP=new ee(0,1,0),Ar.DEFAULT_MATRIX_AUTO_UPDATE=!0,Ar.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;var Ln=new ee,la=new ee,Dp=new ee,ca=new ee,go=new ee,yo=new ee,_0=new ee,kp=new ee,Up=new ee,Fp=new ee,Bp=new Nr,zp=new Nr,Gp=new Nr,ua=class pl{constructor(t=new ee,r=new ee,i=new ee){this.a=t,this.b=r,this.c=i}static getNormal(t,r,i,n){n.subVectors(i,r),Ln.subVectors(t,r),n.cross(Ln);let a=n.lengthSq();return a>0?n.multiplyScalar(1/Math.sqrt(a)):n.set(0,0,0)}static getBarycoord(t,r,i,n,a){Ln.subVectors(n,r),la.subVectors(i,r),Dp.subVectors(t,r);let s=Ln.dot(Ln),o=Ln.dot(la),l=Ln.dot(Dp),c=la.dot(la),u=la.dot(Dp),h=s*c-o*o;if(h===0)return a.set(0,0,0),null;let d=1/h,f=(c*l-o*u)*d,y=(s*u-o*l)*d;return a.set(1-f-y,y,f)}static containsPoint(t,r,i,n){return this.getBarycoord(t,r,i,n,ca)===null?!1:ca.x>=0&&ca.y>=0&&ca.x+ca.y<=1}static getInterpolation(t,r,i,n,a,s,o,l){return this.getBarycoord(t,r,i,n,ca)===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(a,ca.x),l.addScaledVector(s,ca.y),l.addScaledVector(o,ca.z),l)}static getInterpolatedAttribute(t,r,i,n,a,s){return Bp.setScalar(0),zp.setScalar(0),Gp.setScalar(0),Bp.fromBufferAttribute(t,r),zp.fromBufferAttribute(t,i),Gp.fromBufferAttribute(t,n),s.setScalar(0),s.addScaledVector(Bp,a.x),s.addScaledVector(zp,a.y),s.addScaledVector(Gp,a.z),s}static isFrontFacing(t,r,i,n){return Ln.subVectors(i,r),la.subVectors(t,r),Ln.cross(la).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 Ln.subVectors(this.c,this.b),la.subVectors(this.a,this.b),Ln.cross(la).length()*.5}getMidpoint(t){return t.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return pl.getNormal(this.a,this.b,this.c,t)}getPlane(t){return t.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,r){return pl.getBarycoord(t,this.a,this.b,this.c,r)}getInterpolation(t,r,i,n,a){return pl.getInterpolation(t,this.a,this.b,this.c,r,i,n,a)}containsPoint(t){return pl.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return pl.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(t){return t.intersectsTriangle(this)}closestPointToPoint(t,r){let i=this.a,n=this.b,a=this.c,s,o;go.subVectors(n,i),yo.subVectors(a,i),kp.subVectors(t,i);let l=go.dot(kp),c=yo.dot(kp);if(l<=0&&c<=0)return r.copy(i);Up.subVectors(t,n);let u=go.dot(Up),h=yo.dot(Up);if(u>=0&&h<=u)return r.copy(n);let d=l*h-u*c;if(d<=0&&l>=0&&u<=0)return s=l/(l-u),r.copy(i).addScaledVector(go,s);Fp.subVectors(t,a);let f=go.dot(Fp),y=yo.dot(Fp);if(y>=0&&f<=y)return r.copy(a);let g=f*c-l*y;if(g<=0&&c>=0&&y<=0)return o=c/(c-y),r.copy(i).addScaledVector(yo,o);let p=u*y-f*h;if(p<=0&&h-u>=0&&f-y>=0)return _0.subVectors(a,n),o=(h-u)/(h-u+(f-y)),r.copy(n).addScaledVector(_0,o);let m=1/(p+g+d);return s=g*m,o=d*m,r.copy(i).addScaledVector(go,s).addScaledVector(yo,o)}equals(t){return t.a.equals(this.a)&&t.b.equals(this.b)&&t.c.equals(this.c)}},w0={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},Da={h:0,s:0,l:0},rh={h:0,s:0,l:0};function Vp(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 yt=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=Pr){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,_r.toWorkingColorSpace(this,t),this}setRGB(e,t,r,i=_r.workingColorSpace){return this.r=e,this.g=t,this.b=r,_r.toWorkingColorSpace(this,i),this}setHSL(e,t,r,i=_r.workingColorSpace){if(e=Mp(e,1),t=mr(t,0,1),r=mr(r,0,1),t===0)this.r=this.g=this.b=r;else{let n=r<=.5?r*(1+t):r+t-r*t,a=2*r-n;this.r=Vp(a,n,e+1/3),this.g=Vp(a,n,e),this.b=Vp(a,n,e-1/3)}return _r.toWorkingColorSpace(this,i),this}setStyle(e,t=Pr){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,a=i[1],s=i[2];switch(a){case"rgb":case"rgba":if(n=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(s))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(s))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(s))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],a=n.length;if(a===3)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(a===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=Pr){let r=w0[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=na(e.r),this.g=na(e.g),this.b=na(e.b),this}copyLinearToSRGB(e){return this.r=oo(e.r),this.g=oo(e.g),this.b=oo(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Pr){return _r.fromWorkingColorSpace(ki.copy(this),e),Math.round(mr(ki.r*255,0,255))*65536+Math.round(mr(ki.g*255,0,255))*256+Math.round(mr(ki.b*255,0,255))}getHexString(e=Pr){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=_r.workingColorSpace){_r.fromWorkingColorSpace(ki.copy(this),t);let r=ki.r,i=ki.g,n=ki.b,a=Math.max(r,i,n),s=Math.min(r,i,n),o,l,c=(s+a)/2;if(s===a)o=0,l=0;else{let u=a-s;switch(l=c<=.5?u/(a+s):u/(2-a-s),a){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=_r.workingColorSpace){return _r.fromWorkingColorSpace(ki.copy(this),t),e.r=ki.r,e.g=ki.g,e.b=ki.b,e}getStyle(e=Pr){_r.fromWorkingColorSpace(ki.copy(this),e);let t=ki.r,r=ki.g,i=ki.b;return e!==Pr?`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(Da),this.setHSL(Da.h+e,Da.s+t,Da.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(Da),e.getHSL(rh);let r=Pl(Da.h,rh.h,t),i=Pl(Da.s,rh.s,t),n=Pl(Da.l,rh.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}},ki=new yt;yt.NAMES=w0;var hw=0,xi=class extends Wn{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:hw++}),this.uuid=rn(),this.name="",this.type="Material",this.blending=Zt,this.side=it,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=Qc,this.blendDst=Jc,this.blendEquation=Gt,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new yt(0,0,0),this.blendAlpha=0,this.depthFunc=Ja,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=_p,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=is,this.stencilZFail=is,this.stencilZPass=is,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!==Zt&&(r.blending=this.blending),this.side!==it&&(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!==Qc&&(r.blendSrc=this.blendSrc),this.blendDst!==Jc&&(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!==Ja&&(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!==_p&&(r.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(r.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(r.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==is&&(r.stencilFail=this.stencilFail),this.stencilZFail!==is&&(r.stencilZFail=this.stencilZFail),this.stencilZPass!==is&&(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 a=[];for(let s in n){let o=n[s];delete o.metadata,a.push(o)}return a}if(t){let n=i(e.textures),a=i(e.images);n.length>0&&(r.textures=n),a.length>0&&(r.images=a)}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.")}},ti=class extends xi{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new yt(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 Nn,this.combine=yl,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}},ha=dw();function dw(){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 a=new Uint32Array(2048),s=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,a[l]=c|u}for(let l=1024;l<2048;++l)a[l]=939524096+(l-1024<<13);for(let l=1;l<31;++l)s[l]=l<<23;s[31]=1199570944,s[32]=2147483648;for(let l=33;l<63;++l)s[l]=2147483648+(l-32<<23);s[63]=3347054592;for(let l=1;l<64;++l)l!==32&&(o[l]=1024);return{floatView:t,uint32View:r,baseTable:i,shiftTable:n,mantissaTable:a,exponentTable:s,offsetTable:o}}function Yi(e){Math.abs(e)>65504&&console.warn("THREE.DataUtils.toHalfFloat(): Value out of range."),e=mr(e,-65504,65504),ha.floatView[0]=e;let t=ha.uint32View[0],r=t>>23&511;return ha.baseTable[r]+((t&8388607)>>ha.shiftTable[r])}function Dl(e){let t=e>>10;return ha.uint32View[0]=ha.mantissaTable[ha.offsetTable[t]+(e&1023)]+ha.exponentTable[t],ha.floatView[0]}var pw={toHalfFloat:Yi,fromHalfFloat:Dl},pi=new ee,ih=new Xe,Mr=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=Cl,this.updateRanges=[],this.gpuType=Xi,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++)ih.fromBufferAttribute(this,t),ih.applyMatrix3(e),this.setXY(t,ih.x,ih.y);else if(this.itemSize===3)for(let t=0,r=this.count;t<r;t++)pi.fromBufferAttribute(this,t),pi.applyMatrix3(e),this.setXYZ(t,pi.x,pi.y,pi.z);return this}applyMatrix4(e){for(let t=0,r=this.count;t<r;t++)pi.fromBufferAttribute(this,t),pi.applyMatrix4(e),this.setXYZ(t,pi.x,pi.y,pi.z);return this}applyNormalMatrix(e){for(let t=0,r=this.count;t<r;t++)pi.fromBufferAttribute(this,t),pi.applyNormalMatrix(e),this.setXYZ(t,pi.x,pi.y,pi.z);return this}transformDirection(e){for(let t=0,r=this.count;t<r;t++)pi.fromBufferAttribute(this,t),pi.transformDirection(e),this.setXYZ(t,pi.x,pi.y,pi.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=Vi(r,this.array)),r}setComponent(e,t,r){return this.normalized&&(r=yr(r,this.array)),this.array[e*this.itemSize+t]=r,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Vi(t,this.array)),t}setX(e,t){return this.normalized&&(t=yr(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Vi(t,this.array)),t}setY(e,t){return this.normalized&&(t=yr(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=Vi(t,this.array)),t}setZ(e,t){return this.normalized&&(t=yr(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=Vi(t,this.array)),t}setW(e,t){return this.normalized&&(t=yr(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,r){return e*=this.itemSize,this.normalized&&(t=yr(t,this.array),r=yr(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=yr(t,this.array),r=yr(r,this.array),i=yr(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=yr(t,this.array),r=yr(r,this.array),i=yr(i,this.array),n=yr(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!==Cl&&(e.usage=this.usage),e}},fw=class extends Mr{constructor(e,t,r){super(new Int8Array(e),t,r)}},mw=class extends Mr{constructor(e,t,r){super(new Uint8Array(e),t,r)}},gw=class extends Mr{constructor(e,t,r){super(new Uint8ClampedArray(e),t,r)}},yw=class extends Mr{constructor(e,t,r){super(new Int16Array(e),t,r)}},Hp=class extends Mr{constructor(e,t,r){super(new Uint16Array(e),t,r)}},vw=class extends Mr{constructor(e,t,r){super(new Int32Array(e),t,r)}},Wp=class extends Mr{constructor(e,t,r){super(new Uint32Array(e),t,r)}},xw=class extends Mr{constructor(e,t,r){super(new Uint16Array(e),t,r),this.isFloat16BufferAttribute=!0}getX(e){let t=Dl(this.array[e*this.itemSize]);return this.normalized&&(t=Vi(t,this.array)),t}setX(e,t){return this.normalized&&(t=yr(t,this.array)),this.array[e*this.itemSize]=Yi(t),this}getY(e){let t=Dl(this.array[e*this.itemSize+1]);return this.normalized&&(t=Vi(t,this.array)),t}setY(e,t){return this.normalized&&(t=yr(t,this.array)),this.array[e*this.itemSize+1]=Yi(t),this}getZ(e){let t=Dl(this.array[e*this.itemSize+2]);return this.normalized&&(t=Vi(t,this.array)),t}setZ(e,t){return this.normalized&&(t=yr(t,this.array)),this.array[e*this.itemSize+2]=Yi(t),this}getW(e){let t=Dl(this.array[e*this.itemSize+3]);return this.normalized&&(t=Vi(t,this.array)),t}setW(e,t){return this.normalized&&(t=yr(t,this.array)),this.array[e*this.itemSize+3]=Yi(t),this}setXY(e,t,r){return e*=this.itemSize,this.normalized&&(t=yr(t,this.array),r=yr(r,this.array)),this.array[e+0]=Yi(t),this.array[e+1]=Yi(r),this}setXYZ(e,t,r,i){return e*=this.itemSize,this.normalized&&(t=yr(t,this.array),r=yr(r,this.array),i=yr(i,this.array)),this.array[e+0]=Yi(t),this.array[e+1]=Yi(r),this.array[e+2]=Yi(i),this}setXYZW(e,t,r,i,n){return e*=this.itemSize,this.normalized&&(t=yr(t,this.array),r=yr(r,this.array),i=yr(i,this.array),n=yr(n,this.array)),this.array[e+0]=Yi(t),this.array[e+1]=Yi(r),this.array[e+2]=Yi(i),this.array[e+3]=Yi(n),this}},Mt=class extends Mr{constructor(e,t,r){super(new Float32Array(e),t,r)}},bw=0,vn=new Jt,jp=new Ar,vo=new ee,an=new Yr,kl=new Yr,Ai=new ee,ar=class C1 extends Wn{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:bw++}),this.uuid=rn(),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(s0(t)?Wp:Hp)(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 a=new xr().getNormalMatrix(t);i.applyNormalMatrix(a),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 vn.makeRotationFromQuaternion(t),this.applyMatrix4(vn),this}rotateX(t){return vn.makeRotationX(t),this.applyMatrix4(vn),this}rotateY(t){return vn.makeRotationY(t),this.applyMatrix4(vn),this}rotateZ(t){return vn.makeRotationZ(t),this.applyMatrix4(vn),this}translate(t,r,i){return vn.makeTranslation(t,r,i),this.applyMatrix4(vn),this}scale(t,r,i){return vn.makeScale(t,r,i),this.applyMatrix4(vn),this}lookAt(t){return jp.lookAt(t),jp.updateMatrix(),this.applyMatrix4(jp.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(vo).negate(),this.translate(vo.x,vo.y,vo.z),this}setFromPoints(t){let r=this.getAttribute("position");if(r===void 0){let i=[];for(let n=0,a=t.length;n<a;n++){let s=t[n];i.push(s.x,s.y,s.z||0)}this.setAttribute("position",new Mt(i,3))}else{let i=Math.min(t.length,r.count);for(let n=0;n<i;n++){let a=t[n];r.setXYZ(n,a.x,a.y,a.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 Yr);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 ee(-1/0,-1/0,-1/0),new ee(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 a=r[i];an.setFromBufferAttribute(a),this.morphTargetsRelative?(Ai.addVectors(this.boundingBox.min,an.min),this.boundingBox.expandByPoint(Ai),Ai.addVectors(this.boundingBox.max,an.max),this.boundingBox.expandByPoint(Ai)):(this.boundingBox.expandByPoint(an.min),this.boundingBox.expandByPoint(an.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 si);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 ee,1/0);return}if(t){let i=this.boundingSphere.center;if(an.setFromBufferAttribute(t),r)for(let a=0,s=r.length;a<s;a++){let o=r[a];kl.setFromBufferAttribute(o),this.morphTargetsRelative?(Ai.addVectors(an.min,kl.min),an.expandByPoint(Ai),Ai.addVectors(an.max,kl.max),an.expandByPoint(Ai)):(an.expandByPoint(kl.min),an.expandByPoint(kl.max))}an.getCenter(i);let n=0;for(let a=0,s=t.count;a<s;a++)Ai.fromBufferAttribute(t,a),n=Math.max(n,i.distanceToSquared(Ai));if(r)for(let a=0,s=r.length;a<s;a++){let o=r[a],l=this.morphTargetsRelative;for(let c=0,u=o.count;c<u;c++)Ai.fromBufferAttribute(o,c),l&&(vo.fromBufferAttribute(t,c),Ai.add(vo)),n=Math.max(n,i.distanceToSquared(Ai))}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,a=r.uv;this.hasAttribute("tangent")===!1&&this.setAttribute("tangent",new Mr(new Float32Array(4*i.count),4));let s=this.getAttribute("tangent"),o=[],l=[];for(let S=0;S<i.count;S++)o[S]=new ee,l[S]=new ee;let c=new ee,u=new ee,h=new ee,d=new Xe,f=new Xe,y=new Xe,g=new ee,p=new ee;function m(S,w,E){c.fromBufferAttribute(i,S),u.fromBufferAttribute(i,w),h.fromBufferAttribute(i,E),d.fromBufferAttribute(a,S),f.fromBufferAttribute(a,w),y.fromBufferAttribute(a,E),u.sub(c),h.sub(c),f.sub(d),y.sub(d);let P=1/(f.x*y.y-y.x*f.y);isFinite(P)&&(g.copy(u).multiplyScalar(y.y).addScaledVector(h,-f.y).multiplyScalar(P),p.copy(h).multiplyScalar(f.x).addScaledVector(u,-y.x).multiplyScalar(P),o[S].add(g),o[w].add(g),o[E].add(g),l[S].add(p),l[w].add(p),l[E].add(p))}let v=this.groups;v.length===0&&(v=[{start:0,count:t.count}]);for(let S=0,w=v.length;S<w;++S){let E=v[S],P=E.start,N=E.count;for(let D=P,B=P+N;D<B;D+=3)m(t.getX(D+0),t.getX(D+1),t.getX(D+2))}let x=new ee,b=new ee,_=new ee,M=new ee;function C(S){_.fromBufferAttribute(n,S),M.copy(_);let w=o[S];x.copy(w),x.sub(_.multiplyScalar(_.dot(w))).normalize(),b.crossVectors(M,w);let E=b.dot(l[S])<0?-1:1;s.setXYZW(S,x.x,x.y,x.z,E)}for(let S=0,w=v.length;S<w;++S){let E=v[S],P=E.start,N=E.count;for(let D=P,B=P+N;D<B;D+=3)C(t.getX(D+0)),C(t.getX(D+1)),C(t.getX(D+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 Mr(new Float32Array(r.count*3),3),this.setAttribute("normal",i);else for(let d=0,f=i.count;d<f;d++)i.setXYZ(d,0,0,0);let n=new ee,a=new ee,s=new ee,o=new ee,l=new ee,c=new ee,u=new ee,h=new ee;if(t)for(let d=0,f=t.count;d<f;d+=3){let y=t.getX(d+0),g=t.getX(d+1),p=t.getX(d+2);n.fromBufferAttribute(r,y),a.fromBufferAttribute(r,g),s.fromBufferAttribute(r,p),u.subVectors(s,a),h.subVectors(n,a),u.cross(h),o.fromBufferAttribute(i,y),l.fromBufferAttribute(i,g),c.fromBufferAttribute(i,p),o.add(u),l.add(u),c.add(u),i.setXYZ(y,o.x,o.y,o.z),i.setXYZ(g,l.x,l.y,l.z),i.setXYZ(p,c.x,c.y,c.z)}else for(let d=0,f=r.count;d<f;d+=3)n.fromBufferAttribute(r,d+0),a.fromBufferAttribute(r,d+1),s.fromBufferAttribute(r,d+2),u.subVectors(s,a),h.subVectors(n,a),u.cross(h),i.setXYZ(d+0,u.x,u.y,u.z),i.setXYZ(d+1,u.x,u.y,u.z),i.setXYZ(d+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++)Ai.fromBufferAttribute(t,r),Ai.normalize(),t.setXYZ(r,Ai.x,Ai.y,Ai.z)}toNonIndexed(){function t(o,l){let c=o.array,u=o.itemSize,h=o.normalized,d=new c.constructor(l.length*u),f=0,y=0;for(let g=0,p=l.length;g<p;g++){o.isInterleavedBufferAttribute?f=l[g]*o.data.stride+o.offset:f=l[g]*u;for(let m=0;m<u;m++)d[y++]=c[f++]}return new Mr(d,u,h)}if(this.index===null)return console.warn("THREE.BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;let r=new C1,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 a=this.morphAttributes;for(let o in a){let l=[],c=a[o];for(let u=0,h=c.length;u<h;u++){let d=c[u],f=t(d,i);l.push(f)}r.morphAttributes[o]=l}r.morphTargetsRelative=this.morphTargetsRelative;let s=this.groups;for(let o=0,l=s.length;o<l;o++){let c=s[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={},a=!1;for(let l in this.morphAttributes){let c=this.morphAttributes[l],u=[];for(let h=0,d=c.length;h<d;h++){let f=c[h];u.push(f.toJSON(t.data))}u.length>0&&(n[l]=u,a=!0)}a&&(t.data.morphAttributes=n,t.data.morphTargetsRelative=this.morphTargetsRelative);let s=this.groups;s.length>0&&(t.data.groups=JSON.parse(JSON.stringify(s)));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 a=t.morphAttributes;for(let c in a){let u=[],h=a[c];for(let d=0,f=h.length;d<f;d++)u.push(h[d].clone(r));this.morphAttributes[c]=u}this.morphTargetsRelative=t.morphTargetsRelative;let s=t.groups;for(let c=0,u=s.length;c<u;c++){let h=s[c];this.addGroup(h.start,h.count,h.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"})}},E0=new Jt,cs=new ls,nh=new si,M0=new ee,ah=new ee,sh=new ee,oh=new ee,Xp=new ee,lh=new ee,S0=new ee,ch=new ee,hr=class extends Ar{constructor(e=new ar,t=new ti){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 a=r[i].name||String(i);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=i}}}}getVertexPosition(e,t){let r=this.geometry,i=r.attributes.position,n=r.morphAttributes.position,a=r.morphTargetsRelative;t.fromBufferAttribute(i,e);let s=this.morphTargetInfluences;if(n&&s){lh.set(0,0,0);for(let o=0,l=n.length;o<l;o++){let c=s[o],u=n[o];c!==0&&(Xp.fromBufferAttribute(u,e),a?lh.addScaledVector(Xp,c):lh.addScaledVector(Xp.sub(t),c))}t.add(lh)}return t}raycast(e,t){let r=this.geometry,i=this.material,n=this.matrixWorld;i!==void 0&&(r.boundingSphere===null&&r.computeBoundingSphere(),nh.copy(r.boundingSphere),nh.applyMatrix4(n),cs.copy(e.ray).recast(e.near),!(nh.containsPoint(cs.origin)===!1&&(cs.intersectSphere(nh,M0)===null||cs.origin.distanceToSquared(M0)>(e.far-e.near)**2))&&(E0.copy(n).invert(),cs.copy(e.ray).applyMatrix4(E0),!(r.boundingBox!==null&&cs.intersectsBox(r.boundingBox)===!1)&&this._computeIntersections(e,t,cs)))}_computeIntersections(e,t,r){let i,n=this.geometry,a=this.material,s=n.index,o=n.attributes.position,l=n.attributes.uv,c=n.attributes.uv1,u=n.attributes.normal,h=n.groups,d=n.drawRange;if(s!==null)if(Array.isArray(a))for(let f=0,y=h.length;f<y;f++){let g=h[f],p=a[g.materialIndex],m=Math.max(g.start,d.start),v=Math.min(s.count,Math.min(g.start+g.count,d.start+d.count));for(let x=m,b=v;x<b;x+=3){let _=s.getX(x),M=s.getX(x+1),C=s.getX(x+2);i=uh(this,p,e,r,l,c,u,_,M,C),i&&(i.faceIndex=Math.floor(x/3),i.face.materialIndex=g.materialIndex,t.push(i))}}else{let f=Math.max(0,d.start),y=Math.min(s.count,d.start+d.count);for(let g=f,p=y;g<p;g+=3){let m=s.getX(g),v=s.getX(g+1),x=s.getX(g+2);i=uh(this,a,e,r,l,c,u,m,v,x),i&&(i.faceIndex=Math.floor(g/3),t.push(i))}}else if(o!==void 0)if(Array.isArray(a))for(let f=0,y=h.length;f<y;f++){let g=h[f],p=a[g.materialIndex],m=Math.max(g.start,d.start),v=Math.min(o.count,Math.min(g.start+g.count,d.start+d.count));for(let x=m,b=v;x<b;x+=3){let _=x,M=x+1,C=x+2;i=uh(this,p,e,r,l,c,u,_,M,C),i&&(i.faceIndex=Math.floor(x/3),i.face.materialIndex=g.materialIndex,t.push(i))}}else{let f=Math.max(0,d.start),y=Math.min(o.count,d.start+d.count);for(let g=f,p=y;g<p;g+=3){let m=g,v=g+1,x=g+2;i=uh(this,a,e,r,l,c,u,m,v,x),i&&(i.faceIndex=Math.floor(g/3),t.push(i))}}}};function _w(e,t,r,i,n,a,s,o){let l;if(t.side===_t?l=i.intersectTriangle(s,a,n,!0,o):l=i.intersectTriangle(n,a,s,t.side===it,o),l===null)return null;ch.copy(o),ch.applyMatrix4(e.matrixWorld);let c=r.ray.origin.distanceTo(ch);return c<r.near||c>r.far?null:{distance:c,point:ch.clone(),object:e}}function uh(e,t,r,i,n,a,s,o,l,c){e.getVertexPosition(o,ah),e.getVertexPosition(l,sh),e.getVertexPosition(c,oh);let u=_w(e,t,r,i,ah,sh,oh,S0);if(u){let h=new ee;ua.getBarycoord(S0,ah,sh,oh,h),n&&(u.uv=ua.getInterpolatedAttribute(n,o,l,c,h,new Xe)),a&&(u.uv1=ua.getInterpolatedAttribute(a,o,l,c,h,new Xe)),s&&(u.normal=ua.getInterpolatedAttribute(s,o,l,c,h,new ee),u.normal.dot(i.direction)>0&&u.normal.multiplyScalar(-1));let d={a:o,b:l,c,normal:new ee,materialIndex:0};ua.getNormal(ah,sh,oh,d.normal),u.face=d,u.barycoord=h}return u}var da=class R1 extends ar{constructor(t=1,r=1,i=1,n=1,a=1,s=1){super(),this.type="BoxGeometry",this.parameters={width:t,height:r,depth:i,widthSegments:n,heightSegments:a,depthSegments:s};let o=this;n=Math.floor(n),a=Math.floor(a),s=Math.floor(s);let l=[],c=[],u=[],h=[],d=0,f=0;y("z","y","x",-1,-1,i,r,t,s,a,0),y("z","y","x",1,-1,i,r,-t,s,a,1),y("x","z","y",1,1,t,i,r,n,s,2),y("x","z","y",1,-1,t,i,-r,n,s,3),y("x","y","z",1,-1,t,r,i,n,a,4),y("x","y","z",-1,-1,t,r,-i,n,a,5),this.setIndex(l),this.setAttribute("position",new Mt(c,3)),this.setAttribute("normal",new Mt(u,3)),this.setAttribute("uv",new Mt(h,2));function y(g,p,m,v,x,b,_,M,C,S,w){let E=b/C,P=_/S,N=b/2,D=_/2,B=M/2,J=C+1,Q=S+1,j=0,k=0,H=new ee;for(let U=0;U<Q;U++){let X=U*P-D;for(let W=0;W<J;W++){let $=W*E-N;H[g]=$*v,H[p]=X*x,H[m]=B,c.push(H.x,H.y,H.z),H[g]=0,H[p]=0,H[m]=M>0?1:-1,u.push(H.x,H.y,H.z),h.push(W/C),h.push(1-U/S),j+=1}}for(let U=0;U<S;U++)for(let X=0;X<C;X++){let W=d+X+J*U,$=d+X+J*(U+1),G=d+(X+1)+J*(U+1),T=d+(X+1)+J*U;l.push(W,$,T),l.push($,G,T),k+=6}o.addGroup(f,k,w),f+=k,d+=j}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new R1(t.width,t.height,t.depth,t.widthSegments,t.heightSegments,t.depthSegments)}};function xo(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 Hi(e){let t={};for(let r=0;r<e.length;r++){let i=xo(e[r]);for(let n in i)t[n]=i[n]}return t}function ww(e){let t=[];for(let r=0;r<e.length;r++)t.push(e[r].clone());return t}function T0(e){let t=e.getRenderTarget();return t===null?e.outputColorSpace:t.isXRRenderTarget===!0?t.texture.colorSpace:_r.workingColorSpace}var xn={clone:xo,merge:Hi},Ew=`void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}`,Mw=`void main() {
gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
}`,oi=class extends xi{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=Ew,this.fragmentShader=Mw,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=xo(e.uniforms),this.uniformsGroups=ww(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}},hh=class extends Ar{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new Jt,this.projectionMatrix=new Jt,this.projectionMatrixInverse=new Jt,this.coordinateSystem=Hn}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)}},ka=new ee,A0=new Xe,C0=new Xe,li=class extends hh{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=no*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){let e=Math.tan(ns*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return no*2*Math.atan(Math.tan(ns*.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){ka.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(ka.x,ka.y).multiplyScalar(-e/ka.z),ka.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),r.set(ka.x,ka.y).multiplyScalar(-e/ka.z)}getViewSize(e,t){return this.getViewBounds(e,A0,C0),t.subVectors(C0,A0)}setViewOffset(e,t,r,i,n,a){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=a,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){let e=this.near,t=e*Math.tan(ns*.5*this.fov)/this.zoom,r=2*t,i=this.aspect*r,n=-.5*i,a=this.view;if(this.view!==null&&this.view.enabled){let o=a.fullWidth,l=a.fullHeight;n+=a.offsetX*i/o,t-=a.offsetY*r/l,i*=a.width/o,r*=a.height/l}let s=this.filmOffset;s!==0&&(n+=e*s/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}},bo=-90,_o=1,R0=class extends Ar{constructor(e,t,r){super(),this.type="CubeCamera",this.renderTarget=r,this.coordinateSystem=null,this.activeMipmapLevel=0;let i=new li(bo,_o,e,t);i.layers=this.layers,this.add(i);let n=new li(bo,_o,e,t);n.layers=this.layers,this.add(n);let a=new li(bo,_o,e,t);a.layers=this.layers,this.add(a);let s=new li(bo,_o,e,t);s.layers=this.layers,this.add(s);let o=new li(bo,_o,e,t);o.layers=this.layers,this.add(o);let l=new li(bo,_o,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[r,i,n,a,s,o]=t;for(let l of t)this.remove(l);if(e===Hn)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),a.up.set(0,0,1),a.lookAt(0,-1,0),s.up.set(0,1,0),s.lookAt(0,0,1),o.up.set(0,1,0),o.lookAt(0,0,-1);else if(e===Rl)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),a.up.set(0,0,-1),a.lookAt(0,-1,0),s.up.set(0,-1,0),s.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,a,s,o,l,c]=this.children,u=e.getRenderTarget(),h=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),f=e.xr.enabled;e.xr.enabled=!1;let y=r.texture.generateMipmaps;r.texture.generateMipmaps=!1,e.setRenderTarget(r,0,i),e.render(t,n),e.setRenderTarget(r,1,i),e.render(t,a),e.setRenderTarget(r,2,i),e.render(t,s),e.setRenderTarget(r,3,i),e.render(t,o),e.setRenderTarget(r,4,i),e.render(t,l),r.texture.generateMipmaps=y,e.setRenderTarget(r,5,i),e.render(t,c),e.setRenderTarget(u,h,d),e.xr.enabled=f,r.texture.needsPMREMUpdate=!0}},Ul=class extends ei{constructor(e,t,r,i,n,a,s,o,l,c){e=e!==void 0?e:[],t=t!==void 0?t:ta,super(e,t,r,i,n,a,s,o,l,c),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},P0=class extends Pi{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 Ul(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:Zr}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 oi({name:"CubemapFromEquirect",uniforms:xo(r.uniforms),vertexShader:r.vertexShader,fragmentShader:r.fragmentShader,side:_t,blending:Ft});n.uniforms.tEquirect.value=t;let a=new hr(i,n),s=t.minFilter;return t.minFilter===mn&&(t.minFilter=Zr),new R0(1,10,this).update(e,a),t.minFilter=s,a.geometry.dispose(),a.material.dispose(),this}clear(e,t,r,i){let n=e.getRenderTarget();for(let a=0;a<6;a++)e.setRenderTarget(this,a),e.clear(t,r,i);e.setRenderTarget(n)}},I0=class P1{constructor(t,r=25e-5){this.isFogExp2=!0,this.name="",this.color=new yt(t),this.density=r}clone(){return new P1(this.color,this.density)}toJSON(){return{type:"FogExp2",name:this.name,color:this.color.getHex(),density:this.density}}},N0=class I1{constructor(t,r=1,i=1e3){this.isFog=!0,this.name="",this.color=new yt(t),this.near=r,this.far=i}clone(){return new I1(this.color,this.near,this.far)}toJSON(){return{type:"Fog",name:this.name,color:this.color.getHex(),near:this.near,far:this.far}}},us=class extends Ar{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 Nn,this.environmentIntensity=1,this.environmentRotation=new Nn,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}},Fl=class{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=e!==void 0?e.length/t:0,this.usage=Cl,this.updateRanges=[],this.version=0,this.uuid=rn()}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=rn()),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=rn()),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}}},Wi=new ee,wo=class N1{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++)Wi.fromBufferAttribute(this,r),Wi.applyMatrix4(t),this.setXYZ(r,Wi.x,Wi.y,Wi.z);return this}applyNormalMatrix(t){for(let r=0,i=this.count;r<i;r++)Wi.fromBufferAttribute(this,r),Wi.applyNormalMatrix(t),this.setXYZ(r,Wi.x,Wi.y,Wi.z);return this}transformDirection(t){for(let r=0,i=this.count;r<i;r++)Wi.fromBufferAttribute(this,r),Wi.transformDirection(t),this.setXYZ(r,Wi.x,Wi.y,Wi.z);return this}getComponent(t,r){let i=this.array[t*this.data.stride+this.offset+r];return this.normalized&&(i=Vi(i,this.array)),i}setComponent(t,r,i){return this.normalized&&(i=yr(i,this.array)),this.data.array[t*this.data.stride+this.offset+r]=i,this}setX(t,r){return this.normalized&&(r=yr(r,this.array)),this.data.array[t*this.data.stride+this.offset]=r,this}setY(t,r){return this.normalized&&(r=yr(r,this.array)),this.data.array[t*this.data.stride+this.offset+1]=r,this}setZ(t,r){return this.normalized&&(r=yr(r,this.array)),this.data.array[t*this.data.stride+this.offset+2]=r,this}setW(t,r){return this.normalized&&(r=yr(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=Vi(r,this.array)),r}getY(t){let r=this.data.array[t*this.data.stride+this.offset+1];return this.normalized&&(r=Vi(r,this.array)),r}getZ(t){let r=this.data.array[t*this.data.stride+this.offset+2];return this.normalized&&(r=Vi(r,this.array)),r}getW(t){let r=this.data.array[t*this.data.stride+this.offset+3];return this.normalized&&(r=Vi(r,this.array)),r}setXY(t,r,i){return t=t*this.data.stride+this.offset,this.normalized&&(r=yr(r,this.array),i=yr(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=yr(r,this.array),i=yr(i,this.array),n=yr(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,a){return t=t*this.data.stride+this.offset,this.normalized&&(r=yr(r,this.array),i=yr(i,this.array),n=yr(n,this.array),a=yr(a,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]=a,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 a=0;a<this.itemSize;a++)r.push(this.data.array[n+a])}return new Mr(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 N1(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 a=0;a<this.itemSize;a++)r.push(this.data.array[n+a])}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}}},dh=class extends xi{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new yt(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}},Eo,Bl=new ee,Mo=new ee,So=new ee,To=new Xe,zl=new Xe,L0=new Jt,ph=new ee,Gl=new ee,fh=new ee,O0=new Xe,Yp=new Xe,D0=new Xe,qp=class extends Ar{constructor(e=new dh){if(super(),this.isSprite=!0,this.type="Sprite",Eo===void 0){Eo=new ar;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 Fl(t,5);Eo.setIndex([0,1,2,0,2,3]),Eo.setAttribute("position",new wo(r,3,0,!1)),Eo.setAttribute("uv",new wo(r,2,3,!1))}this.geometry=Eo,this.material=e,this.center=new Xe(.5,.5)}raycast(e,t){e.camera===null&&console.error('THREE.Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.'),Mo.setFromMatrixScale(this.matrixWorld),L0.copy(e.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(e.camera.matrixWorldInverse,this.matrixWorld),So.setFromMatrixPosition(this.modelViewMatrix),e.camera.isPerspectiveCamera&&this.material.sizeAttenuation===!1&&Mo.multiplyScalar(-So.z);let r=this.material.rotation,i,n;r!==0&&(n=Math.cos(r),i=Math.sin(r));let a=this.center;mh(ph.set(-.5,-.5,0),So,a,Mo,i,n),mh(Gl.set(.5,-.5,0),So,a,Mo,i,n),mh(fh.set(.5,.5,0),So,a,Mo,i,n),O0.set(0,0),Yp.set(1,0),D0.set(1,1);let s=e.ray.intersectTriangle(ph,Gl,fh,!1,Bl);if(s===null&&(mh(Gl.set(-.5,.5,0),So,a,Mo,i,n),Yp.set(0,1),s=e.ray.intersectTriangle(ph,fh,Gl,!1,Bl),s===null))return;let o=e.ray.origin.distanceTo(Bl);o<e.near||o>e.far||t.push({distance:o,point:Bl.clone(),uv:ua.getInterpolation(Bl,ph,Gl,fh,O0,Yp,D0,new Xe),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 mh(e,t,r,i,n,a){To.subVectors(e,r).addScalar(.5).multiply(i),n!==void 0?(zl.x=a*To.x-n*To.y,zl.y=n*To.x+a*To.y):zl.copy(To),e.copy(t),e.x+=zl.x,e.y+=zl.y,e.applyMatrix4(L0)}var gh=new ee,k0=new ee,U0=class extends Ar{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){gh.setFromMatrixPosition(this.matrixWorld);let r=e.ray.origin.distanceTo(gh);this.getObjectForDistance(r).raycast(e,t)}}update(e){let t=this.levels;if(t.length>1){gh.setFromMatrixPosition(e.matrixWorld),k0.setFromMatrixPosition(this.matrixWorld);let r=gh.distanceTo(k0)/e.zoom;t[0].object.visible=!0;let i,n;for(i=1,n=t.length;i<n;i++){let a=t[i].distance;if(t[i].object.visible&&(a-=a*t[i].hysteresis),r>=a)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 a=r[i];t.object.levels.push({object:a.object.uuid,distance:a.distance,hysteresis:a.hysteresis})}return t}},F0=new ee,B0=new Nr,z0=new Nr,Sw=new ee,G0=new Jt,yh=new ee,Kp=new si,V0=new Jt,Zp=new ls,Qp=class extends hr{constructor(e,t){super(e,t),this.isSkinnedMesh=!0,this.type="SkinnedMesh",this.bindMode=cp,this.bindMatrix=new Jt,this.bindMatrixInverse=new Jt,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){let e=this.geometry;this.boundingBox===null&&(this.boundingBox=new Yr),this.boundingBox.makeEmpty();let t=e.getAttribute("position");for(let r=0;r<t.count;r++)this.getVertexPosition(r,yh),this.boundingBox.expandByPoint(yh)}computeBoundingSphere(){let e=this.geometry;this.boundingSphere===null&&(this.boundingSphere=new si),this.boundingSphere.makeEmpty();let t=e.getAttribute("position");for(let r=0;r<t.count;r++)this.getVertexPosition(r,yh),this.boundingSphere.expandByPoint(yh)}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(),Kp.copy(this.boundingSphere),Kp.applyMatrix4(i),e.ray.intersectsSphere(Kp)!==!1&&(V0.copy(i).invert(),Zp.copy(e.ray).applyMatrix4(V0),!(this.boundingBox!==null&&Zp.intersectsBox(this.boundingBox)===!1)&&this._computeIntersections(e,t,Zp)))}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 Nr,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===cp?this.bindMatrixInverse.copy(this.matrixWorld).invert():this.bindMode===Hg?this.bindMatrixInverse.copy(this.bindMatrix).invert():console.warn("THREE.SkinnedMesh: Unrecognized bindMode: "+this.bindMode)}applyBoneTransform(e,t){let r=this.skeleton,i=this.geometry;B0.fromBufferAttribute(i.attributes.skinIndex,e),z0.fromBufferAttribute(i.attributes.skinWeight,e),F0.copy(t).applyMatrix4(this.bindMatrix),t.set(0,0,0);for(let n=0;n<4;n++){let a=z0.getComponent(n);if(a!==0){let s=B0.getComponent(n);G0.multiplyMatrices(r.bones[s].matrixWorld,r.boneInverses[s]),t.addScaledVector(Sw.copy(F0).applyMatrix4(G0),a)}}return t.applyMatrix4(this.bindMatrixInverse)}},vh=class extends Ar{constructor(){super(),this.isBone=!0,this.type="Bone"}},sn=class extends ei{constructor(e=null,t=1,r=1,i,n,a,s,o,l=Kr,c=Kr,u,h){super(null,a,s,o,l,c,i,n,u,h),this.isDataTexture=!0,this.image={data:e,width:t,height:r},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}},H0=new Jt,Tw=new Jt,Jp=class L1{constructor(t=[],r=[]){this.uuid=rn(),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 Jt)}}calculateInverses(){this.boneInverses.length=0;for(let t=0,r=this.bones.length;t<r;t++){let i=new Jt;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 a=0,s=t.length;a<s;a++){let o=t[a]?t[a].matrixWorld:Tw;H0.multiplyMatrices(o,r[a]),H0.toArray(i,a*16)}n!==null&&(n.needsUpdate=!0)}clone(){return new L1(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 sn(r,t,t,Li,Xi);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 a=t.bones[i],s=r[a];s===void 0&&(console.warn("THREE.Skeleton: No bone found with UUID:",a),s=new vh),this.bones.push(s),this.boneInverses.push(new Jt().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,a=r.length;n<a;n++){let s=r[n];t.bones.push(s.uuid);let o=i[n];t.boneInverses.push(o.toArray())}return t}},hs=class extends Mr{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}},Ao=new Jt,W0=new Jt,xh=[],j0=new Yr,Aw=new Jt,Vl=new hr,Hl=new si,bh=class extends hr{constructor(e,t,r){super(e,t),this.isInstancedMesh=!0,this.instanceMatrix=new hs(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,Aw)}computeBoundingBox(){let e=this.geometry,t=this.count;this.boundingBox===null&&(this.boundingBox=new Yr),e.boundingBox===null&&e.computeBoundingBox(),this.boundingBox.makeEmpty();for(let r=0;r<t;r++)this.getMatrixAt(r,Ao),j0.copy(e.boundingBox).applyMatrix4(Ao),this.boundingBox.union(j0)}computeBoundingSphere(){let e=this.geometry,t=this.count;this.boundingSphere===null&&(this.boundingSphere=new si),e.boundingSphere===null&&e.computeBoundingSphere(),this.boundingSphere.makeEmpty();for(let r=0;r<t;r++)this.getMatrixAt(r,Ao),Hl.copy(e.boundingSphere).applyMatrix4(Ao),this.boundingSphere.union(Hl)}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,a=e*n+1;for(let s=0;s<r.length;s++)r[s]=i[a+s]}raycast(e,t){let r=this.matrixWorld,i=this.count;if(Vl.geometry=this.geometry,Vl.material=this.material,Vl.material!==void 0&&(this.boundingSphere===null&&this.computeBoundingSphere(),Hl.copy(this.boundingSphere),Hl.applyMatrix4(r),e.ray.intersectsSphere(Hl)!==!1))for(let n=0;n<i;n++){this.getMatrixAt(n,Ao),W0.multiplyMatrices(r,Ao),Vl.matrixWorld=W0,Vl.raycast(e,xh);for(let a=0,s=xh.length;a<s;a++){let o=xh[a];o.instanceId=n,o.object=this,t.push(o)}xh.length=0}}setColorAt(e,t){this.instanceColor===null&&(this.instanceColor=new hs(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 sn(new Float32Array(i*this.count),i,this.count,fu,Xi));let n=this.morphTexture.source.data.data,a=0;for(let l=0;l<r.length;l++)a+=r[l];let s=this.geometry.morphTargetsRelative?1:1-a,o=i*e;n[o]=s,n.set(r,o+1)}updateMorphTargets(){}dispose(){return this.dispatchEvent({type:"dispose"}),this.morphTexture!==null&&(this.morphTexture.dispose(),this.morphTexture=null),this}},$p=new ee,Cw=new ee,Rw=new xr,pa=class{constructor(e=new ee(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=$p.subVectors(r,t).cross(Cw.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($p),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||Rw.getNormalMatrix(e),i=this.coplanarPoint($p).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)}},ds=new si,_h=new ee,Wl=class{constructor(e=new pa,t=new pa,r=new pa,i=new pa,n=new pa,a=new pa){this.planes=[e,t,r,i,n,a]}set(e,t,r,i,n,a){let s=this.planes;return s[0].copy(e),s[1].copy(t),s[2].copy(r),s[3].copy(i),s[4].copy(n),s[5].copy(a),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=Hn){let r=this.planes,i=e.elements,n=i[0],a=i[1],s=i[2],o=i[3],l=i[4],c=i[5],u=i[6],h=i[7],d=i[8],f=i[9],y=i[10],g=i[11],p=i[12],m=i[13],v=i[14],x=i[15];if(r[0].setComponents(o-n,h-l,g-d,x-p).normalize(),r[1].setComponents(o+n,h+l,g+d,x+p).normalize(),r[2].setComponents(o+a,h+c,g+f,x+m).normalize(),r[3].setComponents(o-a,h-c,g-f,x-m).normalize(),r[4].setComponents(o-s,h-u,g-y,x-v).normalize(),t===Hn)r[5].setComponents(o+s,h+u,g+y,x+v).normalize();else if(t===Rl)r[5].setComponents(s,u,y,v).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(),ds.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),ds.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(ds)}intersectsSprite(e){return ds.center.set(0,0,0),ds.radius=.7071067811865476,ds.applyMatrix4(e.matrixWorld),this.intersectsSphere(ds)}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(_h.x=i.normal.x>0?e.max.x:e.min.x,_h.y=i.normal.y>0?e.max.y:e.min.y,_h.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(_h)<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 ef(e,t){return e-t}function Pw(e,t){return e.z-t.z}function Iw(e,t){return t.z-e.z}var Nw=class{constructor(){this.index=0,this.pool=[],this.list=[]}push(e,t,r,i){let n=this.pool,a=this.list;this.index>=n.length&&n.push({start:-1,count:-1,z:-1,index:-1});let s=n[this.index];a.push(s),this.index++,s.start=e,s.count=t,s.z=r,s.index=i}reset(){this.list.length=0,this.index=0}},qi=new Jt,Lw=new yt(1,1,1),tf=new Wl,wh=new Yr,ps=new si,jl=new ee,X0=new ee,Ow=new ee,rf=new Nw,Ui=new hr,Eh=[];function Dw(e,t,r=0){let i=t.itemSize;if(e.isInterleavedBufferAttribute||e.array.constructor!==t.array.constructor){let n=e.count;for(let a=0;a<n;a++)for(let s=0;s<i;s++)t.setComponent(a+r,s,e.getComponent(a,s))}else t.array.set(e.array,r*i);t.needsUpdate=!0}function fs(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 Y0=class extends hr{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 ar,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 sn(t,e,e,Li,Xi);this._matricesTexture=r}_initIndirectTexture(){let e=Math.sqrt(this._maxInstanceCount);e=Math.ceil(e);let t=new Uint32Array(e*e),r=new sn(t,e,e,bl,ra);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 sn(t,e,e,Li,Xi);r.colorSpace=_r.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 a=e.getAttribute(n),{array:s,itemSize:o,normalized:l}=a,c=new s.constructor(r*o),u=new Mr(c,o,l);t.setAttribute(n,u)}if(e.getIndex()!==null){let n=r>65535?new Uint32Array(i):new Uint16Array(i);t.setIndex(new Mr(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 Yr);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,qi),this.getBoundingBoxAt(n,wh).applyMatrix4(qi),e.union(wh)}}computeBoundingSphere(){this.boundingSphere===null&&(this.boundingSphere=new si);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,qi),this.getBoundingSphereAt(n,ps).applyMatrix4(qi),e.union(ps)}}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(ef),r=this._availableInstanceIds.shift(),this._instanceInfo[r]=t):(r=this._instanceInfo.length,this._instanceInfo.push(t));let i=this._matricesTexture;qi.identity().toArray(i.image.data,r*16),i.needsUpdate=!0;let n=this._colorsTexture;return n&&(Lw.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 a=e.getIndex();if(a!==null&&(i.indexStart=this._nextIndexStart,i.reservedIndexCount=r===-1?a.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 s;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(ef),s=this._availableGeometryIds.shift(),n[s]=i):(s=this._geometryCount,this._geometryCount++,n.push(i)),this.setGeometryAt(s,e),this._nextIndexStart=i.indexStart+i.reservedIndexCount,this._nextVertexStart=i.vertexStart+i.reservedVertexCount,s}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(),a=t.getIndex(),s=this._geometryInfo[e];if(i&&a.count>s.reservedIndexCount||t.attributes.position.count>s.reservedVertexCount)throw new Error("THREE.BatchedMesh: Reserved space not large enough for provided geometry.");let o=s.vertexStart,l=s.reservedVertexCount;s.vertexCount=t.getAttribute("position").count;for(let c in r.attributes){let u=t.getAttribute(c),h=r.getAttribute(c);Dw(u,h,o);let d=u.itemSize;for(let f=u.count,y=l;f<y;f++){let g=o+f;for(let p=0;p<d;p++)h.setComponent(g,p,0)}h.needsUpdate=!0,h.addUpdateRange(o*d,l*d)}if(i){let c=s.indexStart,u=s.reservedIndexCount;s.indexCount=t.getIndex().count;for(let h=0;h<a.count;h++)n.setX(c+h,o+a.getX(h));for(let h=a.count,d=u;h<d;h++)n.setX(c+h,o);n.needsUpdate=!0,n.addUpdateRange(c,s.reservedIndexCount)}return s.start=i?s.indexStart:s.vertexStart,s.count=i?s.indexCount:s.vertexCount,s.boundingBox=null,t.boundingBox!==null&&(s.boundingBox=t.boundingBox.clone()),s.boundingSphere=null,t.boundingSphere!==null&&(s.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((a,s)=>s).sort((a,s)=>r[a].vertexStart-r[s].vertexStart),n=this.geometry;for(let a=0,s=r.length;a<s;a++){let o=i[a],l=r[o];if(l.active!==!1){if(n.index!==null){if(l.indexStart!==t){let{indexStart:c,vertexStart:u,reservedIndexCount:h}=l,d=n.index,f=d.array,y=e-u;for(let g=c;g<c+h;g++)f[g]=f[g]+y;d.array.copyWithin(t,c,c+h),d.addUpdateRange(t,h),l.indexStart=t}t+=l.reservedIndexCount}if(l.vertexStart!==e){let{vertexStart:c,reservedVertexCount:u}=l,h=n.attributes;for(let d in h){let f=h[d],{array:y,itemSize:g}=f;y.copyWithin(e*g,c*g,(c+u)*g),f.addUpdateRange(e*g,u*g)}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 Yr,a=r.index,s=r.attributes.position;for(let o=i.start,l=i.start+i.count;o<l;o++){let c=o;a&&(c=a.getX(c)),n.expandByPoint(jl.fromBufferAttribute(s,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 si;this.getBoundingBoxAt(e,wh),wh.getCenter(n.center);let a=r.index,s=r.attributes.position,o=0;for(let l=i.start,c=i.start+i.count;l<c;l++){let u=l;a&&(u=a.getX(u)),jl.fromBufferAttribute(s,u),o=Math.max(o,n.center.distanceToSquared(jl))}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(ef);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);fs(this._multiDrawCounts,i),fs(this._multiDrawStarts,n),this._multiDrawCounts=i,this._multiDrawStarts=n,this._maxInstanceCount=e;let a=this._indirectTexture,s=this._matricesTexture,o=this._colorsTexture;a.dispose(),this._initIndirectTexture(),fs(a.image.data,this._indirectTexture.image.data),s.dispose(),this._initMatricesTexture(),fs(s.image.data,this._matricesTexture.image.data),o&&(o.dispose(),this._initColorsTexture(),fs(o.image.data,this._colorsTexture.image.data))}setGeometrySize(e,t){let r=[...this._geometryInfo].filter(a=>a.active);if(Math.max(...r.map(a=>a.vertexStart+a.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(a=>a.indexStart+a.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 ar,this._initializeGeometry(i));let n=this.geometry;i.index&&fs(i.index.array,n.index.array);for(let a in i.attributes)fs(i.attributes[a].array,n.attributes[a].array)}raycast(e,t){let r=this._instanceInfo,i=this._geometryInfo,n=this.matrixWorld,a=this.geometry;Ui.material=this.material,Ui.geometry.index=a.index,Ui.geometry.attributes=a.attributes,Ui.geometry.boundingBox===null&&(Ui.geometry.boundingBox=new Yr),Ui.geometry.boundingSphere===null&&(Ui.geometry.boundingSphere=new si);for(let s=0,o=r.length;s<o;s++){if(!r[s].visible||!r[s].active)continue;let l=r[s].geometryIndex,c=i[l];Ui.geometry.setDrawRange(c.start,c.count),this.getMatrixAt(s,Ui.matrixWorld).premultiply(n),this.getBoundingBoxAt(l,Ui.geometry.boundingBox),this.getBoundingSphereAt(l,Ui.geometry.boundingSphere),Ui.raycast(e,Eh);for(let u=0,h=Eh.length;u<h;u++){let d=Eh[u];d.object=this,d.batchId=s,t.push(d)}Eh.length=0}Ui.material=null,Ui.geometry.index=null,Ui.geometry.attributes={},Ui.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 a=i.getIndex(),s=a===null?1:a.array.BYTES_PER_ELEMENT,o=this._instanceInfo,l=this._multiDrawStarts,c=this._multiDrawCounts,u=this._geometryInfo,h=this.perObjectFrustumCulled,d=this._indirectTexture,f=d.image.data;h&&(qi.multiplyMatrices(r.projectionMatrix,r.matrixWorldInverse).multiply(this.matrixWorld),tf.setFromProjectionMatrix(qi,e.coordinateSystem));let y=0;if(this.sortObjects){qi.copy(this.matrixWorld).invert(),jl.setFromMatrixPosition(r.matrixWorld).applyMatrix4(qi),X0.set(0,0,-1).transformDirection(r.matrixWorld).transformDirection(qi);for(let m=0,v=o.length;m<v;m++)if(o[m].visible&&o[m].active){let x=o[m].geometryIndex;this.getMatrixAt(m,qi),this.getBoundingSphereAt(x,ps).applyMatrix4(qi);let b=!1;if(h&&(b=!tf.intersectsSphere(ps)),!b){let _=u[x],M=Ow.subVectors(ps.center,jl).dot(X0);rf.push(_.start,_.count,M,m)}}let g=rf.list,p=this.customSort;p===null?g.sort(n.transparent?Iw:Pw):p.call(this,g,r);for(let m=0,v=g.length;m<v;m++){let x=g[m];l[y]=x.start*s,c[y]=x.count,f[y]=x.index,y++}rf.reset()}else for(let g=0,p=o.length;g<p;g++)if(o[g].visible&&o[g].active){let m=o[g].geometryIndex,v=!1;if(h&&(this.getMatrixAt(g,qi),this.getBoundingSphereAt(m,ps).applyMatrix4(qi),v=!tf.intersectsSphere(ps)),!v){let x=u[m];l[y]=x.start*s,c[y]=x.count,f[y]=g,y++}}d.needsUpdate=!0,this._multiDrawCount=y,this._visibilityChanged=!1}onBeforeShadow(e,t,r,i,n,a){this.onBeforeRender(e,null,i,n,a)}},ri=class extends xi{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new yt(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}},Mh=new ee,Sh=new ee,q0=new Jt,Xl=new ls,Th=new si,nf=new ee,K0=new ee,jn=class extends Ar{constructor(e=new ar,t=new ri){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++)Mh.fromBufferAttribute(t,i-1),Sh.fromBufferAttribute(t,i),r[i]=r[i-1],r[i]+=Mh.distanceTo(Sh);e.setAttribute("lineDistance",new Mt(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,a=r.drawRange;if(r.boundingSphere===null&&r.computeBoundingSphere(),Th.copy(r.boundingSphere),Th.applyMatrix4(i),Th.radius+=n,e.ray.intersectsSphere(Th)===!1)return;q0.copy(i).invert(),Xl.copy(e.ray).applyMatrix4(q0);let s=n/((this.scale.x+this.scale.y+this.scale.z)/3),o=s*s,l=this.isLineSegments?2:1,c=r.index,u=r.attributes.position;if(c!==null){let h=Math.max(0,a.start),d=Math.min(c.count,a.start+a.count);for(let f=h,y=d-1;f<y;f+=l){let g=c.getX(f),p=c.getX(f+1),m=Ah(this,e,Xl,o,g,p);m&&t.push(m)}if(this.isLineLoop){let f=c.getX(d-1),y=c.getX(h),g=Ah(this,e,Xl,o,f,y);g&&t.push(g)}}else{let h=Math.max(0,a.start),d=Math.min(u.count,a.start+a.count);for(let f=h,y=d-1;f<y;f+=l){let g=Ah(this,e,Xl,o,f,f+1);g&&t.push(g)}if(this.isLineLoop){let f=Ah(this,e,Xl,o,d-1,h);f&&t.push(f)}}}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 a=r[i].name||String(i);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=i}}}}};function Ah(e,t,r,i,n,a){let s=e.geometry.attributes.position;if(Mh.fromBufferAttribute(s,n),Sh.fromBufferAttribute(s,a),r.distanceSqToSegment(Mh,Sh,nf,K0)>i)return;nf.applyMatrix4(e.matrixWorld);let o=t.ray.origin.distanceTo(nf);if(!(o<t.near||o>t.far))return{distance:o,point:K0.clone().applyMatrix4(e.matrixWorld),index:n,face:null,faceIndex:null,barycoord:null,object:e}}var Z0=new ee,Q0=new ee,Fi=class extends jn{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)Z0.fromBufferAttribute(t,i),Q0.fromBufferAttribute(t,i+1),r[i]=i===0?0:r[i-1],r[i+1]=r[i]+Z0.distanceTo(Q0);e.setAttribute("lineDistance",new Mt(r,1))}else console.warn("THREE.LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}},Ch=class extends jn{constructor(e,t){super(e,t),this.isLineLoop=!0,this.type="LineLoop"}},Yl=class extends xi{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new yt(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}},J0=new Jt,af=new ls,Rh=new si,Ph=new ee,Ih=class extends Ar{constructor(e=new ar,t=new Yl){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,a=r.drawRange;if(r.boundingSphere===null&&r.computeBoundingSphere(),Rh.copy(r.boundingSphere),Rh.applyMatrix4(i),Rh.radius+=n,e.ray.intersectsSphere(Rh)===!1)return;J0.copy(i).invert(),af.copy(e.ray).applyMatrix4(J0);let s=n/((this.scale.x+this.scale.y+this.scale.z)/3),o=s*s,l=r.index,c=r.attributes.position;if(l!==null){let u=Math.max(0,a.start),h=Math.min(l.count,a.start+a.count);for(let d=u,f=h;d<f;d++){let y=l.getX(d);Ph.fromBufferAttribute(c,y),$0(Ph,y,o,i,e,t,this)}}else{let u=Math.max(0,a.start),h=Math.min(c.count,a.start+a.count);for(let d=u,f=h;d<f;d++)Ph.fromBufferAttribute(c,d),$0(Ph,d,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 a=r[i].name||String(i);this.morphTargetInfluences.push(0),this.morphTargetDictionary[a]=i}}}}};function $0(e,t,r,i,n,a,s){let o=af.distanceSqToPoint(e);if(o<r){let l=new ee;af.closestPointToPoint(e,l),l.applyMatrix4(i);let c=n.ray.origin.distanceTo(l);if(c<n.near||c>n.far)return;a.push({distance:c,distanceToRay:Math.sqrt(o),point:l,index:t,face:null,faceIndex:null,barycoord:null,object:s})}}var jr=class extends Ar{constructor(){super(),this.isGroup=!0,this.type="Group"}},kw=class extends ei{constructor(e,t,r,i,n,a,s,o,l){super(e,t,r,i,n,a,s,o,l),this.isVideoTexture=!0,this.minFilter=a!==void 0?a:Zr,this.magFilter=n!==void 0?n:Zr,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)}},Uw=class extends ei{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=Kr,this.minFilter=Kr,this.generateMipmaps=!1,this.needsUpdate=!0}},Nh=class extends ei{constructor(e,t,r,i,n,a,s,o,l,c,u,h){super(null,a,s,o,l,c,i,n,u,h),this.isCompressedTexture=!0,this.image={width:t,height:r},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}},Fw=class extends Nh{constructor(e,t,r,i,n,a){super(e,t,r,n,a),this.isCompressedArrayTexture=!0,this.image.depth=i,this.wrapR=Ri,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},Bw=class extends Nh{constructor(e,t,r){super(void 0,e[0].width,e[0].height,t,r,ta),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}},Lh=class extends ei{constructor(e,t,r,i,n,a,s,o,l){super(e,t,r,i,n,a,s,o,l),this.isCanvasTexture=!0,this.needsUpdate=!0}},Oh=class extends ei{constructor(e,t,r,i,n,a,s,o,l,c=es){if(c!==es&&c!==Ra)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");r===void 0&&c===es&&(r=ra),r===void 0&&c===Ra&&(r=Ca),super(null,i,n,a,s,o,c,r,l),this.isDepthTexture=!0,this.image={width:e,height:t},this.magFilter=s!==void 0?s:Kr,this.minFilter=o!==void 0?o:Kr,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}},On=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 a=1;a<=e;a++)r=this.getPoint(a/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,a;t?a=t:a=e*r[n-1];let s=0,o=n-1,l;for(;s<=o;)if(i=Math.floor(s+(o-s)/2),l=r[i]-a,l<0)s=i+1;else if(l>0)o=i-1;else{o=i;break}if(i=o,r[i]===a)return i/(n-1);let c=r[i],u=r[i+1]-c,h=(a-c)/u;return(i+h)/(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),a=this.getPoint(i),s=t||(n.isVector2?new Xe:new ee);return s.copy(a).sub(n).normalize(),s}getTangentAt(e,t){let r=this.getUtoTmapping(e);return this.getTangent(r,t)}computeFrenetFrames(e,t){let r=new ee,i=[],n=[],a=[],s=new ee,o=new Jt;for(let d=0;d<=e;d++){let f=d/e;i[d]=this.getTangentAt(f,new ee)}n[0]=new ee,a[0]=new ee;let l=Number.MAX_VALUE,c=Math.abs(i[0].x),u=Math.abs(i[0].y),h=Math.abs(i[0].z);c<=l&&(l=c,r.set(1,0,0)),u<=l&&(l=u,r.set(0,1,0)),h<=l&&r.set(0,0,1),s.crossVectors(i[0],r).normalize(),n[0].crossVectors(i[0],s),a[0].crossVectors(i[0],n[0]);for(let d=1;d<=e;d++){if(n[d]=n[d-1].clone(),a[d]=a[d-1].clone(),s.crossVectors(i[d-1],i[d]),s.length()>Number.EPSILON){s.normalize();let f=Math.acos(mr(i[d-1].dot(i[d]),-1,1));n[d].applyMatrix4(o.makeRotationAxis(s,f))}a[d].crossVectors(i[d],n[d])}if(t===!0){let d=Math.acos(mr(n[0].dot(n[e]),-1,1));d/=e,i[0].dot(s.crossVectors(n[0],n[e]))>0&&(d=-d);for(let f=1;f<=e;f++)n[f].applyMatrix4(o.makeRotationAxis(i[f],d*f)),a[f].crossVectors(i[f],n[f])}return{tangents:i,normals:n,binormals:a}}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}},Dh=class extends On{constructor(e=0,t=0,r=1,i=1,n=0,a=Math.PI*2,s=!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=a,this.aClockwise=s,this.aRotation=o}getPoint(e,t=new Xe){let r=t,i=Math.PI*2,n=this.aEndAngle-this.aStartAngle,a=Math.abs(n)<Number.EPSILON;for(;n<0;)n+=i;for(;n>i;)n-=i;n<Number.EPSILON&&(a?n=0:n=i),this.aClockwise===!0&&!a&&(n===i?n=-i:n=n-i);let s=this.aStartAngle+e*n,o=this.aX+this.xRadius*Math.cos(s),l=this.aY+this.yRadius*Math.sin(s);if(this.aRotation!==0){let c=Math.cos(this.aRotation),u=Math.sin(this.aRotation),h=o-this.aX,d=l-this.aY;o=h*c-d*u+this.aX,l=h*u+d*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}},ey=class extends Dh{constructor(e,t,r,i,n,a){super(e,t,r,r,i,n,a),this.isArcCurve=!0,this.type="ArcCurve"}};function sf(){let e=0,t=0,r=0,i=0;function n(a,s,o,l){e=a,t=o,r=-3*a+3*s-2*o-l,i=2*a-2*s+o+l}return{initCatmullRom:function(a,s,o,l,c){n(s,o,c*(o-a),c*(l-s))},initNonuniformCatmullRom:function(a,s,o,l,c,u,h){let d=(s-a)/c-(o-a)/(c+u)+(o-s)/u,f=(o-s)/u-(l-s)/(u+h)+(l-o)/h;d*=u,f*=u,n(s,o,d,f)},calc:function(a){let s=a*a,o=s*a;return e+t*a+r*s+i*o}}}var kh=new ee,of=new sf,lf=new sf,cf=new sf,ty=class extends On{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 ee){let r=t,i=this.points,n=i.length,a=(n-(this.closed?0:1))*e,s=Math.floor(a),o=a-s;this.closed?s+=s>0?0:(Math.floor(Math.abs(s)/n)+1)*n:o===0&&s===n-1&&(s=n-2,o=1);let l,c;this.closed||s>0?l=i[(s-1)%n]:(kh.subVectors(i[0],i[1]).add(i[0]),l=kh);let u=i[s%n],h=i[(s+1)%n];if(this.closed||s+2<n?c=i[(s+2)%n]:(kh.subVectors(i[n-1],i[n-2]).add(i[n-1]),c=kh),this.curveType==="centripetal"||this.curveType==="chordal"){let d=this.curveType==="chordal"?.5:.25,f=Math.pow(l.distanceToSquared(u),d),y=Math.pow(u.distanceToSquared(h),d),g=Math.pow(h.distanceToSquared(c),d);y<1e-4&&(y=1),f<1e-4&&(f=y),g<1e-4&&(g=y),of.initNonuniformCatmullRom(l.x,u.x,h.x,c.x,f,y,g),lf.initNonuniformCatmullRom(l.y,u.y,h.y,c.y,f,y,g),cf.initNonuniformCatmullRom(l.z,u.z,h.z,c.z,f,y,g)}else this.curveType==="catmullrom"&&(of.initCatmullRom(l.x,u.x,h.x,c.x,this.tension),lf.initCatmullRom(l.y,u.y,h.y,c.y,this.tension),cf.initCatmullRom(l.z,u.z,h.z,c.z,this.tension));return r.set(of.calc(o),lf.calc(o),cf.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 ee().fromArray(i))}return this.closed=e.closed,this.curveType=e.curveType,this.tension=e.tension,this}};function ry(e,t,r,i,n){let a=(i-t)*.5,s=(n-r)*.5,o=e*e,l=e*o;return(2*r-2*i+a+s)*l+(-3*r+3*i-2*a-s)*o+a*e+r}function zw(e,t){let r=1-e;return r*r*t}function Gw(e,t){return 2*(1-e)*e*t}function Vw(e,t){return e*e*t}function ql(e,t,r,i){return zw(e,t)+Gw(e,r)+Vw(e,i)}function Hw(e,t){let r=1-e;return r*r*r*t}function Ww(e,t){let r=1-e;return 3*r*r*e*t}function jw(e,t){return 3*(1-e)*e*e*t}function Xw(e,t){return e*e*e*t}function Kl(e,t,r,i,n){return Hw(e,t)+Ww(e,r)+jw(e,i)+Xw(e,n)}var uf=class extends On{constructor(e=new Xe,t=new Xe,r=new Xe,i=new Xe){super(),this.isCubicBezierCurve=!0,this.type="CubicBezierCurve",this.v0=e,this.v1=t,this.v2=r,this.v3=i}getPoint(e,t=new Xe){let r=t,i=this.v0,n=this.v1,a=this.v2,s=this.v3;return r.set(Kl(e,i.x,n.x,a.x,s.x),Kl(e,i.y,n.y,a.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.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}},iy=class extends On{constructor(e=new ee,t=new ee,r=new ee,i=new ee){super(),this.isCubicBezierCurve3=!0,this.type="CubicBezierCurve3",this.v0=e,this.v1=t,this.v2=r,this.v3=i}getPoint(e,t=new ee){let r=t,i=this.v0,n=this.v1,a=this.v2,s=this.v3;return r.set(Kl(e,i.x,n.x,a.x,s.x),Kl(e,i.y,n.y,a.y,s.y),Kl(e,i.z,n.z,a.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.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}},hf=class extends On{constructor(e=new Xe,t=new Xe){super(),this.isLineCurve=!0,this.type="LineCurve",this.v1=e,this.v2=t}getPoint(e,t=new Xe){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 Xe){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}},ny=class extends On{constructor(e=new ee,t=new ee){super(),this.isLineCurve3=!0,this.type="LineCurve3",this.v1=e,this.v2=t}getPoint(e,t=new ee){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 ee){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}},df=class extends On{constructor(e=new Xe,t=new Xe,r=new Xe){super(),this.isQuadraticBezierCurve=!0,this.type="QuadraticBezierCurve",this.v0=e,this.v1=t,this.v2=r}getPoint(e,t=new Xe){let r=t,i=this.v0,n=this.v1,a=this.v2;return r.set(ql(e,i.x,n.x,a.x),ql(e,i.y,n.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}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}},pf=class extends On{constructor(e=new ee,t=new ee,r=new ee){super(),this.isQuadraticBezierCurve3=!0,this.type="QuadraticBezierCurve3",this.v0=e,this.v1=t,this.v2=r}getPoint(e,t=new ee){let r=t,i=this.v0,n=this.v1,a=this.v2;return r.set(ql(e,i.x,n.x,a.x),ql(e,i.y,n.y,a.y),ql(e,i.z,n.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}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}},ff=class extends On{constructor(e=[]){super(),this.isSplineCurve=!0,this.type="SplineCurve",this.points=e}getPoint(e,t=new Xe){let r=t,i=this.points,n=(i.length-1)*e,a=Math.floor(n),s=n-a,o=i[a===0?a:a-1],l=i[a],c=i[a>i.length-2?i.length-1:a+1],u=i[a>i.length-3?i.length-1:a+2];return r.set(ry(s,o.x,l.x,c.x,u.x),ry(s,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 Xe().fromArray(i))}return this}},Uh=Object.freeze({__proto__:null,ArcCurve:ey,CatmullRomCurve3:ty,CubicBezierCurve:uf,CubicBezierCurve3:iy,EllipseCurve:Dh,LineCurve:hf,LineCurve3:ny,QuadraticBezierCurve:df,QuadraticBezierCurve3:pf,SplineCurve:ff}),ay=class extends On{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 Uh[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 a=i[n]-r,s=this.curves[n],o=s.getLength(),l=o===0?0:1-a/o;return s.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 a=n[i],s=a.isEllipseCurve?e*2:a.isLineCurve||a.isLineCurve3?1:a.isSplineCurve?e*a.points.length:e,o=a.getPoints(s);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 Uh[i.type]().fromJSON(i))}return this}},Co=class extends ay{constructor(e){super(),this.type="Path",this.currentPoint=new Xe,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 hf(this.currentPoint.clone(),new Xe(e,t));return this.curves.push(r),this.currentPoint.set(e,t),this}quadraticCurveTo(e,t,r,i){let n=new df(this.currentPoint.clone(),new Xe(e,t),new Xe(r,i));return this.curves.push(n),this.currentPoint.set(r,i),this}bezierCurveTo(e,t,r,i,n,a){let s=new uf(this.currentPoint.clone(),new Xe(e,t),new Xe(r,i),new Xe(n,a));return this.curves.push(s),this.currentPoint.set(n,a),this}splineThru(e){let t=[this.currentPoint.clone()].concat(e),r=new ff(t);return this.curves.push(r),this.currentPoint.copy(e[e.length-1]),this}arc(e,t,r,i,n,a){let s=this.currentPoint.x,o=this.currentPoint.y;return this.absarc(e+s,t+o,r,i,n,a),this}absarc(e,t,r,i,n,a){return this.absellipse(e,t,r,r,i,n,a),this}ellipse(e,t,r,i,n,a,s,o){let l=this.currentPoint.x,c=this.currentPoint.y;return this.absellipse(e+l,t+c,r,i,n,a,s,o),this}absellipse(e,t,r,i,n,a,s,o){let l=new Dh(e,t,r,i,n,a,s,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}},mf=class O1 extends ar{constructor(t=[new Xe(0,-.5),new Xe(.5,0),new Xe(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=mr(n,0,Math.PI*2);let a=[],s=[],o=[],l=[],c=[],u=1/r,h=new ee,d=new Xe,f=new ee,y=new ee,g=new ee,p=0,m=0;for(let v=0;v<=t.length-1;v++)switch(v){case 0:p=t[v+1].x-t[v].x,m=t[v+1].y-t[v].y,f.x=m*1,f.y=-p,f.z=m*0,g.copy(f),f.normalize(),l.push(f.x,f.y,f.z);break;case t.length-1:l.push(g.x,g.y,g.z);break;default:p=t[v+1].x-t[v].x,m=t[v+1].y-t[v].y,f.x=m*1,f.y=-p,f.z=m*0,y.copy(f),f.x+=g.x,f.y+=g.y,f.z+=g.z,f.normalize(),l.push(f.x,f.y,f.z),g.copy(y)}for(let v=0;v<=r;v++){let x=i+v*u*n,b=Math.sin(x),_=Math.cos(x);for(let M=0;M<=t.length-1;M++){h.x=t[M].x*b,h.y=t[M].y,h.z=t[M].x*_,s.push(h.x,h.y,h.z),d.x=v/r,d.y=M/(t.length-1),o.push(d.x,d.y);let C=l[3*M+0]*b,S=l[3*M+1],w=l[3*M+0]*_;c.push(C,S,w)}}for(let v=0;v<r;v++)for(let x=0;x<t.length-1;x++){let b=x+v*t.length,_=b,M=b+t.length,C=b+t.length+1,S=b+1;a.push(_,M,S),a.push(C,S,M)}this.setIndex(a),this.setAttribute("position",new Mt(s,3)),this.setAttribute("uv",new Mt(o,2)),this.setAttribute("normal",new Mt(c,3))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new O1(t.points,t.segments,t.phiStart,t.phiLength)}},sy=class D1 extends mf{constructor(t=1,r=1,i=4,n=8){let a=new Co;a.absarc(0,-r/2,t,Math.PI*1.5,0),a.absarc(0,r/2,t,0,Math.PI*.5),super(a.getPoints(i),n),this.type="CapsuleGeometry",this.parameters={radius:t,length:r,capSegments:i,radialSegments:n}}static fromJSON(t){return new D1(t.radius,t.length,t.capSegments,t.radialSegments)}},oy=class k1 extends ar{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 a=[],s=[],o=[],l=[],c=new ee,u=new Xe;s.push(0,0,0),o.push(0,0,1),l.push(.5,.5);for(let h=0,d=3;h<=r;h++,d+=3){let f=i+h/r*n;c.x=t*Math.cos(f),c.y=t*Math.sin(f),s.push(c.x,c.y,c.z),o.push(0,0,1),u.x=(s[d]/t+1)/2,u.y=(s[d+1]/t+1)/2,l.push(u.x,u.y)}for(let h=1;h<=r;h++)a.push(h,h+1,0);this.setIndex(a),this.setAttribute("position",new Mt(s,3)),this.setAttribute("normal",new Mt(o,3)),this.setAttribute("uv",new Mt(l,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new k1(t.radius,t.segments,t.thetaStart,t.thetaLength)}},Zl=class U1 extends ar{constructor(t=1,r=1,i=1,n=32,a=1,s=!1,o=0,l=Math.PI*2){super(),this.type="CylinderGeometry",this.parameters={radiusTop:t,radiusBottom:r,height:i,radialSegments:n,heightSegments:a,openEnded:s,thetaStart:o,thetaLength:l};let c=this;n=Math.floor(n),a=Math.floor(a);let u=[],h=[],d=[],f=[],y=0,g=[],p=i/2,m=0;v(),s===!1&&(t>0&&x(!0),r>0&&x(!1)),this.setIndex(u),this.setAttribute("position",new Mt(h,3)),this.setAttribute("normal",new Mt(d,3)),this.setAttribute("uv",new Mt(f,2));function v(){let b=new ee,_=new ee,M=0,C=(r-t)/i;for(let S=0;S<=a;S++){let w=[],E=S/a,P=E*(r-t)+t;for(let N=0;N<=n;N++){let D=N/n,B=D*l+o,J=Math.sin(B),Q=Math.cos(B);_.x=P*J,_.y=-E*i+p,_.z=P*Q,h.push(_.x,_.y,_.z),b.set(J,C,Q).normalize(),d.push(b.x,b.y,b.z),f.push(D,1-E),w.push(y++)}g.push(w)}for(let S=0;S<n;S++)for(let w=0;w<a;w++){let E=g[w][S],P=g[w+1][S],N=g[w+1][S+1],D=g[w][S+1];(t>0||w!==0)&&(u.push(E,P,D),M+=3),(r>0||w!==a-1)&&(u.push(P,N,D),M+=3)}c.addGroup(m,M,0),m+=M}function x(b){let _=y,M=new Xe,C=new ee,S=0,w=b===!0?t:r,E=b===!0?1:-1;for(let N=1;N<=n;N++)h.push(0,p*E,0),d.push(0,E,0),f.push(.5,.5),y++;let P=y;for(let N=0;N<=n;N++){let D=N/n*l+o,B=Math.cos(D),J=Math.sin(D);C.x=w*J,C.y=p*E,C.z=w*B,h.push(C.x,C.y,C.z),d.push(0,E,0),M.x=B*.5+.5,M.y=J*.5*E+.5,f.push(M.x,M.y),y++}for(let N=0;N<n;N++){let D=_+N,B=P+N;b===!0?u.push(B,B+1,D):u.push(B+1,B,D),S+=3}c.addGroup(m,S,b===!0?1:2),m+=S}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new U1(t.radiusTop,t.radiusBottom,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}},gf=class F1 extends Zl{constructor(t=1,r=1,i=32,n=1,a=!1,s=0,o=Math.PI*2){super(0,t,r,i,n,a,s,o),this.type="ConeGeometry",this.parameters={radius:t,height:r,radialSegments:i,heightSegments:n,openEnded:a,thetaStart:s,thetaLength:o}}static fromJSON(t){return new F1(t.radius,t.height,t.radialSegments,t.heightSegments,t.openEnded,t.thetaStart,t.thetaLength)}},Ro=class B1 extends ar{constructor(t=[],r=[],i=1,n=0){super(),this.type="PolyhedronGeometry",this.parameters={vertices:t,indices:r,radius:i,detail:n};let a=[],s=[];o(n),c(i),u(),this.setAttribute("position",new Mt(a,3)),this.setAttribute("normal",new Mt(a.slice(),3)),this.setAttribute("uv",new Mt(s,2)),n===0?this.computeVertexNormals():this.normalizeNormals();function o(v){let x=new ee,b=new ee,_=new ee;for(let M=0;M<r.length;M+=3)f(r[M+0],x),f(r[M+1],b),f(r[M+2],_),l(x,b,_,v)}function l(v,x,b,_){let M=_+1,C=[];for(let S=0;S<=M;S++){C[S]=[];let w=v.clone().lerp(b,S/M),E=x.clone().lerp(b,S/M),P=M-S;for(let N=0;N<=P;N++)N===0&&S===M?C[S][N]=w:C[S][N]=w.clone().lerp(E,N/P)}for(let S=0;S<M;S++)for(let w=0;w<2*(M-S)-1;w++){let E=Math.floor(w/2);w%2===0?(d(C[S][E+1]),d(C[S+1][E]),d(C[S][E])):(d(C[S][E+1]),d(C[S+1][E+1]),d(C[S+1][E]))}}function c(v){let x=new ee;for(let b=0;b<a.length;b+=3)x.x=a[b+0],x.y=a[b+1],x.z=a[b+2],x.normalize().multiplyScalar(v),a[b+0]=x.x,a[b+1]=x.y,a[b+2]=x.z}function u(){let v=new ee;for(let x=0;x<a.length;x+=3){v.x=a[x+0],v.y=a[x+1],v.z=a[x+2];let b=p(v)/2/Math.PI+.5,_=m(v)/Math.PI+.5;s.push(b,1-_)}y(),h()}function h(){for(let v=0;v<s.length;v+=6){let x=s[v+0],b=s[v+2],_=s[v+4],M=Math.max(x,b,_),C=Math.min(x,b,_);M>.9&&C<.1&&(x<.2&&(s[v+0]+=1),b<.2&&(s[v+2]+=1),_<.2&&(s[v+4]+=1))}}function d(v){a.push(v.x,v.y,v.z)}function f(v,x){let b=v*3;x.x=t[b+0],x.y=t[b+1],x.z=t[b+2]}function y(){let v=new ee,x=new ee,b=new ee,_=new ee,M=new Xe,C=new Xe,S=new Xe;for(let w=0,E=0;w<a.length;w+=9,E+=6){v.set(a[w+0],a[w+1],a[w+2]),x.set(a[w+3],a[w+4],a[w+5]),b.set(a[w+6],a[w+7],a[w+8]),M.set(s[E+0],s[E+1]),C.set(s[E+2],s[E+3]),S.set(s[E+4],s[E+5]),_.copy(v).add(x).add(b).divideScalar(3);let P=p(_);g(M,E+0,v,P),g(C,E+2,x,P),g(S,E+4,b,P)}}function g(v,x,b,_){_<0&&v.x===1&&(s[x]=v.x-1),b.x===0&&b.z===0&&(s[x]=_/2/Math.PI+.5)}function p(v){return Math.atan2(v.z,-v.x)}function m(v){return Math.atan2(-v.y,Math.sqrt(v.x*v.x+v.z*v.z))}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new B1(t.vertices,t.indices,t.radius,t.details)}},ly=class z1 extends Ro{constructor(t=1,r=0){let i=(1+Math.sqrt(5))/2,n=1/i,a=[-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],s=[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(a,s,t,r),this.type="DodecahedronGeometry",this.parameters={radius:t,detail:r}}static fromJSON(t){return new z1(t.radius,t.detail)}},Fh=new ee,Bh=new ee,yf=new ee,zh=new ua,Ql=class extends ar{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(ns*t),n=e.getIndex(),a=e.getAttribute("position"),s=n?n.count:a.count,o=[0,0,0],l=["a","b","c"],c=new Array(3),u={},h=[];for(let d=0;d<s;d+=3){n?(o[0]=n.getX(d),o[1]=n.getX(d+1),o[2]=n.getX(d+2)):(o[0]=d,o[1]=d+1,o[2]=d+2);let{a:f,b:y,c:g}=zh;if(f.fromBufferAttribute(a,o[0]),y.fromBufferAttribute(a,o[1]),g.fromBufferAttribute(a,o[2]),zh.getNormal(yf),c[0]=`${Math.round(f.x*r)},${Math.round(f.y*r)},${Math.round(f.z*r)}`,c[1]=`${Math.round(y.x*r)},${Math.round(y.y*r)},${Math.round(y.z*r)}`,c[2]=`${Math.round(g.x*r)},${Math.round(g.y*r)},${Math.round(g.z*r)}`,!(c[0]===c[1]||c[1]===c[2]||c[2]===c[0]))for(let p=0;p<3;p++){let m=(p+1)%3,v=c[p],x=c[m],b=zh[l[p]],_=zh[l[m]],M=`${v}_${x}`,C=`${x}_${v}`;C in u&&u[C]?(yf.dot(u[C].normal)<=i&&(h.push(b.x,b.y,b.z),h.push(_.x,_.y,_.z)),u[C]=null):M in u||(u[M]={index0:o[p],index1:o[m],normal:yf.clone()})}}for(let d in u)if(u[d]){let{index0:f,index1:y}=u[d];Fh.fromBufferAttribute(a,f),Bh.fromBufferAttribute(a,y),h.push(Fh.x,Fh.y,Fh.z),h.push(Bh.x,Bh.y,Bh.z)}this.setAttribute("position",new Mt(h,3))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}},fa=class extends Co{constructor(e){super(e),this.uuid=rn(),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 Co().fromJSON(i))}return this}},Yw={triangulate:function(e,t,r=2){let i=t&&t.length,n=i?t[0]*r:e.length,a=cy(e,0,n,r,!0),s=[];if(!a||a.next===a.prev)return s;let o,l,c,u,h,d,f;if(i&&(a=Jw(e,t,a,r)),e.length>80*r){o=c=e[0],l=u=e[1];for(let y=r;y<n;y+=r)h=e[y],d=e[y+1],h<o&&(o=h),d<l&&(l=d),h>c&&(c=h),d>u&&(u=d);f=Math.max(c-o,u-l),f=f!==0?32767/f:0}return Jl(a,s,r,o,l,f,0),s}};function cy(e,t,r,i,n){let a,s;if(n===cE(e,t,r,i)>0)for(a=t;a<r;a+=i)s=dy(a,e[a],e[a+1],s);else for(a=r-i;a>=t;a-=i)s=dy(a,e[a],e[a+1],s);return s&&Gh(s,s.next)&&(ec(s),s=s.next),s}function ms(e,t){if(!e)return e;t||(t=e);let r=e,i;do if(i=!1,!r.steiner&&(Gh(r,r.next)||Qr(r.prev,r,r.next)===0)){if(ec(r),r=t=r.prev,r===r.next)break;i=!0}else r=r.next;while(i||r!==t);return t}function Jl(e,t,r,i,n,a,s){if(!e)return;!s&&a&&iE(e,i,n,a);let o=e,l,c;for(;e.prev!==e.next;){if(l=e.prev,c=e.next,a?Kw(e,i,n,a):qw(e)){t.push(l.i/r|0),t.push(e.i/r|0),t.push(c.i/r|0),ec(e),e=c.next,o=c.next;continue}if(e=c,e===o){s?s===1?(e=Zw(ms(e),t,r),Jl(e,t,r,i,n,a,2)):s===2&&Qw(e,t,r,i,n,a):Jl(ms(e),t,r,i,n,a,1);break}}}function qw(e){let t=e.prev,r=e,i=e.next;if(Qr(t,r,i)>=0)return!1;let n=t.x,a=r.x,s=i.x,o=t.y,l=r.y,c=i.y,u=n<a?n<s?n:s:a<s?a:s,h=o<l?o<c?o:c:l<c?l:c,d=n>a?n>s?n:s:a>s?a:s,f=o>l?o>c?o:c:l>c?l:c,y=i.next;for(;y!==t;){if(y.x>=u&&y.x<=d&&y.y>=h&&y.y<=f&&Po(n,o,a,l,s,c,y.x,y.y)&&Qr(y.prev,y,y.next)>=0)return!1;y=y.next}return!0}function Kw(e,t,r,i){let n=e.prev,a=e,s=e.next;if(Qr(n,a,s)>=0)return!1;let o=n.x,l=a.x,c=s.x,u=n.y,h=a.y,d=s.y,f=o<l?o<c?o:c:l<c?l:c,y=u<h?u<d?u:d:h<d?h:d,g=o>l?o>c?o:c:l>c?l:c,p=u>h?u>d?u:d:h>d?h:d,m=vf(f,y,t,r,i),v=vf(g,p,t,r,i),x=e.prevZ,b=e.nextZ;for(;x&&x.z>=m&&b&&b.z<=v;){if(x.x>=f&&x.x<=g&&x.y>=y&&x.y<=p&&x!==n&&x!==s&&Po(o,u,l,h,c,d,x.x,x.y)&&Qr(x.prev,x,x.next)>=0||(x=x.prevZ,b.x>=f&&b.x<=g&&b.y>=y&&b.y<=p&&b!==n&&b!==s&&Po(o,u,l,h,c,d,b.x,b.y)&&Qr(b.prev,b,b.next)>=0))return!1;b=b.nextZ}for(;x&&x.z>=m;){if(x.x>=f&&x.x<=g&&x.y>=y&&x.y<=p&&x!==n&&x!==s&&Po(o,u,l,h,c,d,x.x,x.y)&&Qr(x.prev,x,x.next)>=0)return!1;x=x.prevZ}for(;b&&b.z<=v;){if(b.x>=f&&b.x<=g&&b.y>=y&&b.y<=p&&b!==n&&b!==s&&Po(o,u,l,h,c,d,b.x,b.y)&&Qr(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function Zw(e,t,r){let i=e;do{let n=i.prev,a=i.next.next;!Gh(n,a)&&uy(n,i,i.next,a)&&$l(n,a)&&$l(a,n)&&(t.push(n.i/r|0),t.push(i.i/r|0),t.push(a.i/r|0),ec(i),ec(i.next),i=e=a),i=i.next}while(i!==e);return ms(i)}function Qw(e,t,r,i,n,a){let s=e;do{let o=s.next.next;for(;o!==s.prev;){if(s.i!==o.i&&sE(s,o)){let l=hy(s,o);s=ms(s,s.next),l=ms(l,l.next),Jl(s,t,r,i,n,a,0),Jl(l,t,r,i,n,a,0);return}o=o.next}s=s.next}while(s!==e)}function Jw(e,t,r,i){let n=[],a,s,o,l,c;for(a=0,s=t.length;a<s;a++)o=t[a]*i,l=a<s-1?t[a+1]*i:e.length,c=cy(e,o,l,i,!1),c===c.next&&(c.steiner=!0),n.push(aE(c));for(n.sort($w),a=0;a<n.length;a++)r=eE(n[a],r);return r}function $w(e,t){return e.x-t.x}function eE(e,t){let r=tE(e,t);if(!r)return t;let i=hy(r,e);return ms(i,i.next),ms(r,r.next)}function tE(e,t){let r=t,i=-1/0,n,a=e.x,s=e.y;do{if(s<=r.y&&s>=r.next.y&&r.next.y!==r.y){let d=r.x+(s-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(d<=a&&d>i&&(i=d,n=r.x<r.next.x?r:r.next,d===a))return n}r=r.next}while(r!==t);if(!n)return null;let o=n,l=n.x,c=n.y,u=1/0,h;r=n;do a>=r.x&&r.x>=l&&a!==r.x&&Po(s<c?a:i,s,l,c,s<c?i:a,s,r.x,r.y)&&(h=Math.abs(s-r.y)/(a-r.x),$l(r,e)&&(h<u||h===u&&(r.x>n.x||r.x===n.x&&rE(n,r)))&&(n=r,u=h)),r=r.next;while(r!==o);return n}function rE(e,t){return Qr(e.prev,e,t.prev)<0&&Qr(t.next,e,e.next)<0}function iE(e,t,r,i){let n=e;do n.z===0&&(n.z=vf(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,nE(n)}function nE(e){let t,r,i,n,a,s,o,l,c=1;do{for(r=e,e=null,a=null,s=0;r;){for(s++,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--),a?a.nextZ=n:e=n,n.prevZ=a,a=n;r=i}a.nextZ=null,c*=2}while(s>1);return e}function vf(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 aE(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 Po(e,t,r,i,n,a,s,o){return(n-s)*(t-o)>=(e-s)*(a-o)&&(e-s)*(i-o)>=(r-s)*(t-o)&&(r-s)*(a-o)>=(n-s)*(i-o)}function sE(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!oE(e,t)&&($l(e,t)&&$l(t,e)&&lE(e,t)&&(Qr(e.prev,e,t.prev)||Qr(e,t.prev,t))||Gh(e,t)&&Qr(e.prev,e,e.next)>0&&Qr(t.prev,t,t.next)>0)}function Qr(e,t,r){return(t.y-e.y)*(r.x-t.x)-(t.x-e.x)*(r.y-t.y)}function Gh(e,t){return e.x===t.x&&e.y===t.y}function uy(e,t,r,i){let n=Hh(Qr(e,t,r)),a=Hh(Qr(e,t,i)),s=Hh(Qr(r,i,e)),o=Hh(Qr(r,i,t));return!!(n!==a&&s!==o||n===0&&Vh(e,r,t)||a===0&&Vh(e,i,t)||s===0&&Vh(r,e,i)||o===0&&Vh(r,t,i))}function Vh(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 Hh(e){return e>0?1:e<0?-1:0}function oE(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&&uy(r,r.next,e,t))return!0;r=r.next}while(r!==e);return!1}function $l(e,t){return Qr(e.prev,e,e.next)<0?Qr(e,t,e.next)>=0&&Qr(e,e.prev,t)>=0:Qr(e,t,e.prev)<0||Qr(e,e.next,t)<0}function lE(e,t){let r=e,i=!1,n=(e.x+t.x)/2,a=(e.y+t.y)/2;do r.y>a!=r.next.y>a&&r.next.y!==r.y&&n<(r.next.x-r.x)*(a-r.y)/(r.next.y-r.y)+r.x&&(i=!i),r=r.next;while(r!==e);return i}function hy(e,t){let r=new xf(e.i,e.x,e.y),i=new xf(t.i,t.x,t.y),n=e.next,a=t.prev;return e.next=t,t.prev=e,r.next=n,n.prev=r,i.next=r,r.prev=i,a.next=i,i.prev=a,i}function dy(e,t,r,i){let n=new xf(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 ec(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 xf(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 cE(e,t,r,i){let n=0;for(let a=t,s=r-i;a<r;a+=i)n+=(e[s]-e[a])*(e[a+1]+e[s+1]),s=a;return n}var ma=class G1{static area(t){let r=t.length,i=0;for(let n=r-1,a=0;a<r;n=a++)i+=t[n].x*t[a].y-t[a].x*t[n].y;return i*.5}static isClockWise(t){return G1.area(t)<0}static triangulateShape(t,r){let i=[],n=[],a=[];py(t),fy(i,t);let s=t.length;r.forEach(py);for(let l=0;l<r.length;l++)n.push(s),s+=r[l].length,fy(i,r[l]);let o=Yw.triangulate(i,n);for(let l=0;l<o.length;l+=3)a.push(o.slice(l,l+3));return a}};function py(e){let t=e.length;t>2&&e[t-1].equals(e[0])&&e.pop()}function fy(e,t){for(let r=0;r<t.length;r++)e.push(t[r].x),e.push(t[r].y)}var Wh=class V1 extends ar{constructor(t=new fa([new Xe(.5,.5),new Xe(-.5,.5),new Xe(-.5,-.5),new Xe(.5,-.5)]),r={}){super(),this.type="ExtrudeGeometry",this.parameters={shapes:t,options:r},t=Array.isArray(t)?t:[t];let i=this,n=[],a=[];for(let o=0,l=t.length;o<l;o++){let c=t[o];s(c)}this.setAttribute("position",new Mt(n,3)),this.setAttribute("uv",new Mt(a,2)),this.computeVertexNormals();function s(o){let l=[],c=r.curveSegments!==void 0?r.curveSegments:12,u=r.steps!==void 0?r.steps:1,h=r.depth!==void 0?r.depth:1,d=r.bevelEnabled!==void 0?r.bevelEnabled:!0,f=r.bevelThickness!==void 0?r.bevelThickness:.2,y=r.bevelSize!==void 0?r.bevelSize:f-.1,g=r.bevelOffset!==void 0?r.bevelOffset:0,p=r.bevelSegments!==void 0?r.bevelSegments:3,m=r.extrudePath,v=r.UVGenerator!==void 0?r.UVGenerator:uE,x,b=!1,_,M,C,S;m&&(x=m.getSpacedPoints(u),b=!0,d=!1,_=m.computeFrenetFrames(u,!1),M=new ee,C=new ee,S=new ee),d||(p=0,f=0,y=0,g=0);let w=o.extractPoints(c),E=w.shape,P=w.holes;if(!ma.isClockWise(E)){E=E.reverse();for(let ae=0,de=P.length;ae<de;ae++){let z=P[ae];ma.isClockWise(z)&&(P[ae]=z.reverse())}}let N=ma.triangulateShape(E,P),D=E;for(let ae=0,de=P.length;ae<de;ae++){let z=P[ae];E=E.concat(z)}function B(ae,de,z){return de||console.error("THREE.ExtrudeGeometry: vec does not exist"),ae.clone().addScaledVector(de,z)}let J=E.length,Q=N.length;function j(ae,de,z){let me,we,He,ne=ae.x-de.x,_e=ae.y-de.y,oe=z.x-ae.x,ce=z.y-ae.y,L=ne*ne+_e*_e,A=ne*ce-_e*oe;if(Math.abs(A)>Number.EPSILON){let O=Math.sqrt(L),F=Math.sqrt(oe*oe+ce*ce),Y=de.x-_e/O,re=de.y+ne/O,ue=z.x-ce/F,se=z.y+oe/F,pe=((ue-Y)*ce-(se-re)*oe)/(ne*ce-_e*oe);me=Y+ne*pe-ae.x,we=re+_e*pe-ae.y;let Pe=me*me+we*we;if(Pe<=2)return new Xe(me,we);He=Math.sqrt(Pe/2)}else{let O=!1;ne>Number.EPSILON?oe>Number.EPSILON&&(O=!0):ne<-Number.EPSILON?oe<-Number.EPSILON&&(O=!0):Math.sign(_e)===Math.sign(ce)&&(O=!0),O?(me=-_e,we=ne,He=Math.sqrt(L)):(me=ne,we=_e,He=Math.sqrt(L/2))}return new Xe(me/He,we/He)}let k=[];for(let ae=0,de=D.length,z=de-1,me=ae+1;ae<de;ae++,z++,me++)z===de&&(z=0),me===de&&(me=0),k[ae]=j(D[ae],D[z],D[me]);let H=[],U,X=k.concat();for(let ae=0,de=P.length;ae<de;ae++){let z=P[ae];U=[];for(let me=0,we=z.length,He=we-1,ne=me+1;me<we;me++,He++,ne++)He===we&&(He=0),ne===we&&(ne=0),U[me]=j(z[me],z[He],z[ne]);H.push(U),X=X.concat(U)}for(let ae=0;ae<p;ae++){let de=ae/p,z=f*Math.cos(de*Math.PI/2),me=y*Math.sin(de*Math.PI/2)+g;for(let we=0,He=D.length;we<He;we++){let ne=B(D[we],k[we],me);I(ne.x,ne.y,-z)}for(let we=0,He=P.length;we<He;we++){let ne=P[we];U=H[we];for(let _e=0,oe=ne.length;_e<oe;_e++){let ce=B(ne[_e],U[_e],me);I(ce.x,ce.y,-z)}}}let W=y+g;for(let ae=0;ae<J;ae++){let de=d?B(E[ae],X[ae],W):E[ae];b?(C.copy(_.normals[0]).multiplyScalar(de.x),M.copy(_.binormals[0]).multiplyScalar(de.y),S.copy(x[0]).add(C).add(M),I(S.x,S.y,S.z)):I(de.x,de.y,0)}for(let ae=1;ae<=u;ae++)for(let de=0;de<J;de++){let z=d?B(E[de],X[de],W):E[de];b?(C.copy(_.normals[ae]).multiplyScalar(z.x),M.copy(_.binormals[ae]).multiplyScalar(z.y),S.copy(x[ae]).add(C).add(M),I(S.x,S.y,S.z)):I(z.x,z.y,h/u*ae)}for(let ae=p-1;ae>=0;ae--){let de=ae/p,z=f*Math.cos(de*Math.PI/2),me=y*Math.sin(de*Math.PI/2)+g;for(let we=0,He=D.length;we<He;we++){let ne=B(D[we],k[we],me);I(ne.x,ne.y,h+z)}for(let we=0,He=P.length;we<He;we++){let ne=P[we];U=H[we];for(let _e=0,oe=ne.length;_e<oe;_e++){let ce=B(ne[_e],U[_e],me);b?I(ce.x,ce.y+x[u-1].y,x[u-1].x+z):I(ce.x,ce.y,h+z)}}}$(),G();function $(){let ae=n.length/3;if(d){let de=0,z=J*de;for(let me=0;me<Q;me++){let we=N[me];V(we[2]+z,we[1]+z,we[0]+z)}de=u+p*2,z=J*de;for(let me=0;me<Q;me++){let we=N[me];V(we[0]+z,we[1]+z,we[2]+z)}}else{for(let de=0;de<Q;de++){let z=N[de];V(z[2],z[1],z[0])}for(let de=0;de<Q;de++){let z=N[de];V(z[0]+J*u,z[1]+J*u,z[2]+J*u)}}i.addGroup(ae,n.length/3-ae,0)}function G(){let ae=n.length/3,de=0;T(D,de),de+=D.length;for(let z=0,me=P.length;z<me;z++){let we=P[z];T(we,de),de+=we.length}i.addGroup(ae,n.length/3-ae,1)}function T(ae,de){let z=ae.length;for(;--z>=0;){let me=z,we=z-1;we<0&&(we=ae.length-1);for(let He=0,ne=u+p*2;He<ne;He++){let _e=J*He,oe=J*(He+1),ce=de+me+_e,L=de+we+_e,A=de+we+oe,O=de+me+oe;K(ce,L,A,O)}}}function I(ae,de,z){l.push(ae),l.push(de),l.push(z)}function V(ae,de,z){ie(ae),ie(de),ie(z);let me=n.length/3,we=v.generateTopUV(i,n,me-3,me-2,me-1);le(we[0]),le(we[1]),le(we[2])}function K(ae,de,z,me){ie(ae),ie(de),ie(me),ie(de),ie(z),ie(me);let we=n.length/3,He=v.generateSideWallUV(i,n,we-6,we-3,we-2,we-1);le(He[0]),le(He[1]),le(He[3]),le(He[1]),le(He[2]),le(He[3])}function ie(ae){n.push(l[ae*3+0]),n.push(l[ae*3+1]),n.push(l[ae*3+2])}function le(ae){a.push(ae.x),a.push(ae.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 hE(r,i,t)}static fromJSON(t,r){let i=[];for(let a=0,s=t.shapes.length;a<s;a++){let o=r[t.shapes[a]];i.push(o)}let n=t.options.extrudePath;return n!==void 0&&(t.options.extrudePath=new Uh[n.type]().fromJSON(n)),new V1(i,t.options)}},uE={generateTopUV:function(e,t,r,i,n){let a=t[r*3],s=t[r*3+1],o=t[i*3],l=t[i*3+1],c=t[n*3],u=t[n*3+1];return[new Xe(a,s),new Xe(o,l),new Xe(c,u)]},generateSideWallUV:function(e,t,r,i,n,a){let s=t[r*3],o=t[r*3+1],l=t[r*3+2],c=t[i*3],u=t[i*3+1],h=t[i*3+2],d=t[n*3],f=t[n*3+1],y=t[n*3+2],g=t[a*3],p=t[a*3+1],m=t[a*3+2];return Math.abs(o-u)<Math.abs(s-c)?[new Xe(s,1-l),new Xe(c,1-h),new Xe(d,1-y),new Xe(g,1-m)]:[new Xe(o,1-l),new Xe(u,1-h),new Xe(f,1-y),new Xe(p,1-m)]}};function hE(e,t,r){if(r.shapes=[],Array.isArray(e))for(let i=0,n=e.length;i<n;i++){let a=e[i];r.shapes.push(a.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 my=class H1 extends Ro{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],a=[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,a,t,r),this.type="IcosahedronGeometry",this.parameters={radius:t,detail:r}}static fromJSON(t){return new H1(t.radius,t.detail)}},bf=class W1 extends Ro{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 W1(t.radius,t.detail)}},Io=class j1 extends ar{constructor(t=1,r=1,i=1,n=1){super(),this.type="PlaneGeometry",this.parameters={width:t,height:r,widthSegments:i,heightSegments:n};let a=t/2,s=r/2,o=Math.floor(i),l=Math.floor(n),c=o+1,u=l+1,h=t/o,d=r/l,f=[],y=[],g=[],p=[];for(let m=0;m<u;m++){let v=m*d-s;for(let x=0;x<c;x++){let b=x*h-a;y.push(b,-v,0),g.push(0,0,1),p.push(x/o),p.push(1-m/l)}}for(let m=0;m<l;m++)for(let v=0;v<o;v++){let x=v+c*m,b=v+c*(m+1),_=v+1+c*(m+1),M=v+1+c*m;f.push(x,b,M),f.push(b,_,M)}this.setIndex(f),this.setAttribute("position",new Mt(y,3)),this.setAttribute("normal",new Mt(g,3)),this.setAttribute("uv",new Mt(p,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new j1(t.width,t.height,t.widthSegments,t.heightSegments)}},gy=class X1 extends ar{constructor(t=.5,r=1,i=32,n=1,a=0,s=Math.PI*2){super(),this.type="RingGeometry",this.parameters={innerRadius:t,outerRadius:r,thetaSegments:i,phiSegments:n,thetaStart:a,thetaLength:s},i=Math.max(3,i),n=Math.max(1,n);let o=[],l=[],c=[],u=[],h=t,d=(r-t)/n,f=new ee,y=new Xe;for(let g=0;g<=n;g++){for(let p=0;p<=i;p++){let m=a+p/i*s;f.x=h*Math.cos(m),f.y=h*Math.sin(m),l.push(f.x,f.y,f.z),c.push(0,0,1),y.x=(f.x/r+1)/2,y.y=(f.y/r+1)/2,u.push(y.x,y.y)}h+=d}for(let g=0;g<n;g++){let p=g*(i+1);for(let m=0;m<i;m++){let v=m+p,x=v,b=v+i+1,_=v+i+2,M=v+1;o.push(x,b,M),o.push(b,_,M)}}this.setIndex(o),this.setAttribute("position",new Mt(l,3)),this.setAttribute("normal",new Mt(c,3)),this.setAttribute("uv",new Mt(u,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new X1(t.innerRadius,t.outerRadius,t.thetaSegments,t.phiSegments,t.thetaStart,t.thetaLength)}},yy=class Y1 extends ar{constructor(t=new fa([new Xe(0,.5),new Xe(-.5,-.5),new Xe(.5,-.5)]),r=12){super(),this.type="ShapeGeometry",this.parameters={shapes:t,curveSegments:r};let i=[],n=[],a=[],s=[],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 Mt(n,3)),this.setAttribute("normal",new Mt(a,3)),this.setAttribute("uv",new Mt(s,2));function c(u){let h=n.length/3,d=u.extractPoints(r),f=d.shape,y=d.holes;ma.isClockWise(f)===!1&&(f=f.reverse());for(let p=0,m=y.length;p<m;p++){let v=y[p];ma.isClockWise(v)===!0&&(y[p]=v.reverse())}let g=ma.triangulateShape(f,y);for(let p=0,m=y.length;p<m;p++){let v=y[p];f=f.concat(v)}for(let p=0,m=f.length;p<m;p++){let v=f[p];n.push(v.x,v.y,0),a.push(0,0,1),s.push(v.x,v.y)}for(let p=0,m=g.length;p<m;p++){let v=g[p],x=v[0]+h,b=v[1]+h,_=v[2]+h;i.push(x,b,_),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 dE(r,t)}static fromJSON(t,r){let i=[];for(let n=0,a=t.shapes.length;n<a;n++){let s=r[t.shapes[n]];i.push(s)}return new Y1(i,t.curveSegments)}};function dE(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 Ua=class q1 extends ar{constructor(t=1,r=32,i=16,n=0,a=Math.PI*2,s=0,o=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:t,widthSegments:r,heightSegments:i,phiStart:n,phiLength:a,thetaStart:s,thetaLength:o},r=Math.max(3,Math.floor(r)),i=Math.max(2,Math.floor(i));let l=Math.min(s+o,Math.PI),c=0,u=[],h=new ee,d=new ee,f=[],y=[],g=[],p=[];for(let m=0;m<=i;m++){let v=[],x=m/i,b=0;m===0&&s===0?b=.5/r:m===i&&l===Math.PI&&(b=-.5/r);for(let _=0;_<=r;_++){let M=_/r;h.x=-t*Math.cos(n+M*a)*Math.sin(s+x*o),h.y=t*Math.cos(s+x*o),h.z=t*Math.sin(n+M*a)*Math.sin(s+x*o),y.push(h.x,h.y,h.z),d.copy(h).normalize(),g.push(d.x,d.y,d.z),p.push(M+b,1-x),v.push(c++)}u.push(v)}for(let m=0;m<i;m++)for(let v=0;v<r;v++){let x=u[m][v+1],b=u[m][v],_=u[m+1][v],M=u[m+1][v+1];(m!==0||s>0)&&f.push(x,b,M),(m!==i-1||l<Math.PI)&&f.push(b,_,M)}this.setIndex(f),this.setAttribute("position",new Mt(y,3)),this.setAttribute("normal",new Mt(g,3)),this.setAttribute("uv",new Mt(p,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new q1(t.radius,t.widthSegments,t.heightSegments,t.phiStart,t.phiLength,t.thetaStart,t.thetaLength)}},vy=class K1 extends Ro{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 K1(t.radius,t.detail)}},xy=class Z1 extends ar{constructor(t=1,r=.4,i=12,n=48,a=Math.PI*2){super(),this.type="TorusGeometry",this.parameters={radius:t,tube:r,radialSegments:i,tubularSegments:n,arc:a},i=Math.floor(i),n=Math.floor(n);let s=[],o=[],l=[],c=[],u=new ee,h=new ee,d=new ee;for(let f=0;f<=i;f++)for(let y=0;y<=n;y++){let g=y/n*a,p=f/i*Math.PI*2;h.x=(t+r*Math.cos(p))*Math.cos(g),h.y=(t+r*Math.cos(p))*Math.sin(g),h.z=r*Math.sin(p),o.push(h.x,h.y,h.z),u.x=t*Math.cos(g),u.y=t*Math.sin(g),d.subVectors(h,u).normalize(),l.push(d.x,d.y,d.z),c.push(y/n),c.push(f/i)}for(let f=1;f<=i;f++)for(let y=1;y<=n;y++){let g=(n+1)*f+y-1,p=(n+1)*(f-1)+y-1,m=(n+1)*(f-1)+y,v=(n+1)*f+y;s.push(g,p,v),s.push(p,m,v)}this.setIndex(s),this.setAttribute("position",new Mt(o,3)),this.setAttribute("normal",new Mt(l,3)),this.setAttribute("uv",new Mt(c,2))}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new Z1(t.radius,t.tube,t.radialSegments,t.tubularSegments,t.arc)}},by=class Q1 extends ar{constructor(t=1,r=.4,i=64,n=8,a=2,s=3){super(),this.type="TorusKnotGeometry",this.parameters={radius:t,tube:r,tubularSegments:i,radialSegments:n,p:a,q:s},i=Math.floor(i),n=Math.floor(n);let o=[],l=[],c=[],u=[],h=new ee,d=new ee,f=new ee,y=new ee,g=new ee,p=new ee,m=new ee;for(let x=0;x<=i;++x){let b=x/i*a*Math.PI*2;v(b,a,s,t,f),v(b+.01,a,s,t,y),p.subVectors(y,f),m.addVectors(y,f),g.crossVectors(p,m),m.crossVectors(g,p),g.normalize(),m.normalize();for(let _=0;_<=n;++_){let M=_/n*Math.PI*2,C=-r*Math.cos(M),S=r*Math.sin(M);h.x=f.x+(C*m.x+S*g.x),h.y=f.y+(C*m.y+S*g.y),h.z=f.z+(C*m.z+S*g.z),l.push(h.x,h.y,h.z),d.subVectors(h,f).normalize(),c.push(d.x,d.y,d.z),u.push(x/i),u.push(_/n)}}for(let x=1;x<=i;x++)for(let b=1;b<=n;b++){let _=(n+1)*(x-1)+(b-1),M=(n+1)*x+(b-1),C=(n+1)*x+b,S=(n+1)*(x-1)+b;o.push(_,M,S),o.push(M,C,S)}this.setIndex(o),this.setAttribute("position",new Mt(l,3)),this.setAttribute("normal",new Mt(c,3)),this.setAttribute("uv",new Mt(u,2));function v(x,b,_,M,C){let S=Math.cos(x),w=Math.sin(x),E=_/b*x,P=Math.cos(E);C.x=M*(2+P)*.5*S,C.y=M*(2+P)*w*.5,C.z=M*Math.sin(E)*.5}}copy(t){return super.copy(t),this.parameters=Object.assign({},t.parameters),this}static fromJSON(t){return new Q1(t.radius,t.tube,t.tubularSegments,t.radialSegments,t.p,t.q)}},_y=class J1 extends ar{constructor(t=new pf(new ee(-1,-1,0),new ee(-1,1,0),new ee(1,1,0)),r=64,i=1,n=8,a=!1){super(),this.type="TubeGeometry",this.parameters={path:t,tubularSegments:r,radius:i,radialSegments:n,closed:a};let s=t.computeFrenetFrames(r,a);this.tangents=s.tangents,this.normals=s.normals,this.binormals=s.binormals;let o=new ee,l=new ee,c=new Xe,u=new ee,h=[],d=[],f=[],y=[];g(),this.setIndex(y),this.setAttribute("position",new Mt(h,3)),this.setAttribute("normal",new Mt(d,3)),this.setAttribute("uv",new Mt(f,2));function g(){for(let x=0;x<r;x++)p(x);p(a===!1?r:0),v(),m()}function p(x){u=t.getPointAt(x/r,u);let b=s.normals[x],_=s.binormals[x];for(let M=0;M<=n;M++){let C=M/n*Math.PI*2,S=Math.sin(C),w=-Math.cos(C);l.x=w*b.x+S*_.x,l.y=w*b.y+S*_.y,l.z=w*b.z+S*_.z,l.normalize(),d.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,h.push(o.x,o.y,o.z)}}function m(){for(let x=1;x<=r;x++)for(let b=1;b<=n;b++){let _=(n+1)*(x-1)+(b-1),M=(n+1)*x+(b-1),C=(n+1)*x+b,S=(n+1)*(x-1)+b;y.push(_,M,S),y.push(M,C,S)}}function v(){for(let x=0;x<=r;x++)for(let b=0;b<=n;b++)c.x=x/r,c.y=b/n,f.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 J1(new Uh[t.path.type]().fromJSON(t.path),t.tubularSegments,t.radius,t.radialSegments,t.closed)}},wy=class extends ar{constructor(e=null){if(super(),this.type="WireframeGeometry",this.parameters={geometry:e},e!==null){let t=[],r=new Set,i=new ee,n=new ee;if(e.index!==null){let a=e.attributes.position,s=e.index,o=e.groups;o.length===0&&(o=[{start:0,count:s.count,materialIndex:0}]);for(let l=0,c=o.length;l<c;++l){let u=o[l],h=u.start,d=u.count;for(let f=h,y=h+d;f<y;f+=3)for(let g=0;g<3;g++){let p=s.getX(f+g),m=s.getX(f+(g+1)%3);i.fromBufferAttribute(a,p),n.fromBufferAttribute(a,m),Ey(i,n,r)===!0&&(t.push(i.x,i.y,i.z),t.push(n.x,n.y,n.z))}}}else{let a=e.attributes.position;for(let s=0,o=a.count/3;s<o;s++)for(let l=0;l<3;l++){let c=3*s+l,u=3*s+(l+1)%3;i.fromBufferAttribute(a,c),n.fromBufferAttribute(a,u),Ey(i,n,r)===!0&&(t.push(i.x,i.y,i.z),t.push(n.x,n.y,n.z))}}this.setAttribute("position",new Mt(t,3))}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}};function Ey(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 My=Object.freeze({__proto__:null,BoxGeometry:da,CapsuleGeometry:sy,CircleGeometry:oy,ConeGeometry:gf,CylinderGeometry:Zl,DodecahedronGeometry:ly,EdgesGeometry:Ql,ExtrudeGeometry:Wh,IcosahedronGeometry:my,LatheGeometry:mf,OctahedronGeometry:bf,PlaneGeometry:Io,PolyhedronGeometry:Ro,RingGeometry:gy,ShapeGeometry:yy,SphereGeometry:Ua,TetrahedronGeometry:vy,TorusGeometry:xy,TorusKnotGeometry:by,TubeGeometry:_y,WireframeGeometry:wy}),Sy=class extends xi{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new yt(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}},_f=class extends oi{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}},Ki=class extends xi{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new yt(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 yt(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Pa,this.normalScale=new Xe(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 Nn,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}},on=class extends Ki{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 Xe(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return mr(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 yt(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 yt(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new yt(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}},wf=class extends xi{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new yt(16777215),this.specular=new yt(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new yt(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Pa,this.normalScale=new Xe(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Nn,this.combine=yl,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}},Ty=class extends xi{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new yt(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new yt(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Pa,this.normalScale=new Xe(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}},Ef=class extends xi{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Pa,this.normalScale=new Xe(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}},Ay=class extends xi{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new yt(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new yt(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Pa,this.normalScale=new Xe(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Nn,this.combine=yl,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}},Mf=class extends xi{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=qg,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}},Sf=class extends xi{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}},Cy=class extends xi{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new yt(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=Pa,this.normalScale=new Xe(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}},Ry=class extends ri{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 gs(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 Py(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Iy(e){function t(n,a){return e[n]-e[a]}let r=e.length,i=new Array(r);for(let n=0;n!==r;++n)i[n]=n;return i.sort(t),i}function Tf(e,t,r){let i=e.length,n=new e.constructor(i);for(let a=0,s=0;s!==i;++a){let o=r[a]*t;for(let l=0;l!==t;++l)n[s++]=e[o+l]}return n}function Af(e,t,r,i){let n=1,a=e[0];for(;a!==void 0&&a[i]===void 0;)a=e[n++];if(a===void 0)return;let s=a[i];if(s!==void 0)if(Array.isArray(s))do s=a[i],s!==void 0&&(t.push(a.time),r.push.apply(r,s)),a=e[n++];while(a!==void 0);else if(s.toArray!==void 0)do s=a[i],s!==void 0&&(t.push(a.time),s.toArray(r,r.length)),a=e[n++];while(a!==void 0);else do s=a[i],s!==void 0&&(t.push(a.time),r.push(s)),a=e[n++];while(a!==void 0)}function pE(e,t,r,i,n=30){let a=e.clone();a.name=t;let s=[];for(let l=0;l<a.tracks.length;++l){let c=a.tracks[l],u=c.getValueSize(),h=[],d=[];for(let f=0;f<c.times.length;++f){let y=c.times[f]*n;if(!(y<r||y>=i)){h.push(c.times[f]);for(let g=0;g<u;++g)d.push(c.values[f*u+g])}}h.length!==0&&(c.times=gs(h,c.times.constructor),c.values=gs(d,c.values.constructor),s.push(c))}a.tracks=s;let o=1/0;for(let l=0;l<a.tracks.length;++l)o>a.tracks[l].times[0]&&(o=a.tracks[l].times[0]);for(let l=0;l<a.tracks.length;++l)a.tracks[l].shift(-1*o);return a.resetDuration(),a}function fE(e,t=0,r=e,i=30){i<=0&&(i=30);let n=r.tracks.length,a=t/i;for(let s=0;s<n;++s){let o=r.tracks[s],l=o.ValueTypeName;if(l==="bool"||l==="string")continue;let c=e.tracks.find(function(m){return m.name===o.name&&m.ValueTypeName===l});if(c===void 0)continue;let u=0,h=o.getValueSize();o.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(u=h/3);let d=0,f=c.getValueSize();c.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline&&(d=f/3);let y=o.times.length-1,g;if(a<=o.times[0]){let m=u,v=h-u;g=o.values.slice(m,v)}else if(a>=o.times[y]){let m=y*h+u,v=m+h-u;g=o.values.slice(m,v)}else{let m=o.createInterpolant(),v=u,x=h-u;m.evaluate(a),g=m.resultBuffer.slice(v,x)}l==="quaternion"&&new di().fromArray(g).normalize().conjugate().toArray(g);let p=c.times.length;for(let m=0;m<p;++m){let v=m*f+d;if(l==="quaternion")di.multiplyQuaternionsFlat(c.values,v,g,0,c.values,v);else{let x=f-d*2;for(let b=0;b<x;++b)c.values[v+b]-=g[b]}}}return e.blendMode=xp,e}var mE={convertArray:gs,isTypedArray:Py,getKeyframeOrder:Iy,sortedArray:Tf,flattenJSON:Af,subclip:pE,makeClipAdditive:fE},No=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 a;r:{i:if(!(e<i)){for(let s=r+2;;){if(i===void 0){if(e<n)break i;return r=t.length,this._cachedIndex=r,this.copySampleValue_(r-1)}if(r===s)break;if(n=i,i=t[++r],e<i)break t}a=t.length;break r}if(!(e>=n)){let s=t[1];e<s&&(r=2,n=s);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}a=r,r=0;break r}break e}for(;r<a;){let s=r+a>>>1;e<t[s]?a=s:r=s+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 a=0;a!==i;++a)t[a]=r[n+a];return t}interpolate_(){throw new Error("call to abstract method")}intervalChanged_(){}},Ny=class extends No{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:ts,endingEnd:ts}}intervalChanged_(e,t,r){let i=this.parameterPositions,n=e-2,a=e+1,s=i[n],o=i[a];if(s===void 0)switch(this.getSettings_().endingStart){case rs:n=e,s=2*t-r;break;case Tl:n=i.length-2,s=t+i[n]-i[n+1];break;default:n=e,s=r}if(o===void 0)switch(this.getSettings_().endingEnd){case rs:a=e,o=2*r-t;break;case Tl:a=1,o=r+i[1]-i[0];break;default:a=e-1,o=t}let l=(r-t)*.5,c=this.valueSize;this._weightPrev=l/(t-s),this._weightNext=l/(o-r),this._offsetPrev=n*c,this._offsetNext=a*c}interpolate_(e,t,r,i){let n=this.resultBuffer,a=this.sampleValues,s=this.valueSize,o=e*s,l=o-s,c=this._offsetPrev,u=this._offsetNext,h=this._weightPrev,d=this._weightNext,f=(r-t)/(i-t),y=f*f,g=y*f,p=-h*g+2*h*y-h*f,m=(1+h)*g+(-1.5-2*h)*y+(-.5+h)*f+1,v=(-1-d)*g+(1.5+d)*y+.5*f,x=d*g-d*y;for(let b=0;b!==s;++b)n[b]=p*a[c+b]+m*a[l+b]+v*a[o+b]+x*a[u+b];return n}},Cf=class extends No{constructor(e,t,r,i){super(e,t,r,i)}interpolate_(e,t,r,i){let n=this.resultBuffer,a=this.sampleValues,s=this.valueSize,o=e*s,l=o-s,c=(r-t)/(i-t),u=1-c;for(let h=0;h!==s;++h)n[h]=a[l+h]*u+a[o+h]*c;return n}},Ly=class extends No{constructor(e,t,r,i){super(e,t,r,i)}interpolate_(e){return this.copySampleValue_(e-1)}},Dn=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=gs(t,this.TimeBufferType),this.values=gs(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:gs(e.times,Array),values:gs(e.values,Array)};let i=e.getInterpolation();i!==e.DefaultInterpolation&&(r.interpolation=i)}return r.type=e.ValueTypeName,r}InterpolantFactoryMethodDiscrete(e){return new Ly(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodLinear(e){return new Cf(this.times,this.values,this.getValueSize(),e)}InterpolantFactoryMethodSmooth(e){return new Ny(this.times,this.values,this.getValueSize(),e)}setInterpolation(e){let t;switch(e){case ro:t=this.InterpolantFactoryMethodDiscrete;break;case io:t=this.InterpolantFactoryMethodLinear;break;case Hu: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 ro;case this.InterpolantFactoryMethodLinear:return io;case this.InterpolantFactoryMethodSmooth:return Hu}}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,a=i-1;for(;n!==i&&r[n]<e;)++n;for(;a!==-1&&r[a]>t;)--a;if(++a,n!==0||a!==i){n>=a&&(a=Math.max(a,1),n=a-1);let s=this.getValueSize();this.times=r.slice(n,a),this.values=this.values.slice(n*s,a*s)}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 a=null;for(let s=0;s!==n;s++){let o=r[s];if(typeof o=="number"&&isNaN(o)){console.error("THREE.KeyframeTrack: Time is not a valid number.",this,s,o),e=!1;break}if(a!==null&&a>o){console.error("THREE.KeyframeTrack: Out of order keys.",this,s,o,a),e=!1;break}a=o}if(i!==void 0&&Py(i))for(let s=0,o=i.length;s!==o;++s){let l=i[s];if(isNaN(l)){console.error("THREE.KeyframeTrack: Value is not a valid number.",this,s,l),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),r=this.getValueSize(),i=this.getInterpolation()===Hu,n=e.length-1,a=1;for(let s=1;s<n;++s){let o=!1,l=e[s],c=e[s+1];if(l!==c&&(s!==1||l!==e[0]))if(i)o=!0;else{let u=s*r,h=u-r,d=u+r;for(let f=0;f!==r;++f){let y=t[u+f];if(y!==t[h+f]||y!==t[d+f]){o=!0;break}}}if(o){if(s!==a){e[a]=e[s];let u=s*r,h=a*r;for(let d=0;d!==r;++d)t[h+d]=t[u+d]}++a}}if(n>0){e[a]=e[n];for(let s=n*r,o=a*r,l=0;l!==r;++l)t[o+l]=t[s+l];++a}return a!==e.length?(this.times=e.slice(0,a),this.values=t.slice(0,a*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}};Dn.prototype.TimeBufferType=Float32Array,Dn.prototype.ValueBufferType=Float32Array,Dn.prototype.DefaultInterpolation=io;var ys=class extends Dn{constructor(e,t,r){super(e,t,r)}};ys.prototype.ValueTypeName="bool",ys.prototype.ValueBufferType=Array,ys.prototype.DefaultInterpolation=ro,ys.prototype.InterpolantFactoryMethodLinear=void 0,ys.prototype.InterpolantFactoryMethodSmooth=void 0;var Rf=class extends Dn{};Rf.prototype.ValueTypeName="color";var vs=class extends Dn{};vs.prototype.ValueTypeName="number";var Oy=class extends No{constructor(e,t,r,i){super(e,t,r,i)}interpolate_(e,t,r,i){let n=this.resultBuffer,a=this.sampleValues,s=this.valueSize,o=(r-t)/(i-t),l=e*s;for(let c=l+s;l!==c;l+=4)di.slerpFlat(n,0,a,l-s,a,l,o);return n}},xs=class extends Dn{InterpolantFactoryMethodLinear(e){return new Oy(this.times,this.values,this.getValueSize(),e)}};xs.prototype.ValueTypeName="quaternion",xs.prototype.InterpolantFactoryMethodSmooth=void 0;var bs=class extends Dn{constructor(e,t,r){super(e,t,r)}};bs.prototype.ValueTypeName="string",bs.prototype.ValueBufferType=Array,bs.prototype.DefaultInterpolation=ro,bs.prototype.InterpolantFactoryMethodLinear=void 0,bs.prototype.InterpolantFactoryMethodSmooth=void 0;var _s=class extends Dn{};_s.prototype.ValueTypeName="vector";var Lo=class{constructor(e="",t=-1,r=[],i=Wu){this.name=e,this.tracks=r,this.duration=t,this.blendMode=i,this.uuid=rn(),this.duration<0&&this.resetDuration()}static parse(e){let t=[],r=e.tracks,i=1/(e.fps||1);for(let a=0,s=r.length;a!==s;++a)t.push(yE(r[a]).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,a=r.length;n!==a;++n)t.push(Dn.toJSON(r[n]));return i}static CreateFromMorphTargetSequence(e,t,r,i){let n=t.length,a=[];for(let s=0;s<n;s++){let o=[],l=[];o.push((s+n-1)%n,s,(s+1)%n),l.push(0,1,0);let c=Iy(o);o=Tf(o,1,c),l=Tf(l,1,c),!i&&o[0]===0&&(o.push(n),l.push(l[0])),a.push(new vs(".morphTargetInfluences["+t[s].name+"]",o,l).scale(1/r))}return new this(e,-1,a)}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 s=0,o=e.length;s<o;s++){let l=e[s],c=l.name.match(n);if(c&&c.length>1){let u=c[1],h=i[u];h||(i[u]=h=[]),h.push(l)}}let a=[];for(let s in i)a.push(this.CreateFromMorphTargetSequence(s,i[s],t,r));return a}static parseAnimation(e,t){if(!e)return console.error("THREE.AnimationClip: No animation in JSONLoader data."),null;let r=function(c,u,h,d,f){if(h.length!==0){let y=[],g=[];Af(h,y,g,d),y.length!==0&&f.push(new c(u,y,g))}},i=[],n=e.name||"default",a=e.fps||30,s=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 h={},d;for(d=0;d<u.length;d++)if(u[d].morphTargets)for(let f=0;f<u[d].morphTargets.length;f++)h[u[d].morphTargets[f]]=-1;for(let f in h){let y=[],g=[];for(let p=0;p!==u[d].morphTargets.length;++p){let m=u[d];y.push(m.time),g.push(m.morphTarget===f?1:0)}i.push(new vs(".morphTargetInfluence["+f+"]",y,g))}o=h.length*a}else{let h=".bones["+t[c].name+"]";r(_s,h+".position",u,"pos",i),r(xs,h+".quaternion",u,"rot",i),r(_s,h+".scale",u,"scl",i)}}return i.length===0?null:new this(n,o,i,s)}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 gE(e){switch(e.toLowerCase()){case"scalar":case"double":case"float":case"number":case"integer":return vs;case"vector":case"vector2":case"vector3":case"vector4":return _s;case"color":return Rf;case"quaternion":return xs;case"bool":case"boolean":return ys;case"string":return bs}throw new Error("THREE.KeyframeTrack: Unsupported typeName: "+e)}function yE(e){if(e.type===void 0)throw new Error("THREE.KeyframeTrack: track type undefined, can not parse");let t=gE(e.type);if(e.times===void 0){let r=[],i=[];Af(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 ga={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={}}},Pf=class{constructor(e,t,r){let i=this,n=!1,a=0,s=0,o,l=[];this.onStart=void 0,this.onLoad=e,this.onProgress=t,this.onError=r,this.itemStart=function(c){s++,n===!1&&i.onStart!==void 0&&i.onStart(c,a,s),n=!0},this.itemEnd=function(c){a++,i.onProgress!==void 0&&i.onProgress(c,a,s),a===s&&(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,h=l.length;u<h;u+=2){let d=l[u],f=l[u+1];if(d.global&&(d.lastIndex=0),d.test(c))return f}return null}}},Dy=new Pf,fi=class{constructor(e){this.manager=e!==void 0?e:Dy,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}};fi.DEFAULT_MATERIAL_NAME="__DEFAULT";var ya={},vE=class extends Error{constructor(e,t){super(e),this.response=t}},bn=class extends fi{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=ga.get(e);if(n!==void 0)return this.manager.itemStart(e),setTimeout(()=>{t&&t(n),this.manager.itemEnd(e)},0),n;if(ya[e]!==void 0){ya[e].push({onLoad:t,onProgress:r,onError:i});return}ya[e]=[],ya[e].push({onLoad:t,onProgress:r,onError:i});let a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?"include":"same-origin"}),s=this.mimeType,o=this.responseType;fetch(a).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=ya[e],u=l.body.getReader(),h=l.headers.get("X-File-Size")||l.headers.get("Content-Length"),d=h?parseInt(h):0,f=d!==0,y=0,g=new ReadableStream({start(p){m();function m(){u.read().then(({done:v,value:x})=>{if(v)p.close();else{y+=x.byteLength;let b=new ProgressEvent("progress",{lengthComputable:f,loaded:y,total:d});for(let _=0,M=c.length;_<M;_++){let C=c[_];C.onProgress&&C.onProgress(b)}p.enqueue(x),m()}},v=>{p.error(v)})}}});return new Response(g)}else throw new vE(`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,s));case"json":return l.json();default:if(s===void 0)return l.text();{let c=/charset="?([^;"\s]*)"?/i.exec(s),u=c&&c[1]?c[1].toLowerCase():void 0,h=new TextDecoder(u);return l.arrayBuffer().then(d=>h.decode(d))}}}).then(l=>{ga.add(e,l);let c=ya[e];delete ya[e];for(let u=0,h=c.length;u<h;u++){let d=c[u];d.onLoad&&d.onLoad(l)}}).catch(l=>{let c=ya[e];if(c===void 0)throw this.manager.itemError(e),l;delete ya[e];for(let u=0,h=c.length;u<h;u++){let d=c[u];d.onError&&d.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}},xE=class extends fi{constructor(e){super(e)}load(e,t,r,i){let n=this,a=new bn(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(s){try{t(n.parse(JSON.parse(s)))}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=Lo.parse(e[r]);t.push(i)}return t}},bE=class extends fi{constructor(e){super(e)}load(e,t,r,i){let n=this,a=[],s=new Nh,o=new bn(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(h){let d=n.parse(h,!0);a[u]={width:d.width,height:d.height,format:d.format,mipmaps:d.mipmaps},l+=1,l===6&&(d.mipmapCount===1&&(s.minFilter=Zr),s.image=a,s.format=d.format,s.needsUpdate=!0,t&&t(s))},r,i)}if(Array.isArray(e))for(let u=0,h=e.length;u<h;++u)c(u);else o.load(e,function(u){let h=n.parse(u,!0);if(h.isCubemap){let d=h.mipmaps.length/h.mipmapCount;for(let f=0;f<d;f++){a[f]={mipmaps:[]};for(let y=0;y<h.mipmapCount;y++)a[f].mipmaps.push(h.mipmaps[f*h.mipmapCount+y]),a[f].format=h.format,a[f].width=h.width,a[f].height=h.height}s.image=a}else s.image.width=h.width,s.image.height=h.height,s.mipmaps=h.mipmaps;h.mipmapCount===1&&(s.minFilter=Zr),s.format=h.format,s.needsUpdate=!0,t&&t(s)},r,i);return s}},tc=class extends fi{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,a=ga.get(e);if(a!==void 0)return n.manager.itemStart(e),setTimeout(function(){t&&t(a),n.manager.itemEnd(e)},0),a;let s=Il("img");function o(){c(),ga.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(){s.removeEventListener("load",o,!1),s.removeEventListener("error",l,!1)}return s.addEventListener("load",o,!1),s.addEventListener("error",l,!1),e.slice(0,5)!=="data:"&&this.crossOrigin!==void 0&&(s.crossOrigin=this.crossOrigin),n.manager.itemStart(e),s.src=e,s}},_E=class extends fi{constructor(e){super(e)}load(e,t,r,i){let n=new Ul;n.colorSpace=Pr;let a=new tc(this.manager);a.setCrossOrigin(this.crossOrigin),a.setPath(this.path);let s=0;function o(l){a.load(e[l],function(c){n.images[l]=c,s++,s===6&&(n.needsUpdate=!0,t&&t(n))},void 0,i)}for(let l=0;l<e.length;++l)o(l);return n}},wE=class extends fi{constructor(e){super(e)}load(e,t,r,i){let n=this,a=new sn,s=new bn(this.manager);return s.setResponseType("arraybuffer"),s.setRequestHeader(this.requestHeader),s.setPath(this.path),s.setWithCredentials(n.withCredentials),s.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?a.image=l.image:l.data!==void 0&&(a.image.width=l.width,a.image.height=l.height,a.image.data=l.data),a.wrapS=l.wrapS!==void 0?l.wrapS:Ri,a.wrapT=l.wrapT!==void 0?l.wrapT:Ri,a.magFilter=l.magFilter!==void 0?l.magFilter:Zr,a.minFilter=l.minFilter!==void 0?l.minFilter:Zr,a.anisotropy=l.anisotropy!==void 0?l.anisotropy:1,l.colorSpace!==void 0&&(a.colorSpace=l.colorSpace),l.flipY!==void 0&&(a.flipY=l.flipY),l.format!==void 0&&(a.format=l.format),l.type!==void 0&&(a.type=l.type),l.mipmaps!==void 0&&(a.mipmaps=l.mipmaps,a.minFilter=mn),l.mipmapCount===1&&(a.minFilter=Zr),l.generateMipmaps!==void 0&&(a.generateMipmaps=l.generateMipmaps),a.needsUpdate=!0,t&&t(a,l)},r,i),a}},If=class extends fi{constructor(e){super(e)}load(e,t,r,i){let n=new ei,a=new tc(this.manager);return a.setCrossOrigin(this.crossOrigin),a.setPath(this.path),a.load(e,function(s){n.image=s,n.needsUpdate=!0,t!==void 0&&t(n)},r,i),n}},Fa=class extends Ar{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new yt(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}},ky=class extends Fa{constructor(e,t,r){super(e,r),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(Ar.DEFAULT_UP),this.updateMatrix(),this.groundColor=new yt(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}},Nf=new Jt,Uy=new ee,Fy=new ee,Lf=class{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new Xe(512,512),this.map=null,this.mapPass=null,this.matrix=new Jt,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new Wl,this._frameExtents=new Xe(1,1),this._viewportCount=1,this._viewports=[new Nr(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){let t=this.camera,r=this.matrix;Uy.setFromMatrixPosition(e.matrixWorld),t.position.copy(Uy),Fy.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(Fy),t.updateMatrixWorld(),Nf.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Nf),r.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),r.multiply(Nf)}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}},EE=class extends Lf{constructor(){super(new li(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1}updateMatrices(e){let t=this.camera,r=no*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}},Of=class extends Fa{constructor(e,t,r=0,i=Math.PI/3,n=0,a=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(Ar.DEFAULT_UP),this.updateMatrix(),this.target=new Ar,this.distance=r,this.angle=i,this.penumbra=n,this.decay=a,this.map=null,this.shadow=new EE}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}},By=new Jt,rc=new ee,Df=new ee,ME=class extends Lf{constructor(){super(new li(90,1,.5,500)),this.isPointLightShadow=!0,this._frameExtents=new Xe(4,2),this._viewportCount=6,this._viewports=[new Nr(2,1,1,1),new Nr(0,1,1,1),new Nr(3,1,1,1),new Nr(1,1,1,1),new Nr(3,0,1,1),new Nr(1,0,1,1)],this._cubeDirections=[new ee(1,0,0),new ee(-1,0,0),new ee(0,0,1),new ee(0,0,-1),new ee(0,1,0),new ee(0,-1,0)],this._cubeUps=[new ee(0,1,0),new ee(0,1,0),new ee(0,1,0),new ee(0,1,0),new ee(0,0,1),new ee(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()),rc.setFromMatrixPosition(e.matrixWorld),r.position.copy(rc),Df.copy(r.position),Df.add(this._cubeDirections[t]),r.up.copy(this._cubeUps[t]),r.lookAt(Df),r.updateMatrixWorld(),i.makeTranslation(-rc.x,-rc.y,-rc.z),By.multiplyMatrices(r.projectionMatrix,r.matrixWorldInverse),this._frustum.setFromProjectionMatrix(By)}},jh=class extends Fa{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 ME}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}},Oo=class extends hh{constructor(e=-1,t=1,r=1,i=-1,n=.1,a=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=a,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,a){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=a,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,a=r+e,s=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,a=n+l*this.view.width,s-=c*this.view.offsetY,o=s-c*this.view.height}this.projectionMatrix.makeOrthographic(n,a,s,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}},SE=class extends Lf{constructor(){super(new Oo(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}},Xh=class extends Fa{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Ar.DEFAULT_UP),this.updateMatrix(),this.target=new Ar,this.shadow=new SE}dispose(){this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}},kf=class extends Fa{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}},zy=class extends Fa{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}},Gy=class{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new ee)}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,a=this.coefficients;return t.copy(a[0]).multiplyScalar(.282095),t.addScaledVector(a[1],.488603*i),t.addScaledVector(a[2],.488603*n),t.addScaledVector(a[3],.488603*r),t.addScaledVector(a[4],1.092548*(r*i)),t.addScaledVector(a[5],1.092548*(i*n)),t.addScaledVector(a[6],.315392*(3*n*n-1)),t.addScaledVector(a[7],1.092548*(r*n)),t.addScaledVector(a[8],.546274*(r*r-i*i)),t}getIrradianceAt(e,t){let r=e.x,i=e.y,n=e.z,a=this.coefficients;return t.copy(a[0]).multiplyScalar(.886227),t.addScaledVector(a[1],2*.511664*i),t.addScaledVector(a[2],2*.511664*n),t.addScaledVector(a[3],2*.511664*r),t.addScaledVector(a[4],2*.429043*r*i),t.addScaledVector(a[5],2*.429043*i*n),t.addScaledVector(a[6],.743125*n*n-.247708),t.addScaledVector(a[7],2*.429043*r*n),t.addScaledVector(a[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)}},Vy=class extends Fa{constructor(e=new Gy,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}},Hy=class $1 extends fi{constructor(t){super(t),this.textures={}}load(t,r,i,n){let a=this,s=new bn(a.manager);s.setPath(a.path),s.setRequestHeader(a.requestHeader),s.setWithCredentials(a.withCredentials),s.load(t,function(o){try{r(a.parse(JSON.parse(o)))}catch(l){n?n(l):console.error(l),a.manager.itemError(t)}},i,n)}parse(t){let r=this.textures;function i(a){return r[a]===void 0&&console.warn("THREE.MaterialLoader: Undefined texture",a),r[a]}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 yt().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 a in t.uniforms){let s=t.uniforms[a];switch(n.uniforms[a]={},s.type){case"t":n.uniforms[a].value=i(s.value);break;case"c":n.uniforms[a].value=new yt().setHex(s.value);break;case"v2":n.uniforms[a].value=new Xe().fromArray(s.value);break;case"v3":n.uniforms[a].value=new ee().fromArray(s.value);break;case"v4":n.uniforms[a].value=new Nr().fromArray(s.value);break;case"m3":n.uniforms[a].value=new xr().fromArray(s.value);break;case"m4":n.uniforms[a].value=new Jt().fromArray(s.value);break;default:n.uniforms[a].value=s.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 a in t.extensions)n.extensions[a]=t.extensions[a];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 a=t.normalScale;Array.isArray(a)===!1&&(a=[a,a]),n.normalScale=new Xe().fromArray(a)}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 Xe().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 $1.createMaterialFromType(t)}static createMaterialFromType(t){let r={ShadowMaterial:Sy,SpriteMaterial:dh,RawShaderMaterial:_f,ShaderMaterial:oi,PointsMaterial:Yl,MeshPhysicalMaterial:on,MeshStandardMaterial:Ki,MeshPhongMaterial:wf,MeshToonMaterial:Ty,MeshNormalMaterial:Ef,MeshLambertMaterial:Ay,MeshDepthMaterial:Mf,MeshDistanceMaterial:Sf,MeshBasicMaterial:ti,MeshMatcapMaterial:Cy,LineDashedMaterial:Ry,LineBasicMaterial:ri,Material:xi};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)}},Wy=class extends ar{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}},jy=class extends fi{constructor(e){super(e)}load(e,t,r,i){let n=this,a=new bn(n.manager);a.setPath(n.path),a.setRequestHeader(n.requestHeader),a.setWithCredentials(n.withCredentials),a.load(e,function(s){try{t(n.parse(JSON.parse(s)))}catch(o){i?i(o):console.error(o),n.manager.itemError(e)}},r,i)}parse(e){let t={},r={};function i(h,d){if(t[d]!==void 0)return t[d];let f=h.interleavedBuffers[d],y=n(h,f.buffer),g=ao(f.type,y),p=new Fl(g,f.stride);return p.uuid=f.uuid,t[d]=p,p}function n(h,d){if(r[d]!==void 0)return r[d];let f=h.arrayBuffers[d],y=new Uint32Array(f).buffer;return r[d]=y,y}let a=e.isInstancedBufferGeometry?new Wy:new ar,s=e.data.index;if(s!==void 0){let h=ao(s.type,s.array);a.setIndex(new Mr(h,1))}let o=e.data.attributes;for(let h in o){let d=o[h],f;if(d.isInterleavedBufferAttribute){let y=i(e.data,d.data);f=new wo(y,d.itemSize,d.offset,d.normalized)}else{let y=ao(d.type,d.array),g=d.isInstancedBufferAttribute?hs:Mr;f=new g(y,d.itemSize,d.normalized)}d.name!==void 0&&(f.name=d.name),d.usage!==void 0&&f.setUsage(d.usage),a.setAttribute(h,f)}let l=e.data.morphAttributes;if(l)for(let h in l){let d=l[h],f=[];for(let y=0,g=d.length;y<g;y++){let p=d[y],m;if(p.isInterleavedBufferAttribute){let v=i(e.data,p.data);m=new wo(v,p.itemSize,p.offset,p.normalized)}else{let v=ao(p.type,p.array);m=new Mr(v,p.itemSize,p.normalized)}p.name!==void 0&&(m.name=p.name),f.push(m)}a.morphAttributes[h]=f}e.data.morphTargetsRelative&&(a.morphTargetsRelative=!0);let c=e.data.groups||e.data.drawcalls||e.data.offsets;if(c!==void 0)for(let h=0,d=c.length;h!==d;++h){let f=c[h];a.addGroup(f.start,f.count,f.materialIndex)}let u=e.data.boundingSphere;if(u!==void 0){let h=new ee;u.center!==void 0&&h.fromArray(u.center),a.boundingSphere=new si(h,u.radius)}return e.name&&(a.name=e.name),e.userData&&(a.userData=e.userData),a}},TE=class extends fi{constructor(e){super(e)}load(e,t,r,i){let n=this,a=this.path===""?va.extractUrlBase(e):this.path;this.resourcePath=this.resourcePath||a;let s=new bn(this.manager);s.setPath(this.path),s.setRequestHeader(this.requestHeader),s.setWithCredentials(this.withCredentials),s.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 bn(this.manager);n.setPath(this.path),n.setRequestHeader(this.requestHeader),n.setWithCredentials(this.withCredentials);let a=await n.loadAsync(e,t),s=JSON.parse(a),o=s.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(s)}parse(e,t){let r=this.parseAnimations(e.animations),i=this.parseShapes(e.shapes),n=this.parseGeometries(e.geometries,i),a=this.parseImages(e.images,function(){t!==void 0&&t(l)}),s=this.parseTextures(e.textures,a),o=this.parseMaterials(e.materials,s),l=this.parseObject(e.object,n,o,s,r),c=this.parseSkeletons(e.skeletons,l);if(this.bindSkeletons(l,c),this.bindLightTargets(l),t!==void 0){let u=!1;for(let h in a)if(a[h].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),a=this.parseTextures(e.textures,n),s=this.parseMaterials(e.materials,a),o=this.parseObject(e.object,i,s,a,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,a=e.length;n<a;n++){let s=new Jp().fromJSON(e[n],i);r[s.uuid]=s}return r}parseGeometries(e,t){let r={};if(e!==void 0){let i=new jy;for(let n=0,a=e.length;n<a;n++){let s,o=e[n];switch(o.type){case"BufferGeometry":case"InstancedBufferGeometry":s=i.parse(o);break;default:o.type in My?s=My[o.type].fromJSON(o,t):console.warn(`THREE.ObjectLoader: Unsupported geometry type "${o.type}"`)}s.uuid=o.uuid,o.name!==void 0&&(s.name=o.name),o.userData!==void 0&&(s.userData=o.userData),r[o.uuid]=s}}return r}parseMaterials(e,t){let r={},i={};if(e!==void 0){let n=new Hy;n.setTextures(t);for(let a=0,s=e.length;a<s;a++){let o=e[a];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=Lo.parse(i);t[n.uuid]=n}return t}parseImages(e,t){let r=this,i={},n;function a(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 s(o){if(typeof o=="string"){let l=o,c=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(l)?l:r.resourcePath+l;return a(c)}else return o.data?{data:ao(o.type,o.data),width:o.width,height:o.height}:null}if(e!==void 0&&e.length>0){let o=new Pf(t);n=new tc(o),n.setCrossOrigin(this.crossOrigin);for(let l=0,c=e.length;l<c;l++){let u=e[l],h=u.url;if(Array.isArray(h)){let d=[];for(let f=0,y=h.length;f<y;f++){let g=h[f],p=s(g);p!==null&&(p instanceof HTMLImageElement?d.push(p):d.push(new sn(p.data,p.width,p.height)))}i[u.uuid]=new as(d)}else{let d=s(u.url);i[u.uuid]=new as(d)}}}return i}async parseImagesAsync(e){let t=this,r={},i;async function n(a){if(typeof a=="string"){let s=a,o=/^(\/\/)|([a-z]+:(\/\/)?)/i.test(s)?s:t.resourcePath+s;return await i.loadAsync(o)}else return a.data?{data:ao(a.type,a.data),width:a.width,height:a.height}:null}if(e!==void 0&&e.length>0){i=new tc(this.manager),i.setCrossOrigin(this.crossOrigin);for(let a=0,s=e.length;a<s;a++){let o=e[a],l=o.url;if(Array.isArray(l)){let c=[];for(let u=0,h=l.length;u<h;u++){let d=l[u],f=await n(d);f!==null&&(f instanceof HTMLImageElement?c.push(f):c.push(new sn(f.data,f.width,f.height)))}r[o.uuid]=new as(c)}else{let c=await n(o.url);r[o.uuid]=new as(c)}}}return r}parseTextures(e,t){function r(n,a){return typeof n=="number"?n:(console.warn("THREE.ObjectLoader.parseTexture: Constant should be in numeric form.",n),a[n])}let i={};if(e!==void 0)for(let n=0,a=e.length;n<a;n++){let s=e[n];s.image===void 0&&console.warn('THREE.ObjectLoader: No "image" specified for',s.uuid),t[s.image]===void 0&&console.warn("THREE.ObjectLoader: Undefined image",s.image);let o=t[s.image],l=o.data,c;Array.isArray(l)?(c=new Ul,l.length===6&&(c.needsUpdate=!0)):(l&&l.data?c=new sn:c=new ei,l&&(c.needsUpdate=!0)),c.source=o,c.uuid=s.uuid,s.name!==void 0&&(c.name=s.name),s.mapping!==void 0&&(c.mapping=r(s.mapping,AE)),s.channel!==void 0&&(c.channel=s.channel),s.offset!==void 0&&c.offset.fromArray(s.offset),s.repeat!==void 0&&c.repeat.fromArray(s.repeat),s.center!==void 0&&c.center.fromArray(s.center),s.rotation!==void 0&&(c.rotation=s.rotation),s.wrap!==void 0&&(c.wrapS=r(s.wrap[0],Xy),c.wrapT=r(s.wrap[1],Xy)),s.format!==void 0&&(c.format=s.format),s.internalFormat!==void 0&&(c.internalFormat=s.internalFormat),s.type!==void 0&&(c.type=s.type),s.colorSpace!==void 0&&(c.colorSpace=s.colorSpace),s.minFilter!==void 0&&(c.minFilter=r(s.minFilter,Yy)),s.magFilter!==void 0&&(c.magFilter=r(s.magFilter,Yy)),s.anisotropy!==void 0&&(c.anisotropy=s.anisotropy),s.flipY!==void 0&&(c.flipY=s.flipY),s.generateMipmaps!==void 0&&(c.generateMipmaps=s.generateMipmaps),s.premultiplyAlpha!==void 0&&(c.premultiplyAlpha=s.premultiplyAlpha),s.unpackAlignment!==void 0&&(c.unpackAlignment=s.unpackAlignment),s.compareFunction!==void 0&&(c.compareFunction=s.compareFunction),s.userData!==void 0&&(c.userData=s.userData),i[s.uuid]=c}return i}parseObject(e,t,r,i,n){let a;function s(h){return t[h]===void 0&&console.warn("THREE.ObjectLoader: Undefined geometry",h),t[h]}function o(h){if(h!==void 0){if(Array.isArray(h)){let d=[];for(let f=0,y=h.length;f<y;f++){let g=h[f];r[g]===void 0&&console.warn("THREE.ObjectLoader: Undefined material",g),d.push(r[g])}return d}return r[h]===void 0&&console.warn("THREE.ObjectLoader: Undefined material",h),r[h]}}function l(h){return i[h]===void 0&&console.warn("THREE.ObjectLoader: Undefined texture",h),i[h]}let c,u;switch(e.type){case"Scene":a=new us,e.background!==void 0&&(Number.isInteger(e.background)?a.background=new yt(e.background):a.background=l(e.background)),e.environment!==void 0&&(a.environment=l(e.environment)),e.fog!==void 0&&(e.fog.type==="Fog"?a.fog=new N0(e.fog.color,e.fog.near,e.fog.far):e.fog.type==="FogExp2"&&(a.fog=new I0(e.fog.color,e.fog.density)),e.fog.name!==""&&(a.fog.name=e.fog.name)),e.backgroundBlurriness!==void 0&&(a.backgroundBlurriness=e.backgroundBlurriness),e.backgroundIntensity!==void 0&&(a.backgroundIntensity=e.backgroundIntensity),e.backgroundRotation!==void 0&&a.backgroundRotation.fromArray(e.backgroundRotation),e.environmentIntensity!==void 0&&(a.environmentIntensity=e.environmentIntensity),e.environmentRotation!==void 0&&a.environmentRotation.fromArray(e.environmentRotation);break;case"PerspectiveCamera":a=new li(e.fov,e.aspect,e.near,e.far),e.focus!==void 0&&(a.focus=e.focus),e.zoom!==void 0&&(a.zoom=e.zoom),e.filmGauge!==void 0&&(a.filmGauge=e.filmGauge),e.filmOffset!==void 0&&(a.filmOffset=e.filmOffset),e.view!==void 0&&(a.view=Object.assign({},e.view));break;case"OrthographicCamera":a=new Oo(e.left,e.right,e.top,e.bottom,e.near,e.far),e.zoom!==void 0&&(a.zoom=e.zoom),e.view!==void 0&&(a.view=Object.assign({},e.view));break;case"AmbientLight":a=new kf(e.color,e.intensity);break;case"DirectionalLight":a=new Xh(e.color,e.intensity),a.target=e.target||"";break;case"PointLight":a=new jh(e.color,e.intensity,e.distance,e.decay);break;case"RectAreaLight":a=new zy(e.color,e.intensity,e.width,e.height);break;case"SpotLight":a=new Of(e.color,e.intensity,e.distance,e.angle,e.penumbra,e.decay),a.target=e.target||"";break;case"HemisphereLight":a=new ky(e.color,e.groundColor,e.intensity);break;case"LightProbe":a=new Vy().fromJSON(e);break;case"SkinnedMesh":c=s(e.geometry),u=o(e.material),a=new Qp(c,u),e.bindMode!==void 0&&(a.bindMode=e.bindMode),e.bindMatrix!==void 0&&a.bindMatrix.fromArray(e.bindMatrix),e.skeleton!==void 0&&(a.skeleton=e.skeleton);break;case"Mesh":c=s(e.geometry),u=o(e.material),a=new hr(c,u);break;case"InstancedMesh":c=s(e.geometry),u=o(e.material);let h=e.count,d=e.instanceMatrix,f=e.instanceColor;a=new bh(c,u,h),a.instanceMatrix=new hs(new Float32Array(d.array),16),f!==void 0&&(a.instanceColor=new hs(new Float32Array(f.array),f.itemSize));break;case"BatchedMesh":c=s(e.geometry),u=o(e.material),a=new Y0(e.maxInstanceCount,e.maxVertexCount,e.maxIndexCount,u),a.geometry=c,a.perObjectFrustumCulled=e.perObjectFrustumCulled,a.sortObjects=e.sortObjects,a._drawRanges=e.drawRanges,a._reservedRanges=e.reservedRanges,a._visibility=e.visibility,a._active=e.active,a._bounds=e.bounds.map(y=>{let g=new Yr;g.min.fromArray(y.boxMin),g.max.fromArray(y.boxMax);let p=new si;return p.radius=y.sphereRadius,p.center.fromArray(y.sphereCenter),{boxInitialized:y.boxInitialized,box:g,sphereInitialized:y.sphereInitialized,sphere:p}}),a._maxInstanceCount=e.maxInstanceCount,a._maxVertexCount=e.maxVertexCount,a._maxIndexCount=e.maxIndexCount,a._geometryInitialized=e.geometryInitialized,a._geometryCount=e.geometryCount,a._matricesTexture=l(e.matricesTexture.uuid),e.colorsTexture!==void 0&&(a._colorsTexture=l(e.colorsTexture.uuid));break;case"LOD":a=new U0;break;case"Line":a=new jn(s(e.geometry),o(e.material));break;case"LineLoop":a=new Ch(s(e.geometry),o(e.material));break;case"LineSegments":a=new Fi(s(e.geometry),o(e.material));break;case"PointCloud":case"Points":a=new Ih(s(e.geometry),o(e.material));break;case"Sprite":a=new qp(o(e.material));break;case"Group":a=new jr;break;case"Bone":a=new vh;break;default:a=new Ar}if(a.uuid=e.uuid,e.name!==void 0&&(a.name=e.name),e.matrix!==void 0?(a.matrix.fromArray(e.matrix),e.matrixAutoUpdate!==void 0&&(a.matrixAutoUpdate=e.matrixAutoUpdate),a.matrixAutoUpdate&&a.matrix.decompose(a.position,a.quaternion,a.scale)):(e.position!==void 0&&a.position.fromArray(e.position),e.rotation!==void 0&&a.rotation.fromArray(e.rotation),e.quaternion!==void 0&&a.quaternion.fromArray(e.quaternion),e.scale!==void 0&&a.scale.fromArray(e.scale)),e.up!==void 0&&a.up.fromArray(e.up),e.castShadow!==void 0&&(a.castShadow=e.castShadow),e.receiveShadow!==void 0&&(a.receiveShadow=e.receiveShadow),e.shadow&&(e.shadow.intensity!==void 0&&(a.shadow.intensity=e.shadow.intensity),e.shadow.bias!==void 0&&(a.shadow.bias=e.shadow.bias),e.shadow.normalBias!==void 0&&(a.shadow.normalBias=e.shadow.normalBias),e.shadow.radius!==void 0&&(a.shadow.radius=e.shadow.radius),e.shadow.mapSize!==void 0&&a.shadow.mapSize.fromArray(e.shadow.mapSize),e.shadow.camera!==void 0&&(a.shadow.camera=this.parseObject(e.shadow.camera))),e.visible!==void 0&&(a.visible=e.visible),e.frustumCulled!==void 0&&(a.frustumCulled=e.frustumCulled),e.renderOrder!==void 0&&(a.renderOrder=e.renderOrder),e.userData!==void 0&&(a.userData=e.userData),e.layers!==void 0&&(a.layers.mask=e.layers),e.children!==void 0){let h=e.children;for(let d=0;d<h.length;d++)a.add(this.parseObject(h[d],t,r,i,n))}if(e.animations!==void 0){let h=e.animations;for(let d=0;d<h.length;d++){let f=h[d];a.animations.push(n[f])}}if(e.type==="LOD"){e.autoUpdate!==void 0&&(a.autoUpdate=e.autoUpdate);let h=e.levels;for(let d=0;d<h.length;d++){let f=h[d],y=a.getObjectByProperty("uuid",f.object);y!==void 0&&a.addLevel(y,f.distance,f.hysteresis)}}return a}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 Ar}})}},AE={UVMapping:cu,CubeReflectionMapping:ta,CubeRefractionMapping:Aa,EquirectangularReflectionMapping:vl,EquirectangularRefractionMapping:xl,CubeUVReflectionMapping:Js},Xy={RepeatWrapping:Ni,ClampToEdgeWrapping:Ri,MirroredRepeatWrapping:$s},Yy={NearestFilter:Kr,NearestMipmapNearestFilter:uu,NearestMipmapLinearFilter:$a,LinearFilter:Zr,LinearMipmapNearestFilter:eo,LinearMipmapLinearFilter:mn},qy=class extends fi{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,a=ga.get(e);if(a!==void 0){if(n.manager.itemStart(e),a.then){a.then(l=>{t&&t(l),n.manager.itemEnd(e)}).catch(l=>{i&&i(l)});return}return setTimeout(function(){t&&t(a),n.manager.itemEnd(e)},0),a}let s={};s.credentials=this.crossOrigin==="anonymous"?"same-origin":"include",s.headers=this.requestHeader;let o=fetch(e,s).then(function(l){return l.blob()}).then(function(l){return createImageBitmap(l,Object.assign(n.options,{colorSpaceConversion:"none"}))}).then(function(l){return ga.add(e,l),t&&t(l),n.manager.itemEnd(e),l}).catch(function(l){i&&i(l),ga.remove(e),n.manager.itemError(e),n.manager.itemEnd(e)});ga.add(e,o),n.manager.itemStart(e)}},Yh,Uf=class{static getContext(){return Yh===void 0&&(Yh=new(window.AudioContext||window.webkitAudioContext)),Yh}static setContext(e){Yh=e}},CE=class extends fi{constructor(e){super(e)}load(e,t,r,i){let n=this,a=new bn(this.manager);a.setResponseType("arraybuffer"),a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(o){try{let l=o.slice(0);Uf.getContext().decodeAudioData(l,function(c){t(c)}).catch(s)}catch(l){s(l)}},r,i);function s(o){i?i(o):console.error(o),n.manager.itemError(e)}}},Ky=new Jt,Zy=new Jt,ws=new Jt,RE=class{constructor(){this.type="StereoCamera",this.aspect=1,this.eyeSep=.064,this.cameraL=new li,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new li,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,ws.copy(e.projectionMatrix);let r=t.eyeSep/2,i=r*t.near/t.focus,n=t.near*Math.tan(ns*t.fov*.5)/t.zoom,a,s;Zy.elements[12]=-r,Ky.elements[12]=r,a=-n*t.aspect+i,s=n*t.aspect+i,ws.elements[0]=2*t.near/(s-a),ws.elements[8]=(s+a)/(s-a),this.cameraL.projectionMatrix.copy(ws),a=-n*t.aspect-i,s=n*t.aspect-i,ws.elements[0]=2*t.near/(s-a),ws.elements[8]=(s+a)/(s-a),this.cameraR.projectionMatrix.copy(ws)}this.cameraL.matrixWorld.copy(e.matrixWorld).multiply(Zy),this.cameraR.matrixWorld.copy(e.matrixWorld).multiply(Ky)}},Qy=class extends li{constructor(e=[]){super(),this.isArrayCamera=!0,this.cameras=e}},Ff=class{constructor(e=!0){this.autoStart=e,this.startTime=0,this.oldTime=0,this.elapsedTime=0,this.running=!1}start(){this.startTime=Jy(),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=Jy();e=(t-this.oldTime)/1e3,this.oldTime=t,this.elapsedTime+=e}return e}};function Jy(){return performance.now()}var Es=new ee,$y=new di,PE=new ee,Ms=new ee,IE=class extends Ar{constructor(){super(),this.type="AudioListener",this.context=Uf.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._clock=new Ff}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(Es,$y,PE),Ms.set(0,0,-1).applyQuaternion($y),t.positionX){let i=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(Es.x,i),t.positionY.linearRampToValueAtTime(Es.y,i),t.positionZ.linearRampToValueAtTime(Es.z,i),t.forwardX.linearRampToValueAtTime(Ms.x,i),t.forwardY.linearRampToValueAtTime(Ms.y,i),t.forwardZ.linearRampToValueAtTime(Ms.z,i),t.upX.linearRampToValueAtTime(r.x,i),t.upY.linearRampToValueAtTime(r.y,i),t.upZ.linearRampToValueAtTime(r.z,i)}else t.setPosition(Es.x,Es.y,Es.z),t.setOrientation(Ms.x,Ms.y,Ms.z,r.x,r.y,r.z)}},ev=class extends Ar{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)}},Ss=new ee,tv=new di,NE=new ee,Ts=new ee,LE=class extends ev{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(Ss,tv,NE),Ts.set(0,0,1).applyQuaternion(tv);let t=this.panner;if(t.positionX){let r=this.context.currentTime+this.listener.timeDelta;t.positionX.linearRampToValueAtTime(Ss.x,r),t.positionY.linearRampToValueAtTime(Ss.y,r),t.positionZ.linearRampToValueAtTime(Ss.z,r),t.orientationX.linearRampToValueAtTime(Ts.x,r),t.orientationY.linearRampToValueAtTime(Ts.y,r),t.orientationZ.linearRampToValueAtTime(Ts.z,r)}else t.setPosition(Ss.x,Ss.y,Ss.z),t.setOrientation(Ts.x,Ts.y,Ts.z)}},OE=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}},rv=class{constructor(e,t,r){this.binding=e,this.valueSize=r;let i,n,a;switch(t){case"quaternion":i=this._slerp,n=this._slerpAdditive,a=this._setAdditiveIdentityQuaternion,this.buffer=new Float64Array(r*6),this._workIndex=5;break;case"string":case"bool":i=this._select,n=this._select,a=this._setAdditiveIdentityOther,this.buffer=new Array(r*5);break;default:i=this._lerp,n=this._lerpAdditive,a=this._setAdditiveIdentityNumeric,this.buffer=new Float64Array(r*5)}this._mixBufferRegion=i,this._mixBufferRegionAdditive=n,this._setIdentity=a,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,a=this.cumulativeWeight;if(a===0){for(let s=0;s!==i;++s)r[n+s]=r[s];a=t}else{a+=t;let s=t/a;this._mixBufferRegion(r,n,0,s,i)}this.cumulativeWeight=a}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,a=this.cumulativeWeightAdditive,s=this.binding;if(this.cumulativeWeight=0,this.cumulativeWeightAdditive=0,n<1){let o=t*this._origIndex;this._mixBufferRegion(r,i,o,1-n,t)}a>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]){s.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,a=i;n!==a;++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 a=0;a!==n;++a)e[t+a]=e[r+a]}_slerp(e,t,r,i){di.slerpFlat(e,t,e,t,e,r,i)}_slerpAdditive(e,t,r,i,n){let a=this._workIndex*n;di.multiplyQuaternionsFlat(e,a,e,t,e,r),di.slerpFlat(e,t,e,t,e,a,i)}_lerp(e,t,r,i,n){let a=1-i;for(let s=0;s!==n;++s){let o=t+s;e[o]=e[o]*a+e[r+s]*i}}_lerpAdditive(e,t,r,i,n){for(let a=0;a!==n;++a){let s=t+a;e[s]=e[s]+e[r+a]*i}}},Bf="\\[\\]\\.:\\/",DE=new RegExp("["+Bf+"]","g"),zf="[^"+Bf+"]",kE="[^"+Bf.replace("\\.","")+"]",UE=/((?:WC+[\/:])*)/.source.replace("WC",zf),FE=/(WCOD+)?/.source.replace("WCOD",kE),BE=/(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace("WC",zf),zE=/\.(WC+)(?:\[(.+)\])?/.source.replace("WC",zf),GE=new RegExp("^"+UE+FE+BE+zE+"$"),VE=["material","materials","bones","map"],HE=class{constructor(e,t,r){let i=r||Vr.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()}},Vr=class fl{constructor(t,r,i){this.path=r,this.parsedPath=i||fl.parseTrackName(r),this.node=fl.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 fl.Composite(t,r,i):new fl(t,r,i)}static sanitizeNodeName(t){return t.replace(/\s/g,"_").replace(DE,"")}static parseTrackName(t){let r=GE.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 a=i.nodeName.substring(n+1);VE.indexOf(a)!==-1&&(i.nodeName=i.nodeName.substring(0,n),i.objectName=a)}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(a){for(let s=0;s<a.length;s++){let o=a[s];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,a=i.length;n!==a;++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,a=i.length;n!==a;++n)i[n]=t[r++]}_setValue_array_setNeedsUpdate(t,r){let i=this.resolvedProperty;for(let n=0,a=i.length;n!==a;++n)i[n]=t[r++];this.targetObject.needsUpdate=!0}_setValue_array_setMatrixWorldNeedsUpdate(t,r){let i=this.resolvedProperty;for(let n=0,a=i.length;n!==a;++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,a=r.propertyIndex;if(t||(t=fl.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 s=t[n];if(s===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(a!==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[a]!==void 0&&(a=t.morphTargetDictionary[a])}l=this.BindingType.ArrayElement,this.resolvedProperty=s,this.propertyIndex=a}else s.fromArray!==void 0&&s.toArray!==void 0?(l=this.BindingType.HasFromToArray,this.resolvedProperty=s):Array.isArray(s)?(l=this.BindingType.EntireArray,this.resolvedProperty=s):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}};Vr.Composite=HE,Vr.prototype.BindingType={Direct:0,EntireArray:1,ArrayElement:2,HasFromToArray:3},Vr.prototype.Versioning={None:0,NeedsUpdate:1,MatrixWorldNeedsUpdate:2},Vr.prototype.GetterByBindingType=[Vr.prototype._getValue_direct,Vr.prototype._getValue_array,Vr.prototype._getValue_arrayElement,Vr.prototype._getValue_toArray],Vr.prototype.SetterByBindingTypeAndVersioning=[[Vr.prototype._setValue_direct,Vr.prototype._setValue_direct_setNeedsUpdate,Vr.prototype._setValue_direct_setMatrixWorldNeedsUpdate],[Vr.prototype._setValue_array,Vr.prototype._setValue_array_setNeedsUpdate,Vr.prototype._setValue_array_setMatrixWorldNeedsUpdate],[Vr.prototype._setValue_arrayElement,Vr.prototype._setValue_arrayElement_setNeedsUpdate,Vr.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate],[Vr.prototype._setValue_fromArray,Vr.prototype._setValue_fromArray_setNeedsUpdate,Vr.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate]];var WE=class{constructor(){this.isAnimationObjectGroup=!0,this.uuid=rn(),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,a=n.length,s,o=e.length,l=this.nCachedObjects_;for(let c=0,u=arguments.length;c!==u;++c){let h=arguments[c],d=h.uuid,f=t[d];if(f===void 0){f=o++,t[d]=f,e.push(h);for(let y=0,g=a;y!==g;++y)n[y].push(new Vr(h,r[y],i[y]))}else if(f<l){s=e[f];let y=--l,g=e[y];t[g.uuid]=f,e[f]=g,t[d]=y,e[y]=h;for(let p=0,m=a;p!==m;++p){let v=n[p],x=v[y],b=v[f];v[f]=x,b===void 0&&(b=new Vr(h,r[p],i[p])),v[y]=b}}else e[f]!==s&&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 a=0,s=arguments.length;a!==s;++a){let o=arguments[a],l=o.uuid,c=t[l];if(c!==void 0&&c>=n){let u=n++,h=e[u];t[h.uuid]=c,e[c]=h,t[l]=u,e[u]=o;for(let d=0,f=i;d!==f;++d){let y=r[d],g=y[u],p=y[c];y[c]=g,y[u]=p}}}this.nCachedObjects_=n}uncache(){let e=this._objects,t=this._indicesByUUID,r=this._bindings,i=r.length,n=this.nCachedObjects_,a=e.length;for(let s=0,o=arguments.length;s!==o;++s){let l=arguments[s],c=l.uuid,u=t[c];if(u!==void 0)if(delete t[c],u<n){let h=--n,d=e[h],f=--a,y=e[f];t[d.uuid]=u,e[u]=d,t[y.uuid]=h,e[h]=y,e.pop();for(let g=0,p=i;g!==p;++g){let m=r[g],v=m[h],x=m[f];m[u]=v,m[h]=x,m.pop()}}else{let h=--a,d=e[h];h>0&&(t[d.uuid]=u),e[u]=d,e.pop();for(let f=0,y=i;f!==y;++f){let g=r[f];g[u]=g[h],g.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 a=this._paths,s=this._parsedPaths,o=this._objects,l=o.length,c=this.nCachedObjects_,u=new Array(l);i=n.length,r[e]=i,a.push(e),s.push(t),n.push(u);for(let h=c,d=o.length;h!==d;++h){let f=o[h];u[h]=new Vr(f,e,t)}return u}unsubscribe_(e){let t=this._bindingsIndicesByPath,r=t[e];if(r!==void 0){let i=this._paths,n=this._parsedPaths,a=this._bindings,s=a.length-1,o=a[s],l=e[s];t[l]=r,a[r]=o,a.pop(),n[r]=n[s],n.pop(),i[r]=i[s],i.pop()}}},iv=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,a=n.length,s=new Array(a),o={endingStart:ts,endingEnd:ts};for(let l=0;l!==a;++l){let c=n[l].createInterpolant(null);s[l]=c,c.settings=o}this._interpolantSettings=o,this._interpolants=s,this._propertyBindings=new Array(a),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=jg,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,a=n/i,s=i/n;e.warp(1,a,t),this.warp(s,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,a=this.timeScale,s=this._timeScaleInterpolant;s===null&&(s=i._lendControlInterpolant(),this._timeScaleInterpolant=s);let o=s.parameterPositions,l=s.sampleValues;return o[0]=n,o[1]=n+r,l[0]=e/a,l[1]=t/a,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 a=this._updateTime(t),s=this._updateWeight(e);if(s>0){let o=this._interpolants,l=this._propertyBindings;switch(this.blendMode){case xp:for(let c=0,u=o.length;c!==u;++c)o[c].evaluate(a),l[c].accumulateAdditive(s);break;case Wu:default:for(let c=0,u=o.length;c!==u;++c)o[c].evaluate(a),l[c].accumulate(i,s)}}}_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,a=r===Xg;if(e===0)return n===-1?i:a&&(n&1)===1?t-i:i;if(r===Wg){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,a)):this._setEndings(this.repetitions===0,!0,a)),i>=t||i<0){let s=Math.floor(i/t);i-=t*s,n+=Math.abs(s);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,a)}else this._setEndings(!1,!1,a);this._loopCount=n,this.time=i,this._mixer.dispatchEvent({type:"loop",action:this,loopDelta:s})}}else this.time=i;if(a&&(n&1)===1)return t-i}return i}_setEndings(e,t,r){let i=this._interpolantSettings;r?(i.endingStart=rs,i.endingEnd=rs):(e?i.endingStart=this.zeroSlopeAtStart?rs:ts:i.endingStart=Tl,t?i.endingEnd=this.zeroSlopeAtEnd?rs:ts:i.endingEnd=Tl)}_scheduleFading(e,t,r){let i=this._mixer,n=i.time,a=this._weightInterpolant;a===null&&(a=i._lendControlInterpolant(),this._weightInterpolant=a);let s=a.parameterPositions,o=a.sampleValues;return s[0]=n,o[0]=t,s[1]=n+e,o[1]=r,this}},jE=new Float32Array(1),XE=class extends Wn{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,a=e._propertyBindings,s=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 h=i[u],d=h.name,f=c[d];if(f!==void 0)++f.referenceCount,a[u]=f;else{if(f=a[u],f!==void 0){f._cacheIndex===null&&(++f.referenceCount,this._addInactiveBinding(f,o,d));continue}let y=t&&t._propertyBindings[u].binding.parsedPath;f=new rv(Vr.create(r,d,y),h.ValueTypeName,h.getValueSize()),++f.referenceCount,this._addInactiveBinding(f,o,d),a[u]=f}s[u].resultBuffer=f.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,a=n[t];if(a===void 0)a={knownActions:[e],actionByRoot:{}},e._byClipCacheIndex=0,n[t]=a;else{let s=a.knownActions;e._byClipCacheIndex=s.length,s.push(e)}e._cacheIndex=i.length,i.push(e),a.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,a=this._actionsByClip,s=a[n],o=s.knownActions,l=o[o.length-1],c=e._byClipCacheIndex;l._byClipCacheIndex=c,o[c]=l,o.pop(),e._byClipCacheIndex=null;let u=s.actionByRoot,h=(e._localRoot||this._root).uuid;delete u[h],o.length===0&&delete a[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,a=i[t];a===void 0&&(a={},i[t]=a),a[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,a=this._bindingsByRootAndName,s=a[i],o=t[t.length-1],l=e._cacheIndex;o._cacheIndex=l,t[l]=o,t.pop(),delete s[n],Object.keys(s).length===0&&delete a[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 Cf(new Float32Array(2),new Float32Array(2),1,jE),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,a=typeof e=="string"?Lo.findByName(i,e):e,s=a!==null?a.uuid:e,o=this._actionsByClip[s],l=null;if(r===void 0&&(a!==null?r=a.blendMode:r=Wu),o!==void 0){let u=o.actionByRoot[n];if(u!==void 0&&u.blendMode===r)return u;l=o.knownActions[0],a===null&&(a=l._clip)}if(a===null)return null;let c=new iv(this,a,t,r);return this._bindAction(c,l),this._addInactiveAction(c,s,n),c}existingAction(e,t){let r=t||this._root,i=r.uuid,n=typeof e=="string"?Lo.findByName(r,e):e,a=n?n.uuid:e,s=this._actionsByClip[a];return s!==void 0&&s.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),a=this._accuIndex^=1;for(let l=0;l!==r;++l)t[l]._update(i,e,n,a);let s=this._bindings,o=this._nActiveBindings;for(let l=0;l!==o;++l)s[l].apply(a);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 a=n.knownActions;for(let s=0,o=a.length;s!==o;++s){let l=a[s];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 a in r){let s=r[a].actionByRoot,o=s[t];o!==void 0&&(this._deactivateAction(o),this._removeInactiveAction(o))}let i=this._bindingsByRootAndName,n=i[t];if(n!==void 0)for(let a in n){let s=n[a];s.restoreOriginalState(),this._removeInactiveBinding(s)}}uncacheAction(e,t){let r=this.existingAction(e,t);r!==null&&(this._deactivateAction(r),this._removeInactiveAction(r))}},YE=class e_{constructor(t){this.value=t}clone(){return new e_(this.value.clone===void 0?this.value:this.value.clone())}},qE=0,KE=class extends Wn{constructor(){super(),this.isUniformsGroup=!0,Object.defineProperty(this,"id",{value:qE++}),this.name="",this.usage=Cl,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 a=0;a<n.length;a++)this.uniforms.push(n[a].clone())}return this}clone(){return new this.constructor().copy(this)}},ZE=class extends Fl{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}},QE=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}},nv=new Jt,ic=class{constructor(e,t,r=0,i=1/0){this.ray=new ls(e,t),this.near=r,this.far=i,this.camera=null,this.layers=new eh,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 nv.identity().extractRotation(e.matrixWorld),this.ray.origin.setFromMatrixPosition(e.matrixWorld),this.ray.direction.set(0,0,-1).applyMatrix4(nv),this}intersectObject(e,t=!0,r=[]){return Gf(e,this,r,t),r.sort(av),r}intersectObjects(e,t=!0,r=[]){for(let i=0,n=e.length;i<n;i++)Gf(e[i],this,r,t);return r.sort(av),r}};function av(e,t){return e.distance-t.distance}function Gf(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 a=e.children;for(let s=0,o=a.length;s<o;s++)Gf(a[s],t,r,!0)}}var Vf=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=mr(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(mr(t/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}},JE=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)}},$E=class t_{constructor(t,r,i,n){t_.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 a=this.elements;return a[0]=t,a[2]=r,a[1]=i,a[3]=n,this}},sv=new Xe,eM=class{constructor(e=new Xe(1/0,1/0),t=new Xe(-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=sv.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,sv).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)}},ov=new ee,qh=new ee,tM=class{constructor(e=new ee,t=new ee){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){ov.subVectors(e,this.start),qh.subVectors(this.end,this.start);let r=qh.dot(qh),i=qh.dot(ov)/r;return t&&(i=mr(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)}},lv=new ee,rM=class extends Ar{constructor(e,t){super(),this.light=e,this.matrixAutoUpdate=!1,this.color=t,this.type="SpotLightHelper";let r=new ar,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 a=0,s=1,o=32;a<o;a++,s++){let l=a/o*Math.PI*2,c=s/o*Math.PI*2;i.push(Math.cos(l),Math.sin(l),1,Math.cos(c),Math.sin(c),1)}r.setAttribute("position",new Mt(i,3));let n=new ri({fog:!1,toneMapped:!1});this.cone=new Fi(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),lv.setFromMatrixPosition(this.light.target.matrixWorld),this.cone.lookAt(lv),this.color!==void 0?this.cone.material.color.set(this.color):this.cone.material.color.copy(this.light.color)}},Ba=new ee,Kh=new Jt,Hf=new Jt,iM=class extends Fi{constructor(e){let t=cv(e),r=new ar,i=[],n=[],a=new yt(0,0,1),s=new yt(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(a.r,a.g,a.b),n.push(s.r,s.g,s.b))}r.setAttribute("position",new Mt(i,3)),r.setAttribute("color",new Mt(n,3));let o=new ri({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");Hf.copy(this.root.matrixWorld).invert();for(let n=0,a=0;n<t.length;n++){let s=t[n];s.parent&&s.parent.isBone&&(Kh.multiplyMatrices(Hf,s.matrixWorld),Ba.setFromMatrixPosition(Kh),i.setXYZ(a,Ba.x,Ba.y,Ba.z),Kh.multiplyMatrices(Hf,s.parent.matrixWorld),Ba.setFromMatrixPosition(Kh),i.setXYZ(a+1,Ba.x,Ba.y,Ba.z),a+=2)}r.getAttribute("position").needsUpdate=!0,super.updateMatrixWorld(e)}dispose(){this.geometry.dispose(),this.material.dispose()}};function cv(e){let t=[];e.isBone===!0&&t.push(e);for(let r=0;r<e.children.length;r++)t.push.apply(t,cv(e.children[r]));return t}var nM=class extends hr{constructor(e,t,r){let i=new Ua(t,4,2),n=new ti({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)}},aM=new ee,uv=new yt,hv=new yt,sM=class extends Ar{constructor(e,t,r){super(),this.light=e,this.matrix=e.matrixWorld,this.matrixAutoUpdate=!1,this.color=r,this.type="HemisphereLightHelper";let i=new bf(t);i.rotateY(Math.PI*.5),this.material=new ti({wireframe:!0,fog:!1,toneMapped:!1}),this.color===void 0&&(this.material.vertexColors=!0);let n=i.getAttribute("position"),a=new Float32Array(n.count*3);i.setAttribute("color",new Mr(a,3)),this.add(new hr(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");uv.copy(this.light.color),hv.copy(this.light.groundColor);for(let r=0,i=t.count;r<i;r++){let n=r<i/2?uv:hv;t.setXYZ(r,n.r,n.g,n.b)}t.needsUpdate=!0}this.light.updateWorldMatrix(!0,!1),e.lookAt(aM.setFromMatrixPosition(this.light.matrixWorld).negate())}},oM=class extends Fi{constructor(e=10,t=10,r=4473924,i=8947848){r=new yt(r),i=new yt(i);let n=t/2,a=e/t,s=e/2,o=[],l=[];for(let h=0,d=0,f=-s;h<=t;h++,f+=a){o.push(-s,0,f,s,0,f),o.push(f,0,-s,f,0,s);let y=h===n?r:i;y.toArray(l,d),d+=3,y.toArray(l,d),d+=3,y.toArray(l,d),d+=3,y.toArray(l,d),d+=3}let c=new ar;c.setAttribute("position",new Mt(o,3)),c.setAttribute("color",new Mt(l,3));let u=new ri({vertexColors:!0,toneMapped:!1});super(c,u),this.type="GridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}},lM=class extends Fi{constructor(e=10,t=16,r=8,i=64,n=4473924,a=8947848){n=new yt(n),a=new yt(a);let s=[],o=[];if(t>1)for(let u=0;u<t;u++){let h=u/t*(Math.PI*2),d=Math.sin(h)*e,f=Math.cos(h)*e;s.push(0,0,0),s.push(d,0,f);let y=u&1?n:a;o.push(y.r,y.g,y.b),o.push(y.r,y.g,y.b)}for(let u=0;u<r;u++){let h=u&1?n:a,d=e-e/r*u;for(let f=0;f<i;f++){let y=f/i*(Math.PI*2),g=Math.sin(y)*d,p=Math.cos(y)*d;s.push(g,0,p),o.push(h.r,h.g,h.b),y=(f+1)/i*(Math.PI*2),g=Math.sin(y)*d,p=Math.cos(y)*d,s.push(g,0,p),o.push(h.r,h.g,h.b)}}let l=new ar;l.setAttribute("position",new Mt(s,3)),l.setAttribute("color",new Mt(o,3));let c=new ri({vertexColors:!0,toneMapped:!1});super(l,c),this.type="PolarGridHelper"}dispose(){this.geometry.dispose(),this.material.dispose()}},dv=new ee,Zh=new ee,pv=new ee,cM=class extends Ar{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 ar;i.setAttribute("position",new Mt([-t,t,0,t,t,0,t,-t,0,-t,-t,0,-t,t,0],3));let n=new ri({fog:!1,toneMapped:!1});this.lightPlane=new jn(i,n),this.add(this.lightPlane),i=new ar,i.setAttribute("position",new Mt([0,0,0,0,0,1],3)),this.targetLine=new jn(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),dv.setFromMatrixPosition(this.light.matrixWorld),Zh.setFromMatrixPosition(this.light.target.matrixWorld),pv.subVectors(Zh,dv),this.lightPlane.lookAt(Zh),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(Zh),this.targetLine.scale.z=pv.length()}},Qh=new ee,ii=new hh,uM=class extends Fi{constructor(e){let t=new ar,r=new ri({color:16777215,vertexColors:!0,toneMapped:!1}),i=[],n=[],a={};s("n1","n2"),s("n2","n4"),s("n4","n3"),s("n3","n1"),s("f1","f2"),s("f2","f4"),s("f4","f3"),s("f3","f1"),s("n1","f1"),s("n2","f2"),s("n3","f3"),s("n4","f4"),s("p","n1"),s("p","n2"),s("p","n3"),s("p","n4"),s("u1","u2"),s("u2","u3"),s("u3","u1"),s("c","t"),s("p","c"),s("cn1","cn2"),s("cn3","cn4"),s("cf1","cf2"),s("cf3","cf4");function s(f,y){o(f),o(y)}function o(f){i.push(0,0,0),n.push(0,0,0),a[f]===void 0&&(a[f]=[]),a[f].push(i.length/3-1)}t.setAttribute("position",new Mt(i,3)),t.setAttribute("color",new Mt(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=a,this.update();let l=new yt(16755200),c=new yt(16711680),u=new yt(43775),h=new yt(16777215),d=new yt(3355443);this.setColors(l,c,u,h,d)}setColors(e,t,r,i,n){let a=this.geometry.getAttribute("color");a.setXYZ(0,e.r,e.g,e.b),a.setXYZ(1,e.r,e.g,e.b),a.setXYZ(2,e.r,e.g,e.b),a.setXYZ(3,e.r,e.g,e.b),a.setXYZ(4,e.r,e.g,e.b),a.setXYZ(5,e.r,e.g,e.b),a.setXYZ(6,e.r,e.g,e.b),a.setXYZ(7,e.r,e.g,e.b),a.setXYZ(8,e.r,e.g,e.b),a.setXYZ(9,e.r,e.g,e.b),a.setXYZ(10,e.r,e.g,e.b),a.setXYZ(11,e.r,e.g,e.b),a.setXYZ(12,e.r,e.g,e.b),a.setXYZ(13,e.r,e.g,e.b),a.setXYZ(14,e.r,e.g,e.b),a.setXYZ(15,e.r,e.g,e.b),a.setXYZ(16,e.r,e.g,e.b),a.setXYZ(17,e.r,e.g,e.b),a.setXYZ(18,e.r,e.g,e.b),a.setXYZ(19,e.r,e.g,e.b),a.setXYZ(20,e.r,e.g,e.b),a.setXYZ(21,e.r,e.g,e.b),a.setXYZ(22,e.r,e.g,e.b),a.setXYZ(23,e.r,e.g,e.b),a.setXYZ(24,t.r,t.g,t.b),a.setXYZ(25,t.r,t.g,t.b),a.setXYZ(26,t.r,t.g,t.b),a.setXYZ(27,t.r,t.g,t.b),a.setXYZ(28,t.r,t.g,t.b),a.setXYZ(29,t.r,t.g,t.b),a.setXYZ(30,t.r,t.g,t.b),a.setXYZ(31,t.r,t.g,t.b),a.setXYZ(32,r.r,r.g,r.b),a.setXYZ(33,r.r,r.g,r.b),a.setXYZ(34,r.r,r.g,r.b),a.setXYZ(35,r.r,r.g,r.b),a.setXYZ(36,r.r,r.g,r.b),a.setXYZ(37,r.r,r.g,r.b),a.setXYZ(38,i.r,i.g,i.b),a.setXYZ(39,i.r,i.g,i.b),a.setXYZ(40,n.r,n.g,n.b),a.setXYZ(41,n.r,n.g,n.b),a.setXYZ(42,n.r,n.g,n.b),a.setXYZ(43,n.r,n.g,n.b),a.setXYZ(44,n.r,n.g,n.b),a.setXYZ(45,n.r,n.g,n.b),a.setXYZ(46,n.r,n.g,n.b),a.setXYZ(47,n.r,n.g,n.b),a.setXYZ(48,n.r,n.g,n.b),a.setXYZ(49,n.r,n.g,n.b),a.needsUpdate=!0}update(){let e=this.geometry,t=this.pointMap,r=1,i=1;ii.projectionMatrixInverse.copy(this.camera.projectionMatrixInverse),ci("c",t,e,ii,0,0,-1),ci("t",t,e,ii,0,0,1),ci("n1",t,e,ii,-r,-i,-1),ci("n2",t,e,ii,r,-i,-1),ci("n3",t,e,ii,-r,i,-1),ci("n4",t,e,ii,r,i,-1),ci("f1",t,e,ii,-r,-i,1),ci("f2",t,e,ii,r,-i,1),ci("f3",t,e,ii,-r,i,1),ci("f4",t,e,ii,r,i,1),ci("u1",t,e,ii,r*.7,i*1.1,-1),ci("u2",t,e,ii,-r*.7,i*1.1,-1),ci("u3",t,e,ii,0,i*2,-1),ci("cf1",t,e,ii,-r,0,1),ci("cf2",t,e,ii,r,0,1),ci("cf3",t,e,ii,0,-i,1),ci("cf4",t,e,ii,0,i,1),ci("cn1",t,e,ii,-r,0,-1),ci("cn2",t,e,ii,r,0,-1),ci("cn3",t,e,ii,0,-i,-1),ci("cn4",t,e,ii,0,i,-1),e.getAttribute("position").needsUpdate=!0}dispose(){this.geometry.dispose(),this.material.dispose()}};function ci(e,t,r,i,n,a,s){Qh.set(n,a,s).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],Qh.x,Qh.y,Qh.z)}}var Jh=new Yr,hM=class extends Fi{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 ar;n.setIndex(new Mr(r,1)),n.setAttribute("position",new Mr(i,3)),super(n,new ri({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&&Jh.setFromObject(this.object),Jh.isEmpty())return;let t=Jh.min,r=Jh.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()}},dM=class extends Fi{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 ar;n.setIndex(new Mr(r,1)),n.setAttribute("position",new Mt(i,3)),super(n,new ri({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()}},pM=class extends jn{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],a=new ar;a.setAttribute("position",new Mt(n,3)),a.computeBoundingSphere(),super(a,new ri({color:i,toneMapped:!1})),this.type="PlaneHelper",this.plane=e,this.size=t;let s=[1,1,0,-1,1,0,-1,-1,0,1,1,0,-1,-1,0,1,-1,0],o=new ar;o.setAttribute("position",new Mt(s,3)),o.computeBoundingSphere(),this.add(new hr(o,new ti({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()}},fv=new ee,$h,Wf,fM=class extends Ar{constructor(e=new ee(0,0,1),t=new ee(0,0,0),r=1,i=16776960,n=r*.2,a=n*.2){super(),this.type="ArrowHelper",$h===void 0&&($h=new ar,$h.setAttribute("position",new Mt([0,0,0,0,1,0],3)),Wf=new Zl(0,.5,1,5,1),Wf.translate(0,-.5,0)),this.position.copy(t),this.line=new jn($h,new ri({color:i,toneMapped:!1})),this.line.matrixAutoUpdate=!1,this.add(this.line),this.cone=new hr(Wf,new ti({color:i,toneMapped:!1})),this.cone.matrixAutoUpdate=!1,this.add(this.cone),this.setDirection(e),this.setLength(r,n,a)}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{fv.set(e.z,0,-e.x).normalize();let t=Math.acos(e.y);this.quaternion.setFromAxisAngle(fv,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()}},mM=class extends Fi{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 ar;i.setAttribute("position",new Mt(t,3)),i.setAttribute("color",new Mt(r,3));let n=new ri({vertexColors:!0,toneMapped:!1});super(i,n),this.type="AxesHelper"}setColors(e,t,r){let i=new yt,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()}},gM=class{constructor(){this.type="ShapePath",this.color=new yt,this.subPaths=[],this.currentPath=null}moveTo(e,t){return this.currentPath=new Co,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,a){return this.currentPath.bezierCurveTo(e,t,r,i,n,a),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(e){function t(p){let m=[];for(let v=0,x=p.length;v<x;v++){let b=p[v],_=new fa;_.curves=b.curves,m.push(_)}return m}function r(p,m){let v=m.length,x=!1;for(let b=v-1,_=0;_<v;b=_++){let M=m[b],C=m[_],S=C.x-M.x,w=C.y-M.y;if(Math.abs(w)>Number.EPSILON){if(w<0&&(M=m[_],S=-S,C=m[b],w=-w),p.y<M.y||p.y>C.y)continue;if(p.y===M.y){if(p.x===M.x)return!0}else{let E=w*(p.x-M.x)-S*(p.y-M.y);if(E===0)return!0;if(E<0)continue;x=!x}}else{if(p.y!==M.y)continue;if(C.x<=p.x&&p.x<=M.x||M.x<=p.x&&p.x<=C.x)return!0}}return x}let i=ma.isClockWise,n=this.subPaths;if(n.length===0)return[];let a,s,o,l=[];if(n.length===1)return s=n[0],o=new fa,o.curves=s.curves,l.push(o),l;let c=!i(n[0].getPoints());c=e?!c:c;let u=[],h=[],d=[],f=0,y;h[f]=void 0,d[f]=[];for(let p=0,m=n.length;p<m;p++)s=n[p],y=s.getPoints(),a=i(y),a=e?!a:a,a?(!c&&h[f]&&f++,h[f]={s:new fa,p:y},h[f].s.curves=s.curves,c&&f++,d[f]=[]):d[f].push({h:s,p:y[0]});if(!h[0])return t(n);if(h.length>1){let p=!1,m=0;for(let v=0,x=h.length;v<x;v++)u[v]=[];for(let v=0,x=h.length;v<x;v++){let b=d[v];for(let _=0;_<b.length;_++){let M=b[_],C=!0;for(let S=0;S<h.length;S++)r(M.p,h[S].p)&&(v!==S&&m++,C?(C=!1,u[S].push(M)):p=!0);C&&u[v].push(M)}}m>0&&p===!1&&(d=u)}let g;for(let p=0,m=h.length;p<m;p++){o=h[p].s,l.push(o),g=d[p];for(let v=0,x=g.length;v<x;v++)o.holes.push(g[v].h)}return l}},mv=class extends Wn{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 yM(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 vM(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 xM(e){return e.repeat.x=1,e.repeat.y=1,e.offset.x=0,e.offset.y=0,e}function jf(e,t,r,i){let n=bM(i);switch(r){case pp:return e*t;case mp:return e*t;case gp:return e*t*2;case fu:return e*t/n.components*n.byteLength;case bl:return e*t/n.components*n.byteLength;case yp:return e*t*2/n.components*n.byteLength;case mu:return e*t*2/n.components*n.byteLength;case fp:return e*t*3/n.components*n.byteLength;case Li:return e*t*4/n.components*n.byteLength;case gu:return e*t*4/n.components*n.byteLength;case _l:case wl:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case El:case Ml:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case vu:case bu:return Math.max(e,16)*Math.max(t,8)/4;case yu:case xu:return Math.max(e,8)*Math.max(t,8)/2;case _u:case wu:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Eu:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Mu:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Su:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case Tu:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case Au:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case Cu:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case Ru:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case Pu:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case Iu:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case Nu:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case Lu:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case Ou:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case Du:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case ku:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case Uu:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case Sl:case Fu:case Bu:return Math.ceil(e/4)*Math.ceil(t/4)*16;case vp:case zu:return Math.ceil(e/4)*Math.ceil(t/4)*8;case Gu:case Vu:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw new Error(`Unable to determine texture byte length for ${r} format.`)}function bM(e){switch(e){case gn:case up:return{byteLength:1,components:1};case to:case hp:case yn:return{byteLength:2,components:1};case du:case pu:return{byteLength:2,components:4};case ra:case hu:case Xi:return{byteLength:4,components:1};case dp:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${e}.`)}var _M={contain:yM,cover:vM,fill:xM,getByteLength:jf},wM=class extends Pi{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 gv(){let e=null,t=!1,r=null,i=null;function n(a,s){r(a,s),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(a){r=a},setContext:function(a){e=a}}}function EM(e){let t=new WeakMap;function r(o,l){let c=o.array,u=o.usage,h=c.byteLength,d=e.createBuffer();e.bindBuffer(l,d),e.bufferData(l,c,u),o.onUploadCallback();let f;if(c instanceof Float32Array)f=e.FLOAT;else if(c instanceof Uint16Array)o.isFloat16BufferAttribute?f=e.HALF_FLOAT:f=e.UNSIGNED_SHORT;else if(c instanceof Int16Array)f=e.SHORT;else if(c instanceof Uint32Array)f=e.UNSIGNED_INT;else if(c instanceof Int32Array)f=e.INT;else if(c instanceof Int8Array)f=e.BYTE;else if(c instanceof Uint8Array)f=e.UNSIGNED_BYTE;else if(c instanceof Uint8ClampedArray)f=e.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+c);return{buffer:d,type:f,bytesPerElement:c.BYTES_PER_ELEMENT,version:o.version,size:h}}function i(o,l,c){let u=l.array,h=l.updateRanges;if(e.bindBuffer(c,o),h.length===0)e.bufferSubData(c,0,u);else{h.sort((f,y)=>f.start-y.start);let d=0;for(let f=1;f<h.length;f++){let y=h[d],g=h[f];g.start<=y.start+y.count+1?y.count=Math.max(y.count,g.start+g.count-y.start):(++d,h[d]=g)}h.length=d+1;for(let f=0,y=h.length;f<y;f++){let g=h[f];e.bufferSubData(c,g.start*u.BYTES_PER_ELEMENT,u,g.start,g.count)}l.clearUpdateRanges()}l.onUploadCallback()}function n(o){return o.isInterleavedBufferAttribute&&(o=o.data),t.get(o)}function a(o){o.isInterleavedBufferAttribute&&(o=o.data);let l=t.get(o);l&&(e.deleteBuffer(l.buffer),t.delete(o))}function s(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:a,update:s}}var MM=`#ifdef USE_ALPHAHASH
if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
#endif`,SM=`#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`,TM=`#ifdef USE_ALPHAMAP
diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;
#endif`,AM=`#ifdef USE_ALPHAMAP
uniform sampler2D alphaMap;
#endif`,CM=`#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`,RM=`#ifdef USE_ALPHATEST
uniform float alphaTest;
#endif`,PM=`#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`,IM=`#ifdef USE_AOMAP
uniform sampler2D aoMap;
uniform float aoMapIntensity;
#endif`,NM=`#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`,LM=`#ifdef USE_BATCHING
mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );
#endif`,OM=`vec3 transformed = vec3( position );
#ifdef USE_ALPHAHASH
vPosition = vec3( position );
#endif`,DM=`vec3 objectNormal = vec3( normal );
#ifdef USE_TANGENT
vec3 objectTangent = vec3( tangent.xyz );
#endif`,kM=`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`,UM=`#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`,FM=`#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`,BM=`#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`,zM=`#if NUM_CLIPPING_PLANES > 0
varying vec3 vClipPosition;
uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];
#endif`,GM=`#if NUM_CLIPPING_PLANES > 0
varying vec3 vClipPosition;
#endif`,VM=`#if NUM_CLIPPING_PLANES > 0
vClipPosition = - mvPosition.xyz;
#endif`,HM=`#if defined( USE_COLOR_ALPHA )
diffuseColor *= vColor;
#elif defined( USE_COLOR )
diffuseColor.rgb *= vColor;
#endif`,WM=`#if defined( USE_COLOR_ALPHA )
varying vec4 vColor;
#elif defined( USE_COLOR )
varying vec3 vColor;
#endif`,jM=`#if defined( USE_COLOR_ALPHA )
varying vec4 vColor;
#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )
varying vec3 vColor;
#endif`,XM=`#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`,YM=`#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`,qM=`#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`,KM=`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`,ZM=`#ifdef USE_DISPLACEMENTMAP
uniform sampler2D displacementMap;
uniform float displacementScale;
uniform float displacementBias;
#endif`,QM=`#ifdef USE_DISPLACEMENTMAP
transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );
#endif`,JM=`#ifdef USE_EMISSIVEMAP
vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );
#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE
emissiveColor = sRGBTransferEOTF( emissiveColor );
#endif
totalEmissiveRadiance *= emissiveColor.rgb;
#endif`,$M=`#ifdef USE_EMISSIVEMAP
uniform sampler2D emissiveMap;
#endif`,eS="gl_FragColor = linearToOutputTexel( gl_FragColor );",tS=`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 );
}`,rS=`#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`,iS=`#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`,nS=`#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`,aS=`#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`,sS=`#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`,oS=`#ifdef USE_FOG
vFogDepth = - mvPosition.z;
#endif`,lS=`#ifdef USE_FOG
varying float vFogDepth;
#endif`,cS=`#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`,uS=`#ifdef USE_FOG
uniform vec3 fogColor;
varying float vFogDepth;
#ifdef FOG_EXP2
uniform float fogDensity;
#else
uniform float fogNear;
uniform float fogFar;
#endif
#endif`,hS=`#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
}`,dS=`#ifdef USE_LIGHTMAP
uniform sampler2D lightMap;
uniform float lightMapIntensity;
#endif`,pS=`LambertMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularStrength = specularStrength;`,fS=`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`,mS=`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`,gS=`#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`,yS=`ToonMaterial material;
material.diffuseColor = diffuseColor.rgb;`,vS=`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`,xS=`BlinnPhongMaterial material;
material.diffuseColor = diffuseColor.rgb;
material.specularColor = specular;
material.specularShininess = shininess;
material.specularStrength = specularStrength;`,bS=`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`,_S=`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`,wS=`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 );
}`,ES=`
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`,MS=`#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`,SS=`#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`,TS=`#if defined( USE_LOGDEPTHBUF )
gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;
#endif`,AS=`#if defined( USE_LOGDEPTHBUF )
uniform float logDepthBufFC;
varying float vFragDepth;
varying float vIsPerspective;
#endif`,CS=`#ifdef USE_LOGDEPTHBUF
varying float vFragDepth;
varying float vIsPerspective;
#endif`,RS=`#ifdef USE_LOGDEPTHBUF
vFragDepth = 1.0 + gl_Position.w;
vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );
#endif`,PS=`#ifdef USE_MAP
vec4 sampledDiffuseColor = texture2D( map, vMapUv );
#ifdef DECODE_VIDEO_TEXTURE
sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );
#endif
diffuseColor *= sampledDiffuseColor;
#endif`,IS=`#ifdef USE_MAP
uniform sampler2D map;
#endif`,NS=`#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`,LS=`#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`,OS=`float metalnessFactor = metalness;
#ifdef USE_METALNESSMAP
vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );
metalnessFactor *= texelMetalness.b;
#endif`,DS=`#ifdef USE_METALNESSMAP
uniform sampler2D metalnessMap;
#endif`,kS=`#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`,US=`#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`,FS=`#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`,BS=`#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`,zS=`#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`,GS=`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;`,VS=`#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`,HS=`#ifndef FLAT_SHADED
varying vec3 vNormal;
#ifdef USE_TANGENT
varying vec3 vTangent;
varying vec3 vBitangent;
#endif
#endif`,WS=`#ifndef FLAT_SHADED
varying vec3 vNormal;
#ifdef USE_TANGENT
varying vec3 vTangent;
varying vec3 vBitangent;
#endif
#endif`,jS=`#ifndef FLAT_SHADED
vNormal = normalize( transformedNormal );
#ifdef USE_TANGENT
vTangent = normalize( transformedTangent );
vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w );
#endif
#endif`,XS=`#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`,YS=`#ifdef USE_CLEARCOAT
vec3 clearcoatNormal = nonPerturbedNormal;
#endif`,qS=`#ifdef USE_CLEARCOAT_NORMALMAP
vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;
clearcoatMapN.xy *= clearcoatNormalScale;
clearcoatNormal = normalize( tbn2 * clearcoatMapN );
#endif`,KS=`#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`,ZS=`#ifdef USE_IRIDESCENCEMAP
uniform sampler2D iridescenceMap;
#endif
#ifdef USE_IRIDESCENCE_THICKNESSMAP
uniform sampler2D iridescenceThicknessMap;
#endif`,QS=`#ifdef OPAQUE
diffuseColor.a = 1.0;
#endif
#ifdef USE_TRANSMISSION
diffuseColor.a *= material.transmissionAlpha;
#endif
gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,JS=`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 );
}`,$S=`#ifdef PREMULTIPLIED_ALPHA
gl_FragColor.rgb *= gl_FragColor.a;
#endif`,eT=`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;`,tT=`#ifdef DITHERING
gl_FragColor.rgb = dithering( gl_FragColor.rgb );
#endif`,rT=`#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`,iT=`float roughnessFactor = roughness;
#ifdef USE_ROUGHNESSMAP
vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );
roughnessFactor *= texelRoughness.g;
#endif`,nT=`#ifdef USE_ROUGHNESSMAP
uniform sampler2D roughnessMap;
#endif`,aT=`#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`,sT=`#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`,oT=`#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`,lT=`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;
}`,cT=`#ifdef USE_SKINNING
mat4 boneMatX = getBoneMatrix( skinIndex.x );
mat4 boneMatY = getBoneMatrix( skinIndex.y );
mat4 boneMatZ = getBoneMatrix( skinIndex.z );
mat4 boneMatW = getBoneMatrix( skinIndex.w );
#endif`,uT=`#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`,hT=`#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`,dT=`#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`,pT=`float specularStrength;
#ifdef USE_SPECULARMAP
vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );
specularStrength = texelSpecular.r;
#else
specularStrength = 1.0;
#endif`,fT=`#ifdef USE_SPECULARMAP
uniform sampler2D specularMap;
#endif`,mT=`#if defined( TONE_MAPPING )
gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );
#endif`,gT=`#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; }`,yT=`#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`,vT=`#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`,xT=`#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`,bT=`#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`,_T=`#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`,wT=`#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`,ET=`varying vec2 vUv;
uniform mat3 uvTransform;
void main() {
vUv = ( uvTransform * vec3( uv, 1 ) ).xy;
gl_Position = vec4( position.xy, 1.0, 1.0 );
}`,MT=`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>
}`,ST=`varying vec3 vWorldDirection;
#include <common>
void main() {
vWorldDirection = transformDirection( position, modelMatrix );
#include <begin_vertex>
#include <project_vertex>
gl_Position.z = gl_Position.w;
}`,TT=`#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>
}`,AT=`varying vec3 vWorldDirection;
#include <common>
void main() {
vWorldDirection = transformDirection( position, modelMatrix );
#include <begin_vertex>
#include <project_vertex>
gl_Position.z = gl_Position.w;
}`,CT=`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>
}`,RT=`#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;
}`,PT=`#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
}`,IT=`#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;
}`,NT=`#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 );
}`,LT=`varying vec3 vWorldDirection;
#include <common>
void main() {
vWorldDirection = transformDirection( position, modelMatrix );
#include <begin_vertex>
#include <project_vertex>
}`,OT=`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>
}`,DT=`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>
}`,kT=`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>
}`,UT=`#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>
}`,FT=`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>
}`,BT=`#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>
}`,zT=`#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>
}`,GT=`#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;
}`,VT=`#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>
}`,HT=`#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
}`,WT=`#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
}`,jT=`#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>
}`,XT=`#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>
}`,YT=`#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
}`,qT=`#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>
}`,KT=`#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>
}`,ZT=`#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>
}`,QT=`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>
}`,JT=`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>
}`,$T=`#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>
}`,eA=`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>
}`,tA=`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>
}`,rA=`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>
}`,br={alphahash_fragment:MM,alphahash_pars_fragment:SM,alphamap_fragment:TM,alphamap_pars_fragment:AM,alphatest_fragment:CM,alphatest_pars_fragment:RM,aomap_fragment:PM,aomap_pars_fragment:IM,batching_pars_vertex:NM,batching_vertex:LM,begin_vertex:OM,beginnormal_vertex:DM,bsdfs:kM,iridescence_fragment:UM,bumpmap_pars_fragment:FM,clipping_planes_fragment:BM,clipping_planes_pars_fragment:zM,clipping_planes_pars_vertex:GM,clipping_planes_vertex:VM,color_fragment:HM,color_pars_fragment:WM,color_pars_vertex:jM,color_vertex:XM,common:YM,cube_uv_reflection_fragment:qM,defaultnormal_vertex:KM,displacementmap_pars_vertex:ZM,displacementmap_vertex:QM,emissivemap_fragment:JM,emissivemap_pars_fragment:$M,colorspace_fragment:eS,colorspace_pars_fragment:tS,envmap_fragment:rS,envmap_common_pars_fragment:iS,envmap_pars_fragment:nS,envmap_pars_vertex:aS,envmap_physical_pars_fragment:gS,envmap_vertex:sS,fog_vertex:oS,fog_pars_vertex:lS,fog_fragment:cS,fog_pars_fragment:uS,gradientmap_pars_fragment:hS,lightmap_pars_fragment:dS,lights_lambert_fragment:pS,lights_lambert_pars_fragment:fS,lights_pars_begin:mS,lights_toon_fragment:yS,lights_toon_pars_fragment:vS,lights_phong_fragment:xS,lights_phong_pars_fragment:bS,lights_physical_fragment:_S,lights_physical_pars_fragment:wS,lights_fragment_begin:ES,lights_fragment_maps:MS,lights_fragment_end:SS,logdepthbuf_fragment:TS,logdepthbuf_pars_fragment:AS,logdepthbuf_pars_vertex:CS,logdepthbuf_vertex:RS,map_fragment:PS,map_pars_fragment:IS,map_particle_fragment:NS,map_particle_pars_fragment:LS,metalnessmap_fragment:OS,metalnessmap_pars_fragment:DS,morphinstance_vertex:kS,morphcolor_vertex:US,morphnormal_vertex:FS,morphtarget_pars_vertex:BS,morphtarget_vertex:zS,normal_fragment_begin:GS,normal_fragment_maps:VS,normal_pars_fragment:HS,normal_pars_vertex:WS,normal_vertex:jS,normalmap_pars_fragment:XS,clearcoat_normal_fragment_begin:YS,clearcoat_normal_fragment_maps:qS,clearcoat_pars_fragment:KS,iridescence_pars_fragment:ZS,opaque_fragment:QS,packing:JS,premultiplied_alpha_fragment:$S,project_vertex:eT,dithering_fragment:tT,dithering_pars_fragment:rT,roughnessmap_fragment:iT,roughnessmap_pars_fragment:nT,shadowmap_pars_fragment:aT,shadowmap_pars_vertex:sT,shadowmap_vertex:oT,shadowmask_pars_fragment:lT,skinbase_vertex:cT,skinning_pars_vertex:uT,skinning_vertex:hT,skinnormal_vertex:dT,specularmap_fragment:pT,specularmap_pars_fragment:fT,tonemapping_fragment:mT,tonemapping_pars_fragment:gT,transmission_fragment:yT,transmission_pars_fragment:vT,uv_pars_fragment:xT,uv_pars_vertex:bT,uv_vertex:_T,worldpos_vertex:wT,background_vert:ET,background_frag:MT,backgroundCube_vert:ST,backgroundCube_frag:TT,cube_vert:AT,cube_frag:CT,depth_vert:RT,depth_frag:PT,distanceRGBA_vert:IT,distanceRGBA_frag:NT,equirect_vert:LT,equirect_frag:OT,linedashed_vert:DT,linedashed_frag:kT,meshbasic_vert:UT,meshbasic_frag:FT,meshlambert_vert:BT,meshlambert_frag:zT,meshmatcap_vert:GT,meshmatcap_frag:VT,meshnormal_vert:HT,meshnormal_frag:WT,meshphong_vert:jT,meshphong_frag:XT,meshphysical_vert:YT,meshphysical_frag:qT,meshtoon_vert:KT,meshtoon_frag:ZT,points_vert:QT,points_frag:JT,shadow_vert:$T,shadow_frag:eA,sprite_vert:tA,sprite_frag:rA},kt={common:{diffuse:{value:new yt(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new xr},alphaMap:{value:null},alphaMapTransform:{value:new xr},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new xr}},envmap:{envMap:{value:null},envMapRotation:{value:new xr},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new xr}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new xr}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new xr},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new xr},normalScale:{value:new Xe(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new xr},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new xr}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new xr}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new xr}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new yt(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 yt(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new xr},alphaTest:{value:0},uvTransform:{value:new xr}},sprite:{diffuse:{value:new yt(16777215)},opacity:{value:1},center:{value:new Xe(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new xr},alphaMap:{value:null},alphaMapTransform:{value:new xr},alphaTest:{value:0}}},kn={basic:{uniforms:Hi([kt.common,kt.specularmap,kt.envmap,kt.aomap,kt.lightmap,kt.fog]),vertexShader:br.meshbasic_vert,fragmentShader:br.meshbasic_frag},lambert:{uniforms:Hi([kt.common,kt.specularmap,kt.envmap,kt.aomap,kt.lightmap,kt.emissivemap,kt.bumpmap,kt.normalmap,kt.displacementmap,kt.fog,kt.lights,{emissive:{value:new yt(0)}}]),vertexShader:br.meshlambert_vert,fragmentShader:br.meshlambert_frag},phong:{uniforms:Hi([kt.common,kt.specularmap,kt.envmap,kt.aomap,kt.lightmap,kt.emissivemap,kt.bumpmap,kt.normalmap,kt.displacementmap,kt.fog,kt.lights,{emissive:{value:new yt(0)},specular:{value:new yt(1118481)},shininess:{value:30}}]),vertexShader:br.meshphong_vert,fragmentShader:br.meshphong_frag},standard:{uniforms:Hi([kt.common,kt.envmap,kt.aomap,kt.lightmap,kt.emissivemap,kt.bumpmap,kt.normalmap,kt.displacementmap,kt.roughnessmap,kt.metalnessmap,kt.fog,kt.lights,{emissive:{value:new yt(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:br.meshphysical_vert,fragmentShader:br.meshphysical_frag},toon:{uniforms:Hi([kt.common,kt.aomap,kt.lightmap,kt.emissivemap,kt.bumpmap,kt.normalmap,kt.displacementmap,kt.gradientmap,kt.fog,kt.lights,{emissive:{value:new yt(0)}}]),vertexShader:br.meshtoon_vert,fragmentShader:br.meshtoon_frag},matcap:{uniforms:Hi([kt.common,kt.bumpmap,kt.normalmap,kt.displacementmap,kt.fog,{matcap:{value:null}}]),vertexShader:br.meshmatcap_vert,fragmentShader:br.meshmatcap_frag},points:{uniforms:Hi([kt.points,kt.fog]),vertexShader:br.points_vert,fragmentShader:br.points_frag},dashed:{uniforms:Hi([kt.common,kt.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:br.linedashed_vert,fragmentShader:br.linedashed_frag},depth:{uniforms:Hi([kt.common,kt.displacementmap]),vertexShader:br.depth_vert,fragmentShader:br.depth_frag},normal:{uniforms:Hi([kt.common,kt.bumpmap,kt.normalmap,kt.displacementmap,{opacity:{value:1}}]),vertexShader:br.meshnormal_vert,fragmentShader:br.meshnormal_frag},sprite:{uniforms:Hi([kt.sprite,kt.fog]),vertexShader:br.sprite_vert,fragmentShader:br.sprite_frag},background:{uniforms:{uvTransform:{value:new xr},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:br.background_vert,fragmentShader:br.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new xr}},vertexShader:br.backgroundCube_vert,fragmentShader:br.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:br.cube_vert,fragmentShader:br.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:br.equirect_vert,fragmentShader:br.equirect_frag},distanceRGBA:{uniforms:Hi([kt.common,kt.displacementmap,{referencePosition:{value:new ee},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:br.distanceRGBA_vert,fragmentShader:br.distanceRGBA_frag},shadow:{uniforms:Hi([kt.lights,kt.fog,{color:{value:new yt(0)},opacity:{value:1}}]),vertexShader:br.shadow_vert,fragmentShader:br.shadow_frag}};kn.physical={uniforms:Hi([kn.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new xr},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new xr},clearcoatNormalScale:{value:new Xe(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new xr},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new xr},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new xr},sheen:{value:0},sheenColor:{value:new yt(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new xr},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new xr},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new xr},transmissionSamplerSize:{value:new Xe},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new xr},attenuationDistance:{value:0},attenuationColor:{value:new yt(0)},specularColor:{value:new yt(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new xr},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new xr},anisotropyVector:{value:new Xe},anisotropyMap:{value:null},anisotropyMapTransform:{value:new xr}}]),vertexShader:br.meshphysical_vert,fragmentShader:br.meshphysical_frag};var ed={r:0,b:0,g:0},As=new Nn,iA=new Jt;function nA(e,t,r,i,n,a,s){let o=new yt(0),l=a===!0?0:1,c,u,h=null,d=0,f=null;function y(x){let b=x.isScene===!0?x.background:null;return b&&b.isTexture&&(b=(x.backgroundBlurriness>0?r:t).get(b)),b}function g(x){let b=!1,_=y(x);_===null?m(o,l):_&&_.isColor&&(m(_,1),b=!0);let M=e.xr.getEnvironmentBlendMode();M==="additive"?i.buffers.color.setClear(0,0,0,1,s):M==="alpha-blend"&&i.buffers.color.setClear(0,0,0,0,s),(e.autoClear||b)&&(i.buffers.depth.setTest(!0),i.buffers.depth.setMask(!0),i.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))}function p(x,b){let _=y(b);_&&(_.isCubeTexture||_.mapping===Js)?(u===void 0&&(u=new hr(new da(1,1,1),new oi({name:"BackgroundCubeMaterial",uniforms:xo(kn.backgroundCube.uniforms),vertexShader:kn.backgroundCube.vertexShader,fragmentShader:kn.backgroundCube.fragmentShader,side:_t,depthTest:!1,depthWrite:!1,fog:!1})),u.geometry.deleteAttribute("normal"),u.geometry.deleteAttribute("uv"),u.onBeforeRender=function(M,C,S){this.matrixWorld.copyPosition(S.matrixWorld)},Object.defineProperty(u.material,"envMap",{get:function(){return this.uniforms.envMap.value}}),n.update(u)),As.copy(b.backgroundRotation),As.x*=-1,As.y*=-1,As.z*=-1,_.isCubeTexture&&_.isRenderTargetTexture===!1&&(As.y*=-1,As.z*=-1),u.material.uniforms.envMap.value=_,u.material.uniforms.flipEnvMap.value=_.isCubeTexture&&_.isRenderTargetTexture===!1?-1:1,u.material.uniforms.backgroundBlurriness.value=b.backgroundBlurriness,u.material.uniforms.backgroundIntensity.value=b.backgroundIntensity,u.material.uniforms.backgroundRotation.value.setFromMatrix4(iA.makeRotationFromEuler(As)),u.material.toneMapped=_r.getTransfer(_.colorSpace)!==kr,(h!==_||d!==_.version||f!==e.toneMapping)&&(u.material.needsUpdate=!0,h=_,d=_.version,f=e.toneMapping),u.layers.enableAll(),x.unshift(u,u.geometry,u.material,0,0,null)):_&&_.isTexture&&(c===void 0&&(c=new hr(new Io(2,2),new oi({name:"BackgroundMaterial",uniforms:xo(kn.background.uniforms),vertexShader:kn.background.vertexShader,fragmentShader:kn.background.fragmentShader,side:it,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=_,c.material.uniforms.backgroundIntensity.value=b.backgroundIntensity,c.material.toneMapped=_r.getTransfer(_.colorSpace)!==kr,_.matrixAutoUpdate===!0&&_.updateMatrix(),c.material.uniforms.uvTransform.value.copy(_.matrix),(h!==_||d!==_.version||f!==e.toneMapping)&&(c.material.needsUpdate=!0,h=_,d=_.version,f=e.toneMapping),c.layers.enableAll(),x.unshift(c,c.geometry,c.material,0,0,null))}function m(x,b){x.getRGB(ed,T0(e)),i.buffers.color.setClear(ed.r,ed.g,ed.b,b,s)}function v(){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(x,b=1){o.set(x),l=b,m(o,l)},getClearAlpha:function(){return l},setClearAlpha:function(x){l=x,m(o,l)},render:g,addToRenderList:p,dispose:v}}function aA(e,t){let r=e.getParameter(e.MAX_VERTEX_ATTRIBS),i={},n=d(null),a=n,s=!1;function o(E,P,N,D,B){let J=!1,Q=h(D,N,P);a!==Q&&(a=Q,c(a.object)),J=f(E,D,N,B),J&&y(E,D,N,B),B!==null&&t.update(B,e.ELEMENT_ARRAY_BUFFER),(J||s)&&(s=!1,b(E,P,N,D),B!==null&&e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t.get(B).buffer))}function l(){return e.createVertexArray()}function c(E){return e.bindVertexArray(E)}function u(E){return e.deleteVertexArray(E)}function h(E,P,N){let D=N.wireframe===!0,B=i[E.id];B===void 0&&(B={},i[E.id]=B);let J=B[P.id];J===void 0&&(J={},B[P.id]=J);let Q=J[D];return Q===void 0&&(Q=d(l()),J[D]=Q),Q}function d(E){let P=[],N=[],D=[];for(let B=0;B<r;B++)P[B]=0,N[B]=0,D[B]=0;return{geometry:null,program:null,wireframe:!1,newAttributes:P,enabledAttributes:N,attributeDivisors:D,object:E,attributes:{},index:null}}function f(E,P,N,D){let B=a.attributes,J=P.attributes,Q=0,j=N.getAttributes();for(let k in j)if(j[k].location>=0){let H=B[k],U=J[k];if(U===void 0&&(k==="instanceMatrix"&&E.instanceMatrix&&(U=E.instanceMatrix),k==="instanceColor"&&E.instanceColor&&(U=E.instanceColor)),H===void 0||H.attribute!==U||U&&H.data!==U.data)return!0;Q++}return a.attributesNum!==Q||a.index!==D}function y(E,P,N,D){let B={},J=P.attributes,Q=0,j=N.getAttributes();for(let k in j)if(j[k].location>=0){let H=J[k];H===void 0&&(k==="instanceMatrix"&&E.instanceMatrix&&(H=E.instanceMatrix),k==="instanceColor"&&E.instanceColor&&(H=E.instanceColor));let U={};U.attribute=H,H&&H.data&&(U.data=H.data),B[k]=U,Q++}a.attributes=B,a.attributesNum=Q,a.index=D}function g(){let E=a.newAttributes;for(let P=0,N=E.length;P<N;P++)E[P]=0}function p(E){m(E,0)}function m(E,P){let N=a.newAttributes,D=a.enabledAttributes,B=a.attributeDivisors;N[E]=1,D[E]===0&&(e.enableVertexAttribArray(E),D[E]=1),B[E]!==P&&(e.vertexAttribDivisor(E,P),B[E]=P)}function v(){let E=a.newAttributes,P=a.enabledAttributes;for(let N=0,D=P.length;N<D;N++)P[N]!==E[N]&&(e.disableVertexAttribArray(N),P[N]=0)}function x(E,P,N,D,B,J,Q){Q===!0?e.vertexAttribIPointer(E,P,N,B,J):e.vertexAttribPointer(E,P,N,D,B,J)}function b(E,P,N,D){g();let B=D.attributes,J=N.getAttributes(),Q=P.defaultAttributeValues;for(let j in J){let k=J[j];if(k.location>=0){let H=B[j];if(H===void 0&&(j==="instanceMatrix"&&E.instanceMatrix&&(H=E.instanceMatrix),j==="instanceColor"&&E.instanceColor&&(H=E.instanceColor)),H!==void 0){let U=H.normalized,X=H.itemSize,W=t.get(H);if(W===void 0)continue;let $=W.buffer,G=W.type,T=W.bytesPerElement,I=G===e.INT||G===e.UNSIGNED_INT||H.gpuType===hu;if(H.isInterleavedBufferAttribute){let V=H.data,K=V.stride,ie=H.offset;if(V.isInstancedInterleavedBuffer){for(let le=0;le<k.locationSize;le++)m(k.location+le,V.meshPerAttribute);E.isInstancedMesh!==!0&&D._maxInstanceCount===void 0&&(D._maxInstanceCount=V.meshPerAttribute*V.count)}else for(let le=0;le<k.locationSize;le++)p(k.location+le);e.bindBuffer(e.ARRAY_BUFFER,$);for(let le=0;le<k.locationSize;le++)x(k.location+le,X/k.locationSize,G,U,K*T,(ie+X/k.locationSize*le)*T,I)}else{if(H.isInstancedBufferAttribute){for(let V=0;V<k.locationSize;V++)m(k.location+V,H.meshPerAttribute);E.isInstancedMesh!==!0&&D._maxInstanceCount===void 0&&(D._maxInstanceCount=H.meshPerAttribute*H.count)}else for(let V=0;V<k.locationSize;V++)p(k.location+V);e.bindBuffer(e.ARRAY_BUFFER,$);for(let V=0;V<k.locationSize;V++)x(k.location+V,X/k.locationSize,G,U,X*T,X/k.locationSize*V*T,I)}}else if(Q!==void 0){let U=Q[j];if(U!==void 0)switch(U.length){case 2:e.vertexAttrib2fv(k.location,U);break;case 3:e.vertexAttrib3fv(k.location,U);break;case 4:e.vertexAttrib4fv(k.location,U);break;default:e.vertexAttrib1fv(k.location,U)}}}}v()}function _(){S();for(let E in i){let P=i[E];for(let N in P){let D=P[N];for(let B in D)u(D[B].object),delete D[B];delete P[N]}delete i[E]}}function M(E){if(i[E.id]===void 0)return;let P=i[E.id];for(let N in P){let D=P[N];for(let B in D)u(D[B].object),delete D[B];delete P[N]}delete i[E.id]}function C(E){for(let P in i){let N=i[P];if(N[E.id]===void 0)continue;let D=N[E.id];for(let B in D)u(D[B].object),delete D[B];delete N[E.id]}}function S(){w(),s=!0,a!==n&&(a=n,c(a.object))}function w(){n.geometry=null,n.program=null,n.wireframe=!1}return{setup:o,reset:S,resetDefaultState:w,dispose:_,releaseStatesOfGeometry:M,releaseStatesOfProgram:C,initAttributes:g,enableAttribute:p,disableUnusedAttributes:v}}function sA(e,t,r){let i;function n(c){i=c}function a(c,u){e.drawArrays(i,c,u),r.update(u,i,1)}function s(c,u,h){h!==0&&(e.drawArraysInstanced(i,c,u,h),r.update(u,i,h))}function o(c,u,h){if(h===0)return;t.get("WEBGL_multi_draw").multiDrawArraysWEBGL(i,c,0,u,0,h);let d=0;for(let f=0;f<h;f++)d+=u[f];r.update(d,i,1)}function l(c,u,h,d){if(h===0)return;let f=t.get("WEBGL_multi_draw");if(f===null)for(let y=0;y<c.length;y++)s(c[y],u[y],d[y]);else{f.multiDrawArraysInstancedWEBGL(i,c,0,u,0,d,0,h);let y=0;for(let g=0;g<h;g++)y+=u[g]*d[g];r.update(y,i,1)}}this.setMode=n,this.render=a,this.renderInstances=s,this.renderMultiDraw=o,this.renderMultiDrawInstances=l}function oA(e,t,r,i){let n;function a(){if(n!==void 0)return n;if(t.has("EXT_texture_filter_anisotropic")===!0){let C=t.get("EXT_texture_filter_anisotropic");n=e.getParameter(C.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else n=0;return n}function s(C){return!(C!==Li&&i.convert(C)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_FORMAT))}function o(C){let S=C===yn&&(t.has("EXT_color_buffer_half_float")||t.has("EXT_color_buffer_float"));return!(C!==gn&&i.convert(C)!==e.getParameter(e.IMPLEMENTATION_COLOR_READ_TYPE)&&C!==Xi&&!S)}function l(C){if(C==="highp"){if(e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.HIGH_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return"highp";C="mediump"}return C==="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 h=r.logarithmicDepthBuffer===!0,d=r.reverseDepthBuffer===!0&&t.has("EXT_clip_control"),f=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),y=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),g=e.getParameter(e.MAX_TEXTURE_SIZE),p=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),m=e.getParameter(e.MAX_VERTEX_ATTRIBS),v=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),x=e.getParameter(e.MAX_VARYING_VECTORS),b=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),_=y>0,M=e.getParameter(e.MAX_SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:a,getMaxPrecision:l,textureFormatReadable:s,textureTypeReadable:o,precision:c,logarithmicDepthBuffer:h,reverseDepthBuffer:d,maxTextures:f,maxVertexTextures:y,maxTextureSize:g,maxCubemapSize:p,maxAttributes:m,maxVertexUniforms:v,maxVaryings:x,maxFragmentUniforms:b,vertexTextures:_,maxSamples:M}}function lA(e){let t=this,r=null,i=0,n=!1,a=!1,s=new pa,o=new xr,l={value:null,needsUpdate:!1};this.uniform=l,this.numPlanes=0,this.numIntersection=0,this.init=function(h,d){let f=h.length!==0||d||i!==0||n;return n=d,i=h.length,f},this.beginShadows=function(){a=!0,u(null)},this.endShadows=function(){a=!1},this.setGlobalState=function(h,d){r=u(h,d,0)},this.setState=function(h,d,f){let y=h.clippingPlanes,g=h.clipIntersection,p=h.clipShadows,m=e.get(h);if(!n||y===null||y.length===0||a&&!p)a?u(null):c();else{let v=a?0:i,x=v*4,b=m.clippingState||null;l.value=b,b=u(y,d,x,f);for(let _=0;_!==x;++_)b[_]=r[_];m.clippingState=b,this.numIntersection=g?this.numPlanes:0,this.numPlanes+=v}};function c(){l.value!==r&&(l.value=r,l.needsUpdate=i>0),t.numPlanes=i,t.numIntersection=0}function u(h,d,f,y){let g=h!==null?h.length:0,p=null;if(g!==0){if(p=l.value,y!==!0||p===null){let m=f+g*4,v=d.matrixWorldInverse;o.getNormalMatrix(v),(p===null||p.length<m)&&(p=new Float32Array(m));for(let x=0,b=f;x!==g;++x,b+=4)s.copy(h[x]).applyMatrix4(v,o),s.normal.toArray(p,b),p[b+3]=s.constant}l.value=p,l.needsUpdate=!0}return t.numPlanes=g,t.numIntersection=0,p}}function cA(e){let t=new WeakMap;function r(s,o){return o===vl?s.mapping=ta:o===xl&&(s.mapping=Aa),s}function i(s){if(s&&s.isTexture){let o=s.mapping;if(o===vl||o===xl)if(t.has(s)){let l=t.get(s).texture;return r(l,s.mapping)}else{let l=s.image;if(l&&l.height>0){let c=new P0(l.height);return c.fromEquirectangularTexture(e,s),t.set(s,c),s.addEventListener("dispose",n),r(c.texture,s.mapping)}else return null}}return s}function n(s){let o=s.target;o.removeEventListener("dispose",n);let l=t.get(o);l!==void 0&&(t.delete(o),l.dispose())}function a(){t=new WeakMap}return{get:i,dispose:a}}var Do=4,yv=[.125,.215,.35,.446,.526,.582],Cs=20,Xf=new Oo,vv=new yt,Yf=null,qf=0,Kf=0,Zf=!1,Rs=(1+Math.sqrt(5))/2,ko=1/Rs,xv=[new ee(-Rs,ko,0),new ee(Rs,ko,0),new ee(-ko,0,Rs),new ee(ko,0,Rs),new ee(0,Rs,-ko),new ee(0,Rs,ko),new ee(-1,1,-1),new ee(1,1,-1),new ee(-1,1,1),new ee(1,1,1)],td=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){Yf=this._renderer.getRenderTarget(),qf=this._renderer.getActiveCubeFace(),Kf=this._renderer.getActiveMipmapLevel(),Zf=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=wv(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=_v(),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(Yf,qf,Kf),this._renderer.xr.enabled=Zf,e.scissorTest=!1,rd(e,0,0,e.width,e.height)}_fromTexture(e,t){e.mapping===ta||e.mapping===Aa?this._setSize(e.image.length===0?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4),Yf=this._renderer.getRenderTarget(),qf=this._renderer.getActiveCubeFace(),Kf=this._renderer.getActiveMipmapLevel(),Zf=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:Zr,minFilter:Zr,generateMipmaps:!1,type:yn,format:Li,colorSpace:Oi,depthBuffer:!1},i=bv(e,t,r);if(this._pingPongRenderTarget===null||this._pingPongRenderTarget.width!==e||this._pingPongRenderTarget.height!==t){this._pingPongRenderTarget!==null&&this._dispose(),this._pingPongRenderTarget=bv(e,t,r);let{_lodMax:n}=this;({sizeLods:this._sizeLods,lodPlanes:this._lodPlanes,sigmas:this._sigmas}=uA(n)),this._blurMaterial=hA(n,e,t)}return i}_compileMaterial(e){let t=new hr(this._lodPlanes[0],e);this._renderer.compile(t,Xf)}_sceneToCubeUV(e,t,r,i){let n=new li(90,1,t,r),a=[1,-1,1,1,1,1],s=[1,1,1,-1,-1,-1],o=this._renderer,l=o.autoClear,c=o.toneMapping;o.getClearColor(vv),o.toneMapping=ea,o.autoClear=!1;let u=new ti({name:"PMREM.Background",side:_t,depthWrite:!1,depthTest:!1}),h=new hr(new da,u),d=!1,f=e.background;f?f.isColor&&(u.color.copy(f),e.background=null,d=!0):(u.color.copy(vv),d=!0);for(let y=0;y<6;y++){let g=y%3;g===0?(n.up.set(0,a[y],0),n.lookAt(s[y],0,0)):g===1?(n.up.set(0,0,a[y]),n.lookAt(0,s[y],0)):(n.up.set(0,a[y],0),n.lookAt(0,0,s[y]));let p=this._cubeSize;rd(i,g*p,y>2?p:0,p,p),o.setRenderTarget(i),d&&o.render(h,n),o.render(e,n)}h.geometry.dispose(),h.material.dispose(),o.toneMapping=c,o.autoClear=l,e.background=f}_textureToCubeUV(e,t){let r=this._renderer,i=e.mapping===ta||e.mapping===Aa;i?(this._cubemapMaterial===null&&(this._cubemapMaterial=wv()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=_v());let n=i?this._cubemapMaterial:this._equirectMaterial,a=new hr(this._lodPlanes[0],n),s=n.uniforms;s.envMap.value=e;let o=this._cubeSize;rd(t,0,0,3*o,2*o),r.setRenderTarget(t),r.render(a,Xf)}_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 a=Math.sqrt(this._sigmas[n]*this._sigmas[n]-this._sigmas[n-1]*this._sigmas[n-1]),s=xv[(i-n-1)%xv.length];this._blur(e,n-1,n,a,s)}t.autoClear=r}_blur(e,t,r,i,n){let a=this._pingPongRenderTarget;this._halfBlur(e,a,t,r,i,"latitudinal",n),this._halfBlur(a,e,r,r,i,"longitudinal",n)}_halfBlur(e,t,r,i,n,a,s){let o=this._renderer,l=this._blurMaterial;a!=="latitudinal"&&a!=="longitudinal"&&console.error("blur direction must be either latitudinal or longitudinal!");let c=3,u=new hr(this._lodPlanes[i],l),h=l.uniforms,d=this._sizeLods[r]-1,f=isFinite(n)?Math.PI/(2*d):2*Math.PI/(2*Cs-1),y=n/f,g=isFinite(n)?1+Math.floor(c*y):Cs;g>Cs&&console.warn(`sigmaRadians, ${n}, is too large and will clip, as it requested ${g} samples when the maximum is set to ${Cs}`);let p=[],m=0;for(let M=0;M<Cs;++M){let C=M/y,S=Math.exp(-C*C/2);p.push(S),M===0?m+=S:M<g&&(m+=2*S)}for(let M=0;M<p.length;M++)p[M]=p[M]/m;h.envMap.value=e.texture,h.samples.value=g,h.weights.value=p,h.latitudinal.value=a==="latitudinal",s&&(h.poleAxis.value=s);let{_lodMax:v}=this;h.dTheta.value=f,h.mipInt.value=v-r;let x=this._sizeLods[i],b=3*x*(i>v-Do?i-v+Do:0),_=4*(this._cubeSize-x);rd(t,b,_,3*x,2*x),o.setRenderTarget(t),o.render(u,Xf)}};function uA(e){let t=[],r=[],i=[],n=e,a=e-Do+1+yv.length;for(let s=0;s<a;s++){let o=Math.pow(2,n);r.push(o);let l=1/o;s>e-Do?l=yv[s-e+Do-1]:s===0&&(l=0),i.push(l);let c=1/(o-2),u=-c,h=1+c,d=[u,u,h,u,h,h,u,u,h,h,u,h],f=6,y=6,g=3,p=2,m=1,v=new Float32Array(g*y*f),x=new Float32Array(p*y*f),b=new Float32Array(m*y*f);for(let M=0;M<f;M++){let C=M%3*2/3-1,S=M>2?0:-1,w=[C,S,0,C+2/3,S,0,C+2/3,S+1,0,C,S,0,C+2/3,S+1,0,C,S+1,0];v.set(w,g*y*M),x.set(d,p*y*M);let E=[M,M,M,M,M,M];b.set(E,m*y*M)}let _=new ar;_.setAttribute("position",new Mr(v,g)),_.setAttribute("uv",new Mr(x,p)),_.setAttribute("faceIndex",new Mr(b,m)),t.push(_),n>Do&&n--}return{lodPlanes:t,sizeLods:r,sigmas:i}}function bv(e,t,r){let i=new Pi(e,t,r);return i.texture.mapping=Js,i.texture.name="PMREM.cubeUv",i.scissorTest=!0,i}function rd(e,t,r,i,n){e.viewport.set(t,r,i,n),e.scissor.set(t,r,i,n)}function hA(e,t,r){let i=new Float32Array(Cs),n=new ee(0,1,0);return new oi({name:"SphericalGaussianBlur",defines:{n:Cs,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:Qf(),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:Ft,depthTest:!1,depthWrite:!1})}function _v(){return new oi({name:"EquirectangularToCubeUV",uniforms:{envMap:{value:null}},vertexShader:Qf(),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:Ft,depthTest:!1,depthWrite:!1})}function wv(){return new oi({name:"CubemapToCubeUV",uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Qf(),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:Ft,depthTest:!1,depthWrite:!1})}function Qf(){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 dA(e){let t=new WeakMap,r=null;function i(o){if(o&&o.isTexture){let l=o.mapping,c=l===vl||l===xl,u=l===ta||l===Aa;if(c||u){let h=t.get(o),d=h!==void 0?h.texture.pmremVersion:0;if(o.isRenderTargetTexture&&o.pmremVersion!==d)return r===null&&(r=new td(e)),h=c?r.fromEquirectangular(o,h):r.fromCubemap(o,h),h.texture.pmremVersion=o.pmremVersion,t.set(o,h),h.texture;if(h!==void 0)return h.texture;{let f=o.image;return c&&f&&f.height>0||u&&f&&n(f)?(r===null&&(r=new td(e)),h=c?r.fromEquirectangular(o):r.fromCubemap(o),h.texture.pmremVersion=o.pmremVersion,t.set(o,h),o.addEventListener("dispose",a),h.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 a(o){let l=o.target;l.removeEventListener("dispose",a);let c=t.get(l);c!==void 0&&(t.delete(l),c.dispose())}function s(){t=new WeakMap,r!==null&&(r.dispose(),r=null)}return{get:i,dispose:s}}function pA(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&&so("THREE.WebGLRenderer: "+i+" extension not supported."),n}}}function fA(e,t,r,i){let n={},a=new WeakMap;function s(h){let d=h.target;d.index!==null&&t.remove(d.index);for(let y in d.attributes)t.remove(d.attributes[y]);d.removeEventListener("dispose",s),delete n[d.id];let f=a.get(d);f&&(t.remove(f),a.delete(d)),i.releaseStatesOfGeometry(d),d.isInstancedBufferGeometry===!0&&delete d._maxInstanceCount,r.memory.geometries--}function o(h,d){return n[d.id]===!0||(d.addEventListener("dispose",s),n[d.id]=!0,r.memory.geometries++),d}function l(h){let d=h.attributes;for(let f in d)t.update(d[f],e.ARRAY_BUFFER)}function c(h){let d=[],f=h.index,y=h.attributes.position,g=0;if(f!==null){let v=f.array;g=f.version;for(let x=0,b=v.length;x<b;x+=3){let _=v[x+0],M=v[x+1],C=v[x+2];d.push(_,M,M,C,C,_)}}else if(y!==void 0){let v=y.array;g=y.version;for(let x=0,b=v.length/3-1;x<b;x+=3){let _=x+0,M=x+1,C=x+2;d.push(_,M,M,C,C,_)}}else return;let p=new(s0(d)?Wp:Hp)(d,1);p.version=g;let m=a.get(h);m&&t.remove(m),a.set(h,p)}function u(h){let d=a.get(h);if(d){let f=h.index;f!==null&&d.version<f.version&&c(h)}else c(h);return a.get(h)}return{get:o,update:l,getWireframeAttribute:u}}function mA(e,t,r){let i;function n(d){i=d}let a,s;function o(d){a=d.type,s=d.bytesPerElement}function l(d,f){e.drawElements(i,f,a,d*s),r.update(f,i,1)}function c(d,f,y){y!==0&&(e.drawElementsInstanced(i,f,a,d*s,y),r.update(f,i,y))}function u(d,f,y){if(y===0)return;t.get("WEBGL_multi_draw").multiDrawElementsWEBGL(i,f,0,a,d,0,y);let g=0;for(let p=0;p<y;p++)g+=f[p];r.update(g,i,1)}function h(d,f,y,g){if(y===0)return;let p=t.get("WEBGL_multi_draw");if(p===null)for(let m=0;m<d.length;m++)c(d[m]/s,f[m],g[m]);else{p.multiDrawElementsInstancedWEBGL(i,f,0,a,d,0,g,0,y);let m=0;for(let v=0;v<y;v++)m+=f[v]*g[v];r.update(m,i,1)}}this.setMode=n,this.setIndex=o,this.render=l,this.renderInstances=c,this.renderMultiDraw=u,this.renderMultiDrawInstances=h}function gA(e){let t={geometries:0,textures:0},r={frame:0,calls:0,triangles:0,points:0,lines:0};function i(a,s,o){switch(r.calls++,s){case e.TRIANGLES:r.triangles+=o*(a/3);break;case e.LINES:r.lines+=o*(a/2);break;case e.LINE_STRIP:r.lines+=o*(a-1);break;case e.LINE_LOOP:r.lines+=o*a;break;case e.POINTS:r.points+=o*a;break;default:console.error("THREE.WebGLInfo: Unknown draw mode:",s);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 yA(e,t,r){let i=new WeakMap,n=new Nr;function a(s,o,l){let c=s.morphTargetInfluences,u=o.morphAttributes.position||o.morphAttributes.normal||o.morphAttributes.color,h=u!==void 0?u.length:0,d=i.get(o);if(d===void 0||d.count!==h){let f=function(){S.dispose(),i.delete(o),o.removeEventListener("dispose",f)};d!==void 0&&d.texture.dispose();let y=o.morphAttributes.position!==void 0,g=o.morphAttributes.normal!==void 0,p=o.morphAttributes.color!==void 0,m=o.morphAttributes.position||[],v=o.morphAttributes.normal||[],x=o.morphAttributes.color||[],b=0;y===!0&&(b=1),g===!0&&(b=2),p===!0&&(b=3);let _=o.attributes.position.count*b,M=1;_>t.maxTextureSize&&(M=Math.ceil(_/t.maxTextureSize),_=t.maxTextureSize);let C=new Float32Array(_*M*4*h),S=new Yu(C,_,M,h);S.type=Xi,S.needsUpdate=!0;let w=b*4;for(let E=0;E<h;E++){let P=m[E],N=v[E],D=x[E],B=_*M*4*E;for(let J=0;J<P.count;J++){let Q=J*w;y===!0&&(n.fromBufferAttribute(P,J),C[B+Q+0]=n.x,C[B+Q+1]=n.y,C[B+Q+2]=n.z,C[B+Q+3]=0),g===!0&&(n.fromBufferAttribute(N,J),C[B+Q+4]=n.x,C[B+Q+5]=n.y,C[B+Q+6]=n.z,C[B+Q+7]=0),p===!0&&(n.fromBufferAttribute(D,J),C[B+Q+8]=n.x,C[B+Q+9]=n.y,C[B+Q+10]=n.z,C[B+Q+11]=D.itemSize===4?n.w:1)}}d={count:h,texture:S,size:new Xe(_,M)},i.set(o,d),o.addEventListener("dispose",f)}if(s.isInstancedMesh===!0&&s.morphTexture!==null)l.getUniforms().setValue(e,"morphTexture",s.morphTexture,r);else{let f=0;for(let g=0;g<c.length;g++)f+=c[g];let y=o.morphTargetsRelative?1:1-f;l.getUniforms().setValue(e,"morphTargetBaseInfluence",y),l.getUniforms().setValue(e,"morphTargetInfluences",c)}l.getUniforms().setValue(e,"morphTargetsTexture",d.texture,r),l.getUniforms().setValue(e,"morphTargetsTextureSize",d.size)}return{update:a}}function vA(e,t,r,i){let n=new WeakMap;function a(l){let c=i.render.frame,u=l.geometry,h=t.get(l,u);if(n.get(h)!==c&&(t.update(h),n.set(h,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 d=l.skeleton;n.get(d)!==c&&(d.update(),n.set(d,c))}return h}function s(){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:a,dispose:s}}var Ev=new ei,Mv=new Oh(1,1),Sv=new Yu,Tv=new Ap,Av=new Ul,Cv=[],Rv=[],Pv=new Float32Array(16),Iv=new Float32Array(9),Nv=new Float32Array(4);function Uo(e,t,r){let i=e[0];if(i<=0||i>0)return e;let n=t*r,a=Cv[n];if(a===void 0&&(a=new Float32Array(n),Cv[n]=a),t!==0){i.toArray(a,0);for(let s=1,o=0;s!==t;++s)o+=r,e[s].toArray(a,o)}return a}function bi(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 _i(e,t){for(let r=0,i=t.length;r<i;r++)e[r]=t[r]}function id(e,t){let r=Rv[t];r===void 0&&(r=new Int32Array(t),Rv[t]=r);for(let i=0;i!==t;++i)r[i]=e.allocateTextureUnit();return r}function xA(e,t){let r=this.cache;r[0]!==t&&(e.uniform1f(this.addr,t),r[0]=t)}function bA(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(bi(r,t))return;e.uniform2fv(this.addr,t),_i(r,t)}}function _A(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(bi(r,t))return;e.uniform3fv(this.addr,t),_i(r,t)}}function wA(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(bi(r,t))return;e.uniform4fv(this.addr,t),_i(r,t)}}function EA(e,t){let r=this.cache,i=t.elements;if(i===void 0){if(bi(r,t))return;e.uniformMatrix2fv(this.addr,!1,t),_i(r,t)}else{if(bi(r,i))return;Nv.set(i),e.uniformMatrix2fv(this.addr,!1,Nv),_i(r,i)}}function MA(e,t){let r=this.cache,i=t.elements;if(i===void 0){if(bi(r,t))return;e.uniformMatrix3fv(this.addr,!1,t),_i(r,t)}else{if(bi(r,i))return;Iv.set(i),e.uniformMatrix3fv(this.addr,!1,Iv),_i(r,i)}}function SA(e,t){let r=this.cache,i=t.elements;if(i===void 0){if(bi(r,t))return;e.uniformMatrix4fv(this.addr,!1,t),_i(r,t)}else{if(bi(r,i))return;Pv.set(i),e.uniformMatrix4fv(this.addr,!1,Pv),_i(r,i)}}function TA(e,t){let r=this.cache;r[0]!==t&&(e.uniform1i(this.addr,t),r[0]=t)}function AA(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(bi(r,t))return;e.uniform2iv(this.addr,t),_i(r,t)}}function CA(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(bi(r,t))return;e.uniform3iv(this.addr,t),_i(r,t)}}function RA(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(bi(r,t))return;e.uniform4iv(this.addr,t),_i(r,t)}}function PA(e,t){let r=this.cache;r[0]!==t&&(e.uniform1ui(this.addr,t),r[0]=t)}function IA(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(bi(r,t))return;e.uniform2uiv(this.addr,t),_i(r,t)}}function NA(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(bi(r,t))return;e.uniform3uiv(this.addr,t),_i(r,t)}}function LA(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(bi(r,t))return;e.uniform4uiv(this.addr,t),_i(r,t)}}function OA(e,t,r){let i=this.cache,n=r.allocateTextureUnit();i[0]!==n&&(e.uniform1i(this.addr,n),i[0]=n);let a;this.type===e.SAMPLER_2D_SHADOW?(Mv.compareFunction=wp,a=Mv):a=Ev,r.setTexture2D(t||a,n)}function DA(e,t,r){let i=this.cache,n=r.allocateTextureUnit();i[0]!==n&&(e.uniform1i(this.addr,n),i[0]=n),r.setTexture3D(t||Tv,n)}function kA(e,t,r){let i=this.cache,n=r.allocateTextureUnit();i[0]!==n&&(e.uniform1i(this.addr,n),i[0]=n),r.setTextureCube(t||Av,n)}function UA(e,t,r){let i=this.cache,n=r.allocateTextureUnit();i[0]!==n&&(e.uniform1i(this.addr,n),i[0]=n),r.setTexture2DArray(t||Sv,n)}function FA(e){switch(e){case 5126:return xA;case 35664:return bA;case 35665:return _A;case 35666:return wA;case 35674:return EA;case 35675:return MA;case 35676:return SA;case 5124:case 35670:return TA;case 35667:case 35671:return AA;case 35668:case 35672:return CA;case 35669:case 35673:return RA;case 5125:return PA;case 36294:return IA;case 36295:return NA;case 36296:return LA;case 35678:case 36198:case 36298:case 36306:case 35682:return OA;case 35679:case 36299:case 36307:return DA;case 35680:case 36300:case 36308:case 36293:return kA;case 36289:case 36303:case 36311:case 36292:return UA}}function BA(e,t){e.uniform1fv(this.addr,t)}function zA(e,t){let r=Uo(t,this.size,2);e.uniform2fv(this.addr,r)}function GA(e,t){let r=Uo(t,this.size,3);e.uniform3fv(this.addr,r)}function VA(e,t){let r=Uo(t,this.size,4);e.uniform4fv(this.addr,r)}function HA(e,t){let r=Uo(t,this.size,4);e.uniformMatrix2fv(this.addr,!1,r)}function WA(e,t){let r=Uo(t,this.size,9);e.uniformMatrix3fv(this.addr,!1,r)}function jA(e,t){let r=Uo(t,this.size,16);e.uniformMatrix4fv(this.addr,!1,r)}function XA(e,t){e.uniform1iv(this.addr,t)}function YA(e,t){e.uniform2iv(this.addr,t)}function qA(e,t){e.uniform3iv(this.addr,t)}function KA(e,t){e.uniform4iv(this.addr,t)}function ZA(e,t){e.uniform1uiv(this.addr,t)}function QA(e,t){e.uniform2uiv(this.addr,t)}function JA(e,t){e.uniform3uiv(this.addr,t)}function $A(e,t){e.uniform4uiv(this.addr,t)}function eC(e,t,r){let i=this.cache,n=t.length,a=id(r,n);bi(i,a)||(e.uniform1iv(this.addr,a),_i(i,a));for(let s=0;s!==n;++s)r.setTexture2D(t[s]||Ev,a[s])}function tC(e,t,r){let i=this.cache,n=t.length,a=id(r,n);bi(i,a)||(e.uniform1iv(this.addr,a),_i(i,a));for(let s=0;s!==n;++s)r.setTexture3D(t[s]||Tv,a[s])}function rC(e,t,r){let i=this.cache,n=t.length,a=id(r,n);bi(i,a)||(e.uniform1iv(this.addr,a),_i(i,a));for(let s=0;s!==n;++s)r.setTextureCube(t[s]||Av,a[s])}function iC(e,t,r){let i=this.cache,n=t.length,a=id(r,n);bi(i,a)||(e.uniform1iv(this.addr,a),_i(i,a));for(let s=0;s!==n;++s)r.setTexture2DArray(t[s]||Sv,a[s])}function nC(e){switch(e){case 5126:return BA;case 35664:return zA;case 35665:return GA;case 35666:return VA;case 35674:return HA;case 35675:return WA;case 35676:return jA;case 5124:case 35670:return XA;case 35667:case 35671:return YA;case 35668:case 35672:return qA;case 35669:case 35673:return KA;case 5125:return ZA;case 36294:return QA;case 36295:return JA;case 36296:return $A;case 35678:case 36198:case 36298:case 36306:case 35682:return eC;case 35679:case 36299:case 36307:return tC;case 35680:case 36300:case 36308:case 36293:return rC;case 36289:case 36303:case 36311:case 36292:return iC}}var aC=class{constructor(e,t,r){this.id=e,this.addr=r,this.cache=[],this.type=t.type,this.setValue=FA(t.type)}},sC=class{constructor(e,t,r){this.id=e,this.addr=r,this.cache=[],this.type=t.type,this.size=t.size,this.setValue=nC(t.type)}},oC=class{constructor(e){this.id=e,this.seq=[],this.map={}}setValue(e,t,r){let i=this.seq;for(let n=0,a=i.length;n!==a;++n){let s=i[n];s.setValue(e,t[s.id],r)}}},Jf=/(\w+)(\])?(\[|\.)?/g;function Lv(e,t){e.seq.push(t),e.map[t.id]=t}function lC(e,t,r){let i=e.name,n=i.length;for(Jf.lastIndex=0;;){let a=Jf.exec(i),s=Jf.lastIndex,o=a[1],l=a[2]==="]",c=a[3];if(l&&(o=o|0),c===void 0||c==="["&&s+2===n){Lv(r,c===void 0?new aC(o,e,t):new sC(o,e,t));break}else{let u=r.map[o];u===void 0&&(u=new oC(o),Lv(r,u)),r=u}}}var nd=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),a=e.getUniformLocation(t,n.name);lC(n,a,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,a=t.length;n!==a;++n){let s=t[n],o=r[s.id];o.needsUpdate!==!1&&s.setValue(e,o.value,i)}}static seqWithValue(e,t){let r=[];for(let i=0,n=e.length;i!==n;++i){let a=e[i];a.id in t&&r.push(a)}return r}};function Ov(e,t,r){let i=e.createShader(t);return e.shaderSource(i,r),e.compileShader(i),i}var cC=37297,uC=0;function hC(e,t){let r=e.split(`
`),i=[],n=Math.max(t-6,0),a=Math.min(t+6,r.length);for(let s=n;s<a;s++){let o=s+1;i.push(`${o===t?">":" "} ${o}: ${r[s]}`)}return i.join(`
`)}var Dv=new xr;function dC(e){_r._getMatrix(Dv,_r.workingColorSpace,e);let t=`mat3( ${Dv.elements.map(r=>r.toFixed(4))} )`;switch(_r.getTransfer(e)){case Al:return[t,"LinearTransferOETF"];case kr:return[t,"sRGBTransferOETF"];default:return console.warn("THREE.WebGLProgram: Unsupported color space: ",e),[t,"LinearTransferOETF"]}}function kv(e,t,r){let i=e.getShaderParameter(t,e.COMPILE_STATUS),n=e.getShaderInfoLog(t).trim();if(i&&n==="")return"";let a=/ERROR: 0:(\d+)/.exec(n);if(a){let s=parseInt(a[1]);return r.toUpperCase()+`
`+n+`
`+hC(e.getShaderSource(t),s)}else return n}function pC(e,t){let r=dC(t);return[`vec4 ${e}( vec4 value ) {`,` return ${r[1]}( vec4( value.rgb * ${r[0]}, value.a ) );`,"}"].join(`
`)}function fC(e,t){let r;switch(t){case np:r="Linear";break;case ap:r="Reinhard";break;case sp:r="Cineon";break;case lu:r="ACESFilmic";break;case op:r="AgX";break;case lp:r="Neutral";break;case Vg:r="Custom";break;default:console.warn("THREE.WebGLProgram: Unsupported toneMapping:",t),r="Linear"}return"vec3 "+e+"( vec3 color ) { return "+r+"ToneMapping( color ); }"}var ad=new ee;function mC(){_r.getLuminanceCoefficients(ad);let e=ad.x.toFixed(4),t=ad.y.toFixed(4),r=ad.z.toFixed(4);return["float luminance( const in vec3 rgb ) {",` const vec3 weights = vec3( ${e}, ${t}, ${r} );`," return dot( weights, rgb );","}"].join(`
`)}function gC(e){return[e.extensionClipCullDistance?"#extension GL_ANGLE_clip_cull_distance : require":"",e.extensionMultiDraw?"#extension GL_ANGLE_multi_draw : require":""].filter(nc).join(`
`)}function yC(e){let t=[];for(let r in e){let i=e[r];i!==!1&&t.push("#define "+r+" "+i)}return t.join(`
`)}function vC(e,t){let r={},i=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let n=0;n<i;n++){let a=e.getActiveAttrib(t,n),s=a.name,o=1;a.type===e.FLOAT_MAT2&&(o=2),a.type===e.FLOAT_MAT3&&(o=3),a.type===e.FLOAT_MAT4&&(o=4),r[s]={type:a.type,location:e.getAttribLocation(t,s),locationSize:o}}return r}function nc(e){return e!==""}function Uv(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 Fv(e,t){return e.replace(/NUM_CLIPPING_PLANES/g,t.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g,t.numClippingPlanes-t.numClipIntersection)}var xC=/^[ \t]*#include +<([\w\d./]+)>/gm;function $f(e){return e.replace(xC,_C)}var bC=new Map;function _C(e,t){let r=br[t];if(r===void 0){let i=bC.get(t);if(i!==void 0)r=br[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 $f(r)}var wC=/#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 Bv(e){return e.replace(wC,EC)}function EC(e,t,r,i){let n="";for(let a=parseInt(t);a<parseInt(r);a++)n+=i.replace(/\[\s*i\s*\]/g,"[ "+a+" ]").replace(/UNROLLED_LOOP_INDEX/g,a);return n}function zv(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 MC(e){let t="SHADOWMAP_TYPE_BASIC";return e.shadowMapType===Me?t="SHADOWMAP_TYPE_PCF":e.shadowMapType===nt?t="SHADOWMAP_TYPE_PCF_SOFT":e.shadowMapType===ft&&(t="SHADOWMAP_TYPE_VSM"),t}function SC(e){let t="ENVMAP_TYPE_CUBE";if(e.envMap)switch(e.envMapMode){case ta:case Aa:t="ENVMAP_TYPE_CUBE";break;case Js:t="ENVMAP_TYPE_CUBE_UV";break}return t}function TC(e){let t="ENVMAP_MODE_REFLECTION";if(e.envMap)switch(e.envMapMode){case Aa:t="ENVMAP_MODE_REFRACTION";break}return t}function AC(e){let t="ENVMAP_BLENDING_NONE";if(e.envMap)switch(e.combine){case yl:t="ENVMAP_BLENDING_MULTIPLY";break;case zg:t="ENVMAP_BLENDING_MIX";break;case Gg:t="ENVMAP_BLENDING_ADD";break}return t}function CC(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 RC(e,t,r,i){let n=e.getContext(),a=r.defines,s=r.vertexShader,o=r.fragmentShader,l=MC(r),c=SC(r),u=TC(r),h=AC(r),d=CC(r),f=gC(r),y=yC(a),g=n.createProgram(),p,m,v=r.glslVersion?"#version "+r.glslVersion+`
`:"";r.isRawShaderMaterial?(p=["#define SHADER_TYPE "+r.shaderType,"#define SHADER_NAME "+r.shaderName,y].filter(nc).join(`
`),p.length>0&&(p+=`
`),m=["#define SHADER_TYPE "+r.shaderType,"#define SHADER_NAME "+r.shaderName,y].filter(nc).join(`
`),m.length>0&&(m+=`
`)):(p=[zv(r),"#define SHADER_TYPE "+r.shaderType,"#define SHADER_NAME "+r.shaderName,y,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(nc).join(`
`),m=[zv(r),"#define SHADER_TYPE "+r.shaderType,"#define SHADER_NAME "+r.shaderName,y,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 "+h:"",d?"#define CUBEUV_TEXEL_WIDTH "+d.texelWidth:"",d?"#define CUBEUV_TEXEL_HEIGHT "+d.texelHeight:"",d?"#define CUBEUV_MAX_MIP "+d.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!==ea?"#define TONE_MAPPING":"",r.toneMapping!==ea?br.tonemapping_pars_fragment:"",r.toneMapping!==ea?fC("toneMapping",r.toneMapping):"",r.dithering?"#define DITHERING":"",r.opaque?"#define OPAQUE":"",br.colorspace_pars_fragment,pC("linearToOutputTexel",r.outputColorSpace),mC(),r.useDepthPacking?"#define DEPTH_PACKING "+r.depthPacking:"",`
`].filter(nc).join(`
`)),s=$f(s),s=Uv(s,r),s=Fv(s,r),o=$f(o),o=Uv(o,r),o=Fv(o,r),s=Bv(s),o=Bv(o),r.isRawShaderMaterial!==!0&&(v=`#version 300 es
`,p=[f,"#define attribute in","#define varying out","#define texture2D texture"].join(`
`)+`
`+p,m=["#define varying in",r.glslVersion===Ep?"":"layout(location = 0) out highp vec4 pc_fragColor;",r.glslVersion===Ep?"":"#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(`
`)+`
`+m);let x=v+p+s,b=v+m+o,_=Ov(n,n.VERTEX_SHADER,x),M=Ov(n,n.FRAGMENT_SHADER,b);n.attachShader(g,_),n.attachShader(g,M),r.index0AttributeName!==void 0?n.bindAttribLocation(g,0,r.index0AttributeName):r.morphTargets===!0&&n.bindAttribLocation(g,0,"position"),n.linkProgram(g);function C(P){if(e.debug.checkShaderErrors){let N=n.getProgramInfoLog(g).trim(),D=n.getShaderInfoLog(_).trim(),B=n.getShaderInfoLog(M).trim(),J=!0,Q=!0;if(n.getProgramParameter(g,n.LINK_STATUS)===!1)if(J=!1,typeof e.debug.onShaderError=="function")e.debug.onShaderError(n,g,_,M);else{let j=kv(n,_,"vertex"),k=kv(n,M,"fragment");console.error("THREE.WebGLProgram: Shader Error "+n.getError()+" - VALIDATE_STATUS "+n.getProgramParameter(g,n.VALIDATE_STATUS)+`
Material Name: `+P.name+`
Material Type: `+P.type+`
Program Info Log: `+N+`
`+j+`
`+k)}else N!==""?console.warn("THREE.WebGLProgram: Program Info Log:",N):(D===""||B==="")&&(Q=!1);Q&&(P.diagnostics={runnable:J,programLog:N,vertexShader:{log:D,prefix:p},fragmentShader:{log:B,prefix:m}})}n.deleteShader(_),n.deleteShader(M),S=new nd(n,g),w=vC(n,g)}let S;this.getUniforms=function(){return S===void 0&&C(this),S};let w;this.getAttributes=function(){return w===void 0&&C(this),w};let E=r.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return E===!1&&(E=n.getProgramParameter(g,cC)),E},this.destroy=function(){i.releaseStatesOfProgram(this),n.deleteProgram(g),this.program=void 0},this.type=r.shaderType,this.name=r.shaderName,this.id=uC++,this.cacheKey=t,this.usedTimes=1,this.program=g,this.vertexShader=_,this.fragmentShader=M,this}var PC=0,IC=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),a=this._getShaderCacheForMaterial(e);return a.has(i)===!1&&(a.add(i),i.usedTimes++),a.has(n)===!1&&(a.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 NC(e),t.set(e,r)),r}},NC=class{constructor(e){this.id=PC++,this.code=e,this.usedTimes=0}};function LC(e,t,r,i,n,a,s){let o=new eh,l=new IC,c=new Set,u=[],h=n.logarithmicDepthBuffer,d=n.vertexTextures,f=n.precision,y={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 g(w){return c.add(w),w===0?"uv":`uv${w}`}function p(w,E,P,N,D){let B=N.fog,J=D.geometry,Q=w.isMeshStandardMaterial?N.environment:null,j=(w.isMeshStandardMaterial?r:t).get(w.envMap||Q),k=j&&j.mapping===Js?j.image.height:null,H=y[w.type];w.precision!==null&&(f=n.getMaxPrecision(w.precision),f!==w.precision&&console.warn("THREE.WebGLProgram.getParameters:",w.precision,"not supported, using",f,"instead."));let U=J.morphAttributes.position||J.morphAttributes.normal||J.morphAttributes.color,X=U!==void 0?U.length:0,W=0;J.morphAttributes.position!==void 0&&(W=1),J.morphAttributes.normal!==void 0&&(W=2),J.morphAttributes.color!==void 0&&(W=3);let $,G,T,I;if(H){let gt=kn[H];$=gt.vertexShader,G=gt.fragmentShader}else $=w.vertexShader,G=w.fragmentShader,l.update(w),T=l.getVertexShaderID(w),I=l.getFragmentShaderID(w);let V=e.getRenderTarget(),K=e.state.buffers.depth.getReversed(),ie=D.isInstancedMesh===!0,le=D.isBatchedMesh===!0,ae=!!w.map,de=!!w.matcap,z=!!j,me=!!w.aoMap,we=!!w.lightMap,He=!!w.bumpMap,ne=!!w.normalMap,_e=!!w.displacementMap,oe=!!w.emissiveMap,ce=!!w.metalnessMap,L=!!w.roughnessMap,A=w.anisotropy>0,O=w.clearcoat>0,F=w.dispersion>0,Y=w.iridescence>0,re=w.sheen>0,ue=w.transmission>0,se=A&&!!w.anisotropyMap,pe=O&&!!w.clearcoatMap,Pe=O&&!!w.clearcoatNormalMap,Ce=O&&!!w.clearcoatRoughnessMap,je=Y&&!!w.iridescenceMap,st=Y&&!!w.iridescenceThicknessMap,Pt=re&&!!w.sheenColorMap,ut=re&&!!w.sheenRoughnessMap,ot=!!w.specularMap,tt=!!w.specularColorMap,Ht=!!w.specularIntensityMap,fe=ue&&!!w.transmissionMap,qe=ue&&!!w.thicknessMap,Ue=!!w.gradientMap,Ie=!!w.alphaMap,mt=w.alphaTest>0,lt=!!w.alphaHash,Ut=!!w.extensions,xt=ea;w.toneMapped&&(V===null||V.isXRRenderTarget===!0)&&(xt=e.toneMapping);let Dt={shaderID:H,shaderType:w.type,shaderName:w.name,vertexShader:$,fragmentShader:G,defines:w.defines,customVertexShaderID:T,customFragmentShaderID:I,isRawShaderMaterial:w.isRawShaderMaterial===!0,glslVersion:w.glslVersion,precision:f,batching:le,batchingColor:le&&D._colorsTexture!==null,instancing:ie,instancingColor:ie&&D.instanceColor!==null,instancingMorph:ie&&D.morphTexture!==null,supportsVertexTextures:d,outputColorSpace:V===null?e.outputColorSpace:V.isXRRenderTarget===!0?V.texture.colorSpace:Oi,alphaToCoverage:!!w.alphaToCoverage,map:ae,matcap:de,envMap:z,envMapMode:z&&j.mapping,envMapCubeUVHeight:k,aoMap:me,lightMap:we,bumpMap:He,normalMap:ne,displacementMap:d&&_e,emissiveMap:oe,normalMapObjectSpace:ne&&w.normalMapType===Zg,normalMapTangentSpace:ne&&w.normalMapType===Pa,metalnessMap:ce,roughnessMap:L,anisotropy:A,anisotropyMap:se,clearcoat:O,clearcoatMap:pe,clearcoatNormalMap:Pe,clearcoatRoughnessMap:Ce,dispersion:F,iridescence:Y,iridescenceMap:je,iridescenceThicknessMap:st,sheen:re,sheenColorMap:Pt,sheenRoughnessMap:ut,specularMap:ot,specularColorMap:tt,specularIntensityMap:Ht,transmission:ue,transmissionMap:fe,thicknessMap:qe,gradientMap:Ue,opaque:w.transparent===!1&&w.blending===Zt&&w.alphaToCoverage===!1,alphaMap:Ie,alphaTest:mt,alphaHash:lt,combine:w.combine,mapUv:ae&&g(w.map.channel),aoMapUv:me&&g(w.aoMap.channel),lightMapUv:we&&g(w.lightMap.channel),bumpMapUv:He&&g(w.bumpMap.channel),normalMapUv:ne&&g(w.normalMap.channel),displacementMapUv:_e&&g(w.displacementMap.channel),emissiveMapUv:oe&&g(w.emissiveMap.channel),metalnessMapUv:ce&&g(w.metalnessMap.channel),roughnessMapUv:L&&g(w.roughnessMap.channel),anisotropyMapUv:se&&g(w.anisotropyMap.channel),clearcoatMapUv:pe&&g(w.clearcoatMap.channel),clearcoatNormalMapUv:Pe&&g(w.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:Ce&&g(w.clearcoatRoughnessMap.channel),iridescenceMapUv:je&&g(w.iridescenceMap.channel),iridescenceThicknessMapUv:st&&g(w.iridescenceThicknessMap.channel),sheenColorMapUv:Pt&&g(w.sheenColorMap.channel),sheenRoughnessMapUv:ut&&g(w.sheenRoughnessMap.channel),specularMapUv:ot&&g(w.specularMap.channel),specularColorMapUv:tt&&g(w.specularColorMap.channel),specularIntensityMapUv:Ht&&g(w.specularIntensityMap.channel),transmissionMapUv:fe&&g(w.transmissionMap.channel),thicknessMapUv:qe&&g(w.thicknessMap.channel),alphaMapUv:Ie&&g(w.alphaMap.channel),vertexTangents:!!J.attributes.tangent&&(ne||A),vertexColors:w.vertexColors,vertexAlphas:w.vertexColors===!0&&!!J.attributes.color&&J.attributes.color.itemSize===4,pointsUvs:D.isPoints===!0&&!!J.attributes.uv&&(ae||Ie),fog:!!B,useFog:w.fog===!0,fogExp2:!!B&&B.isFogExp2,flatShading:w.flatShading===!0,sizeAttenuation:w.sizeAttenuation===!0,logarithmicDepthBuffer:h,reverseDepthBuffer:K,skinning:D.isSkinnedMesh===!0,morphTargets:J.morphAttributes.position!==void 0,morphNormals:J.morphAttributes.normal!==void 0,morphColors:J.morphAttributes.color!==void 0,morphTargetsCount:X,morphTextureStride:W,numDirLights:E.directional.length,numPointLights:E.point.length,numSpotLights:E.spot.length,numSpotLightMaps:E.spotLightMap.length,numRectAreaLights:E.rectArea.length,numHemiLights:E.hemi.length,numDirLightShadows:E.directionalShadowMap.length,numPointLightShadows:E.pointShadowMap.length,numSpotLightShadows:E.spotShadowMap.length,numSpotLightShadowsWithMaps:E.numSpotLightShadowsWithMaps,numLightProbes:E.numLightProbes,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:w.dithering,shadowMapEnabled:e.shadowMap.enabled&&P.length>0,shadowMapType:e.shadowMap.type,toneMapping:xt,decodeVideoTexture:ae&&w.map.isVideoTexture===!0&&_r.getTransfer(w.map.colorSpace)===kr,decodeVideoTextureEmissive:oe&&w.emissiveMap.isVideoTexture===!0&&_r.getTransfer(w.emissiveMap.colorSpace)===kr,premultipliedAlpha:w.premultipliedAlpha,doubleSided:w.side===Rt,flipSided:w.side===_t,useDepthPacking:w.depthPacking>=0,depthPacking:w.depthPacking||0,index0AttributeName:w.index0AttributeName,extensionClipCullDistance:Ut&&w.extensions.clipCullDistance===!0&&i.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(Ut&&w.extensions.multiDraw===!0||le)&&i.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:i.has("KHR_parallel_shader_compile"),customProgramCacheKey:w.customProgramCacheKey()};return Dt.vertexUv1s=c.has(1),Dt.vertexUv2s=c.has(2),Dt.vertexUv3s=c.has(3),c.clear(),Dt}function m(w){let E=[];if(w.shaderID?E.push(w.shaderID):(E.push(w.customVertexShaderID),E.push(w.customFragmentShaderID)),w.defines!==void 0)for(let P in w.defines)E.push(P),E.push(w.defines[P]);return w.isRawShaderMaterial===!1&&(v(E,w),x(E,w),E.push(e.outputColorSpace)),E.push(w.customProgramCacheKey),E.join()}function v(w,E){w.push(E.precision),w.push(E.outputColorSpace),w.push(E.envMapMode),w.push(E.envMapCubeUVHeight),w.push(E.mapUv),w.push(E.alphaMapUv),w.push(E.lightMapUv),w.push(E.aoMapUv),w.push(E.bumpMapUv),w.push(E.normalMapUv),w.push(E.displacementMapUv),w.push(E.emissiveMapUv),w.push(E.metalnessMapUv),w.push(E.roughnessMapUv),w.push(E.anisotropyMapUv),w.push(E.clearcoatMapUv),w.push(E.clearcoatNormalMapUv),w.push(E.clearcoatRoughnessMapUv),w.push(E.iridescenceMapUv),w.push(E.iridescenceThicknessMapUv),w.push(E.sheenColorMapUv),w.push(E.sheenRoughnessMapUv),w.push(E.specularMapUv),w.push(E.specularColorMapUv),w.push(E.specularIntensityMapUv),w.push(E.transmissionMapUv),w.push(E.thicknessMapUv),w.push(E.combine),w.push(E.fogExp2),w.push(E.sizeAttenuation),w.push(E.morphTargetsCount),w.push(E.morphAttributeCount),w.push(E.numDirLights),w.push(E.numPointLights),w.push(E.numSpotLights),w.push(E.numSpotLightMaps),w.push(E.numHemiLights),w.push(E.numRectAreaLights),w.push(E.numDirLightShadows),w.push(E.numPointLightShadows),w.push(E.numSpotLightShadows),w.push(E.numSpotLightShadowsWithMaps),w.push(E.numLightProbes),w.push(E.shadowMapType),w.push(E.toneMapping),w.push(E.numClippingPlanes),w.push(E.numClipIntersection),w.push(E.depthPacking)}function x(w,E){o.disableAll(),E.supportsVertexTextures&&o.enable(0),E.instancing&&o.enable(1),E.instancingColor&&o.enable(2),E.instancingMorph&&o.enable(3),E.matcap&&o.enable(4),E.envMap&&o.enable(5),E.normalMapObjectSpace&&o.enable(6),E.normalMapTangentSpace&&o.enable(7),E.clearcoat&&o.enable(8),E.iridescence&&o.enable(9),E.alphaTest&&o.enable(10),E.vertexColors&&o.enable(11),E.vertexAlphas&&o.enable(12),E.vertexUv1s&&o.enable(13),E.vertexUv2s&&o.enable(14),E.vertexUv3s&&o.enable(15),E.vertexTangents&&o.enable(16),E.anisotropy&&o.enable(17),E.alphaHash&&o.enable(18),E.batching&&o.enable(19),E.dispersion&&o.enable(20),E.batchingColor&&o.enable(21),w.push(o.mask),o.disableAll(),E.fog&&o.enable(0),E.useFog&&o.enable(1),E.flatShading&&o.enable(2),E.logarithmicDepthBuffer&&o.enable(3),E.reverseDepthBuffer&&o.enable(4),E.skinning&&o.enable(5),E.morphTargets&&o.enable(6),E.morphNormals&&o.enable(7),E.morphColors&&o.enable(8),E.premultipliedAlpha&&o.enable(9),E.shadowMapEnabled&&o.enable(10),E.doubleSided&&o.enable(11),E.flipSided&&o.enable(12),E.useDepthPacking&&o.enable(13),E.dithering&&o.enable(14),E.transmission&&o.enable(15),E.sheen&&o.enable(16),E.opaque&&o.enable(17),E.pointsUvs&&o.enable(18),E.decodeVideoTexture&&o.enable(19),E.decodeVideoTextureEmissive&&o.enable(20),E.alphaToCoverage&&o.enable(21),w.push(o.mask)}function b(w){let E=y[w.type],P;if(E){let N=kn[E];P=xn.clone(N.uniforms)}else P=w.uniforms;return P}function _(w,E){let P;for(let N=0,D=u.length;N<D;N++){let B=u[N];if(B.cacheKey===E){P=B,++P.usedTimes;break}}return P===void 0&&(P=new RC(e,E,w,a),u.push(P)),P}function M(w){if(--w.usedTimes===0){let E=u.indexOf(w);u[E]=u[u.length-1],u.pop(),w.destroy()}}function C(w){l.remove(w)}function S(){l.dispose()}return{getParameters:p,getProgramCacheKey:m,getUniforms:b,acquireProgram:_,releaseProgram:M,releaseShaderCache:C,programs:u,dispose:S}}function OC(){let e=new WeakMap;function t(s){return e.has(s)}function r(s){let o=e.get(s);return o===void 0&&(o={},e.set(s,o)),o}function i(s){e.delete(s)}function n(s,o,l){e.get(s)[o]=l}function a(){e=new WeakMap}return{has:t,get:r,remove:i,update:n,dispose:a}}function DC(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 Gv(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 Vv(){let e=[],t=0,r=[],i=[],n=[];function a(){t=0,r.length=0,i.length=0,n.length=0}function s(h,d,f,y,g,p){let m=e[t];return m===void 0?(m={id:h.id,object:h,geometry:d,material:f,groupOrder:y,renderOrder:h.renderOrder,z:g,group:p},e[t]=m):(m.id=h.id,m.object=h,m.geometry=d,m.material=f,m.groupOrder=y,m.renderOrder=h.renderOrder,m.z=g,m.group=p),t++,m}function o(h,d,f,y,g,p){let m=s(h,d,f,y,g,p);f.transmission>0?i.push(m):f.transparent===!0?n.push(m):r.push(m)}function l(h,d,f,y,g,p){let m=s(h,d,f,y,g,p);f.transmission>0?i.unshift(m):f.transparent===!0?n.unshift(m):r.unshift(m)}function c(h,d){r.length>1&&r.sort(h||DC),i.length>1&&i.sort(d||Gv),n.length>1&&n.sort(d||Gv)}function u(){for(let h=t,d=e.length;h<d;h++){let f=e[h];if(f.id===null)break;f.id=null,f.object=null,f.geometry=null,f.material=null,f.group=null}}return{opaque:r,transmissive:i,transparent:n,init:a,push:o,unshift:l,finish:u,sort:c}}function kC(){let e=new WeakMap;function t(i,n){let a=e.get(i),s;return a===void 0?(s=new Vv,e.set(i,[s])):n>=a.length?(s=new Vv,a.push(s)):s=a[n],s}function r(){e=new WeakMap}return{get:t,dispose:r}}function UC(){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 ee,color:new yt};break;case"SpotLight":r={position:new ee,direction:new ee,color:new yt,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":r={position:new ee,color:new yt,distance:0,decay:0};break;case"HemisphereLight":r={direction:new ee,skyColor:new yt,groundColor:new yt};break;case"RectAreaLight":r={color:new yt,position:new ee,halfWidth:new ee,halfHeight:new ee};break}return e[t.id]=r,r}}}function FC(){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 Xe};break;case"SpotLight":r={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Xe};break;case"PointLight":r={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new Xe,shadowCameraNear:1,shadowCameraFar:1e3};break}return e[t.id]=r,r}}}var BC=0;function zC(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+(t.map?1:0)-(e.map?1:0)}function GC(e){let t=new UC,r=FC(),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 ee);let n=new ee,a=new Jt,s=new Jt;function o(c){let u=0,h=0,d=0;for(let w=0;w<9;w++)i.probe[w].set(0,0,0);let f=0,y=0,g=0,p=0,m=0,v=0,x=0,b=0,_=0,M=0,C=0;c.sort(zC);for(let w=0,E=c.length;w<E;w++){let P=c[w],N=P.color,D=P.intensity,B=P.distance,J=P.shadow&&P.shadow.map?P.shadow.map.texture:null;if(P.isAmbientLight)u+=N.r*D,h+=N.g*D,d+=N.b*D;else if(P.isLightProbe){for(let Q=0;Q<9;Q++)i.probe[Q].addScaledVector(P.sh.coefficients[Q],D);C++}else if(P.isDirectionalLight){let Q=t.get(P);if(Q.color.copy(P.color).multiplyScalar(P.intensity),P.castShadow){let j=P.shadow,k=r.get(P);k.shadowIntensity=j.intensity,k.shadowBias=j.bias,k.shadowNormalBias=j.normalBias,k.shadowRadius=j.radius,k.shadowMapSize=j.mapSize,i.directionalShadow[f]=k,i.directionalShadowMap[f]=J,i.directionalShadowMatrix[f]=P.shadow.matrix,v++}i.directional[f]=Q,f++}else if(P.isSpotLight){let Q=t.get(P);Q.position.setFromMatrixPosition(P.matrixWorld),Q.color.copy(N).multiplyScalar(D),Q.distance=B,Q.coneCos=Math.cos(P.angle),Q.penumbraCos=Math.cos(P.angle*(1-P.penumbra)),Q.decay=P.decay,i.spot[g]=Q;let j=P.shadow;if(P.map&&(i.spotLightMap[_]=P.map,_++,j.updateMatrices(P),P.castShadow&&M++),i.spotLightMatrix[g]=j.matrix,P.castShadow){let k=r.get(P);k.shadowIntensity=j.intensity,k.shadowBias=j.bias,k.shadowNormalBias=j.normalBias,k.shadowRadius=j.radius,k.shadowMapSize=j.mapSize,i.spotShadow[g]=k,i.spotShadowMap[g]=J,b++}g++}else if(P.isRectAreaLight){let Q=t.get(P);Q.color.copy(N).multiplyScalar(D),Q.halfWidth.set(P.width*.5,0,0),Q.halfHeight.set(0,P.height*.5,0),i.rectArea[p]=Q,p++}else if(P.isPointLight){let Q=t.get(P);if(Q.color.copy(P.color).multiplyScalar(P.intensity),Q.distance=P.distance,Q.decay=P.decay,P.castShadow){let j=P.shadow,k=r.get(P);k.shadowIntensity=j.intensity,k.shadowBias=j.bias,k.shadowNormalBias=j.normalBias,k.shadowRadius=j.radius,k.shadowMapSize=j.mapSize,k.shadowCameraNear=j.camera.near,k.shadowCameraFar=j.camera.far,i.pointShadow[y]=k,i.pointShadowMap[y]=J,i.pointShadowMatrix[y]=P.shadow.matrix,x++}i.point[y]=Q,y++}else if(P.isHemisphereLight){let Q=t.get(P);Q.skyColor.copy(P.color).multiplyScalar(D),Q.groundColor.copy(P.groundColor).multiplyScalar(D),i.hemi[m]=Q,m++}}p>0&&(e.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=kt.LTC_FLOAT_1,i.rectAreaLTC2=kt.LTC_FLOAT_2):(i.rectAreaLTC1=kt.LTC_HALF_1,i.rectAreaLTC2=kt.LTC_HALF_2)),i.ambient[0]=u,i.ambient[1]=h,i.ambient[2]=d;let S=i.hash;(S.directionalLength!==f||S.pointLength!==y||S.spotLength!==g||S.rectAreaLength!==p||S.hemiLength!==m||S.numDirectionalShadows!==v||S.numPointShadows!==x||S.numSpotShadows!==b||S.numSpotMaps!==_||S.numLightProbes!==C)&&(i.directional.length=f,i.spot.length=g,i.rectArea.length=p,i.point.length=y,i.hemi.length=m,i.directionalShadow.length=v,i.directionalShadowMap.length=v,i.pointShadow.length=x,i.pointShadowMap.length=x,i.spotShadow.length=b,i.spotShadowMap.length=b,i.directionalShadowMatrix.length=v,i.pointShadowMatrix.length=x,i.spotLightMatrix.length=b+_-M,i.spotLightMap.length=_,i.numSpotLightShadowsWithMaps=M,i.numLightProbes=C,S.directionalLength=f,S.pointLength=y,S.spotLength=g,S.rectAreaLength=p,S.hemiLength=m,S.numDirectionalShadows=v,S.numPointShadows=x,S.numSpotShadows=b,S.numSpotMaps=_,S.numLightProbes=C,i.version=BC++)}function l(c,u){let h=0,d=0,f=0,y=0,g=0,p=u.matrixWorldInverse;for(let m=0,v=c.length;m<v;m++){let x=c[m];if(x.isDirectionalLight){let b=i.directional[h];b.direction.setFromMatrixPosition(x.matrixWorld),n.setFromMatrixPosition(x.target.matrixWorld),b.direction.sub(n),b.direction.transformDirection(p),h++}else if(x.isSpotLight){let b=i.spot[f];b.position.setFromMatrixPosition(x.matrixWorld),b.position.applyMatrix4(p),b.direction.setFromMatrixPosition(x.matrixWorld),n.setFromMatrixPosition(x.target.matrixWorld),b.direction.sub(n),b.direction.transformDirection(p),f++}else if(x.isRectAreaLight){let b=i.rectArea[y];b.position.setFromMatrixPosition(x.matrixWorld),b.position.applyMatrix4(p),s.identity(),a.copy(x.matrixWorld),a.premultiply(p),s.extractRotation(a),b.halfWidth.set(x.width*.5,0,0),b.halfHeight.set(0,x.height*.5,0),b.halfWidth.applyMatrix4(s),b.halfHeight.applyMatrix4(s),y++}else if(x.isPointLight){let b=i.point[d];b.position.setFromMatrixPosition(x.matrixWorld),b.position.applyMatrix4(p),d++}else if(x.isHemisphereLight){let b=i.hemi[g];b.direction.setFromMatrixPosition(x.matrixWorld),b.direction.transformDirection(p),g++}}}return{setup:o,setupView:l,state:i}}function Hv(e){let t=new GC(e),r=[],i=[];function n(u){c.camera=u,r.length=0,i.length=0}function a(u){r.push(u)}function s(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:a,pushShadow:s}}function VC(e){let t=new WeakMap;function r(n,a=0){let s=t.get(n),o;return s===void 0?(o=new Hv(e),t.set(n,[o])):a>=s.length?(o=new Hv(e),s.push(o)):o=s[a],o}function i(){t=new WeakMap}return{get:r,dispose:i}}var HC=`void main() {
gl_Position = vec4( position, 1.0 );
}`,WC=`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 jC(e,t,r){let i=new Wl,n=new Xe,a=new Xe,s=new Nr,o=new Mf({depthPacking:Kg}),l=new Sf,c={},u=r.maxTextureSize,h={[it]:_t,[_t]:it,[Rt]:Rt},d=new oi({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new Xe},radius:{value:4}},vertexShader:HC,fragmentShader:WC}),f=d.clone();f.defines.HORIZONTAL_PASS=1;let y=new ar;y.setAttribute("position",new Mr(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let g=new hr(y,d),p=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=Me;let m=this.type;this.render=function(M,C,S){if(p.enabled===!1||p.autoUpdate===!1&&p.needsUpdate===!1||M.length===0)return;let w=e.getRenderTarget(),E=e.getActiveCubeFace(),P=e.getActiveMipmapLevel(),N=e.state;N.setBlending(Ft),N.buffers.color.setClear(1,1,1,1),N.buffers.depth.setTest(!0),N.setScissorTest(!1);let D=m!==ft&&this.type===ft,B=m===ft&&this.type!==ft;for(let J=0,Q=M.length;J<Q;J++){let j=M[J],k=j.shadow;if(k===void 0){console.warn("THREE.WebGLShadowMap:",j,"has no shadow.");continue}if(k.autoUpdate===!1&&k.needsUpdate===!1)continue;n.copy(k.mapSize);let H=k.getFrameExtents();if(n.multiply(H),a.copy(k.mapSize),(n.x>u||n.y>u)&&(n.x>u&&(a.x=Math.floor(u/H.x),n.x=a.x*H.x,k.mapSize.x=a.x),n.y>u&&(a.y=Math.floor(u/H.y),n.y=a.y*H.y,k.mapSize.y=a.y)),k.map===null||D===!0||B===!0){let X=this.type!==ft?{minFilter:Kr,magFilter:Kr}:{};k.map!==null&&k.map.dispose(),k.map=new Pi(n.x,n.y,X),k.map.texture.name=j.name+".shadowMap",k.camera.updateProjectionMatrix()}e.setRenderTarget(k.map),e.clear();let U=k.getViewportCount();for(let X=0;X<U;X++){let W=k.getViewport(X);s.set(a.x*W.x,a.y*W.y,a.x*W.z,a.y*W.w),N.viewport(s),k.updateMatrices(j,X),i=k.getFrustum(),b(C,S,k.camera,j,this.type)}k.isPointLightShadow!==!0&&this.type===ft&&v(k,S),k.needsUpdate=!1}m=this.type,p.needsUpdate=!1,e.setRenderTarget(w,E,P)};function v(M,C){let S=t.update(g);d.defines.VSM_SAMPLES!==M.blurSamples&&(d.defines.VSM_SAMPLES=M.blurSamples,f.defines.VSM_SAMPLES=M.blurSamples,d.needsUpdate=!0,f.needsUpdate=!0),M.mapPass===null&&(M.mapPass=new Pi(n.x,n.y)),d.uniforms.shadow_pass.value=M.map.texture,d.uniforms.resolution.value=M.mapSize,d.uniforms.radius.value=M.radius,e.setRenderTarget(M.mapPass),e.clear(),e.renderBufferDirect(C,null,S,d,g,null),f.uniforms.shadow_pass.value=M.mapPass.texture,f.uniforms.resolution.value=M.mapSize,f.uniforms.radius.value=M.radius,e.setRenderTarget(M.map),e.clear(),e.renderBufferDirect(C,null,S,f,g,null)}function x(M,C,S,w){let E=null,P=S.isPointLight===!0?M.customDistanceMaterial:M.customDepthMaterial;if(P!==void 0)E=P;else if(E=S.isPointLight===!0?l:o,e.localClippingEnabled&&C.clipShadows===!0&&Array.isArray(C.clippingPlanes)&&C.clippingPlanes.length!==0||C.displacementMap&&C.displacementScale!==0||C.alphaMap&&C.alphaTest>0||C.map&&C.alphaTest>0){let N=E.uuid,D=C.uuid,B=c[N];B===void 0&&(B={},c[N]=B);let J=B[D];J===void 0&&(J=E.clone(),B[D]=J,C.addEventListener("dispose",_)),E=J}if(E.visible=C.visible,E.wireframe=C.wireframe,w===ft?E.side=C.shadowSide!==null?C.shadowSide:C.side:E.side=C.shadowSide!==null?C.shadowSide:h[C.side],E.alphaMap=C.alphaMap,E.alphaTest=C.alphaTest,E.map=C.map,E.clipShadows=C.clipShadows,E.clippingPlanes=C.clippingPlanes,E.clipIntersection=C.clipIntersection,E.displacementMap=C.displacementMap,E.displacementScale=C.displacementScale,E.displacementBias=C.displacementBias,E.wireframeLinewidth=C.wireframeLinewidth,E.linewidth=C.linewidth,S.isPointLight===!0&&E.isMeshDistanceMaterial===!0){let N=e.properties.get(E);N.light=S}return E}function b(M,C,S,w,E){if(M.visible===!1)return;if(M.layers.test(C.layers)&&(M.isMesh||M.isLine||M.isPoints)&&(M.castShadow||M.receiveShadow&&E===ft)&&(!M.frustumCulled||i.intersectsObject(M))){M.modelViewMatrix.multiplyMatrices(S.matrixWorldInverse,M.matrixWorld);let N=t.update(M),D=M.material;if(Array.isArray(D)){let B=N.groups;for(let J=0,Q=B.length;J<Q;J++){let j=B[J],k=D[j.materialIndex];if(k&&k.visible){let H=x(M,k,w,E);M.onBeforeShadow(e,M,C,S,N,H,j),e.renderBufferDirect(S,null,N,H,M,j),M.onAfterShadow(e,M,C,S,N,H,j)}}}else if(D.visible){let B=x(M,D,w,E);M.onBeforeShadow(e,M,C,S,N,B,null),e.renderBufferDirect(S,null,N,B,M,null),M.onAfterShadow(e,M,C,S,N,B,null)}}let P=M.children;for(let N=0,D=P.length;N<D;N++)b(P[N],C,S,w,E)}function _(M){M.target.removeEventListener("dispose",_);for(let C in c){let S=c[C],w=M.target.uuid;w in S&&(S[w].dispose(),delete S[w])}}}var XC={[tu]:ru,[iu]:su,[nu]:ou,[Ja]:au,[ru]:tu,[su]:iu,[ou]:nu,[au]:Ja};function YC(e,t){function r(){let fe=!1,qe=new Nr,Ue=null,Ie=new Nr(0,0,0,0);return{setMask:function(mt){Ue!==mt&&!fe&&(e.colorMask(mt,mt,mt,mt),Ue=mt)},setLocked:function(mt){fe=mt},setClear:function(mt,lt,Ut,xt,Dt){Dt===!0&&(mt*=xt,lt*=xt,Ut*=xt),qe.set(mt,lt,Ut,xt),Ie.equals(qe)===!1&&(e.clearColor(mt,lt,Ut,xt),Ie.copy(qe))},reset:function(){fe=!1,Ue=null,Ie.set(-1,0,0,0)}}}function i(){let fe=!1,qe=!1,Ue=null,Ie=null,mt=null;return{setReversed:function(lt){if(qe!==lt){let Ut=t.get("EXT_clip_control");qe?Ut.clipControlEXT(Ut.LOWER_LEFT_EXT,Ut.ZERO_TO_ONE_EXT):Ut.clipControlEXT(Ut.LOWER_LEFT_EXT,Ut.NEGATIVE_ONE_TO_ONE_EXT);let xt=mt;mt=null,this.setClear(xt)}qe=lt},getReversed:function(){return qe},setTest:function(lt){lt?V(e.DEPTH_TEST):K(e.DEPTH_TEST)},setMask:function(lt){Ue!==lt&&!fe&&(e.depthMask(lt),Ue=lt)},setFunc:function(lt){if(qe&&(lt=XC[lt]),Ie!==lt){switch(lt){case tu:e.depthFunc(e.NEVER);break;case ru:e.depthFunc(e.ALWAYS);break;case iu:e.depthFunc(e.LESS);break;case Ja:e.depthFunc(e.LEQUAL);break;case nu:e.depthFunc(e.EQUAL);break;case au:e.depthFunc(e.GEQUAL);break;case su:e.depthFunc(e.GREATER);break;case ou:e.depthFunc(e.NOTEQUAL);break;default:e.depthFunc(e.LEQUAL)}Ie=lt}},setLocked:function(lt){fe=lt},setClear:function(lt){mt!==lt&&(qe&&(lt=1-lt),e.clearDepth(lt),mt=lt)},reset:function(){fe=!1,Ue=null,Ie=null,mt=null,qe=!1}}}function n(){let fe=!1,qe=null,Ue=null,Ie=null,mt=null,lt=null,Ut=null,xt=null,Dt=null;return{setTest:function(gt){fe||(gt?V(e.STENCIL_TEST):K(e.STENCIL_TEST))},setMask:function(gt){qe!==gt&&!fe&&(e.stencilMask(gt),qe=gt)},setFunc:function(gt,Vt,$e){(Ue!==gt||Ie!==Vt||mt!==$e)&&(e.stencilFunc(gt,Vt,$e),Ue=gt,Ie=Vt,mt=$e)},setOp:function(gt,Vt,$e){(lt!==gt||Ut!==Vt||xt!==$e)&&(e.stencilOp(gt,Vt,$e),lt=gt,Ut=Vt,xt=$e)},setLocked:function(gt){fe=gt},setClear:function(gt){Dt!==gt&&(e.clearStencil(gt),Dt=gt)},reset:function(){fe=!1,qe=null,Ue=null,Ie=null,mt=null,lt=null,Ut=null,xt=null,Dt=null}}}let a=new r,s=new i,o=new n,l=new WeakMap,c=new WeakMap,u={},h={},d=new WeakMap,f=[],y=null,g=!1,p=null,m=null,v=null,x=null,b=null,_=null,M=null,C=new yt(0,0,0),S=0,w=!1,E=null,P=null,N=null,D=null,B=null,J=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),Q=!1,j=0,k=e.getParameter(e.VERSION);k.indexOf("WebGL")!==-1?(j=parseFloat(/^WebGL (\d)/.exec(k)[1]),Q=j>=1):k.indexOf("OpenGL ES")!==-1&&(j=parseFloat(/^OpenGL ES (\d)/.exec(k)[1]),Q=j>=2);let H=null,U={},X=e.getParameter(e.SCISSOR_BOX),W=e.getParameter(e.VIEWPORT),$=new Nr().fromArray(X),G=new Nr().fromArray(W);function T(fe,qe,Ue,Ie){let mt=new Uint8Array(4),lt=e.createTexture();e.bindTexture(fe,lt),e.texParameteri(fe,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(fe,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let Ut=0;Ut<Ue;Ut++)fe===e.TEXTURE_3D||fe===e.TEXTURE_2D_ARRAY?e.texImage3D(qe,0,e.RGBA,1,1,Ie,0,e.RGBA,e.UNSIGNED_BYTE,mt):e.texImage2D(qe+Ut,0,e.RGBA,1,1,0,e.RGBA,e.UNSIGNED_BYTE,mt);return lt}let I={};I[e.TEXTURE_2D]=T(e.TEXTURE_2D,e.TEXTURE_2D,1),I[e.TEXTURE_CUBE_MAP]=T(e.TEXTURE_CUBE_MAP,e.TEXTURE_CUBE_MAP_POSITIVE_X,6),I[e.TEXTURE_2D_ARRAY]=T(e.TEXTURE_2D_ARRAY,e.TEXTURE_2D_ARRAY,1,1),I[e.TEXTURE_3D]=T(e.TEXTURE_3D,e.TEXTURE_3D,1,1),a.setClear(0,0,0,1),s.setClear(1),o.setClear(0),V(e.DEPTH_TEST),s.setFunc(Ja),He(!1),ne(dt),V(e.CULL_FACE),me(Ft);function V(fe){u[fe]!==!0&&(e.enable(fe),u[fe]=!0)}function K(fe){u[fe]!==!1&&(e.disable(fe),u[fe]=!1)}function ie(fe,qe){return h[fe]!==qe?(e.bindFramebuffer(fe,qe),h[fe]=qe,fe===e.DRAW_FRAMEBUFFER&&(h[e.FRAMEBUFFER]=qe),fe===e.FRAMEBUFFER&&(h[e.DRAW_FRAMEBUFFER]=qe),!0):!1}function le(fe,qe){let Ue=f,Ie=!1;if(fe){Ue=d.get(qe),Ue===void 0&&(Ue=[],d.set(qe,Ue));let mt=fe.textures;if(Ue.length!==mt.length||Ue[0]!==e.COLOR_ATTACHMENT0){for(let lt=0,Ut=mt.length;lt<Ut;lt++)Ue[lt]=e.COLOR_ATTACHMENT0+lt;Ue.length=mt.length,Ie=!0}}else Ue[0]!==e.BACK&&(Ue[0]=e.BACK,Ie=!0);Ie&&e.drawBuffers(Ue)}function ae(fe){return y!==fe?(e.useProgram(fe),y=fe,!0):!1}let de={[Gt]:e.FUNC_ADD,[Er]:e.FUNC_SUBTRACT,[Xr]:e.FUNC_REVERSE_SUBTRACT};de[Ti]=e.MIN,de[Ta]=e.MAX;let z={[fn]:e.ZERO,[gl]:e.ONE,[Ig]:e.SRC_COLOR,[Qc]:e.SRC_ALPHA,[Dg]:e.SRC_ALPHA_SATURATE,[eu]:e.DST_COLOR,[$c]:e.DST_ALPHA,[Ng]:e.ONE_MINUS_SRC_COLOR,[Jc]:e.ONE_MINUS_SRC_ALPHA,[Og]:e.ONE_MINUS_DST_COLOR,[Lg]:e.ONE_MINUS_DST_ALPHA,[kg]:e.CONSTANT_COLOR,[Ug]:e.ONE_MINUS_CONSTANT_COLOR,[Fg]:e.CONSTANT_ALPHA,[Bg]:e.ONE_MINUS_CONSTANT_ALPHA};function me(fe,qe,Ue,Ie,mt,lt,Ut,xt,Dt,gt){if(fe===Ft){g===!0&&(K(e.BLEND),g=!1);return}if(g===!1&&(V(e.BLEND),g=!0),fe!==cr){if(fe!==p||gt!==w){if((m!==Gt||b!==Gt)&&(e.blendEquation(e.FUNC_ADD),m=Gt,b=Gt),gt)switch(fe){case Zt:e.blendFuncSeparate(e.ONE,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case or:e.blendFunc(e.ONE,e.ONE);break;case lr:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case gr:e.blendFuncSeparate(e.ZERO,e.SRC_COLOR,e.ZERO,e.SRC_ALPHA);break;default:console.error("THREE.WebGLState: Invalid blending: ",fe);break}else switch(fe){case Zt:e.blendFuncSeparate(e.SRC_ALPHA,e.ONE_MINUS_SRC_ALPHA,e.ONE,e.ONE_MINUS_SRC_ALPHA);break;case or:e.blendFunc(e.SRC_ALPHA,e.ONE);break;case lr:e.blendFuncSeparate(e.ZERO,e.ONE_MINUS_SRC_COLOR,e.ZERO,e.ONE);break;case gr:e.blendFunc(e.ZERO,e.SRC_COLOR);break;default:console.error("THREE.WebGLState: Invalid blending: ",fe);break}v=null,x=null,_=null,M=null,C.set(0,0,0),S=0,p=fe,w=gt}return}mt=mt||qe,lt=lt||Ue,Ut=Ut||Ie,(qe!==m||mt!==b)&&(e.blendEquationSeparate(de[qe],de[mt]),m=qe,b=mt),(Ue!==v||Ie!==x||lt!==_||Ut!==M)&&(e.blendFuncSeparate(z[Ue],z[Ie],z[lt],z[Ut]),v=Ue,x=Ie,_=lt,M=Ut),(xt.equals(C)===!1||Dt!==S)&&(e.blendColor(xt.r,xt.g,xt.b,Dt),C.copy(xt),S=Dt),p=fe,w=!1}function we(fe,qe){fe.side===Rt?K(e.CULL_FACE):V(e.CULL_FACE);let Ue=fe.side===_t;qe&&(Ue=!Ue),He(Ue),fe.blending===Zt&&fe.transparent===!1?me(Ft):me(fe.blending,fe.blendEquation,fe.blendSrc,fe.blendDst,fe.blendEquationAlpha,fe.blendSrcAlpha,fe.blendDstAlpha,fe.blendColor,fe.blendAlpha,fe.premultipliedAlpha),s.setFunc(fe.depthFunc),s.setTest(fe.depthTest),s.setMask(fe.depthWrite),a.setMask(fe.colorWrite);let Ie=fe.stencilWrite;o.setTest(Ie),Ie&&(o.setMask(fe.stencilWriteMask),o.setFunc(fe.stencilFunc,fe.stencilRef,fe.stencilFuncMask),o.setOp(fe.stencilFail,fe.stencilZFail,fe.stencilZPass)),oe(fe.polygonOffset,fe.polygonOffsetFactor,fe.polygonOffsetUnits),fe.alphaToCoverage===!0?V(e.SAMPLE_ALPHA_TO_COVERAGE):K(e.SAMPLE_ALPHA_TO_COVERAGE)}function He(fe){E!==fe&&(fe?e.frontFace(e.CW):e.frontFace(e.CCW),E=fe)}function ne(fe){fe!==et?(V(e.CULL_FACE),fe!==P&&(fe===dt?e.cullFace(e.BACK):fe===St?e.cullFace(e.FRONT):e.cullFace(e.FRONT_AND_BACK))):K(e.CULL_FACE),P=fe}function _e(fe){fe!==N&&(Q&&e.lineWidth(fe),N=fe)}function oe(fe,qe,Ue){fe?(V(e.POLYGON_OFFSET_FILL),(D!==qe||B!==Ue)&&(e.polygonOffset(qe,Ue),D=qe,B=Ue)):K(e.POLYGON_OFFSET_FILL)}function ce(fe){fe?V(e.SCISSOR_TEST):K(e.SCISSOR_TEST)}function L(fe){fe===void 0&&(fe=e.TEXTURE0+J-1),H!==fe&&(e.activeTexture(fe),H=fe)}function A(fe,qe,Ue){Ue===void 0&&(H===null?Ue=e.TEXTURE0+J-1:Ue=H);let Ie=U[Ue];Ie===void 0&&(Ie={type:void 0,texture:void 0},U[Ue]=Ie),(Ie.type!==fe||Ie.texture!==qe)&&(H!==Ue&&(e.activeTexture(Ue),H=Ue),e.bindTexture(fe,qe||I[fe]),Ie.type=fe,Ie.texture=qe)}function O(){let fe=U[H];fe!==void 0&&fe.type!==void 0&&(e.bindTexture(fe.type,null),fe.type=void 0,fe.texture=void 0)}function F(){try{e.compressedTexImage2D.apply(e,arguments)}catch(fe){console.error("THREE.WebGLState:",fe)}}function Y(){try{e.compressedTexImage3D.apply(e,arguments)}catch(fe){console.error("THREE.WebGLState:",fe)}}function re(){try{e.texSubImage2D.apply(e,arguments)}catch(fe){console.error("THREE.WebGLState:",fe)}}function ue(){try{e.texSubImage3D.apply(e,arguments)}catch(fe){console.error("THREE.WebGLState:",fe)}}function se(){try{e.compressedTexSubImage2D.apply(e,arguments)}catch(fe){console.error("THREE.WebGLState:",fe)}}function pe(){try{e.compressedTexSubImage3D.apply(e,arguments)}catch(fe){console.error("THREE.WebGLState:",fe)}}function Pe(){try{e.texStorage2D.apply(e,arguments)}catch(fe){console.error("THREE.WebGLState:",fe)}}function Ce(){try{e.texStorage3D.apply(e,arguments)}catch(fe){console.error("THREE.WebGLState:",fe)}}function je(){try{e.texImage2D.apply(e,arguments)}catch(fe){console.error("THREE.WebGLState:",fe)}}function st(){try{e.texImage3D.apply(e,arguments)}catch(fe){console.error("THREE.WebGLState:",fe)}}function Pt(fe){$.equals(fe)===!1&&(e.scissor(fe.x,fe.y,fe.z,fe.w),$.copy(fe))}function ut(fe){G.equals(fe)===!1&&(e.viewport(fe.x,fe.y,fe.z,fe.w),G.copy(fe))}function ot(fe,qe){let Ue=c.get(qe);Ue===void 0&&(Ue=new WeakMap,c.set(qe,Ue));let Ie=Ue.get(fe);Ie===void 0&&(Ie=e.getUniformBlockIndex(qe,fe.name),Ue.set(fe,Ie))}function tt(fe,qe){let Ue=c.get(qe).get(fe);l.get(qe)!==Ue&&(e.uniformBlockBinding(qe,Ue,fe.__bindingPointIndex),l.set(qe,Ue))}function Ht(){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),s.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={},H=null,U={},h={},d=new WeakMap,f=[],y=null,g=!1,p=null,m=null,v=null,x=null,b=null,_=null,M=null,C=new yt(0,0,0),S=0,w=!1,E=null,P=null,N=null,D=null,B=null,$.set(0,0,e.canvas.width,e.canvas.height),G.set(0,0,e.canvas.width,e.canvas.height),a.reset(),s.reset(),o.reset()}return{buffers:{color:a,depth:s,stencil:o},enable:V,disable:K,bindFramebuffer:ie,drawBuffers:le,useProgram:ae,setBlending:me,setMaterial:we,setFlipSided:He,setCullFace:ne,setLineWidth:_e,setPolygonOffset:oe,setScissorTest:ce,activeTexture:L,bindTexture:A,unbindTexture:O,compressedTexImage2D:F,compressedTexImage3D:Y,texImage2D:je,texImage3D:st,updateUBOMapping:ot,uniformBlockBinding:tt,texStorage2D:Pe,texStorage3D:Ce,texSubImage2D:re,texSubImage3D:ue,compressedTexSubImage2D:se,compressedTexSubImage3D:pe,scissor:Pt,viewport:ut,reset:Ht}}function qC(e,t,r,i,n,a,s){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 Xe,u=new WeakMap,h,d=new WeakMap,f=!1;try{f=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function y(L,A){return f?new OffscreenCanvas(L,A):Il("canvas")}function g(L,A,O){let F=1,Y=ce(L);if((Y.width>O||Y.height>O)&&(F=O/Math.max(Y.width,Y.height)),F<1)if(typeof HTMLImageElement<"u"&&L instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&L instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&L instanceof ImageBitmap||typeof VideoFrame<"u"&&L instanceof VideoFrame){let re=Math.floor(F*Y.width),ue=Math.floor(F*Y.height);h===void 0&&(h=y(re,ue));let se=A?y(re,ue):h;return se.width=re,se.height=ue,se.getContext("2d").drawImage(L,0,0,re,ue),console.warn("THREE.WebGLRenderer: Texture has been resized from ("+Y.width+"x"+Y.height+") to ("+re+"x"+ue+")."),se}else return"data"in L&&console.warn("THREE.WebGLRenderer: Image in DataTexture is too big ("+Y.width+"x"+Y.height+")."),L;return L}function p(L){return L.generateMipmaps}function m(L){e.generateMipmap(L)}function v(L){return L.isWebGLCubeRenderTarget?e.TEXTURE_CUBE_MAP:L.isWebGL3DRenderTarget?e.TEXTURE_3D:L.isWebGLArrayRenderTarget||L.isCompressedArrayTexture?e.TEXTURE_2D_ARRAY:e.TEXTURE_2D}function x(L,A,O,F,Y=!1){if(L!==null){if(e[L]!==void 0)return e[L];console.warn("THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format '"+L+"'")}let re=A;if(A===e.RED&&(O===e.FLOAT&&(re=e.R32F),O===e.HALF_FLOAT&&(re=e.R16F),O===e.UNSIGNED_BYTE&&(re=e.R8)),A===e.RED_INTEGER&&(O===e.UNSIGNED_BYTE&&(re=e.R8UI),O===e.UNSIGNED_SHORT&&(re=e.R16UI),O===e.UNSIGNED_INT&&(re=e.R32UI),O===e.BYTE&&(re=e.R8I),O===e.SHORT&&(re=e.R16I),O===e.INT&&(re=e.R32I)),A===e.RG&&(O===e.FLOAT&&(re=e.RG32F),O===e.HALF_FLOAT&&(re=e.RG16F),O===e.UNSIGNED_BYTE&&(re=e.RG8)),A===e.RG_INTEGER&&(O===e.UNSIGNED_BYTE&&(re=e.RG8UI),O===e.UNSIGNED_SHORT&&(re=e.RG16UI),O===e.UNSIGNED_INT&&(re=e.RG32UI),O===e.BYTE&&(re=e.RG8I),O===e.SHORT&&(re=e.RG16I),O===e.INT&&(re=e.RG32I)),A===e.RGB_INTEGER&&(O===e.UNSIGNED_BYTE&&(re=e.RGB8UI),O===e.UNSIGNED_SHORT&&(re=e.RGB16UI),O===e.UNSIGNED_INT&&(re=e.RGB32UI),O===e.BYTE&&(re=e.RGB8I),O===e.SHORT&&(re=e.RGB16I),O===e.INT&&(re=e.RGB32I)),A===e.RGBA_INTEGER&&(O===e.UNSIGNED_BYTE&&(re=e.RGBA8UI),O===e.UNSIGNED_SHORT&&(re=e.RGBA16UI),O===e.UNSIGNED_INT&&(re=e.RGBA32UI),O===e.BYTE&&(re=e.RGBA8I),O===e.SHORT&&(re=e.RGBA16I),O===e.INT&&(re=e.RGBA32I)),A===e.RGB&&O===e.UNSIGNED_INT_5_9_9_9_REV&&(re=e.RGB9_E5),A===e.RGBA){let ue=Y?Al:_r.getTransfer(F);O===e.FLOAT&&(re=e.RGBA32F),O===e.HALF_FLOAT&&(re=e.RGBA16F),O===e.UNSIGNED_BYTE&&(re=ue===kr?e.SRGB8_ALPHA8:e.RGBA8),O===e.UNSIGNED_SHORT_4_4_4_4&&(re=e.RGBA4),O===e.UNSIGNED_SHORT_5_5_5_1&&(re=e.RGB5_A1)}return(re===e.R16F||re===e.R32F||re===e.RG16F||re===e.RG32F||re===e.RGBA16F||re===e.RGBA32F)&&t.get("EXT_color_buffer_float"),re}function b(L,A){let O;return L?A===null||A===ra||A===Ca?O=e.DEPTH24_STENCIL8:A===Xi?O=e.DEPTH32F_STENCIL8:A===to&&(O=e.DEPTH24_STENCIL8,console.warn("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):A===null||A===ra||A===Ca?O=e.DEPTH_COMPONENT24:A===Xi?O=e.DEPTH_COMPONENT32F:A===to&&(O=e.DEPTH_COMPONENT16),O}function _(L,A){return p(L)===!0||L.isFramebufferTexture&&L.minFilter!==Kr&&L.minFilter!==Zr?Math.log2(Math.max(A.width,A.height))+1:L.mipmaps!==void 0&&L.mipmaps.length>0?L.mipmaps.length:L.isCompressedTexture&&Array.isArray(L.image)?A.mipmaps.length:1}function M(L){let A=L.target;A.removeEventListener("dispose",M),S(A),A.isVideoTexture&&u.delete(A)}function C(L){let A=L.target;A.removeEventListener("dispose",C),E(A)}function S(L){let A=i.get(L);if(A.__webglInit===void 0)return;let O=L.source,F=d.get(O);if(F){let Y=F[A.__cacheKey];Y.usedTimes--,Y.usedTimes===0&&w(L),Object.keys(F).length===0&&d.delete(O)}i.remove(L)}function w(L){let A=i.get(L);e.deleteTexture(A.__webglTexture);let O=L.source,F=d.get(O);delete F[A.__cacheKey],s.memory.textures--}function E(L){let A=i.get(L);if(L.depthTexture&&(L.depthTexture.dispose(),i.remove(L.depthTexture)),L.isWebGLCubeRenderTarget)for(let F=0;F<6;F++){if(Array.isArray(A.__webglFramebuffer[F]))for(let Y=0;Y<A.__webglFramebuffer[F].length;Y++)e.deleteFramebuffer(A.__webglFramebuffer[F][Y]);else e.deleteFramebuffer(A.__webglFramebuffer[F]);A.__webglDepthbuffer&&e.deleteRenderbuffer(A.__webglDepthbuffer[F])}else{if(Array.isArray(A.__webglFramebuffer))for(let F=0;F<A.__webglFramebuffer.length;F++)e.deleteFramebuffer(A.__webglFramebuffer[F]);else e.deleteFramebuffer(A.__webglFramebuffer);if(A.__webglDepthbuffer&&e.deleteRenderbuffer(A.__webglDepthbuffer),A.__webglMultisampledFramebuffer&&e.deleteFramebuffer(A.__webglMultisampledFramebuffer),A.__webglColorRenderbuffer)for(let F=0;F<A.__webglColorRenderbuffer.length;F++)A.__webglColorRenderbuffer[F]&&e.deleteRenderbuffer(A.__webglColorRenderbuffer[F]);A.__webglDepthRenderbuffer&&e.deleteRenderbuffer(A.__webglDepthRenderbuffer)}let O=L.textures;for(let F=0,Y=O.length;F<Y;F++){let re=i.get(O[F]);re.__webglTexture&&(e.deleteTexture(re.__webglTexture),s.memory.textures--),i.remove(O[F])}i.remove(L)}let P=0;function N(){P=0}function D(){let L=P;return L>=n.maxTextures&&console.warn("THREE.WebGLTextures: Trying to use "+L+" texture units while this GPU supports only "+n.maxTextures),P+=1,L}function B(L){let A=[];return A.push(L.wrapS),A.push(L.wrapT),A.push(L.wrapR||0),A.push(L.magFilter),A.push(L.minFilter),A.push(L.anisotropy),A.push(L.internalFormat),A.push(L.format),A.push(L.type),A.push(L.generateMipmaps),A.push(L.premultiplyAlpha),A.push(L.flipY),A.push(L.unpackAlignment),A.push(L.colorSpace),A.join()}function J(L,A){let O=i.get(L);if(L.isVideoTexture&&_e(L),L.isRenderTargetTexture===!1&&L.version>0&&O.__version!==L.version){let F=L.image;if(F===null)console.warn("THREE.WebGLRenderer: Texture marked for update but no image data found.");else if(F.complete===!1)console.warn("THREE.WebGLRenderer: Texture marked for update but image is incomplete");else{G(O,L,A);return}}r.bindTexture(e.TEXTURE_2D,O.__webglTexture,e.TEXTURE0+A)}function Q(L,A){let O=i.get(L);if(L.version>0&&O.__version!==L.version){G(O,L,A);return}r.bindTexture(e.TEXTURE_2D_ARRAY,O.__webglTexture,e.TEXTURE0+A)}function j(L,A){let O=i.get(L);if(L.version>0&&O.__version!==L.version){G(O,L,A);return}r.bindTexture(e.TEXTURE_3D,O.__webglTexture,e.TEXTURE0+A)}function k(L,A){let O=i.get(L);if(L.version>0&&O.__version!==L.version){T(O,L,A);return}r.bindTexture(e.TEXTURE_CUBE_MAP,O.__webglTexture,e.TEXTURE0+A)}let H={[Ni]:e.REPEAT,[Ri]:e.CLAMP_TO_EDGE,[$s]:e.MIRRORED_REPEAT},U={[Kr]:e.NEAREST,[uu]:e.NEAREST_MIPMAP_NEAREST,[$a]:e.NEAREST_MIPMAP_LINEAR,[Zr]:e.LINEAR,[eo]:e.LINEAR_MIPMAP_NEAREST,[mn]:e.LINEAR_MIPMAP_LINEAR},X={[Qg]:e.NEVER,[i0]:e.ALWAYS,[Jg]:e.LESS,[wp]:e.LEQUAL,[$g]:e.EQUAL,[r0]:e.GEQUAL,[e0]:e.GREATER,[t0]:e.NOTEQUAL};function W(L,A){if(A.type===Xi&&t.has("OES_texture_float_linear")===!1&&(A.magFilter===Zr||A.magFilter===eo||A.magFilter===$a||A.magFilter===mn||A.minFilter===Zr||A.minFilter===eo||A.minFilter===$a||A.minFilter===mn)&&console.warn("THREE.WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),e.texParameteri(L,e.TEXTURE_WRAP_S,H[A.wrapS]),e.texParameteri(L,e.TEXTURE_WRAP_T,H[A.wrapT]),(L===e.TEXTURE_3D||L===e.TEXTURE_2D_ARRAY)&&e.texParameteri(L,e.TEXTURE_WRAP_R,H[A.wrapR]),e.texParameteri(L,e.TEXTURE_MAG_FILTER,U[A.magFilter]),e.texParameteri(L,e.TEXTURE_MIN_FILTER,U[A.minFilter]),A.compareFunction&&(e.texParameteri(L,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(L,e.TEXTURE_COMPARE_FUNC,X[A.compareFunction])),t.has("EXT_texture_filter_anisotropic")===!0){if(A.magFilter===Kr||A.minFilter!==$a&&A.minFilter!==mn||A.type===Xi&&t.has("OES_texture_float_linear")===!1)return;if(A.anisotropy>1||i.get(A).__currentAnisotropy){let O=t.get("EXT_texture_filter_anisotropic");e.texParameterf(L,O.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(A.anisotropy,n.getMaxAnisotropy())),i.get(A).__currentAnisotropy=A.anisotropy}}}function $(L,A){let O=!1;L.__webglInit===void 0&&(L.__webglInit=!0,A.addEventListener("dispose",M));let F=A.source,Y=d.get(F);Y===void 0&&(Y={},d.set(F,Y));let re=B(A);if(re!==L.__cacheKey){Y[re]===void 0&&(Y[re]={texture:e.createTexture(),usedTimes:0},s.memory.textures++,O=!0),Y[re].usedTimes++;let ue=Y[L.__cacheKey];ue!==void 0&&(Y[L.__cacheKey].usedTimes--,ue.usedTimes===0&&w(A)),L.__cacheKey=re,L.__webglTexture=Y[re].texture}return O}function G(L,A,O){let F=e.TEXTURE_2D;(A.isDataArrayTexture||A.isCompressedArrayTexture)&&(F=e.TEXTURE_2D_ARRAY),A.isData3DTexture&&(F=e.TEXTURE_3D);let Y=$(L,A),re=A.source;r.bindTexture(F,L.__webglTexture,e.TEXTURE0+O);let ue=i.get(re);if(re.version!==ue.__version||Y===!0){r.activeTexture(e.TEXTURE0+O);let se=_r.getPrimaries(_r.workingColorSpace),pe=A.colorSpace===ia?null:_r.getPrimaries(A.colorSpace),Pe=A.colorSpace===ia||se===pe?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,A.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,A.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,A.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,Pe);let Ce=g(A.image,!1,n.maxTextureSize);Ce=oe(A,Ce);let je=a.convert(A.format,A.colorSpace),st=a.convert(A.type),Pt=x(A.internalFormat,je,st,A.colorSpace,A.isVideoTexture);W(F,A);let ut,ot=A.mipmaps,tt=A.isVideoTexture!==!0,Ht=ue.__version===void 0||Y===!0,fe=re.dataReady,qe=_(A,Ce);if(A.isDepthTexture)Pt=b(A.format===Ra,A.type),Ht&&(tt?r.texStorage2D(e.TEXTURE_2D,1,Pt,Ce.width,Ce.height):r.texImage2D(e.TEXTURE_2D,0,Pt,Ce.width,Ce.height,0,je,st,null));else if(A.isDataTexture)if(ot.length>0){tt&&Ht&&r.texStorage2D(e.TEXTURE_2D,qe,Pt,ot[0].width,ot[0].height);for(let Ue=0,Ie=ot.length;Ue<Ie;Ue++)ut=ot[Ue],tt?fe&&r.texSubImage2D(e.TEXTURE_2D,Ue,0,0,ut.width,ut.height,je,st,ut.data):r.texImage2D(e.TEXTURE_2D,Ue,Pt,ut.width,ut.height,0,je,st,ut.data);A.generateMipmaps=!1}else tt?(Ht&&r.texStorage2D(e.TEXTURE_2D,qe,Pt,Ce.width,Ce.height),fe&&r.texSubImage2D(e.TEXTURE_2D,0,0,0,Ce.width,Ce.height,je,st,Ce.data)):r.texImage2D(e.TEXTURE_2D,0,Pt,Ce.width,Ce.height,0,je,st,Ce.data);else if(A.isCompressedTexture)if(A.isCompressedArrayTexture){tt&&Ht&&r.texStorage3D(e.TEXTURE_2D_ARRAY,qe,Pt,ot[0].width,ot[0].height,Ce.depth);for(let Ue=0,Ie=ot.length;Ue<Ie;Ue++)if(ut=ot[Ue],A.format!==Li)if(je!==null)if(tt){if(fe)if(A.layerUpdates.size>0){let mt=jf(ut.width,ut.height,A.format,A.type);for(let lt of A.layerUpdates){let Ut=ut.data.subarray(lt*mt/ut.data.BYTES_PER_ELEMENT,(lt+1)*mt/ut.data.BYTES_PER_ELEMENT);r.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,Ue,0,0,lt,ut.width,ut.height,1,je,Ut)}A.clearLayerUpdates()}else r.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,Ue,0,0,0,ut.width,ut.height,Ce.depth,je,ut.data)}else r.compressedTexImage3D(e.TEXTURE_2D_ARRAY,Ue,Pt,ut.width,ut.height,Ce.depth,0,ut.data,0,0);else console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else tt?fe&&r.texSubImage3D(e.TEXTURE_2D_ARRAY,Ue,0,0,0,ut.width,ut.height,Ce.depth,je,st,ut.data):r.texImage3D(e.TEXTURE_2D_ARRAY,Ue,Pt,ut.width,ut.height,Ce.depth,0,je,st,ut.data)}else{tt&&Ht&&r.texStorage2D(e.TEXTURE_2D,qe,Pt,ot[0].width,ot[0].height);for(let Ue=0,Ie=ot.length;Ue<Ie;Ue++)ut=ot[Ue],A.format!==Li?je!==null?tt?fe&&r.compressedTexSubImage2D(e.TEXTURE_2D,Ue,0,0,ut.width,ut.height,je,ut.data):r.compressedTexImage2D(e.TEXTURE_2D,Ue,Pt,ut.width,ut.height,0,ut.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):tt?fe&&r.texSubImage2D(e.TEXTURE_2D,Ue,0,0,ut.width,ut.height,je,st,ut.data):r.texImage2D(e.TEXTURE_2D,Ue,Pt,ut.width,ut.height,0,je,st,ut.data)}else if(A.isDataArrayTexture)if(tt){if(Ht&&r.texStorage3D(e.TEXTURE_2D_ARRAY,qe,Pt,Ce.width,Ce.height,Ce.depth),fe)if(A.layerUpdates.size>0){let Ue=jf(Ce.width,Ce.height,A.format,A.type);for(let Ie of A.layerUpdates){let mt=Ce.data.subarray(Ie*Ue/Ce.data.BYTES_PER_ELEMENT,(Ie+1)*Ue/Ce.data.BYTES_PER_ELEMENT);r.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,Ie,Ce.width,Ce.height,1,je,st,mt)}A.clearLayerUpdates()}else r.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,Ce.width,Ce.height,Ce.depth,je,st,Ce.data)}else r.texImage3D(e.TEXTURE_2D_ARRAY,0,Pt,Ce.width,Ce.height,Ce.depth,0,je,st,Ce.data);else if(A.isData3DTexture)tt?(Ht&&r.texStorage3D(e.TEXTURE_3D,qe,Pt,Ce.width,Ce.height,Ce.depth),fe&&r.texSubImage3D(e.TEXTURE_3D,0,0,0,0,Ce.width,Ce.height,Ce.depth,je,st,Ce.data)):r.texImage3D(e.TEXTURE_3D,0,Pt,Ce.width,Ce.height,Ce.depth,0,je,st,Ce.data);else if(A.isFramebufferTexture){if(Ht)if(tt)r.texStorage2D(e.TEXTURE_2D,qe,Pt,Ce.width,Ce.height);else{let Ue=Ce.width,Ie=Ce.height;for(let mt=0;mt<qe;mt++)r.texImage2D(e.TEXTURE_2D,mt,Pt,Ue,Ie,0,je,st,null),Ue>>=1,Ie>>=1}}else if(ot.length>0){if(tt&&Ht){let Ue=ce(ot[0]);r.texStorage2D(e.TEXTURE_2D,qe,Pt,Ue.width,Ue.height)}for(let Ue=0,Ie=ot.length;Ue<Ie;Ue++)ut=ot[Ue],tt?fe&&r.texSubImage2D(e.TEXTURE_2D,Ue,0,0,je,st,ut):r.texImage2D(e.TEXTURE_2D,Ue,Pt,je,st,ut);A.generateMipmaps=!1}else if(tt){if(Ht){let Ue=ce(Ce);r.texStorage2D(e.TEXTURE_2D,qe,Pt,Ue.width,Ue.height)}fe&&r.texSubImage2D(e.TEXTURE_2D,0,0,0,je,st,Ce)}else r.texImage2D(e.TEXTURE_2D,0,Pt,je,st,Ce);p(A)&&m(F),ue.__version=re.version,A.onUpdate&&A.onUpdate(A)}L.__version=A.version}function T(L,A,O){if(A.image.length!==6)return;let F=$(L,A),Y=A.source;r.bindTexture(e.TEXTURE_CUBE_MAP,L.__webglTexture,e.TEXTURE0+O);let re=i.get(Y);if(Y.version!==re.__version||F===!0){r.activeTexture(e.TEXTURE0+O);let ue=_r.getPrimaries(_r.workingColorSpace),se=A.colorSpace===ia?null:_r.getPrimaries(A.colorSpace),pe=A.colorSpace===ia||ue===se?e.NONE:e.BROWSER_DEFAULT_WEBGL;e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,A.flipY),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,A.premultiplyAlpha),e.pixelStorei(e.UNPACK_ALIGNMENT,A.unpackAlignment),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,pe);let Pe=A.isCompressedTexture||A.image[0].isCompressedTexture,Ce=A.image[0]&&A.image[0].isDataTexture,je=[];for(let Ie=0;Ie<6;Ie++)!Pe&&!Ce?je[Ie]=g(A.image[Ie],!0,n.maxCubemapSize):je[Ie]=Ce?A.image[Ie].image:A.image[Ie],je[Ie]=oe(A,je[Ie]);let st=je[0],Pt=a.convert(A.format,A.colorSpace),ut=a.convert(A.type),ot=x(A.internalFormat,Pt,ut,A.colorSpace),tt=A.isVideoTexture!==!0,Ht=re.__version===void 0||F===!0,fe=Y.dataReady,qe=_(A,st);W(e.TEXTURE_CUBE_MAP,A);let Ue;if(Pe){tt&&Ht&&r.texStorage2D(e.TEXTURE_CUBE_MAP,qe,ot,st.width,st.height);for(let Ie=0;Ie<6;Ie++){Ue=je[Ie].mipmaps;for(let mt=0;mt<Ue.length;mt++){let lt=Ue[mt];A.format!==Li?Pt!==null?tt?fe&&r.compressedTexSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+Ie,mt,0,0,lt.width,lt.height,Pt,lt.data):r.compressedTexImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+Ie,mt,ot,lt.width,lt.height,0,lt.data):console.warn("THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):tt?fe&&r.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+Ie,mt,0,0,lt.width,lt.height,Pt,ut,lt.data):r.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+Ie,mt,ot,lt.width,lt.height,0,Pt,ut,lt.data)}}}else{if(Ue=A.mipmaps,tt&&Ht){Ue.length>0&&qe++;let Ie=ce(je[0]);r.texStorage2D(e.TEXTURE_CUBE_MAP,qe,ot,Ie.width,Ie.height)}for(let Ie=0;Ie<6;Ie++)if(Ce){tt?fe&&r.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+Ie,0,0,0,je[Ie].width,je[Ie].height,Pt,ut,je[Ie].data):r.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+Ie,0,ot,je[Ie].width,je[Ie].height,0,Pt,ut,je[Ie].data);for(let mt=0;mt<Ue.length;mt++){let lt=Ue[mt].image[Ie].image;tt?fe&&r.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+Ie,mt+1,0,0,lt.width,lt.height,Pt,ut,lt.data):r.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+Ie,mt+1,ot,lt.width,lt.height,0,Pt,ut,lt.data)}}else{tt?fe&&r.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+Ie,0,0,0,Pt,ut,je[Ie]):r.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+Ie,0,ot,Pt,ut,je[Ie]);for(let mt=0;mt<Ue.length;mt++){let lt=Ue[mt];tt?fe&&r.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+Ie,mt+1,0,0,Pt,ut,lt.image[Ie]):r.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+Ie,mt+1,ot,Pt,ut,lt.image[Ie])}}}p(A)&&m(e.TEXTURE_CUBE_MAP),re.__version=Y.version,A.onUpdate&&A.onUpdate(A)}L.__version=A.version}function I(L,A,O,F,Y,re){let ue=a.convert(O.format,O.colorSpace),se=a.convert(O.type),pe=x(O.internalFormat,ue,se,O.colorSpace),Pe=i.get(A),Ce=i.get(O);if(Ce.__renderTarget=A,!Pe.__hasExternalTextures){let je=Math.max(1,A.width>>re),st=Math.max(1,A.height>>re);Y===e.TEXTURE_3D||Y===e.TEXTURE_2D_ARRAY?r.texImage3D(Y,re,pe,je,st,A.depth,0,ue,se,null):r.texImage2D(Y,re,pe,je,st,0,ue,se,null)}r.bindFramebuffer(e.FRAMEBUFFER,L),ne(A)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,F,Y,Ce.__webglTexture,0,He(A)):(Y===e.TEXTURE_2D||Y>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&Y<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,F,Y,Ce.__webglTexture,re),r.bindFramebuffer(e.FRAMEBUFFER,null)}function V(L,A,O){if(e.bindRenderbuffer(e.RENDERBUFFER,L),A.depthBuffer){let F=A.depthTexture,Y=F&&F.isDepthTexture?F.type:null,re=b(A.stencilBuffer,Y),ue=A.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,se=He(A);ne(A)?o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,se,re,A.width,A.height):O?e.renderbufferStorageMultisample(e.RENDERBUFFER,se,re,A.width,A.height):e.renderbufferStorage(e.RENDERBUFFER,re,A.width,A.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,ue,e.RENDERBUFFER,L)}else{let F=A.textures;for(let Y=0;Y<F.length;Y++){let re=F[Y],ue=a.convert(re.format,re.colorSpace),se=a.convert(re.type),pe=x(re.internalFormat,ue,se,re.colorSpace),Pe=He(A);O&&ne(A)===!1?e.renderbufferStorageMultisample(e.RENDERBUFFER,Pe,pe,A.width,A.height):ne(A)?o.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,Pe,pe,A.width,A.height):e.renderbufferStorage(e.RENDERBUFFER,pe,A.width,A.height)}}e.bindRenderbuffer(e.RENDERBUFFER,null)}function K(L,A){if(A&&A.isWebGLCubeRenderTarget)throw new Error("Depth Texture with cube render targets is not supported");if(r.bindFramebuffer(e.FRAMEBUFFER,L),!(A.depthTexture&&A.depthTexture.isDepthTexture))throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture");let O=i.get(A.depthTexture);O.__renderTarget=A,(!O.__webglTexture||A.depthTexture.image.width!==A.width||A.depthTexture.image.height!==A.height)&&(A.depthTexture.image.width=A.width,A.depthTexture.image.height=A.height,A.depthTexture.needsUpdate=!0),J(A.depthTexture,0);let F=O.__webglTexture,Y=He(A);if(A.depthTexture.format===es)ne(A)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,F,0,Y):e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_ATTACHMENT,e.TEXTURE_2D,F,0);else if(A.depthTexture.format===Ra)ne(A)?o.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.TEXTURE_2D,F,0,Y):e.framebufferTexture2D(e.FRAMEBUFFER,e.DEPTH_STENCIL_ATTACHMENT,e.TEXTURE_2D,F,0);else throw new Error("Unknown depthTexture format")}function ie(L){let A=i.get(L),O=L.isWebGLCubeRenderTarget===!0;if(A.__boundDepthTexture!==L.depthTexture){let F=L.depthTexture;if(A.__depthDisposeCallback&&A.__depthDisposeCallback(),F){let Y=()=>{delete A.__boundDepthTexture,delete A.__depthDisposeCallback,F.removeEventListener("dispose",Y)};F.addEventListener("dispose",Y),A.__depthDisposeCallback=Y}A.__boundDepthTexture=F}if(L.depthTexture&&!A.__autoAllocateDepthBuffer){if(O)throw new Error("target.depthTexture not supported in Cube render targets");K(A.__webglFramebuffer,L)}else if(O){A.__webglDepthbuffer=[];for(let F=0;F<6;F++)if(r.bindFramebuffer(e.FRAMEBUFFER,A.__webglFramebuffer[F]),A.__webglDepthbuffer[F]===void 0)A.__webglDepthbuffer[F]=e.createRenderbuffer(),V(A.__webglDepthbuffer[F],L,!1);else{let Y=L.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,re=A.__webglDepthbuffer[F];e.bindRenderbuffer(e.RENDERBUFFER,re),e.framebufferRenderbuffer(e.FRAMEBUFFER,Y,e.RENDERBUFFER,re)}}else if(r.bindFramebuffer(e.FRAMEBUFFER,A.__webglFramebuffer),A.__webglDepthbuffer===void 0)A.__webglDepthbuffer=e.createRenderbuffer(),V(A.__webglDepthbuffer,L,!1);else{let F=L.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,Y=A.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,Y),e.framebufferRenderbuffer(e.FRAMEBUFFER,F,e.RENDERBUFFER,Y)}r.bindFramebuffer(e.FRAMEBUFFER,null)}function le(L,A,O){let F=i.get(L);A!==void 0&&I(F.__webglFramebuffer,L,L.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0),O!==void 0&&ie(L)}function ae(L){let A=L.texture,O=i.get(L),F=i.get(A);L.addEventListener("dispose",C);let Y=L.textures,re=L.isWebGLCubeRenderTarget===!0,ue=Y.length>1;if(ue||(F.__webglTexture===void 0&&(F.__webglTexture=e.createTexture()),F.__version=A.version,s.memory.textures++),re){O.__webglFramebuffer=[];for(let se=0;se<6;se++)if(A.mipmaps&&A.mipmaps.length>0){O.__webglFramebuffer[se]=[];for(let pe=0;pe<A.mipmaps.length;pe++)O.__webglFramebuffer[se][pe]=e.createFramebuffer()}else O.__webglFramebuffer[se]=e.createFramebuffer()}else{if(A.mipmaps&&A.mipmaps.length>0){O.__webglFramebuffer=[];for(let se=0;se<A.mipmaps.length;se++)O.__webglFramebuffer[se]=e.createFramebuffer()}else O.__webglFramebuffer=e.createFramebuffer();if(ue)for(let se=0,pe=Y.length;se<pe;se++){let Pe=i.get(Y[se]);Pe.__webglTexture===void 0&&(Pe.__webglTexture=e.createTexture(),s.memory.textures++)}if(L.samples>0&&ne(L)===!1){O.__webglMultisampledFramebuffer=e.createFramebuffer(),O.__webglColorRenderbuffer=[],r.bindFramebuffer(e.FRAMEBUFFER,O.__webglMultisampledFramebuffer);for(let se=0;se<Y.length;se++){let pe=Y[se];O.__webglColorRenderbuffer[se]=e.createRenderbuffer(),e.bindRenderbuffer(e.RENDERBUFFER,O.__webglColorRenderbuffer[se]);let Pe=a.convert(pe.format,pe.colorSpace),Ce=a.convert(pe.type),je=x(pe.internalFormat,Pe,Ce,pe.colorSpace,L.isXRRenderTarget===!0),st=He(L);e.renderbufferStorageMultisample(e.RENDERBUFFER,st,je,L.width,L.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+se,e.RENDERBUFFER,O.__webglColorRenderbuffer[se])}e.bindRenderbuffer(e.RENDERBUFFER,null),L.depthBuffer&&(O.__webglDepthRenderbuffer=e.createRenderbuffer(),V(O.__webglDepthRenderbuffer,L,!0)),r.bindFramebuffer(e.FRAMEBUFFER,null)}}if(re){r.bindTexture(e.TEXTURE_CUBE_MAP,F.__webglTexture),W(e.TEXTURE_CUBE_MAP,A);for(let se=0;se<6;se++)if(A.mipmaps&&A.mipmaps.length>0)for(let pe=0;pe<A.mipmaps.length;pe++)I(O.__webglFramebuffer[se][pe],L,A,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+se,pe);else I(O.__webglFramebuffer[se],L,A,e.COLOR_ATTACHMENT0,e.TEXTURE_CUBE_MAP_POSITIVE_X+se,0);p(A)&&m(e.TEXTURE_CUBE_MAP),r.unbindTexture()}else if(ue){for(let se=0,pe=Y.length;se<pe;se++){let Pe=Y[se],Ce=i.get(Pe);r.bindTexture(e.TEXTURE_2D,Ce.__webglTexture),W(e.TEXTURE_2D,Pe),I(O.__webglFramebuffer,L,Pe,e.COLOR_ATTACHMENT0+se,e.TEXTURE_2D,0),p(Pe)&&m(e.TEXTURE_2D)}r.unbindTexture()}else{let se=e.TEXTURE_2D;if((L.isWebGL3DRenderTarget||L.isWebGLArrayRenderTarget)&&(se=L.isWebGL3DRenderTarget?e.TEXTURE_3D:e.TEXTURE_2D_ARRAY),r.bindTexture(se,F.__webglTexture),W(se,A),A.mipmaps&&A.mipmaps.length>0)for(let pe=0;pe<A.mipmaps.length;pe++)I(O.__webglFramebuffer[pe],L,A,e.COLOR_ATTACHMENT0,se,pe);else I(O.__webglFramebuffer,L,A,e.COLOR_ATTACHMENT0,se,0);p(A)&&m(se),r.unbindTexture()}L.depthBuffer&&ie(L)}function de(L){let A=L.textures;for(let O=0,F=A.length;O<F;O++){let Y=A[O];if(p(Y)){let re=v(L),ue=i.get(Y).__webglTexture;r.bindTexture(re,ue),m(re),r.unbindTexture()}}}let z=[],me=[];function we(L){if(L.samples>0){if(ne(L)===!1){let A=L.textures,O=L.width,F=L.height,Y=e.COLOR_BUFFER_BIT,re=L.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,ue=i.get(L),se=A.length>1;if(se)for(let pe=0;pe<A.length;pe++)r.bindFramebuffer(e.FRAMEBUFFER,ue.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+pe,e.RENDERBUFFER,null),r.bindFramebuffer(e.FRAMEBUFFER,ue.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+pe,e.TEXTURE_2D,null,0);r.bindFramebuffer(e.READ_FRAMEBUFFER,ue.__webglMultisampledFramebuffer),r.bindFramebuffer(e.DRAW_FRAMEBUFFER,ue.__webglFramebuffer);for(let pe=0;pe<A.length;pe++){if(L.resolveDepthBuffer&&(L.depthBuffer&&(Y|=e.DEPTH_BUFFER_BIT),L.stencilBuffer&&L.resolveStencilBuffer&&(Y|=e.STENCIL_BUFFER_BIT)),se){e.framebufferRenderbuffer(e.READ_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.RENDERBUFFER,ue.__webglColorRenderbuffer[pe]);let Pe=i.get(A[pe]).__webglTexture;e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,Pe,0)}e.blitFramebuffer(0,0,O,F,0,0,O,F,Y,e.NEAREST),l===!0&&(z.length=0,me.length=0,z.push(e.COLOR_ATTACHMENT0+pe),L.depthBuffer&&L.resolveDepthBuffer===!1&&(z.push(re),me.push(re),e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,me)),e.invalidateFramebuffer(e.READ_FRAMEBUFFER,z))}if(r.bindFramebuffer(e.READ_FRAMEBUFFER,null),r.bindFramebuffer(e.DRAW_FRAMEBUFFER,null),se)for(let pe=0;pe<A.length;pe++){r.bindFramebuffer(e.FRAMEBUFFER,ue.__webglMultisampledFramebuffer),e.framebufferRenderbuffer(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0+pe,e.RENDERBUFFER,ue.__webglColorRenderbuffer[pe]);let Pe=i.get(A[pe]).__webglTexture;r.bindFramebuffer(e.FRAMEBUFFER,ue.__webglFramebuffer),e.framebufferTexture2D(e.DRAW_FRAMEBUFFER,e.COLOR_ATTACHMENT0+pe,e.TEXTURE_2D,Pe,0)}r.bindFramebuffer(e.DRAW_FRAMEBUFFER,ue.__webglMultisampledFramebuffer)}else if(L.depthBuffer&&L.resolveDepthBuffer===!1&&l){let A=L.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;e.invalidateFramebuffer(e.DRAW_FRAMEBUFFER,[A])}}}function He(L){return Math.min(n.maxSamples,L.samples)}function ne(L){let A=i.get(L);return L.samples>0&&t.has("WEBGL_multisampled_render_to_texture")===!0&&A.__useRenderToTexture!==!1}function _e(L){let A=s.render.frame;u.get(L)!==A&&(u.set(L,A),L.update())}function oe(L,A){let O=L.colorSpace,F=L.format,Y=L.type;return L.isCompressedTexture===!0||L.isVideoTexture===!0||O!==Oi&&O!==ia&&(_r.getTransfer(O)===kr?(F!==Li||Y!==gn)&&console.warn("THREE.WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):console.error("THREE.WebGLTextures: Unsupported texture color space:",O)),A}function ce(L){return typeof HTMLImageElement<"u"&&L instanceof HTMLImageElement?(c.width=L.naturalWidth||L.width,c.height=L.naturalHeight||L.height):typeof VideoFrame<"u"&&L instanceof VideoFrame?(c.width=L.displayWidth,c.height=L.displayHeight):(c.width=L.width,c.height=L.height),c}this.allocateTextureUnit=D,this.resetTextureUnits=N,this.setTexture2D=J,this.setTexture2DArray=Q,this.setTexture3D=j,this.setTextureCube=k,this.rebindTextures=le,this.setupRenderTarget=ae,this.updateRenderTargetMipmap=de,this.updateMultisampleRenderTarget=we,this.setupDepthRenderbuffer=ie,this.setupFrameBufferTexture=I,this.useMultisampledRTT=ne}function Wv(e,t){function r(i,n=ia){let a,s=_r.getTransfer(n);if(i===gn)return e.UNSIGNED_BYTE;if(i===du)return e.UNSIGNED_SHORT_4_4_4_4;if(i===pu)return e.UNSIGNED_SHORT_5_5_5_1;if(i===dp)return e.UNSIGNED_INT_5_9_9_9_REV;if(i===up)return e.BYTE;if(i===hp)return e.SHORT;if(i===to)return e.UNSIGNED_SHORT;if(i===hu)return e.INT;if(i===ra)return e.UNSIGNED_INT;if(i===Xi)return e.FLOAT;if(i===yn)return e.HALF_FLOAT;if(i===pp)return e.ALPHA;if(i===fp)return e.RGB;if(i===Li)return e.RGBA;if(i===mp)return e.LUMINANCE;if(i===gp)return e.LUMINANCE_ALPHA;if(i===es)return e.DEPTH_COMPONENT;if(i===Ra)return e.DEPTH_STENCIL;if(i===fu)return e.RED;if(i===bl)return e.RED_INTEGER;if(i===yp)return e.RG;if(i===mu)return e.RG_INTEGER;if(i===gu)return e.RGBA_INTEGER;if(i===_l||i===wl||i===El||i===Ml)if(s===kr)if(a=t.get("WEBGL_compressed_texture_s3tc_srgb"),a!==null){if(i===_l)return a.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===wl)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===El)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===Ml)return a.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(a=t.get("WEBGL_compressed_texture_s3tc"),a!==null){if(i===_l)return a.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===wl)return a.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===El)return a.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===Ml)return a.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===yu||i===vu||i===xu||i===bu)if(a=t.get("WEBGL_compressed_texture_pvrtc"),a!==null){if(i===yu)return a.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===vu)return a.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===xu)return a.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===bu)return a.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===_u||i===wu||i===Eu)if(a=t.get("WEBGL_compressed_texture_etc"),a!==null){if(i===_u||i===wu)return s===kr?a.COMPRESSED_SRGB8_ETC2:a.COMPRESSED_RGB8_ETC2;if(i===Eu)return s===kr?a.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:a.COMPRESSED_RGBA8_ETC2_EAC}else return null;if(i===Mu||i===Su||i===Tu||i===Au||i===Cu||i===Ru||i===Pu||i===Iu||i===Nu||i===Lu||i===Ou||i===Du||i===ku||i===Uu)if(a=t.get("WEBGL_compressed_texture_astc"),a!==null){if(i===Mu)return s===kr?a.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:a.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===Su)return s===kr?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:a.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===Tu)return s===kr?a.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:a.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===Au)return s===kr?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:a.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===Cu)return s===kr?a.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:a.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===Ru)return s===kr?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:a.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===Pu)return s===kr?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:a.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===Iu)return s===kr?a.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:a.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===Nu)return s===kr?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:a.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===Lu)return s===kr?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:a.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===Ou)return s===kr?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:a.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===Du)return s===kr?a.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:a.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===ku)return s===kr?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:a.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===Uu)return s===kr?a.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:a.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===Sl||i===Fu||i===Bu)if(a=t.get("EXT_texture_compression_bptc"),a!==null){if(i===Sl)return s===kr?a.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:a.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===Fu)return a.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===Bu)return a.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===vp||i===zu||i===Gu||i===Vu)if(a=t.get("EXT_texture_compression_rgtc"),a!==null){if(i===Sl)return a.COMPRESSED_RED_RGTC1_EXT;if(i===zu)return a.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===Gu)return a.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===Vu)return a.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===Ca?e.UNSIGNED_INT_24_8:e[i]!==void 0?e[i]:null}return{convert:r}}var KC={type:"move"},em=class{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new jr,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 jr,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new ee,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new ee),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new jr,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new ee,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new ee),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,a=null,s=this._targetRay,o=this._grip,l=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(l&&e.hand){a=!0;for(let y of e.hand.values()){let g=t.getJointPose(y,r),p=this._getHandJoint(l,y);g!==null&&(p.matrix.fromArray(g.transform.matrix),p.matrix.decompose(p.position,p.rotation,p.scale),p.matrixWorldNeedsUpdate=!0,p.jointRadius=g.radius),p.visible=g!==null}let c=l.joints["index-finger-tip"],u=l.joints["thumb-tip"],h=c.position.distanceTo(u.position),d=.02,f=.005;l.inputState.pinching&&h>d+f?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&h<=d-f&&(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));s!==null&&(i=t.getPose(e.targetRaySpace,r),i===null&&n!==null&&(i=n),i!==null&&(s.matrix.fromArray(i.transform.matrix),s.matrix.decompose(s.position,s.rotation,s.scale),s.matrixWorldNeedsUpdate=!0,i.linearVelocity?(s.hasLinearVelocity=!0,s.linearVelocity.copy(i.linearVelocity)):s.hasLinearVelocity=!1,i.angularVelocity?(s.hasAngularVelocity=!0,s.angularVelocity.copy(i.angularVelocity)):s.hasAngularVelocity=!1,this.dispatchEvent(KC)))}return s!==null&&(s.visible=i!==null),o!==null&&(o.visible=n!==null),l!==null&&(l.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let r=new jr;r.matrixAutoUpdate=!1,r.visible=!1,e.joints[t.jointName]=r,e.add(r)}return e.joints[t.jointName]}},ZC=`
void main() {
gl_Position = vec4( position, 1.0 );
}`,QC=`
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;
}
}`,JC=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 ei,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 oi({vertexShader:ZC,fragmentShader:QC,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new hr(new Io(20,20),r)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},$C=class extends Wn{constructor(e,t){super();let r=this,i=null,n=1,a=null,s="local-floor",o=1,l=null,c=null,u=null,h=null,d=null,f=null,y=new JC,g=t.getContextAttributes(),p=null,m=null,v=[],x=[],b=new Xe,_=null,M=new li;M.viewport=new Nr;let C=new li;C.viewport=new Nr;let S=[M,C],w=new Qy,E=null,P=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function($){let G=v[$];return G===void 0&&(G=new em,v[$]=G),G.getTargetRaySpace()},this.getControllerGrip=function($){let G=v[$];return G===void 0&&(G=new em,v[$]=G),G.getGripSpace()},this.getHand=function($){let G=v[$];return G===void 0&&(G=new em,v[$]=G),G.getHandSpace()};function N($){let G=x.indexOf($.inputSource);if(G===-1)return;let T=v[G];T!==void 0&&(T.update($.inputSource,$.frame,l||a),T.dispatchEvent({type:$.type,data:$.inputSource}))}function D(){i.removeEventListener("select",N),i.removeEventListener("selectstart",N),i.removeEventListener("selectend",N),i.removeEventListener("squeeze",N),i.removeEventListener("squeezestart",N),i.removeEventListener("squeezeend",N),i.removeEventListener("end",D),i.removeEventListener("inputsourceschange",B);for(let $=0;$<v.length;$++){let G=x[$];G!==null&&(x[$]=null,v[$].disconnect(G))}E=null,P=null,y.reset(),e.setRenderTarget(p),d=null,h=null,u=null,i=null,m=null,W.stop(),r.isPresenting=!1,e.setPixelRatio(_),e.setSize(b.width,b.height,!1),r.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function($){n=$,r.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function($){s=$,r.isPresenting===!0&&console.warn("THREE.WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return l||a},this.setReferenceSpace=function($){l=$},this.getBaseLayer=function(){return h!==null?h:d},this.getBinding=function(){return u},this.getFrame=function(){return f},this.getSession=function(){return i},this.setSession=async function($){if(i=$,i!==null){if(p=e.getRenderTarget(),i.addEventListener("select",N),i.addEventListener("selectstart",N),i.addEventListener("selectend",N),i.addEventListener("squeeze",N),i.addEventListener("squeezestart",N),i.addEventListener("squeezeend",N),i.addEventListener("end",D),i.addEventListener("inputsourceschange",B),g.xrCompatible!==!0&&await t.makeXRCompatible(),_=e.getPixelRatio(),e.getSize(b),i.renderState.layers===void 0){let G={antialias:g.antialias,alpha:!0,depth:g.depth,stencil:g.stencil,framebufferScaleFactor:n};d=new XRWebGLLayer(i,t,G),i.updateRenderState({baseLayer:d}),e.setPixelRatio(1),e.setSize(d.framebufferWidth,d.framebufferHeight,!1),m=new Pi(d.framebufferWidth,d.framebufferHeight,{format:Li,type:gn,colorSpace:e.outputColorSpace,stencilBuffer:g.stencil})}else{let G=null,T=null,I=null;g.depth&&(I=g.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,G=g.stencil?Ra:es,T=g.stencil?Ca:ra);let V={colorFormat:t.RGBA8,depthFormat:I,scaleFactor:n};u=new XRWebGLBinding(i,t),h=u.createProjectionLayer(V),i.updateRenderState({layers:[h]}),e.setPixelRatio(1),e.setSize(h.textureWidth,h.textureHeight,!1),m=new Pi(h.textureWidth,h.textureHeight,{format:Li,type:gn,depthTexture:new Oh(h.textureWidth,h.textureHeight,T,void 0,void 0,void 0,void 0,void 0,void 0,G),stencilBuffer:g.stencil,colorSpace:e.outputColorSpace,samples:g.antialias?4:0,resolveDepthBuffer:h.ignoreDepthValues===!1})}m.isXRRenderTarget=!0,this.setFoveation(o),l=null,a=await i.requestReferenceSpace(s),W.setContext(i),W.start(),r.isPresenting=!0,r.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(i!==null)return i.environmentBlendMode},this.getDepthTexture=function(){return y.getDepthTexture()};function B($){for(let G=0;G<$.removed.length;G++){let T=$.removed[G],I=x.indexOf(T);I>=0&&(x[I]=null,v[I].disconnect(T))}for(let G=0;G<$.added.length;G++){let T=$.added[G],I=x.indexOf(T);if(I===-1){for(let K=0;K<v.length;K++)if(K>=x.length){x.push(T),I=K;break}else if(x[K]===null){x[K]=T,I=K;break}if(I===-1)break}let V=v[I];V&&V.connect(T)}}let J=new ee,Q=new ee;function j($,G,T){J.setFromMatrixPosition(G.matrixWorld),Q.setFromMatrixPosition(T.matrixWorld);let I=J.distanceTo(Q),V=G.projectionMatrix.elements,K=T.projectionMatrix.elements,ie=V[14]/(V[10]-1),le=V[14]/(V[10]+1),ae=(V[9]+1)/V[5],de=(V[9]-1)/V[5],z=(V[8]-1)/V[0],me=(K[8]+1)/K[0],we=ie*z,He=ie*me,ne=I/(-z+me),_e=ne*-z;if(G.matrixWorld.decompose($.position,$.quaternion,$.scale),$.translateX(_e),$.translateZ(ne),$.matrixWorld.compose($.position,$.quaternion,$.scale),$.matrixWorldInverse.copy($.matrixWorld).invert(),V[10]===-1)$.projectionMatrix.copy(G.projectionMatrix),$.projectionMatrixInverse.copy(G.projectionMatrixInverse);else{let oe=ie+ne,ce=le+ne,L=we-_e,A=He+(I-_e),O=ae*le/ce*oe,F=de*le/ce*oe;$.projectionMatrix.makePerspective(L,A,O,F,oe,ce),$.projectionMatrixInverse.copy($.projectionMatrix).invert()}}function k($,G){G===null?$.matrixWorld.copy($.matrix):$.matrixWorld.multiplyMatrices(G.matrixWorld,$.matrix),$.matrixWorldInverse.copy($.matrixWorld).invert()}this.updateCamera=function($){if(i===null)return;let G=$.near,T=$.far;y.texture!==null&&(y.depthNear>0&&(G=y.depthNear),y.depthFar>0&&(T=y.depthFar)),w.near=C.near=M.near=G,w.far=C.far=M.far=T,(E!==w.near||P!==w.far)&&(i.updateRenderState({depthNear:w.near,depthFar:w.far}),E=w.near,P=w.far),M.layers.mask=$.layers.mask|2,C.layers.mask=$.layers.mask|4,w.layers.mask=M.layers.mask|C.layers.mask;let I=$.parent,V=w.cameras;k(w,I);for(let K=0;K<V.length;K++)k(V[K],I);V.length===2?j(w,M,C):w.projectionMatrix.copy(M.projectionMatrix),H($,w,I)};function H($,G,T){T===null?$.matrix.copy(G.matrixWorld):($.matrix.copy(T.matrixWorld),$.matrix.invert(),$.matrix.multiply(G.matrixWorld)),$.matrix.decompose($.position,$.quaternion,$.scale),$.updateMatrixWorld(!0),$.projectionMatrix.copy(G.projectionMatrix),$.projectionMatrixInverse.copy(G.projectionMatrixInverse),$.isPerspectiveCamera&&($.fov=no*2*Math.atan(1/$.projectionMatrix.elements[5]),$.zoom=1)}this.getCamera=function(){return w},this.getFoveation=function(){if(!(h===null&&d===null))return o},this.setFoveation=function($){o=$,h!==null&&(h.fixedFoveation=$),d!==null&&d.fixedFoveation!==void 0&&(d.fixedFoveation=$)},this.hasDepthSensing=function(){return y.texture!==null},this.getDepthSensingMesh=function(){return y.getMesh(w)};let U=null;function X($,G){if(c=G.getViewerPose(l||a),f=G,c!==null){let T=c.views;d!==null&&(e.setRenderTargetFramebuffer(m,d.framebuffer),e.setRenderTarget(m));let I=!1;T.length!==w.cameras.length&&(w.cameras.length=0,I=!0);for(let K=0;K<T.length;K++){let ie=T[K],le=null;if(d!==null)le=d.getViewport(ie);else{let de=u.getViewSubImage(h,ie);le=de.viewport,K===0&&(e.setRenderTargetTextures(m,de.colorTexture,h.ignoreDepthValues?void 0:de.depthStencilTexture),e.setRenderTarget(m))}let ae=S[K];ae===void 0&&(ae=new li,ae.layers.enable(K),ae.viewport=new Nr,S[K]=ae),ae.matrix.fromArray(ie.transform.matrix),ae.matrix.decompose(ae.position,ae.quaternion,ae.scale),ae.projectionMatrix.fromArray(ie.projectionMatrix),ae.projectionMatrixInverse.copy(ae.projectionMatrix).invert(),ae.viewport.set(le.x,le.y,le.width,le.height),K===0&&(w.matrix.copy(ae.matrix),w.matrix.decompose(w.position,w.quaternion,w.scale)),I===!0&&w.cameras.push(ae)}let V=i.enabledFeatures;if(V&&V.includes("depth-sensing")){let K=u.getDepthInformation(T[0]);K&&K.isValid&&K.texture&&y.init(e,K,i.renderState)}}for(let T=0;T<v.length;T++){let I=x[T],V=v[T];I!==null&&V!==void 0&&V.update(I,G,l||a)}U&&U($,G),G.detectedPlanes&&r.dispatchEvent({type:"planesdetected",data:G}),f=null}let W=new gv;W.setAnimationLoop(X),this.setAnimationLoop=function($){U=$},this.dispose=function(){}}},Ps=new Nn,eR=new Jt;function tR(e,t){function r(p,m){p.matrixAutoUpdate===!0&&p.updateMatrix(),m.value.copy(p.matrix)}function i(p,m){m.color.getRGB(p.fogColor.value,T0(e)),m.isFog?(p.fogNear.value=m.near,p.fogFar.value=m.far):m.isFogExp2&&(p.fogDensity.value=m.density)}function n(p,m,v,x,b){m.isMeshBasicMaterial||m.isMeshLambertMaterial?a(p,m):m.isMeshToonMaterial?(a(p,m),h(p,m)):m.isMeshPhongMaterial?(a(p,m),u(p,m)):m.isMeshStandardMaterial?(a(p,m),d(p,m),m.isMeshPhysicalMaterial&&f(p,m,b)):m.isMeshMatcapMaterial?(a(p,m),y(p,m)):m.isMeshDepthMaterial?a(p,m):m.isMeshDistanceMaterial?(a(p,m),g(p,m)):m.isMeshNormalMaterial?a(p,m):m.isLineBasicMaterial?(s(p,m),m.isLineDashedMaterial&&o(p,m)):m.isPointsMaterial?l(p,m,v,x):m.isSpriteMaterial?c(p,m):m.isShadowMaterial?(p.color.value.copy(m.color),p.opacity.value=m.opacity):m.isShaderMaterial&&(m.uniformsNeedUpdate=!1)}function a(p,m){p.opacity.value=m.opacity,m.color&&p.diffuse.value.copy(m.color),m.emissive&&p.emissive.value.copy(m.emissive).multiplyScalar(m.emissiveIntensity),m.map&&(p.map.value=m.map,r(m.map,p.mapTransform)),m.alphaMap&&(p.alphaMap.value=m.alphaMap,r(m.alphaMap,p.alphaMapTransform)),m.bumpMap&&(p.bumpMap.value=m.bumpMap,r(m.bumpMap,p.bumpMapTransform),p.bumpScale.value=m.bumpScale,m.side===_t&&(p.bumpScale.value*=-1)),m.normalMap&&(p.normalMap.value=m.normalMap,r(m.normalMap,p.normalMapTransform),p.normalScale.value.copy(m.normalScale),m.side===_t&&p.normalScale.value.negate()),m.displacementMap&&(p.displacementMap.value=m.displacementMap,r(m.displacementMap,p.displacementMapTransform),p.displacementScale.value=m.displacementScale,p.displacementBias.value=m.displacementBias),m.emissiveMap&&(p.emissiveMap.value=m.emissiveMap,r(m.emissiveMap,p.emissiveMapTransform)),m.specularMap&&(p.specularMap.value=m.specularMap,r(m.specularMap,p.specularMapTransform)),m.alphaTest>0&&(p.alphaTest.value=m.alphaTest);let v=t.get(m),x=v.envMap,b=v.envMapRotation;x&&(p.envMap.value=x,Ps.copy(b),Ps.x*=-1,Ps.y*=-1,Ps.z*=-1,x.isCubeTexture&&x.isRenderTargetTexture===!1&&(Ps.y*=-1,Ps.z*=-1),p.envMapRotation.value.setFromMatrix4(eR.makeRotationFromEuler(Ps)),p.flipEnvMap.value=x.isCubeTexture&&x.isRenderTargetTexture===!1?-1:1,p.reflectivity.value=m.reflectivity,p.ior.value=m.ior,p.refractionRatio.value=m.refractionRatio),m.lightMap&&(p.lightMap.value=m.lightMap,p.lightMapIntensity.value=m.lightMapIntensity,r(m.lightMap,p.lightMapTransform)),m.aoMap&&(p.aoMap.value=m.aoMap,p.aoMapIntensity.value=m.aoMapIntensity,r(m.aoMap,p.aoMapTransform))}function s(p,m){p.diffuse.value.copy(m.color),p.opacity.value=m.opacity,m.map&&(p.map.value=m.map,r(m.map,p.mapTransform))}function o(p,m){p.dashSize.value=m.dashSize,p.totalSize.value=m.dashSize+m.gapSize,p.scale.value=m.scale}function l(p,m,v,x){p.diffuse.value.copy(m.color),p.opacity.value=m.opacity,p.size.value=m.size*v,p.scale.value=x*.5,m.map&&(p.map.value=m.map,r(m.map,p.uvTransform)),m.alphaMap&&(p.alphaMap.value=m.alphaMap,r(m.alphaMap,p.alphaMapTransform)),m.alphaTest>0&&(p.alphaTest.value=m.alphaTest)}function c(p,m){p.diffuse.value.copy(m.color),p.opacity.value=m.opacity,p.rotation.value=m.rotation,m.map&&(p.map.value=m.map,r(m.map,p.mapTransform)),m.alphaMap&&(p.alphaMap.value=m.alphaMap,r(m.alphaMap,p.alphaMapTransform)),m.alphaTest>0&&(p.alphaTest.value=m.alphaTest)}function u(p,m){p.specular.value.copy(m.specular),p.shininess.value=Math.max(m.shininess,1e-4)}function h(p,m){m.gradientMap&&(p.gradientMap.value=m.gradientMap)}function d(p,m){p.metalness.value=m.metalness,m.metalnessMap&&(p.metalnessMap.value=m.metalnessMap,r(m.metalnessMap,p.metalnessMapTransform)),p.roughness.value=m.roughness,m.roughnessMap&&(p.roughnessMap.value=m.roughnessMap,r(m.roughnessMap,p.roughnessMapTransform)),m.envMap&&(p.envMapIntensity.value=m.envMapIntensity)}function f(p,m,v){p.ior.value=m.ior,m.sheen>0&&(p.sheenColor.value.copy(m.sheenColor).multiplyScalar(m.sheen),p.sheenRoughness.value=m.sheenRoughness,m.sheenColorMap&&(p.sheenColorMap.value=m.sheenColorMap,r(m.sheenColorMap,p.sheenColorMapTransform)),m.sheenRoughnessMap&&(p.sheenRoughnessMap.value=m.sheenRoughnessMap,r(m.sheenRoughnessMap,p.sheenRoughnessMapTransform))),m.clearcoat>0&&(p.clearcoat.value=m.clearcoat,p.clearcoatRoughness.value=m.clearcoatRoughness,m.clearcoatMap&&(p.clearcoatMap.value=m.clearcoatMap,r(m.clearcoatMap,p.clearcoatMapTransform)),m.clearcoatRoughnessMap&&(p.clearcoatRoughnessMap.value=m.clearcoatRoughnessMap,r(m.clearcoatRoughnessMap,p.clearcoatRoughnessMapTransform)),m.clearcoatNormalMap&&(p.clearcoatNormalMap.value=m.clearcoatNormalMap,r(m.clearcoatNormalMap,p.clearcoatNormalMapTransform),p.clearcoatNormalScale.value.copy(m.clearcoatNormalScale),m.side===_t&&p.clearcoatNormalScale.value.negate())),m.dispersion>0&&(p.dispersion.value=m.dispersion),m.iridescence>0&&(p.iridescence.value=m.iridescence,p.iridescenceIOR.value=m.iridescenceIOR,p.iridescenceThicknessMinimum.value=m.iridescenceThicknessRange[0],p.iridescenceThicknessMaximum.value=m.iridescenceThicknessRange[1],m.iridescenceMap&&(p.iridescenceMap.value=m.iridescenceMap,r(m.iridescenceMap,p.iridescenceMapTransform)),m.iridescenceThicknessMap&&(p.iridescenceThicknessMap.value=m.iridescenceThicknessMap,r(m.iridescenceThicknessMap,p.iridescenceThicknessMapTransform))),m.transmission>0&&(p.transmission.value=m.transmission,p.transmissionSamplerMap.value=v.texture,p.transmissionSamplerSize.value.set(v.width,v.height),m.transmissionMap&&(p.transmissionMap.value=m.transmissionMap,r(m.transmissionMap,p.transmissionMapTransform)),p.thickness.value=m.thickness,m.thicknessMap&&(p.thicknessMap.value=m.thicknessMap,r(m.thicknessMap,p.thicknessMapTransform)),p.attenuationDistance.value=m.attenuationDistance,p.attenuationColor.value.copy(m.attenuationColor)),m.anisotropy>0&&(p.anisotropyVector.value.set(m.anisotropy*Math.cos(m.anisotropyRotation),m.anisotropy*Math.sin(m.anisotropyRotation)),m.anisotropyMap&&(p.anisotropyMap.value=m.anisotropyMap,r(m.anisotropyMap,p.anisotropyMapTransform))),p.specularIntensity.value=m.specularIntensity,p.specularColor.value.copy(m.specularColor),m.specularColorMap&&(p.specularColorMap.value=m.specularColorMap,r(m.specularColorMap,p.specularColorMapTransform)),m.specularIntensityMap&&(p.specularIntensityMap.value=m.specularIntensityMap,r(m.specularIntensityMap,p.specularIntensityMapTransform))}function y(p,m){m.matcap&&(p.matcap.value=m.matcap)}function g(p,m){let v=t.get(m).light;p.referencePosition.value.setFromMatrixPosition(v.matrixWorld),p.nearDistance.value=v.shadow.camera.near,p.farDistance.value=v.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:n}}function rR(e,t,r,i){let n={},a={},s=[],o=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function l(v,x){let b=x.program;i.uniformBlockBinding(v,b)}function c(v,x){let b=n[v.id];b===void 0&&(y(v),b=u(v),n[v.id]=b,v.addEventListener("dispose",p));let _=x.program;i.updateUBOMapping(v,_);let M=t.render.frame;a[v.id]!==M&&(d(v),a[v.id]=M)}function u(v){let x=h();v.__bindingPointIndex=x;let b=e.createBuffer(),_=v.__size,M=v.usage;return e.bindBuffer(e.UNIFORM_BUFFER,b),e.bufferData(e.UNIFORM_BUFFER,_,M),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,x,b),b}function h(){for(let v=0;v<o;v++)if(s.indexOf(v)===-1)return s.push(v),v;return console.error("THREE.WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function d(v){let x=n[v.id],b=v.uniforms,_=v.__cache;e.bindBuffer(e.UNIFORM_BUFFER,x);for(let M=0,C=b.length;M<C;M++){let S=Array.isArray(b[M])?b[M]:[b[M]];for(let w=0,E=S.length;w<E;w++){let P=S[w];if(f(P,M,w,_)===!0){let N=P.__offset,D=Array.isArray(P.value)?P.value:[P.value],B=0;for(let J=0;J<D.length;J++){let Q=D[J],j=g(Q);typeof Q=="number"||typeof Q=="boolean"?(P.__data[0]=Q,e.bufferSubData(e.UNIFORM_BUFFER,N+B,P.__data)):Q.isMatrix3?(P.__data[0]=Q.elements[0],P.__data[1]=Q.elements[1],P.__data[2]=Q.elements[2],P.__data[3]=0,P.__data[4]=Q.elements[3],P.__data[5]=Q.elements[4],P.__data[6]=Q.elements[5],P.__data[7]=0,P.__data[8]=Q.elements[6],P.__data[9]=Q.elements[7],P.__data[10]=Q.elements[8],P.__data[11]=0):(Q.toArray(P.__data,B),B+=j.storage/Float32Array.BYTES_PER_ELEMENT)}e.bufferSubData(e.UNIFORM_BUFFER,N,P.__data)}}}e.bindBuffer(e.UNIFORM_BUFFER,null)}function f(v,x,b,_){let M=v.value,C=x+"_"+b;if(_[C]===void 0)return typeof M=="number"||typeof M=="boolean"?_[C]=M:_[C]=M.clone(),!0;{let S=_[C];if(typeof M=="number"||typeof M=="boolean"){if(S!==M)return _[C]=M,!0}else if(S.equals(M)===!1)return S.copy(M),!0}return!1}function y(v){let x=v.uniforms,b=0,_=16;for(let C=0,S=x.length;C<S;C++){let w=Array.isArray(x[C])?x[C]:[x[C]];for(let E=0,P=w.length;E<P;E++){let N=w[E],D=Array.isArray(N.value)?N.value:[N.value];for(let B=0,J=D.length;B<J;B++){let Q=D[B],j=g(Q),k=b%_,H=k%j.boundary,U=k+H;b+=H,U!==0&&_-U<j.storage&&(b+=_-U),N.__data=new Float32Array(j.storage/Float32Array.BYTES_PER_ELEMENT),N.__offset=b,b+=j.storage}}}let M=b%_;return M>0&&(b+=_-M),v.__size=b,v.__cache={},this}function g(v){let x={boundary:0,storage:0};return typeof v=="number"||typeof v=="boolean"?(x.boundary=4,x.storage=4):v.isVector2?(x.boundary=8,x.storage=8):v.isVector3||v.isColor?(x.boundary=16,x.storage=12):v.isVector4?(x.boundary=16,x.storage=16):v.isMatrix3?(x.boundary=48,x.storage=48):v.isMatrix4?(x.boundary=64,x.storage=64):v.isTexture?console.warn("THREE.WebGLRenderer: Texture samplers can not be part of an uniforms group."):console.warn("THREE.WebGLRenderer: Unsupported uniform value type.",v),x}function p(v){let x=v.target;x.removeEventListener("dispose",p);let b=s.indexOf(x.__bindingPointIndex);s.splice(b,1),e.deleteBuffer(n[x.id]),delete n[x.id],delete a[x.id]}function m(){for(let v in n)e.deleteBuffer(n[v]);s=[],n={},a={}}return{bind:l,update:c,dispose:m}}var sd=class{constructor(e={}){let{canvas:t=o0(),context:r=null,depth:i=!0,stencil:n=!1,alpha:a=!1,antialias:s=!1,premultipliedAlpha:o=!0,preserveDrawingBuffer:l=!1,powerPreference:c="default",failIfMajorPerformanceCaveat:u=!1,reverseDepthBuffer:h=!1}=e;this.isWebGLRenderer=!0;let d;if(r!==null){if(typeof WebGLRenderingContext<"u"&&r instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");d=r.getContextAttributes().alpha}else d=a;let f=new Uint32Array(4),y=new Int32Array(4),g=null,p=null,m=[],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=Pr,this.toneMapping=ea,this.toneMappingExposure=1;let x=this,b=!1,_=0,M=0,C=null,S=-1,w=null,E=new Nr,P=new Nr,N=null,D=new yt(0),B=0,J=t.width,Q=t.height,j=1,k=null,H=null,U=new Nr(0,0,J,Q),X=new Nr(0,0,J,Q),W=!1,$=new Wl,G=!1,T=!1,I=new Jt,V=new Jt,K=new ee,ie=new Nr,le={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},ae=!1;function de(){return C===null?j:1}let z=r;function me(te,Te){return t.getContext(te,Te)}try{let te={alpha:!0,depth:i,stencil:n,antialias:s,premultipliedAlpha:o,preserveDrawingBuffer:l,powerPreference:c,failIfMajorPerformanceCaveat:u};if("setAttribute"in t&&t.setAttribute("data-engine","three.js r171"),t.addEventListener("webglcontextlost",Ue,!1),t.addEventListener("webglcontextrestored",Ie,!1),t.addEventListener("webglcontextcreationerror",mt,!1),z===null){let Te="webgl2";if(z=me(Te,te),z===null)throw me(Te)?new Error("Error creating WebGL context with your selected attributes."):new Error("Error creating WebGL context.")}}catch(te){throw console.error("THREE.WebGLRenderer: "+te.message),te}let we,He,ne,_e,oe,ce,L,A,O,F,Y,re,ue,se,pe,Pe,Ce,je,st,Pt,ut,ot,tt,Ht;function fe(){we=new pA(z),we.init(),ot=new Wv(z,we),He=new oA(z,we,e,ot),ne=new YC(z,we),He.reverseDepthBuffer&&h&&ne.buffers.depth.setReversed(!0),_e=new gA(z),oe=new OC,ce=new qC(z,we,ne,oe,He,ot,_e),L=new cA(x),A=new dA(x),O=new EM(z),tt=new aA(z,O),F=new fA(z,O,_e,tt),Y=new vA(z,F,O,_e),st=new yA(z,He,ce),Pe=new lA(oe),re=new LC(x,L,A,we,He,tt,Pe),ue=new tR(x,oe),se=new kC,pe=new VC(we),je=new nA(x,L,A,ne,Y,d,o),Ce=new jC(x,Y,He),Ht=new rR(z,_e,He,ne),Pt=new sA(z,we,_e),ut=new mA(z,we,_e),_e.programs=re.programs,x.capabilities=He,x.extensions=we,x.properties=oe,x.renderLists=se,x.shadowMap=Ce,x.state=ne,x.info=_e}fe();let qe=new $C(x,z);this.xr=qe,this.getContext=function(){return z},this.getContextAttributes=function(){return z.getContextAttributes()},this.forceContextLoss=function(){let te=we.get("WEBGL_lose_context");te&&te.loseContext()},this.forceContextRestore=function(){let te=we.get("WEBGL_lose_context");te&&te.restoreContext()},this.getPixelRatio=function(){return j},this.setPixelRatio=function(te){te!==void 0&&(j=te,this.setSize(J,Q,!1))},this.getSize=function(te){return te.set(J,Q)},this.setSize=function(te,Te,ke=!0){if(qe.isPresenting){console.warn("THREE.WebGLRenderer: Can't change size while VR device is presenting.");return}J=te,Q=Te,t.width=Math.floor(te*j),t.height=Math.floor(Te*j),ke===!0&&(t.style.width=te+"px",t.style.height=Te+"px"),this.setViewport(0,0,te,Te)},this.getDrawingBufferSize=function(te){return te.set(J*j,Q*j).floor()},this.setDrawingBufferSize=function(te,Te,ke){J=te,Q=Te,j=ke,t.width=Math.floor(te*ke),t.height=Math.floor(Te*ke),this.setViewport(0,0,te,Te)},this.getCurrentViewport=function(te){return te.copy(E)},this.getViewport=function(te){return te.copy(U)},this.setViewport=function(te,Te,ke,Ge){te.isVector4?U.set(te.x,te.y,te.z,te.w):U.set(te,Te,ke,Ge),ne.viewport(E.copy(U).multiplyScalar(j).round())},this.getScissor=function(te){return te.copy(X)},this.setScissor=function(te,Te,ke,Ge){te.isVector4?X.set(te.x,te.y,te.z,te.w):X.set(te,Te,ke,Ge),ne.scissor(P.copy(X).multiplyScalar(j).round())},this.getScissorTest=function(){return W},this.setScissorTest=function(te){ne.setScissorTest(W=te)},this.setOpaqueSort=function(te){k=te},this.setTransparentSort=function(te){H=te},this.getClearColor=function(te){return te.copy(je.getClearColor())},this.setClearColor=function(){je.setClearColor.apply(je,arguments)},this.getClearAlpha=function(){return je.getClearAlpha()},this.setClearAlpha=function(){je.setClearAlpha.apply(je,arguments)},this.clear=function(te=!0,Te=!0,ke=!0){let Ge=0;if(te){let Se=!1;if(C!==null){let pt=C.texture.format;Se=pt===gu||pt===mu||pt===bl}if(Se){let pt=C.texture.type,Wt=pt===gn||pt===ra||pt===to||pt===Ca||pt===du||pt===pu,jt=je.getClearColor(),tr=je.getClearAlpha(),$t=jt.r,ur=jt.g,Tt=jt.b;Wt?(f[0]=$t,f[1]=ur,f[2]=Tt,f[3]=tr,z.clearBufferuiv(z.COLOR,0,f)):(y[0]=$t,y[1]=ur,y[2]=Tt,y[3]=tr,z.clearBufferiv(z.COLOR,0,y))}else Ge|=z.COLOR_BUFFER_BIT}Te&&(Ge|=z.DEPTH_BUFFER_BIT),ke&&(Ge|=z.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),z.clear(Ge)},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",Ue,!1),t.removeEventListener("webglcontextrestored",Ie,!1),t.removeEventListener("webglcontextcreationerror",mt,!1),je.dispose(),se.dispose(),pe.dispose(),oe.dispose(),L.dispose(),A.dispose(),Y.dispose(),tt.dispose(),Ht.dispose(),re.dispose(),qe.dispose(),qe.removeEventListener("sessionstart",$e),qe.removeEventListener("sessionend",Tr),ni.stop()};function Ue(te){te.preventDefault(),console.log("THREE.WebGLRenderer: Context Lost."),b=!0}function Ie(){console.log("THREE.WebGLRenderer: Context Restored."),b=!1;let te=_e.autoReset,Te=Ce.enabled,ke=Ce.autoUpdate,Ge=Ce.needsUpdate,Se=Ce.type;fe(),_e.autoReset=te,Ce.enabled=Te,Ce.autoUpdate=ke,Ce.needsUpdate=Ge,Ce.type=Se}function mt(te){console.error("THREE.WebGLRenderer: A WebGL context could not be created. Reason: ",te.statusMessage)}function lt(te){let Te=te.target;Te.removeEventListener("dispose",lt),Ut(Te)}function Ut(te){xt(te),oe.remove(te)}function xt(te){let Te=oe.get(te).programs;Te!==void 0&&(Te.forEach(function(ke){re.releaseProgram(ke)}),te.isShaderMaterial&&re.releaseShaderCache(te))}this.renderBufferDirect=function(te,Te,ke,Ge,Se,pt){Te===null&&(Te=le);let Wt=Se.isMesh&&Se.matrixWorld.determinant()<0,jt=Bi(te,Te,ke,Ge,Se);ne.setMaterial(Ge,Wt);let tr=ke.index,$t=1;if(Ge.wireframe===!0){if(tr=F.getWireframeAttribute(ke),tr===void 0)return;$t=2}let ur=ke.drawRange,Tt=ke.attributes.position,Cr=ur.start*$t,Fr=(ur.start+ur.count)*$t;pt!==null&&(Cr=Math.max(Cr,pt.start*$t),Fr=Math.min(Fr,(pt.start+pt.count)*$t)),tr!==null?(Cr=Math.max(Cr,0),Fr=Math.min(Fr,tr.count)):Tt!=null&&(Cr=Math.max(Cr,0),Fr=Math.min(Fr,Tt.count));let zr=Fr-Cr;if(zr<0||zr===1/0)return;tt.setup(Se,Ge,jt,ke,tr);let Ir,dr=Pt;if(tr!==null&&(Ir=O.get(tr),dr=ut,dr.setIndex(Ir)),Se.isMesh)Ge.wireframe===!0?(ne.setLineWidth(Ge.wireframeLinewidth*de()),dr.setMode(z.LINES)):dr.setMode(z.TRIANGLES);else if(Se.isLine){let ir=Ge.linewidth;ir===void 0&&(ir=1),ne.setLineWidth(ir*de()),Se.isLineSegments?dr.setMode(z.LINES):Se.isLineLoop?dr.setMode(z.LINE_LOOP):dr.setMode(z.LINE_STRIP)}else Se.isPoints?dr.setMode(z.POINTS):Se.isSprite&&dr.setMode(z.TRIANGLES);if(Se.isBatchedMesh)if(Se._multiDrawInstances!==null)dr.renderMultiDrawInstances(Se._multiDrawStarts,Se._multiDrawCounts,Se._multiDrawCount,Se._multiDrawInstances);else if(we.get("WEBGL_multi_draw"))dr.renderMultiDraw(Se._multiDrawStarts,Se._multiDrawCounts,Se._multiDrawCount);else{let ir=Se._multiDrawStarts,Mi=Se._multiDrawCounts,zn=Se._multiDrawCount,ji=tr?O.get(tr).bytesPerElement:1,Kn=oe.get(Ge).currentProgram.getUniforms();for(let yi=0;yi<zn;yi++)Kn.setValue(z,"_gl_DrawID",yi),dr.render(ir[yi]/ji,Mi[yi])}else if(Se.isInstancedMesh)dr.renderInstances(Cr,zr,Se.count);else if(ke.isInstancedBufferGeometry){let ir=ke._maxInstanceCount!==void 0?ke._maxInstanceCount:1/0,Mi=Math.min(ke.instanceCount,ir);dr.renderInstances(Cr,zr,Mi)}else dr.render(Cr,zr)};function Dt(te,Te,ke){te.transparent===!0&&te.side===Rt&&te.forceSinglePass===!1?(te.side=_t,te.needsUpdate=!0,Ei(te,Te,ke),te.side=it,te.needsUpdate=!0,Ei(te,Te,ke),te.side=Rt):Ei(te,Te,ke)}this.compile=function(te,Te,ke=null){ke===null&&(ke=te),p=pe.get(ke),p.init(Te),v.push(p),ke.traverseVisible(function(Se){Se.isLight&&Se.layers.test(Te.layers)&&(p.pushLight(Se),Se.castShadow&&p.pushShadow(Se))}),te!==ke&&te.traverseVisible(function(Se){Se.isLight&&Se.layers.test(Te.layers)&&(p.pushLight(Se),Se.castShadow&&p.pushShadow(Se))}),p.setupLights();let Ge=new Set;return te.traverse(function(Se){if(!(Se.isMesh||Se.isPoints||Se.isLine||Se.isSprite))return;let pt=Se.material;if(pt)if(Array.isArray(pt))for(let Wt=0;Wt<pt.length;Wt++){let jt=pt[Wt];Dt(jt,ke,Se),Ge.add(jt)}else Dt(pt,ke,Se),Ge.add(pt)}),v.pop(),p=null,Ge},this.compileAsync=function(te,Te,ke=null){let Ge=this.compile(te,Te,ke);return new Promise(Se=>{function pt(){if(Ge.forEach(function(Wt){oe.get(Wt).currentProgram.isReady()&&Ge.delete(Wt)}),Ge.size===0){Se(te);return}setTimeout(pt,10)}we.get("KHR_parallel_shader_compile")!==null?pt():setTimeout(pt,10)})};let gt=null;function Vt(te){gt&>(te)}function $e(){ni.stop()}function Tr(){ni.start()}let ni=new gv;ni.setAnimationLoop(Vt),typeof self<"u"&&ni.setContext(self),this.setAnimationLoop=function(te){gt=te,qe.setAnimationLoop(te),te===null?ni.stop():ni.start()},qe.addEventListener("sessionstart",$e),qe.addEventListener("sessionend",Tr),this.render=function(te,Te){if(Te!==void 0&&Te.isCamera!==!0){console.error("THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(b===!0)return;if(te.matrixWorldAutoUpdate===!0&&te.updateMatrixWorld(),Te.parent===null&&Te.matrixWorldAutoUpdate===!0&&Te.updateMatrixWorld(),qe.enabled===!0&&qe.isPresenting===!0&&(qe.cameraAutoUpdate===!0&&qe.updateCamera(Te),Te=qe.getCamera()),te.isScene===!0&&te.onBeforeRender(x,te,Te,C),p=pe.get(te,v.length),p.init(Te),v.push(p),V.multiplyMatrices(Te.projectionMatrix,Te.matrixWorldInverse),$.setFromProjectionMatrix(V),T=this.localClippingEnabled,G=Pe.init(this.clippingPlanes,T),g=se.get(te,m.length),g.init(),m.push(g),qe.enabled===!0&&qe.isPresenting===!0){let pt=x.xr.getDepthSensingMesh();pt!==null&&$r(pt,Te,-1/0,x.sortObjects)}$r(te,Te,0,x.sortObjects),g.finish(),x.sortObjects===!0&&g.sort(k,H),ae=qe.enabled===!1||qe.isPresenting===!1||qe.hasDepthSensing()===!1,ae&&je.addToRenderList(g,te),this.info.render.frame++,G===!0&&Pe.beginShadows();let ke=p.state.shadowsArray;Ce.render(ke,te,Te),G===!0&&Pe.endShadows(),this.info.autoReset===!0&&this.info.reset();let Ge=g.opaque,Se=g.transmissive;if(p.setupLights(),Te.isArrayCamera){let pt=Te.cameras;if(Se.length>0)for(let Wt=0,jt=pt.length;Wt<jt;Wt++){let tr=pt[Wt];Yo(Ge,Se,te,tr)}ae&&je.render(te);for(let Wt=0,jt=pt.length;Wt<jt;Wt++){let tr=pt[Wt];qn(g,te,tr,tr.viewport)}}else Se.length>0&&Yo(Ge,Se,te,Te),ae&&je.render(te),qn(g,te,Te);C!==null&&(ce.updateMultisampleRenderTarget(C),ce.updateRenderTargetMipmap(C)),te.isScene===!0&&te.onAfterRender(x,te,Te),tt.resetDefaultState(),S=-1,w=null,v.pop(),v.length>0?(p=v[v.length-1],G===!0&&Pe.setGlobalState(x.clippingPlanes,p.state.camera)):p=null,m.pop(),m.length>0?g=m[m.length-1]:g=null};function $r(te,Te,ke,Ge){if(te.visible===!1)return;if(te.layers.test(Te.layers)){if(te.isGroup)ke=te.renderOrder;else if(te.isLOD)te.autoUpdate===!0&&te.update(Te);else if(te.isLight)p.pushLight(te),te.castShadow&&p.pushShadow(te);else if(te.isSprite){if(!te.frustumCulled||$.intersectsSprite(te)){Ge&&ie.setFromMatrixPosition(te.matrixWorld).applyMatrix4(V);let pt=Y.update(te),Wt=te.material;Wt.visible&&g.push(te,pt,Wt,ke,ie.z,null)}}else if((te.isMesh||te.isLine||te.isPoints)&&(!te.frustumCulled||$.intersectsObject(te))){let pt=Y.update(te),Wt=te.material;if(Ge&&(te.boundingSphere!==void 0?(te.boundingSphere===null&&te.computeBoundingSphere(),ie.copy(te.boundingSphere.center)):(pt.boundingSphere===null&&pt.computeBoundingSphere(),ie.copy(pt.boundingSphere.center)),ie.applyMatrix4(te.matrixWorld).applyMatrix4(V)),Array.isArray(Wt)){let jt=pt.groups;for(let tr=0,$t=jt.length;tr<$t;tr++){let ur=jt[tr],Tt=Wt[ur.materialIndex];Tt&&Tt.visible&&g.push(te,pt,Tt,ke,ie.z,ur)}}else Wt.visible&&g.push(te,pt,Wt,ke,ie.z,null)}}let Se=te.children;for(let pt=0,Wt=Se.length;pt<Wt;pt++)$r(Se[pt],Te,ke,Ge)}function qn(te,Te,ke,Ge){let Se=te.opaque,pt=te.transmissive,Wt=te.transparent;p.setupLightsView(ke),G===!0&&Pe.setGlobalState(x.clippingPlanes,ke),Ge&&ne.viewport(E.copy(Ge)),Se.length>0&&Va(Se,Te,ke),pt.length>0&&Va(pt,Te,ke),Wt.length>0&&Va(Wt,Te,ke),ne.buffers.depth.setTest(!0),ne.buffers.depth.setMask(!0),ne.buffers.color.setMask(!0),ne.setPolygonOffset(!1)}function Yo(te,Te,ke,Ge){if((ke.isScene===!0?ke.overrideMaterial:null)!==null)return;p.state.transmissionRenderTarget[Ge.id]===void 0&&(p.state.transmissionRenderTarget[Ge.id]=new Pi(1,1,{generateMipmaps:!0,type:we.has("EXT_color_buffer_half_float")||we.has("EXT_color_buffer_float")?yn:gn,minFilter:mn,samples:4,stencilBuffer:n,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:_r.workingColorSpace}));let Se=p.state.transmissionRenderTarget[Ge.id],pt=Ge.viewport||E;Se.setSize(pt.z,pt.w);let Wt=x.getRenderTarget();x.setRenderTarget(Se),x.getClearColor(D),B=x.getClearAlpha(),B<1&&x.setClearColor(16777215,.5),x.clear(),ae&&je.render(ke);let jt=x.toneMapping;x.toneMapping=ea;let tr=Ge.viewport;if(Ge.viewport!==void 0&&(Ge.viewport=void 0),p.setupLightsView(Ge),G===!0&&Pe.setGlobalState(x.clippingPlanes,Ge),Va(te,ke,Ge),ce.updateMultisampleRenderTarget(Se),ce.updateRenderTargetMipmap(Se),we.has("WEBGL_multisampled_render_to_texture")===!1){let $t=!1;for(let ur=0,Tt=Te.length;ur<Tt;ur++){let Cr=Te[ur],Fr=Cr.object,zr=Cr.geometry,Ir=Cr.material,dr=Cr.group;if(Ir.side===Rt&&Fr.layers.test(Ge.layers)){let ir=Ir.side;Ir.side=_t,Ir.needsUpdate=!0,Bn(Fr,ke,Ge,zr,Ir,dr),Ir.side=ir,Ir.needsUpdate=!0,$t=!0}}$t===!0&&(ce.updateMultisampleRenderTarget(Se),ce.updateRenderTargetMipmap(Se))}x.setRenderTarget(Wt),x.setClearColor(D,B),tr!==void 0&&(Ge.viewport=tr),x.toneMapping=jt}function Va(te,Te,ke){let Ge=Te.isScene===!0?Te.overrideMaterial:null;for(let Se=0,pt=te.length;Se<pt;Se++){let Wt=te[Se],jt=Wt.object,tr=Wt.geometry,$t=Ge===null?Wt.material:Ge,ur=Wt.group;jt.layers.test(ke.layers)&&Bn(jt,Te,ke,tr,$t,ur)}}function Bn(te,Te,ke,Ge,Se,pt){te.onBeforeRender(x,Te,ke,Ge,Se,pt),te.modelViewMatrix.multiplyMatrices(ke.matrixWorldInverse,te.matrixWorld),te.normalMatrix.getNormalMatrix(te.modelViewMatrix),Se.onBeforeRender(x,Te,ke,Ge,te,pt),Se.transparent===!0&&Se.side===Rt&&Se.forceSinglePass===!1?(Se.side=_t,Se.needsUpdate=!0,x.renderBufferDirect(ke,Te,Ge,Se,te,pt),Se.side=it,Se.needsUpdate=!0,x.renderBufferDirect(ke,Te,Ge,Se,te,pt),Se.side=Rt):x.renderBufferDirect(ke,Te,Ge,Se,te,pt),te.onAfterRender(x,Te,ke,Ge,Se,pt)}function Ei(te,Te,ke){Te.isScene!==!0&&(Te=le);let Ge=oe.get(te),Se=p.state.lights,pt=p.state.shadowsArray,Wt=Se.state.version,jt=re.getParameters(te,Se.state,pt,Te,ke),tr=re.getProgramCacheKey(jt),$t=Ge.programs;Ge.environment=te.isMeshStandardMaterial?Te.environment:null,Ge.fog=Te.fog,Ge.envMap=(te.isMeshStandardMaterial?A:L).get(te.envMap||Ge.environment),Ge.envMapRotation=Ge.environment!==null&&te.envMap===null?Te.environmentRotation:te.envMapRotation,$t===void 0&&(te.addEventListener("dispose",lt),$t=new Map,Ge.programs=$t);let ur=$t.get(tr);if(ur!==void 0){if(Ge.currentProgram===ur&&Ge.lightsStateVersion===Wt)return ai(te,jt),ur}else jt.uniforms=re.getUniforms(te),te.onBeforeCompile(jt,x),ur=re.acquireProgram(jt,tr),$t.set(tr,ur),Ge.uniforms=jt.uniforms;let Tt=Ge.uniforms;return(!te.isShaderMaterial&&!te.isRawShaderMaterial||te.clipping===!0)&&(Tt.clippingPlanes=Pe.uniform),ai(te,jt),Ge.needsLights=ba(te),Ge.lightsStateVersion=Wt,Ge.needsLights&&(Tt.ambientLightColor.value=Se.state.ambient,Tt.lightProbe.value=Se.state.probe,Tt.directionalLights.value=Se.state.directional,Tt.directionalLightShadows.value=Se.state.directionalShadow,Tt.spotLights.value=Se.state.spot,Tt.spotLightShadows.value=Se.state.spotShadow,Tt.rectAreaLights.value=Se.state.rectArea,Tt.ltc_1.value=Se.state.rectAreaLTC1,Tt.ltc_2.value=Se.state.rectAreaLTC2,Tt.pointLights.value=Se.state.point,Tt.pointLightShadows.value=Se.state.pointShadow,Tt.hemisphereLights.value=Se.state.hemi,Tt.directionalShadowMap.value=Se.state.directionalShadowMap,Tt.directionalShadowMatrix.value=Se.state.directionalShadowMatrix,Tt.spotShadowMap.value=Se.state.spotShadowMap,Tt.spotLightMatrix.value=Se.state.spotLightMatrix,Tt.spotLightMap.value=Se.state.spotLightMap,Tt.pointShadowMap.value=Se.state.pointShadowMap,Tt.pointShadowMatrix.value=Se.state.pointShadowMatrix),Ge.currentProgram=ur,Ge.uniformsList=null,ur}function Sn(te){if(te.uniformsList===null){let Te=te.currentProgram.getUniforms();te.uniformsList=nd.seqWithValue(Te.seq,te.uniforms)}return te.uniformsList}function ai(te,Te){let ke=oe.get(te);ke.outputColorSpace=Te.outputColorSpace,ke.batching=Te.batching,ke.batchingColor=Te.batchingColor,ke.instancing=Te.instancing,ke.instancingColor=Te.instancingColor,ke.instancingMorph=Te.instancingMorph,ke.skinning=Te.skinning,ke.morphTargets=Te.morphTargets,ke.morphNormals=Te.morphNormals,ke.morphColors=Te.morphColors,ke.morphTargetsCount=Te.morphTargetsCount,ke.numClippingPlanes=Te.numClippingPlanes,ke.numIntersection=Te.numClipIntersection,ke.vertexAlphas=Te.vertexAlphas,ke.vertexTangents=Te.vertexTangents,ke.toneMapping=Te.toneMapping}function Bi(te,Te,ke,Ge,Se){Te.isScene!==!0&&(Te=le),ce.resetTextureUnits();let pt=Te.fog,Wt=Ge.isMeshStandardMaterial?Te.environment:null,jt=C===null?x.outputColorSpace:C.isXRRenderTarget===!0?C.texture.colorSpace:Oi,tr=(Ge.isMeshStandardMaterial?A:L).get(Ge.envMap||Wt),$t=Ge.vertexColors===!0&&!!ke.attributes.color&&ke.attributes.color.itemSize===4,ur=!!ke.attributes.tangent&&(!!Ge.normalMap||Ge.anisotropy>0),Tt=!!ke.morphAttributes.position,Cr=!!ke.morphAttributes.normal,Fr=!!ke.morphAttributes.color,zr=ea;Ge.toneMapped&&(C===null||C.isXRRenderTarget===!0)&&(zr=x.toneMapping);let Ir=ke.morphAttributes.position||ke.morphAttributes.normal||ke.morphAttributes.color,dr=Ir!==void 0?Ir.length:0,ir=oe.get(Ge),Mi=p.state.lights;if(G===!0&&(T===!0||te!==w)){let vi=te===w&&Ge.id===S;Pe.setState(Ge,te,vi)}let zn=!1;Ge.version===ir.__version?(ir.needsLights&&ir.lightsStateVersion!==Mi.state.version||ir.outputColorSpace!==jt||Se.isBatchedMesh&&ir.batching===!1||!Se.isBatchedMesh&&ir.batching===!0||Se.isBatchedMesh&&ir.batchingColor===!0&&Se.colorTexture===null||Se.isBatchedMesh&&ir.batchingColor===!1&&Se.colorTexture!==null||Se.isInstancedMesh&&ir.instancing===!1||!Se.isInstancedMesh&&ir.instancing===!0||Se.isSkinnedMesh&&ir.skinning===!1||!Se.isSkinnedMesh&&ir.skinning===!0||Se.isInstancedMesh&&ir.instancingColor===!0&&Se.instanceColor===null||Se.isInstancedMesh&&ir.instancingColor===!1&&Se.instanceColor!==null||Se.isInstancedMesh&&ir.instancingMorph===!0&&Se.morphTexture===null||Se.isInstancedMesh&&ir.instancingMorph===!1&&Se.morphTexture!==null||ir.envMap!==tr||Ge.fog===!0&&ir.fog!==pt||ir.numClippingPlanes!==void 0&&(ir.numClippingPlanes!==Pe.numPlanes||ir.numIntersection!==Pe.numIntersection)||ir.vertexAlphas!==$t||ir.vertexTangents!==ur||ir.morphTargets!==Tt||ir.morphNormals!==Cr||ir.morphColors!==Fr||ir.toneMapping!==zr||ir.morphTargetsCount!==dr)&&(zn=!0):(zn=!0,ir.__version=Ge.version);let ji=ir.currentProgram;zn===!0&&(ji=Ei(Ge,Te,Se));let Kn=!1,yi=!1,_a=!1,Dr=ji.getUniforms(),Si=ir.uniforms;if(ne.useProgram(ji.program)&&(Kn=!0,yi=!0,_a=!0),Ge.id!==S&&(S=Ge.id,yi=!0),Kn||w!==te){ne.buffers.depth.getReversed()?(I.copy(te.projectionMatrix),Q_(I),J_(I),Dr.setValue(z,"projectionMatrix",I)):Dr.setValue(z,"projectionMatrix",te.projectionMatrix),Dr.setValue(z,"viewMatrix",te.matrixWorldInverse);let vi=Dr.map.cameraPosition;vi!==void 0&&vi.setValue(z,K.setFromMatrixPosition(te.matrixWorld)),He.logarithmicDepthBuffer&&Dr.setValue(z,"logDepthBufFC",2/(Math.log(te.far+1)/Math.LN2)),(Ge.isMeshPhongMaterial||Ge.isMeshToonMaterial||Ge.isMeshLambertMaterial||Ge.isMeshBasicMaterial||Ge.isMeshStandardMaterial||Ge.isShaderMaterial)&&Dr.setValue(z,"isOrthographic",te.isOrthographicCamera===!0),w!==te&&(w=te,yi=!0,_a=!0)}if(Se.isSkinnedMesh){Dr.setOptional(z,Se,"bindMatrix"),Dr.setOptional(z,Se,"bindMatrixInverse");let vi=Se.skeleton;vi&&(vi.boneTexture===null&&vi.computeBoneTexture(),Dr.setValue(z,"boneTexture",vi.boneTexture,ce))}Se.isBatchedMesh&&(Dr.setOptional(z,Se,"batchingTexture"),Dr.setValue(z,"batchingTexture",Se._matricesTexture,ce),Dr.setOptional(z,Se,"batchingIdTexture"),Dr.setValue(z,"batchingIdTexture",Se._indirectTexture,ce),Dr.setOptional(z,Se,"batchingColorTexture"),Se._colorsTexture!==null&&Dr.setValue(z,"batchingColorTexture",Se._colorsTexture,ce));let zi=ke.morphAttributes;if((zi.position!==void 0||zi.normal!==void 0||zi.color!==void 0)&&st.update(Se,ke,ji),(yi||ir.receiveShadow!==Se.receiveShadow)&&(ir.receiveShadow=Se.receiveShadow,Dr.setValue(z,"receiveShadow",Se.receiveShadow)),Ge.isMeshGouraudMaterial&&Ge.envMap!==null&&(Si.envMap.value=tr,Si.flipEnvMap.value=tr.isCubeTexture&&tr.isRenderTargetTexture===!1?-1:1),Ge.isMeshStandardMaterial&&Ge.envMap===null&&Te.environment!==null&&(Si.envMapIntensity.value=Te.environmentIntensity),yi&&(Dr.setValue(z,"toneMappingExposure",x.toneMappingExposure),ir.needsLights&&Fs(Si,_a),pt&&Ge.fog===!0&&ue.refreshFogUniforms(Si,pt),ue.refreshMaterialUniforms(Si,Ge,j,Q,p.state.transmissionRenderTarget[te.id]),nd.upload(z,Sn(ir),Si,ce)),Ge.isShaderMaterial&&Ge.uniformsNeedUpdate===!0&&(nd.upload(z,Sn(ir),Si,ce),Ge.uniformsNeedUpdate=!1),Ge.isSpriteMaterial&&Dr.setValue(z,"center",Se.center),Dr.setValue(z,"modelViewMatrix",Se.modelViewMatrix),Dr.setValue(z,"normalMatrix",Se.normalMatrix),Dr.setValue(z,"modelMatrix",Se.matrixWorld),Ge.isShaderMaterial||Ge.isRawShaderMaterial){let vi=Ge.uniformsGroups;for(let Qi=0,qo=vi.length;Qi<qo;Qi++){let Tn=vi[Qi];Ht.update(Tn,ji),Ht.bind(Tn,ji)}}return ji}function Fs(te,Te){te.ambientLightColor.needsUpdate=Te,te.lightProbe.needsUpdate=Te,te.directionalLights.needsUpdate=Te,te.directionalLightShadows.needsUpdate=Te,te.pointLights.needsUpdate=Te,te.pointLightShadows.needsUpdate=Te,te.spotLights.needsUpdate=Te,te.spotLightShadows.needsUpdate=Te,te.rectAreaLights.needsUpdate=Te,te.hemisphereLights.needsUpdate=Te}function ba(te){return te.isMeshLambertMaterial||te.isMeshToonMaterial||te.isMeshPhongMaterial||te.isMeshStandardMaterial||te.isShadowMaterial||te.isShaderMaterial&&te.lights===!0}this.getActiveCubeFace=function(){return _},this.getActiveMipmapLevel=function(){return M},this.getRenderTarget=function(){return C},this.setRenderTargetTextures=function(te,Te,ke){oe.get(te.texture).__webglTexture=Te,oe.get(te.depthTexture).__webglTexture=ke;let Ge=oe.get(te);Ge.__hasExternalTextures=!0,Ge.__autoAllocateDepthBuffer=ke===void 0,Ge.__autoAllocateDepthBuffer||we.has("WEBGL_multisampled_render_to_texture")===!0&&(console.warn("THREE.WebGLRenderer: Render-to-texture extension was disabled because an external texture was provided"),Ge.__useRenderToTexture=!1)},this.setRenderTargetFramebuffer=function(te,Te){let ke=oe.get(te);ke.__webglFramebuffer=Te,ke.__useDefaultFramebuffer=Te===void 0},this.setRenderTarget=function(te,Te=0,ke=0){C=te,_=Te,M=ke;let Ge=!0,Se=null,pt=!1,Wt=!1;if(te){let jt=oe.get(te);if(jt.__useDefaultFramebuffer!==void 0)ne.bindFramebuffer(z.FRAMEBUFFER,null),Ge=!1;else if(jt.__webglFramebuffer===void 0)ce.setupRenderTarget(te);else if(jt.__hasExternalTextures)ce.rebindTextures(te,oe.get(te.texture).__webglTexture,oe.get(te.depthTexture).__webglTexture);else if(te.depthBuffer){let ur=te.depthTexture;if(jt.__boundDepthTexture!==ur){if(ur!==null&&oe.has(ur)&&(te.width!==ur.image.width||te.height!==ur.image.height))throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.");ce.setupDepthRenderbuffer(te)}}let tr=te.texture;(tr.isData3DTexture||tr.isDataArrayTexture||tr.isCompressedArrayTexture)&&(Wt=!0);let $t=oe.get(te).__webglFramebuffer;te.isWebGLCubeRenderTarget?(Array.isArray($t[Te])?Se=$t[Te][ke]:Se=$t[Te],pt=!0):te.samples>0&&ce.useMultisampledRTT(te)===!1?Se=oe.get(te).__webglMultisampledFramebuffer:Array.isArray($t)?Se=$t[ke]:Se=$t,E.copy(te.viewport),P.copy(te.scissor),N=te.scissorTest}else E.copy(U).multiplyScalar(j).floor(),P.copy(X).multiplyScalar(j).floor(),N=W;if(ne.bindFramebuffer(z.FRAMEBUFFER,Se)&&Ge&&ne.drawBuffers(te,Se),ne.viewport(E),ne.scissor(P),ne.setScissorTest(N),pt){let jt=oe.get(te.texture);z.framebufferTexture2D(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_CUBE_MAP_POSITIVE_X+Te,jt.__webglTexture,ke)}else if(Wt){let jt=oe.get(te.texture),tr=Te||0;z.framebufferTextureLayer(z.FRAMEBUFFER,z.COLOR_ATTACHMENT0,jt.__webglTexture,ke||0,tr)}S=-1},this.readRenderTargetPixels=function(te,Te,ke,Ge,Se,pt,Wt){if(!(te&&te.isWebGLRenderTarget)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let jt=oe.get(te).__webglFramebuffer;if(te.isWebGLCubeRenderTarget&&Wt!==void 0&&(jt=jt[Wt]),jt){ne.bindFramebuffer(z.FRAMEBUFFER,jt);try{let tr=te.texture,$t=tr.format,ur=tr.type;if(!He.textureFormatReadable($t)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(!He.textureTypeReadable(ur)){console.error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}Te>=0&&Te<=te.width-Ge&&ke>=0&&ke<=te.height-Se&&z.readPixels(Te,ke,Ge,Se,ot.convert($t),ot.convert(ur),pt)}finally{let tr=C!==null?oe.get(C).__webglFramebuffer:null;ne.bindFramebuffer(z.FRAMEBUFFER,tr)}}},this.readRenderTargetPixelsAsync=async function(te,Te,ke,Ge,Se,pt,Wt){if(!(te&&te.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let jt=oe.get(te).__webglFramebuffer;if(te.isWebGLCubeRenderTarget&&Wt!==void 0&&(jt=jt[Wt]),jt){let tr=te.texture,$t=tr.format,ur=tr.type;if(!He.textureFormatReadable($t))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(!He.textureTypeReadable(ur))throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");if(Te>=0&&Te<=te.width-Ge&&ke>=0&&ke<=te.height-Se){ne.bindFramebuffer(z.FRAMEBUFFER,jt);let Tt=z.createBuffer();z.bindBuffer(z.PIXEL_PACK_BUFFER,Tt),z.bufferData(z.PIXEL_PACK_BUFFER,pt.byteLength,z.STREAM_READ),z.readPixels(Te,ke,Ge,Se,ot.convert($t),ot.convert(ur),0);let Cr=C!==null?oe.get(C).__webglFramebuffer:null;ne.bindFramebuffer(z.FRAMEBUFFER,Cr);let Fr=z.fenceSync(z.SYNC_GPU_COMMANDS_COMPLETE,0);return z.flush(),await Z_(z,Fr,4),z.bindBuffer(z.PIXEL_PACK_BUFFER,Tt),z.getBufferSubData(z.PIXEL_PACK_BUFFER,0,pt),z.deleteBuffer(Tt),z.deleteSync(Fr),pt}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")}},this.copyFramebufferToTexture=function(te,Te=null,ke=0){te.isTexture!==!0&&(so("WebGLRenderer: copyFramebufferToTexture function signature has changed."),Te=arguments[0]||null,te=arguments[1]);let Ge=Math.pow(2,-ke),Se=Math.floor(te.image.width*Ge),pt=Math.floor(te.image.height*Ge),Wt=Te!==null?Te.x:0,jt=Te!==null?Te.y:0;ce.setTexture2D(te,0),z.copyTexSubImage2D(z.TEXTURE_2D,ke,0,0,Wt,jt,Se,pt),ne.unbindTexture()};let Od=z.createFramebuffer(),Wm=z.createFramebuffer();this.copyTextureToTexture=function(te,Te,ke=null,Ge=null,Se=0,pt=null){te.isTexture!==!0&&(so("WebGLRenderer: copyTextureToTexture function signature has changed."),Ge=arguments[0]||null,te=arguments[1],Te=arguments[2],pt=arguments[3]||0,ke=null),pt===null&&(Se!==0?(so("WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels."),pt=Se,Se=0):pt=0);let Wt,jt,tr,$t,ur,Tt,Cr,Fr,zr,Ir=te.isCompressedTexture?te.mipmaps[pt]:te.image;if(ke!==null)Wt=ke.max.x-ke.min.x,jt=ke.max.y-ke.min.y,tr=ke.isBox3?ke.max.z-ke.min.z:1,$t=ke.min.x,ur=ke.min.y,Tt=ke.isBox3?ke.min.z:0;else{let zi=Math.pow(2,-Se);Wt=Math.floor(Ir.width*zi),jt=Math.floor(Ir.height*zi),te.isDataArrayTexture?tr=Ir.depth:te.isData3DTexture?tr=Math.floor(Ir.depth*zi):tr=1,$t=0,ur=0,Tt=0}Ge!==null?(Cr=Ge.x,Fr=Ge.y,zr=Ge.z):(Cr=0,Fr=0,zr=0);let dr=ot.convert(Te.format),ir=ot.convert(Te.type),Mi;Te.isData3DTexture?(ce.setTexture3D(Te,0),Mi=z.TEXTURE_3D):Te.isDataArrayTexture||Te.isCompressedArrayTexture?(ce.setTexture2DArray(Te,0),Mi=z.TEXTURE_2D_ARRAY):(ce.setTexture2D(Te,0),Mi=z.TEXTURE_2D),z.pixelStorei(z.UNPACK_FLIP_Y_WEBGL,Te.flipY),z.pixelStorei(z.UNPACK_PREMULTIPLY_ALPHA_WEBGL,Te.premultiplyAlpha),z.pixelStorei(z.UNPACK_ALIGNMENT,Te.unpackAlignment);let zn=z.getParameter(z.UNPACK_ROW_LENGTH),ji=z.getParameter(z.UNPACK_IMAGE_HEIGHT),Kn=z.getParameter(z.UNPACK_SKIP_PIXELS),yi=z.getParameter(z.UNPACK_SKIP_ROWS),_a=z.getParameter(z.UNPACK_SKIP_IMAGES);z.pixelStorei(z.UNPACK_ROW_LENGTH,Ir.width),z.pixelStorei(z.UNPACK_IMAGE_HEIGHT,Ir.height),z.pixelStorei(z.UNPACK_SKIP_PIXELS,$t),z.pixelStorei(z.UNPACK_SKIP_ROWS,ur),z.pixelStorei(z.UNPACK_SKIP_IMAGES,Tt);let Dr=te.isDataArrayTexture||te.isData3DTexture,Si=Te.isDataArrayTexture||Te.isData3DTexture;if(te.isDepthTexture){let zi=oe.get(te),vi=oe.get(Te),Qi=oe.get(zi.__renderTarget),qo=oe.get(vi.__renderTarget);ne.bindFramebuffer(z.READ_FRAMEBUFFER,Qi.__webglFramebuffer),ne.bindFramebuffer(z.DRAW_FRAMEBUFFER,qo.__webglFramebuffer);for(let Tn=0;Tn<tr;Tn++)Dr&&(z.framebufferTextureLayer(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,oe.get(te).__webglTexture,Se,Tt+Tn),z.framebufferTextureLayer(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,oe.get(Te).__webglTexture,pt,zr+Tn)),z.blitFramebuffer($t,ur,Wt,jt,Cr,Fr,Wt,jt,z.DEPTH_BUFFER_BIT,z.NEAREST);ne.bindFramebuffer(z.READ_FRAMEBUFFER,null),ne.bindFramebuffer(z.DRAW_FRAMEBUFFER,null)}else if(Se!==0||te.isRenderTargetTexture||oe.has(te)){let zi=oe.get(te),vi=oe.get(Te);ne.bindFramebuffer(z.READ_FRAMEBUFFER,Od),ne.bindFramebuffer(z.DRAW_FRAMEBUFFER,Wm);for(let Qi=0;Qi<tr;Qi++)Dr?z.framebufferTextureLayer(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,zi.__webglTexture,Se,Tt+Qi):z.framebufferTexture2D(z.READ_FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_2D,zi.__webglTexture,Se),Si?z.framebufferTextureLayer(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,vi.__webglTexture,pt,zr+Qi):z.framebufferTexture2D(z.DRAW_FRAMEBUFFER,z.COLOR_ATTACHMENT0,z.TEXTURE_2D,vi.__webglTexture,pt),Se!==0?z.blitFramebuffer($t,ur,Wt,jt,Cr,Fr,Wt,jt,z.COLOR_BUFFER_BIT,z.NEAREST):Si?z.copyTexSubImage3D(Mi,pt,Cr,Fr,zr+Qi,$t,ur,Wt,jt):z.copyTexSubImage2D(Mi,pt,Cr,Fr,$t,ur,Wt,jt);ne.bindFramebuffer(z.READ_FRAMEBUFFER,null),ne.bindFramebuffer(z.DRAW_FRAMEBUFFER,null)}else Si?te.isDataTexture||te.isData3DTexture?z.texSubImage3D(Mi,pt,Cr,Fr,zr,Wt,jt,tr,dr,ir,Ir.data):Te.isCompressedArrayTexture?z.compressedTexSubImage3D(Mi,pt,Cr,Fr,zr,Wt,jt,tr,dr,Ir.data):z.texSubImage3D(Mi,pt,Cr,Fr,zr,Wt,jt,tr,dr,ir,Ir):te.isDataTexture?z.texSubImage2D(z.TEXTURE_2D,pt,Cr,Fr,Wt,jt,dr,ir,Ir.data):te.isCompressedTexture?z.compressedTexSubImage2D(z.TEXTURE_2D,pt,Cr,Fr,Ir.width,Ir.height,dr,Ir.data):z.texSubImage2D(z.TEXTURE_2D,pt,Cr,Fr,Wt,jt,dr,ir,Ir);z.pixelStorei(z.UNPACK_ROW_LENGTH,zn),z.pixelStorei(z.UNPACK_IMAGE_HEIGHT,ji),z.pixelStorei(z.UNPACK_SKIP_PIXELS,Kn),z.pixelStorei(z.UNPACK_SKIP_ROWS,yi),z.pixelStorei(z.UNPACK_SKIP_IMAGES,_a),pt===0&&Te.generateMipmaps&&z.generateMipmap(Mi),ne.unbindTexture()},this.copyTextureToTexture3D=function(te,Te,ke=null,Ge=null,Se=0){return te.isTexture!==!0&&(so("WebGLRenderer: copyTextureToTexture3D function signature has changed."),ke=arguments[0]||null,Ge=arguments[1]||null,te=arguments[2],Te=arguments[3],Se=arguments[4]||0),so('WebGLRenderer: copyTextureToTexture3D function has been deprecated. Use "copyTextureToTexture" instead.'),this.copyTextureToTexture(te,Te,ke,Ge,Se)},this.initRenderTarget=function(te){oe.get(te).__webglFramebuffer===void 0&&ce.setupRenderTarget(te)},this.initTexture=function(te){te.isCubeTexture?ce.setTextureCube(te,0):te.isData3DTexture?ce.setTexture3D(te,0):te.isDataArrayTexture||te.isCompressedArrayTexture?ce.setTexture2DArray(te,0):ce.setTexture2D(te,0),ne.unbindTexture()},this.resetState=function(){_=0,M=0,C=null,ne.reset(),tt.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return Hn}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;let t=this.getContext();t.drawingBufferColorspace=_r._getDrawingBufferColorSpace(e),t.unpackColorSpace=_r._getUnpackColorSpace()}},iR={triangulate:function(e,t,r=2){let i=t&&t.length,n=i?t[0]*r:e.length,a=jv(e,0,n,r,!0),s=[];if(!a||a.next===a.prev)return s;let o,l,c,u,h,d,f;if(i&&(a=lR(e,t,a,r)),e.length>80*r){o=c=e[0],l=u=e[1];for(let y=r;y<n;y+=r)h=e[y],d=e[y+1],h<o&&(o=h),d<l&&(l=d),h>c&&(c=h),d>u&&(u=d);f=Math.max(c-o,u-l),f=f!==0?32767/f:0}return ac(a,s,r,o,l,f,0),s}};function jv(e,t,r,i,n){let a,s;if(n===xR(e,t,r,i)>0)for(a=t;a<r;a+=i)s=qv(a,e[a],e[a+1],s);else for(a=r-i;a>=t;a-=i)s=qv(a,e[a],e[a+1],s);return s&&od(s,s.next)&&(oc(s),s=s.next),s}function Is(e,t){if(!e)return e;t||(t=e);let r=e,i;do if(i=!1,!r.steiner&&(od(r,r.next)||Jr(r.prev,r,r.next)===0)){if(oc(r),r=t=r.prev,r===r.next)break;i=!0}else r=r.next;while(i||r!==t);return t}function ac(e,t,r,i,n,a,s){if(!e)return;!s&&a&&pR(e,i,n,a);let o=e,l,c;for(;e.prev!==e.next;){if(l=e.prev,c=e.next,a?aR(e,i,n,a):nR(e)){t.push(l.i/r|0),t.push(e.i/r|0),t.push(c.i/r|0),oc(e),e=c.next,o=c.next;continue}if(e=c,e===o){s?s===1?(e=sR(Is(e),t,r),ac(e,t,r,i,n,a,2)):s===2&&oR(e,t,r,i,n,a):ac(Is(e),t,r,i,n,a,1);break}}}function nR(e){let t=e.prev,r=e,i=e.next;if(Jr(t,r,i)>=0)return!1;let n=t.x,a=r.x,s=i.x,o=t.y,l=r.y,c=i.y,u=n<a?n<s?n:s:a<s?a:s,h=o<l?o<c?o:c:l<c?l:c,d=n>a?n>s?n:s:a>s?a:s,f=o>l?o>c?o:c:l>c?l:c,y=i.next;for(;y!==t;){if(y.x>=u&&y.x<=d&&y.y>=h&&y.y<=f&&Fo(n,o,a,l,s,c,y.x,y.y)&&Jr(y.prev,y,y.next)>=0)return!1;y=y.next}return!0}function aR(e,t,r,i){let n=e.prev,a=e,s=e.next;if(Jr(n,a,s)>=0)return!1;let o=n.x,l=a.x,c=s.x,u=n.y,h=a.y,d=s.y,f=o<l?o<c?o:c:l<c?l:c,y=u<h?u<d?u:d:h<d?h:d,g=o>l?o>c?o:c:l>c?l:c,p=u>h?u>d?u:d:h>d?h:d,m=tm(f,y,t,r,i),v=tm(g,p,t,r,i),x=e.prevZ,b=e.nextZ;for(;x&&x.z>=m&&b&&b.z<=v;){if(x.x>=f&&x.x<=g&&x.y>=y&&x.y<=p&&x!==n&&x!==s&&Fo(o,u,l,h,c,d,x.x,x.y)&&Jr(x.prev,x,x.next)>=0||(x=x.prevZ,b.x>=f&&b.x<=g&&b.y>=y&&b.y<=p&&b!==n&&b!==s&&Fo(o,u,l,h,c,d,b.x,b.y)&&Jr(b.prev,b,b.next)>=0))return!1;b=b.nextZ}for(;x&&x.z>=m;){if(x.x>=f&&x.x<=g&&x.y>=y&&x.y<=p&&x!==n&&x!==s&&Fo(o,u,l,h,c,d,x.x,x.y)&&Jr(x.prev,x,x.next)>=0)return!1;x=x.prevZ}for(;b&&b.z<=v;){if(b.x>=f&&b.x<=g&&b.y>=y&&b.y<=p&&b!==n&&b!==s&&Fo(o,u,l,h,c,d,b.x,b.y)&&Jr(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function sR(e,t,r){let i=e;do{let n=i.prev,a=i.next.next;!od(n,a)&&Xv(n,i,i.next,a)&&sc(n,a)&&sc(a,n)&&(t.push(n.i/r|0),t.push(i.i/r|0),t.push(a.i/r|0),oc(i),oc(i.next),i=e=a),i=i.next}while(i!==e);return Is(i)}function oR(e,t,r,i,n,a){let s=e;do{let o=s.next.next;for(;o!==s.prev;){if(s.i!==o.i&&gR(s,o)){let l=Yv(s,o);s=Is(s,s.next),l=Is(l,l.next),ac(s,t,r,i,n,a,0),ac(l,t,r,i,n,a,0);return}o=o.next}s=s.next}while(s!==e)}function lR(e,t,r,i){let n=[],a,s,o,l,c;for(a=0,s=t.length;a<s;a++)o=t[a]*i,l=a<s-1?t[a+1]*i:e.length,c=jv(e,o,l,i,!1),c===c.next&&(c.steiner=!0),n.push(mR(c));for(n.sort(cR),a=0;a<n.length;a++)r=uR(n[a],r);return r}function cR(e,t){return e.x-t.x}function uR(e,t){let r=hR(e,t);if(!r)return t;let i=Yv(r,e);return Is(i,i.next),Is(r,r.next)}function hR(e,t){let r=t,i=-1/0,n,a=e.x,s=e.y;do{if(s<=r.y&&s>=r.next.y&&r.next.y!==r.y){let d=r.x+(s-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(d<=a&&d>i&&(i=d,n=r.x<r.next.x?r:r.next,d===a))return n}r=r.next}while(r!==t);if(!n)return null;let o=n,l=n.x,c=n.y,u=1/0,h;r=n;do a>=r.x&&r.x>=l&&a!==r.x&&Fo(s<c?a:i,s,l,c,s<c?i:a,s,r.x,r.y)&&(h=Math.abs(s-r.y)/(a-r.x),sc(r,e)&&(h<u||h===u&&(r.x>n.x||r.x===n.x&&dR(n,r)))&&(n=r,u=h)),r=r.next;while(r!==o);return n}function dR(e,t){return Jr(e.prev,e,t.prev)<0&&Jr(t.next,e,e.next)<0}function pR(e,t,r,i){let n=e;do n.z===0&&(n.z=tm(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,fR(n)}function fR(e){let t,r,i,n,a,s,o,l,c=1;do{for(r=e,e=null,a=null,s=0;r;){for(s++,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--),a?a.nextZ=n:e=n,n.prevZ=a,a=n;r=i}a.nextZ=null,c*=2}while(s>1);return e}function tm(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 mR(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 Fo(e,t,r,i,n,a,s,o){return(n-s)*(t-o)>=(e-s)*(a-o)&&(e-s)*(i-o)>=(r-s)*(t-o)&&(r-s)*(a-o)>=(n-s)*(i-o)}function gR(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!yR(e,t)&&(sc(e,t)&&sc(t,e)&&vR(e,t)&&(Jr(e.prev,e,t.prev)||Jr(e,t.prev,t))||od(e,t)&&Jr(e.prev,e,e.next)>0&&Jr(t.prev,t,t.next)>0)}function Jr(e,t,r){return(t.y-e.y)*(r.x-t.x)-(t.x-e.x)*(r.y-t.y)}function od(e,t){return e.x===t.x&&e.y===t.y}function Xv(e,t,r,i){let n=cd(Jr(e,t,r)),a=cd(Jr(e,t,i)),s=cd(Jr(r,i,e)),o=cd(Jr(r,i,t));return!!(n!==a&&s!==o||n===0&&ld(e,r,t)||a===0&&ld(e,i,t)||s===0&&ld(r,e,i)||o===0&&ld(r,t,i))}function ld(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 cd(e){return e>0?1:e<0?-1:0}function yR(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&&Xv(r,r.next,e,t))return!0;r=r.next}while(r!==e);return!1}function sc(e,t){return Jr(e.prev,e,e.next)<0?Jr(e,t,e.next)>=0&&Jr(e,e.prev,t)>=0:Jr(e,t,e.prev)<0||Jr(e,e.next,t)<0}function vR(e,t){let r=e,i=!1,n=(e.x+t.x)/2,a=(e.y+t.y)/2;do r.y>a!=r.next.y>a&&r.next.y!==r.y&&n<(r.next.x-r.x)*(a-r.y)/(r.next.y-r.y)+r.x&&(i=!i),r=r.next;while(r!==e);return i}function Yv(e,t){let r=new rm(e.i,e.x,e.y),i=new rm(t.i,t.x,t.y),n=e.next,a=t.prev;return e.next=t,t.prev=e,r.next=n,n.prev=r,i.next=r,r.prev=i,a.next=i,i.prev=a,i}function qv(e,t,r,i){let n=new rm(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 oc(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 rm(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 xR(e,t,r,i){let n=0;for(let a=t,s=r-i;a<r;a+=i)n+=(e[s]-e[a])*(e[a+1]+e[s+1]),s=a;return n}var im=e=>e&&typeof e=="object"&&!Array.isArray(e)?e.quoted:e;function bR(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 _R(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(bR(t)>n)throw Object.assign(Error("Saved zone exceeds the remaining typed-geometry byte budget."),{code:"ZONE_GEOMETRY_BUDGET"});let a=new Float64Array(t.size*2),s=0,o=(y,g)=>{let p=r([y,g]);if(!p.every(Number.isFinite)||s>=t.size)throw Error("Invalid saved zone coordinate.");a[s*2]=p[0],a[s*2+1]=p[1],s++},l=t.sourcePoints[1];if(l instanceof Float64Array)for(let y=0;y<l.length;y+=2)o(l[y],l[y+1]);else for(let y of t.sourcePoints)!Array.isArray(y)||im(y[0])!=="xy"||o(Number(im(y[1])),Number(im(y[2])));if(s!==t.size)throw Error("Saved zone point count changed.");s>3&&a[0]===a[(s-1)*2]&&a[1]===a[(s-1)*2+1]&&s--;let c=new Float32Array(s*3),u=t.filled?new Int8Array(s*3):null;for(let y=0;y<s;y++)c[y*3]=a[y*2],c[y*3+1]=a[y*2+1],u&&(u[y*3+2]=127);let h=null;if(t.filled){let y=i(a.subarray(0,s*2),void 0,2);if(!y.length||y.length%3||y.length>(s-2)*3)throw Error("Saved zone could not be triangulated faithfully.");let g=s>65535?Uint32Array:Uint16Array;h=new g(y.length);for(let p=0;p<y.length;p++){let m=y[p];if(!Number.isInteger(m)||m<0||m>=s)throw Error("Invalid saved zone triangulation index.");h[p]=m}}let d=c.byteLength+(u?.byteLength||0)+(h?.byteLength||0);if(d>n)throw Object.assign(Error("Saved zone exceeds its typed-geometry byte budget."),{code:"ZONE_GEOMETRY_BUDGET"});let f=new e.BufferGeometry;return f.setAttribute("position",new e.BufferAttribute(c,3)),u&&f.setAttribute("normal",new e.BufferAttribute(u,3,!0)),h&&f.setIndex(new e.BufferAttribute(h,1)),{geometry:f,bytes:d,vertices:s}}var Kv={type:"change"},nm={type:"start"},Zv={type:"end"},ud=new ls,Qv=new pa,wR=Math.cos(70*Xu.DEG2RAD),wi=new ee,Zi=2*Math.PI,Hr={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},am=1e-6,sm=class extends mv{constructor(e,t=null){super(e,t),this.state=Hr.NONE,this.enabled=!0,this.target=new ee,this.cursor=new ee,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:ht.ROTATE,MIDDLE:ht.DOLLY,RIGHT:ht.PAN},this.touches={ONE:bt.ROTATE,TWO:bt.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._domElementKeyEvents=null,this._lastPosition=new ee,this._lastQuaternion=new di,this._lastTargetPosition=new ee,this._quat=new di().setFromUnitVectors(e.up,new ee(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new Vf,this._sphericalDelta=new Vf,this._scale=1,this._panOffset=new ee,this._rotateStart=new Xe,this._rotateEnd=new Xe,this._rotateDelta=new Xe,this._panStart=new Xe,this._panEnd=new Xe,this._panDelta=new Xe,this._dollyStart=new Xe,this._dollyEnd=new Xe,this._dollyDelta=new Xe,this._dollyDirection=new ee,this._mouse=new Xe,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=MR.bind(this),this._onPointerDown=ER.bind(this),this._onPointerUp=SR.bind(this),this._onContextMenu=NR.bind(this),this._onMouseWheel=CR.bind(this),this._onKeyDown=RR.bind(this),this._onTouchStart=PR.bind(this),this._onTouchMove=IR.bind(this),this._onMouseDown=TR.bind(this),this._onMouseMove=AR.bind(this),this._interceptControlDown=LR.bind(this),this._interceptControlUp=OR.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(Kv),this.update(),this.state=Hr.NONE}update(e=null){let t=this.object.position;wi.copy(t).sub(this.target),wi.applyQuaternion(this._quat),this._spherical.setFromVector3(wi),this.autoRotate&&this.state===Hr.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+=Zi:r>Math.PI&&(r-=Zi),i<-Math.PI?i+=Zi:i>Math.PI&&(i-=Zi),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 a=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),n=a!=this._spherical.radius}if(wi.setFromSpherical(this._spherical),wi.applyQuaternion(this._quatInverse),t.copy(this.target).add(wi),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 a=null;if(this.object.isPerspectiveCamera){let s=wi.length();a=this._clampDistance(s*this._scale);let o=s-a;this.object.position.addScaledVector(this._dollyDirection,o),this.object.updateMatrixWorld(),n=!!o}else if(this.object.isOrthographicCamera){let s=new ee(this._mouse.x,this._mouse.y,0);s.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 ee(this._mouse.x,this._mouse.y,0);l.unproject(this.object),this.object.position.sub(l).add(s),this.object.updateMatrixWorld(),a=wi.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;a!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(a).add(this.object.position):(ud.origin.copy(this.object.position),ud.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(ud.direction))<wR?this.object.lookAt(this.target):(Qv.setFromNormalAndCoplanarPoint(this.object.up,this.target),ud.intersectPlane(Qv,this.target))))}else if(this.object.isOrthographicCamera){let a=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),a!==this.object.zoom&&(this.object.updateProjectionMatrix(),n=!0)}return this._scale=1,this._performCursorZoom=!1,n||this._lastPosition.distanceToSquared(this.object.position)>am||8*(1-this._lastQuaternion.dot(this.object.quaternion))>am||this._lastTargetPosition.distanceToSquared(this.target)>am?(this.dispatchEvent(Kv),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?Zi/60*this.autoRotateSpeed*e:Zi/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){wi.setFromMatrixColumn(t,0),wi.multiplyScalar(-e),this._panOffset.add(wi)}_panUp(e,t){this.screenSpacePanning===!0?wi.setFromMatrixColumn(t,1):(wi.setFromMatrixColumn(t,0),wi.crossVectors(this.object.up,wi)),wi.multiplyScalar(e),this._panOffset.add(wi)}_pan(e,t){let r=this.domElement;if(this.object.isPerspectiveCamera){let i=this.object.position;wi.copy(i).sub(this.target);let n=wi.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,a=r.width,s=r.height;this._mouse.x=i/a*2-1,this._mouse.y=-(n/s)*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(Zi*this._rotateDelta.x/t.clientHeight),this._rotateUp(Zi*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(Zi*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(-Zi*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(Zi*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(-Zi*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(Zi*this._rotateDelta.x/t.clientHeight),this._rotateUp(Zi*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 a=(e.pageX+t.x)*.5,s=(e.pageY+t.y)*.5;this._updateZoomParameters(a,s)}_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 Xe,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 ER(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 MR(e){this.enabled!==!1&&(e.pointerType==="touch"?this._onTouchMove(e):this._onMouseMove(e))}function SR(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(Zv),this.state=Hr.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 TR(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 ht.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(e),this.state=Hr.DOLLY;break;case ht.ROTATE:if(e.ctrlKey||e.metaKey||e.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(e),this.state=Hr.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(e),this.state=Hr.ROTATE}break;case ht.PAN:if(e.ctrlKey||e.metaKey||e.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(e),this.state=Hr.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(e),this.state=Hr.PAN}break;default:this.state=Hr.NONE}this.state!==Hr.NONE&&this.dispatchEvent(nm)}function AR(e){switch(this.state){case Hr.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(e);break;case Hr.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(e);break;case Hr.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(e);break}}function CR(e){this.enabled===!1||this.enableZoom===!1||this.state!==Hr.NONE||(e.preventDefault(),this.dispatchEvent(nm),this._handleMouseWheel(this._customWheelEvent(e)),this.dispatchEvent(Zv))}function RR(e){this.enabled!==!1&&this._handleKeyDown(e)}function PR(e){switch(this._trackPointer(e),this._pointers.length){case 1:switch(this.touches.ONE){case bt.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(e),this.state=Hr.TOUCH_ROTATE;break;case bt.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(e),this.state=Hr.TOUCH_PAN;break;default:this.state=Hr.NONE}break;case 2:switch(this.touches.TWO){case bt.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(e),this.state=Hr.TOUCH_DOLLY_PAN;break;case bt.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(e),this.state=Hr.TOUCH_DOLLY_ROTATE;break;default:this.state=Hr.NONE}break;default:this.state=Hr.NONE}this.state!==Hr.NONE&&this.dispatchEvent(nm)}function IR(e){switch(this._trackPointer(e),this.state){case Hr.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(e),this.update();break;case Hr.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(e),this.update();break;case Hr.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(e),this.update();break;case Hr.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(e),this.update();break;default:this.state=Hr.NONE}}function NR(e){this.enabled!==!1&&e.preventDefault()}function LR(e){e.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function OR(e){e.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function DR(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(),a=-this._inputAngle(t);r.applyAxisAngle(n,a),i.applyAxisAngle(n,a),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 kR(e,t,r){e.mouseButtons.LEFT=r?t.MOUSE.PAN:t.MOUSE.ROTATE,e.touches.ONE=r?t.TOUCH.PAN:t.TOUCH.ROTATE}function Jv(e,t){if(t===Yg)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),e;if(t===ju||t===bp){let r=e.getIndex();if(r===null){let s=[],o=e.getAttribute("position");if(o!==void 0){for(let l=0;l<o.count;l++)s.push(l);e.setIndex(s),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===ju)for(let s=1;s<=i;s++)n.push(r.getX(0)),n.push(r.getX(s)),n.push(r.getX(s+1));else for(let s=0;s<i;s++)s%2===0?(n.push(r.getX(s)),n.push(r.getX(s+1)),n.push(r.getX(s+2))):(n.push(r.getX(s+2)),n.push(r.getX(s+1)),n.push(r.getX(s)));n.length/3!==i&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");let a=e.clone();return a.setIndex(n),a.clearGroups(),a}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",t),e}var UR=class extends fi{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new VR(t)}),this.register(function(t){return new HR(t)}),this.register(function(t){return new JR(t)}),this.register(function(t){return new $R(t)}),this.register(function(t){return new e2(t)}),this.register(function(t){return new jR(t)}),this.register(function(t){return new XR(t)}),this.register(function(t){return new YR(t)}),this.register(function(t){return new qR(t)}),this.register(function(t){return new GR(t)}),this.register(function(t){return new KR(t)}),this.register(function(t){return new WR(t)}),this.register(function(t){return new QR(t)}),this.register(function(t){return new ZR(t)}),this.register(function(t){return new BR(t)}),this.register(function(t){return new t2(t)}),this.register(function(t){return new r2(t)})}load(e,t,r,i){let n=this,a;if(this.resourcePath!=="")a=this.resourcePath;else if(this.path!==""){let l=va.extractUrlBase(e);a=va.resolveURL(l,this.path)}else a=va.extractUrlBase(e);this.manager.itemStart(e);let s=function(l){i?i(l):console.error(l),n.manager.itemError(e),n.manager.itemEnd(e)},o=new bn(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,a,function(c){t(c),n.manager.itemEnd(e)},s)}catch(c){s(c)}},r,s)}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,a={},s={},o=new TextDecoder;if(typeof e=="string")n=JSON.parse(e);else if(e instanceof ArrayBuffer)if(o.decode(new Uint8Array(e,0,4))===$v){try{a[Sr.KHR_BINARY_GLTF]=new i2(e)}catch(c){i&&i(c);return}n=JSON.parse(a[Sr.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 g2(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"),s[u.name]=u,a[u.name]=!0}if(n.extensionsUsed)for(let c=0;c<n.extensionsUsed.length;++c){let u=n.extensionsUsed[c],h=n.extensionsRequired||[];switch(u){case Sr.KHR_MATERIALS_UNLIT:a[u]=new zR;break;case Sr.KHR_DRACO_MESH_COMPRESSION:a[u]=new n2(n,this.dracoLoader);break;case Sr.KHR_TEXTURE_TRANSFORM:a[u]=new a2;break;case Sr.KHR_MESH_QUANTIZATION:a[u]=new s2;break;default:h.indexOf(u)>=0&&s[u]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+u+'".')}}l.setExtensions(a),l.setPlugins(s),l.parse(r,i)}parseAsync(e,t){let r=this;return new Promise(function(i,n){r.parse(e,t,i,n)})}};function FR(){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 Sr={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"},BR=class{constructor(e){this.parser=e,this.name=Sr.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,a=((n.extensions&&n.extensions[this.name]||{}).lights||[])[e],s,o=new yt(16777215);a.color!==void 0&&o.setRGB(a.color[0],a.color[1],a.color[2],Oi);let l=a.range!==void 0?a.range:0;switch(a.type){case"directional":s=new Xh(o),s.target.position.set(0,0,-1),s.add(s.target);break;case"point":s=new jh(o),s.distance=l;break;case"spot":s=new Of(o),s.distance=l,a.spot=a.spot||{},a.spot.innerConeAngle=a.spot.innerConeAngle!==void 0?a.spot.innerConeAngle:0,a.spot.outerConeAngle=a.spot.outerConeAngle!==void 0?a.spot.outerConeAngle:Math.PI/4,s.angle=a.spot.outerConeAngle,s.penumbra=1-a.spot.innerConeAngle/a.spot.outerConeAngle,s.target.position.set(0,0,-1),s.add(s.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+a.type)}return s.position.set(0,0,0),s.decay=2,xa(s,a),a.intensity!==void 0&&(s.intensity=a.intensity),s.name=t.createUniqueName(a.name||"light_"+e),i=Promise.resolve(s),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(a){return r._getNodeRef(t.cache,n,a)})}},zR=class{constructor(){this.name=Sr.KHR_MATERIALS_UNLIT}getMaterialType(){return ti}extendParams(e,t,r){let i=[];e.color=new yt(1,1,1),e.opacity=1;let n=t.pbrMetallicRoughness;if(n){if(Array.isArray(n.baseColorFactor)){let a=n.baseColorFactor;e.color.setRGB(a[0],a[1],a[2],Oi),e.opacity=a[3]}n.baseColorTexture!==void 0&&i.push(r.assignTexture(e,"map",n.baseColorTexture,Pr))}return Promise.all(i)}},GR=class{constructor(e){this.parser=e,this.name=Sr.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()}},VR=class{constructor(e){this.parser=e,this.name=Sr.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:on}extendMaterialParams(e,t){let r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let n=[],a=i.extensions[this.name];if(a.clearcoatFactor!==void 0&&(t.clearcoat=a.clearcoatFactor),a.clearcoatTexture!==void 0&&n.push(r.assignTexture(t,"clearcoatMap",a.clearcoatTexture)),a.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=a.clearcoatRoughnessFactor),a.clearcoatRoughnessTexture!==void 0&&n.push(r.assignTexture(t,"clearcoatRoughnessMap",a.clearcoatRoughnessTexture)),a.clearcoatNormalTexture!==void 0&&(n.push(r.assignTexture(t,"clearcoatNormalMap",a.clearcoatNormalTexture)),a.clearcoatNormalTexture.scale!==void 0)){let s=a.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new Xe(s,s)}return Promise.all(n)}},HR=class{constructor(e){this.parser=e,this.name=Sr.KHR_MATERIALS_DISPERSION}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:on}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()}},WR=class{constructor(e){this.parser=e,this.name=Sr.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:on}extendMaterialParams(e,t){let r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let n=[],a=i.extensions[this.name];return a.iridescenceFactor!==void 0&&(t.iridescence=a.iridescenceFactor),a.iridescenceTexture!==void 0&&n.push(r.assignTexture(t,"iridescenceMap",a.iridescenceTexture)),a.iridescenceIor!==void 0&&(t.iridescenceIOR=a.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),a.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=a.iridescenceThicknessMinimum),a.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=a.iridescenceThicknessMaximum),a.iridescenceThicknessTexture!==void 0&&n.push(r.assignTexture(t,"iridescenceThicknessMap",a.iridescenceThicknessTexture)),Promise.all(n)}},jR=class{constructor(e){this.parser=e,this.name=Sr.KHR_MATERIALS_SHEEN}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:on}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 yt(0,0,0),t.sheenRoughness=0,t.sheen=1;let a=i.extensions[this.name];if(a.sheenColorFactor!==void 0){let s=a.sheenColorFactor;t.sheenColor.setRGB(s[0],s[1],s[2],Oi)}return a.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=a.sheenRoughnessFactor),a.sheenColorTexture!==void 0&&n.push(r.assignTexture(t,"sheenColorMap",a.sheenColorTexture,Pr)),a.sheenRoughnessTexture!==void 0&&n.push(r.assignTexture(t,"sheenRoughnessMap",a.sheenRoughnessTexture)),Promise.all(n)}},XR=class{constructor(e){this.parser=e,this.name=Sr.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:on}extendMaterialParams(e,t){let r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let n=[],a=i.extensions[this.name];return a.transmissionFactor!==void 0&&(t.transmission=a.transmissionFactor),a.transmissionTexture!==void 0&&n.push(r.assignTexture(t,"transmissionMap",a.transmissionTexture)),Promise.all(n)}},YR=class{constructor(e){this.parser=e,this.name=Sr.KHR_MATERIALS_VOLUME}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:on}extendMaterialParams(e,t){let r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let n=[],a=i.extensions[this.name];t.thickness=a.thicknessFactor!==void 0?a.thicknessFactor:0,a.thicknessTexture!==void 0&&n.push(r.assignTexture(t,"thicknessMap",a.thicknessTexture)),t.attenuationDistance=a.attenuationDistance||1/0;let s=a.attenuationColor||[1,1,1];return t.attenuationColor=new yt().setRGB(s[0],s[1],s[2],Oi),Promise.all(n)}},qR=class{constructor(e){this.parser=e,this.name=Sr.KHR_MATERIALS_IOR}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:on}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()}},KR=class{constructor(e){this.parser=e,this.name=Sr.KHR_MATERIALS_SPECULAR}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:on}extendMaterialParams(e,t){let r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let n=[],a=i.extensions[this.name];t.specularIntensity=a.specularFactor!==void 0?a.specularFactor:1,a.specularTexture!==void 0&&n.push(r.assignTexture(t,"specularIntensityMap",a.specularTexture));let s=a.specularColorFactor||[1,1,1];return t.specularColor=new yt().setRGB(s[0],s[1],s[2],Oi),a.specularColorTexture!==void 0&&n.push(r.assignTexture(t,"specularColorMap",a.specularColorTexture,Pr)),Promise.all(n)}},ZR=class{constructor(e){this.parser=e,this.name=Sr.EXT_MATERIALS_BUMP}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:on}extendMaterialParams(e,t){let r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let n=[],a=i.extensions[this.name];return t.bumpScale=a.bumpFactor!==void 0?a.bumpFactor:1,a.bumpTexture!==void 0&&n.push(r.assignTexture(t,"bumpMap",a.bumpTexture)),Promise.all(n)}},QR=class{constructor(e){this.parser=e,this.name=Sr.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){let t=this.parser.json.materials[e];return!t.extensions||!t.extensions[this.name]?null:on}extendMaterialParams(e,t){let r=this.parser,i=r.json.materials[e];if(!i.extensions||!i.extensions[this.name])return Promise.resolve();let n=[],a=i.extensions[this.name];return a.anisotropyStrength!==void 0&&(t.anisotropy=a.anisotropyStrength),a.anisotropyRotation!==void 0&&(t.anisotropyRotation=a.anisotropyRotation),a.anisotropyTexture!==void 0&&n.push(r.assignTexture(t,"anisotropyMap",a.anisotropyTexture)),Promise.all(n)}},JR=class{constructor(e){this.parser=e,this.name=Sr.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],a=t.options.ktx2Loader;if(!a){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,a)}},$R=class{constructor(e){this.parser=e,this.name=Sr.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 a=n.extensions[t],s=i.images[a.source],o=r.textureLoader;if(s.uri){let l=r.options.manager.getHandler(s.uri);l!==null&&(o=l)}return this.detectSupport().then(function(l){if(l)return r.loadTextureImage(e,a.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}},e2=class{constructor(e){this.parser=e,this.name=Sr.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 a=n.extensions[t],s=i.images[a.source],o=r.textureLoader;if(s.uri){let l=r.options.manager.getHandler(s.uri);l!==null&&(o=l)}return this.detectSupport().then(function(l){if(l)return r.loadTextureImage(e,a.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}},t2=class{constructor(e){this.name=Sr.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),a=this.parser.options.meshoptDecoder;if(!a||!a.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(s){let o=i.byteOffset||0,l=i.byteLength||0,c=i.count,u=i.byteStride,h=new Uint8Array(s,o,l);return a.decodeGltfBufferAsync?a.decodeGltfBufferAsync(c,u,h,i.mode,i.filter).then(function(d){return d.buffer}):a.ready.then(function(){let d=new ArrayBuffer(c*u);return a.decodeGltfBuffer(new Uint8Array(d),c,u,h,i.mode,i.filter),d})})}else return null}},r2=class{constructor(e){this.name=Sr.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!==_n.TRIANGLES&&o.mode!==_n.TRIANGLE_STRIP&&o.mode!==_n.TRIANGLE_FAN&&o.mode!==void 0)return null;let n=r.extensions[this.name].attributes,a=[],s={};for(let o in n)a.push(this.parser.getDependency("accessor",n[o]).then(l=>(s[o]=l,s[o])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(o=>{let l=o.pop(),c=l.isGroup?l.children:[l],u=o[0].count,h=[];for(let d of c){let f=new Jt,y=new ee,g=new di,p=new ee(1,1,1),m=new bh(d.geometry,d.material,u);for(let v=0;v<u;v++)s.TRANSLATION&&y.fromBufferAttribute(s.TRANSLATION,v),s.ROTATION&&g.fromBufferAttribute(s.ROTATION,v),s.SCALE&&p.fromBufferAttribute(s.SCALE,v),m.setMatrixAt(v,f.compose(y,g,p));for(let v in s)if(v==="_COLOR_0"){let x=s[v];m.instanceColor=new hs(x.array,x.itemSize,x.normalized)}else v!=="TRANSLATION"&&v!=="ROTATION"&&v!=="SCALE"&&d.geometry.setAttribute(v,s[v]);Ar.prototype.copy.call(m,d),this.parser.assignFinalMaterial(m),h.push(m)}return l.isGroup?(l.clear(),l.add(...h),l):h[0]}))}},$v="glTF",lc=12,ex={JSON:1313821514,BIN:5130562},i2=class{constructor(e){this.name=Sr.KHR_BINARY_GLTF,this.content=null,this.body=null;let t=new DataView(e,0,lc),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!==$v)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-lc,n=new DataView(e,lc),a=0;for(;a<i;){let s=n.getUint32(a,!0);a+=4;let o=n.getUint32(a,!0);if(a+=4,o===ex.JSON){let l=new Uint8Array(e,lc+a,s);this.content=r.decode(l)}else if(o===ex.BIN){let l=lc+a;this.body=e.slice(l,l+s)}a+=s}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}},n2=class{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=Sr.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,a=e.extensions[this.name].attributes,s={},o={},l={};for(let c in a){let u=lm[c]||c.toLowerCase();s[u]=a[c]}for(let c in e.attributes){let u=lm[c]||c.toLowerCase();if(a[c]!==void 0){let h=r.accessors[e.attributes[c]],d=Bo[h.componentType];l[u]=d.name,o[u]=h.normalized===!0}}return t.getDependency("bufferView",n).then(function(c){return new Promise(function(u,h){i.decodeDracoFile(c,function(d){for(let f in d.attributes){let y=d.attributes[f],g=o[f];g!==void 0&&(y.normalized=g)}u(d)},s,l,Oi,h)})})}},a2=class{constructor(){this.name=Sr.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}},s2=class{constructor(){this.name=Sr.KHR_MESH_QUANTIZATION}},tx=class extends No{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 a=0;a!==i;a++)t[a]=r[n+a];return t}interpolate_(e,t,r,i){let n=this.resultBuffer,a=this.sampleValues,s=this.valueSize,o=s*2,l=s*3,c=i-t,u=(r-t)/c,h=u*u,d=h*u,f=e*l,y=f-l,g=-2*d+3*h,p=d-h,m=1-g,v=p-h+u;for(let x=0;x!==s;x++){let b=a[y+x+s],_=a[y+x+o]*c,M=a[f+x+s],C=a[f+x]*c;n[x]=m*b+v*_+g*M+p*C}return n}},o2=new di,l2=class extends tx{interpolate_(e,t,r,i){let n=super.interpolate_(e,t,r,i);return o2.fromArray(n).normalize().toArray(n),n}},_n={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},Bo={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},rx={9728:Kr,9729:Zr,9984:uu,9985:eo,9986:$a,9987:mn},ix={33071:Ri,33648:$s,10497:Ni},om={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},lm={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"},za={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},c2={CUBICSPLINE:void 0,LINEAR:io,STEP:ro},cm={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function u2(e){return e.DefaultMaterial===void 0&&(e.DefaultMaterial=new Ki({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:it})),e.DefaultMaterial}function Ns(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 xa(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 h2(e,t,r){let i=!1,n=!1,a=!1;for(let c=0,u=t.length;c<u;c++){let h=t[c];if(h.POSITION!==void 0&&(i=!0),h.NORMAL!==void 0&&(n=!0),h.COLOR_0!==void 0&&(a=!0),i&&n&&a)break}if(!i&&!n&&!a)return Promise.resolve(e);let s=[],o=[],l=[];for(let c=0,u=t.length;c<u;c++){let h=t[c];if(i){let d=h.POSITION!==void 0?r.getDependency("accessor",h.POSITION):e.attributes.position;s.push(d)}if(n){let d=h.NORMAL!==void 0?r.getDependency("accessor",h.NORMAL):e.attributes.normal;o.push(d)}if(a){let d=h.COLOR_0!==void 0?r.getDependency("accessor",h.COLOR_0):e.attributes.color;l.push(d)}}return Promise.all([Promise.all(s),Promise.all(o),Promise.all(l)]).then(function(c){let u=c[0],h=c[1],d=c[2];return i&&(e.morphAttributes.position=u),n&&(e.morphAttributes.normal=h),a&&(e.morphAttributes.color=d),e.morphTargetsRelative=!0,e})}function d2(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 p2(e){let t,r=e.extensions&&e.extensions[Sr.KHR_DRACO_MESH_COMPRESSION];if(r?t="draco:"+r.bufferView+":"+r.indices+":"+um(r.attributes):t=e.indices+":"+um(e.attributes)+":"+e.mode,e.targets!==void 0)for(let i=0,n=e.targets.length;i<n;i++)t+=":"+um(e.targets[i]);return t}function um(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 hm(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 f2(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 m2=new Jt,g2=class{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new FR,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,a=-1;if(typeof navigator<"u"){let s=navigator.userAgent;r=/^((?!chrome|android).)*safari/i.test(s)===!0;let o=s.match(/Version\/(\d+)/);i=r&&o?parseInt(o[1],10):-1,n=s.indexOf("Firefox")>-1,a=n?s.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||r&&i<17||n&&a<98?this.textureLoader=new If(this.options.manager):this.textureLoader=new qy(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new bn(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(a){return a._markDefs&&a._markDefs()}),Promise.all(this._invokeAll(function(a){return a.beforeRoot&&a.beforeRoot()})).then(function(){return Promise.all([r.getDependencies("scene"),r.getDependencies("animation"),r.getDependencies("camera")])}).then(function(a){let s={scene:a[0][i.scene||0],scenes:a[0],animations:a[1],cameras:a[2],asset:i.asset,parser:r,userData:{}};return Ns(n,s,i),xa(s,i),Promise.all(r._invokeAll(function(o){return o.afterRoot&&o.afterRoot(s)})).then(function(){for(let o of s.scenes)o.updateMatrixWorld();e(s)})}).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 a=t[i].joints;for(let s=0,o=a.length;s<o;s++)e[a[s]].isBone=!0}for(let i=0,n=e.length;i<n;i++){let a=e[i];a.mesh!==void 0&&(this._addNodeRef(this.meshCache,a.mesh),a.skin!==void 0&&(r[a.mesh].isSkinnedMesh=!0)),a.camera!==void 0&&this._addNodeRef(this.cameraCache,a.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=(a,s)=>{let o=this.associations.get(a);o!=null&&this.associations.set(s,o);for(let[l,c]of a.children.entries())n(c,s.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,a){return r.getDependency(e,a)})),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[Sr.KHR_BINARY_GLTF].body);let i=this.options;return new Promise(function(n,a){r.load(va.resolveURL(t.uri,i.path),n,void 0,function(){a(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 a=om[i.type],s=Bo[i.componentType],o=i.normalized===!0,l=new s(i.count*a);return Promise.resolve(new Mr(l,a,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(a){let s=a[0],o=om[i.type],l=Bo[i.componentType],c=l.BYTES_PER_ELEMENT,u=c*o,h=i.byteOffset||0,d=i.bufferView!==void 0?r.bufferViews[i.bufferView].byteStride:void 0,f=i.normalized===!0,y,g;if(d&&d!==u){let p=Math.floor(h/d),m="InterleavedBuffer:"+i.bufferView+":"+i.componentType+":"+p+":"+i.count,v=t.cache.get(m);v||(y=new l(s,p*d,i.count*d/c),v=new Fl(y,d/c),t.cache.add(m,v)),g=new wo(v,o,h%d/c,f)}else s===null?y=new l(i.count*o):y=new l(s,h,i.count*o),g=new Mr(y,o,f);if(i.sparse!==void 0){let p=om.SCALAR,m=Bo[i.sparse.indices.componentType],v=i.sparse.indices.byteOffset||0,x=i.sparse.values.byteOffset||0,b=new m(a[1],v,i.sparse.count*p),_=new l(a[2],x,i.sparse.count*o);s!==null&&(g=new Mr(g.array.slice(),g.itemSize,g.normalized)),g.normalized=!1;for(let M=0,C=b.length;M<C;M++){let S=b[M];if(g.setX(S,_[M*o]),o>=2&&g.setY(S,_[M*o+1]),o>=3&&g.setZ(S,_[M*o+2]),o>=4&&g.setW(S,_[M*o+3]),o>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}g.normalized=f}return g})}loadTexture(e){let t=this.json,r=this.options,i=t.textures[e].source,n=t.images[i],a=this.textureLoader;if(n.uri){let s=r.manager.getHandler(n.uri);s!==null&&(a=s)}return this.loadTextureImage(e,i,a)}loadTextureImage(e,t,r){let i=this,n=this.json,a=n.textures[e],s=n.images[t],o=(s.uri||s.bufferView)+":"+a.sampler;if(this.textureCache[o])return this.textureCache[o];let l=this.loadImageSource(t,r).then(function(c){c.flipY=!1,c.name=a.name||s.name||"",c.name===""&&typeof s.uri=="string"&&s.uri.startsWith("data:image/")===!1&&(c.name=s.uri);let u=(n.samplers||{})[a.sampler]||{};return c.magFilter=rx[u.magFilter]||Zr,c.minFilter=rx[u.minFilter]||mn,c.wrapS=ix[u.wrapS]||Ni,c.wrapT=ix[u.wrapT]||Ni,c.generateMipmaps=!c.isCompressedTexture&&c.minFilter!==Kr&&c.minFilter!==Zr,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 a=i.images[e],s=self.URL||self.webkitURL,o=a.uri||"",l=!1;if(a.bufferView!==void 0)o=r.getDependency("bufferView",a.bufferView).then(function(u){l=!0;let h=new Blob([u],{type:a.mimeType});return o=s.createObjectURL(h),o});else if(a.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(h,d){let f=h;t.isImageBitmapLoader===!0&&(f=function(y){let g=new ei(y);g.needsUpdate=!0,h(g)}),t.load(va.resolveURL(u,n.path),f,void 0,d)})}).then(function(u){return l===!0&&s.revokeObjectURL(o),xa(u,a),u.userData.mimeType=a.mimeType||f2(a.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(a){if(!a)return null;if(r.texCoord!==void 0&&r.texCoord>0&&(a=a.clone(),a.channel=r.texCoord),n.extensions[Sr.KHR_TEXTURE_TRANSFORM]){let s=r.extensions!==void 0?r.extensions[Sr.KHR_TEXTURE_TRANSFORM]:void 0;if(s){let o=n.associations.get(a);a=n.extensions[Sr.KHR_TEXTURE_TRANSFORM].extendTexture(a,s),n.associations.set(a,o)}}return i!==void 0&&(a.colorSpace=i),e[t]=a,a})}assignFinalMaterial(e){let t=e.geometry,r=e.material,i=t.attributes.tangent===void 0,n=t.attributes.color!==void 0,a=t.attributes.normal===void 0;if(e.isPoints){let s="PointsMaterial:"+r.uuid,o=this.cache.get(s);o||(o=new Yl,xi.prototype.copy.call(o,r),o.color.copy(r.color),o.map=r.map,o.sizeAttenuation=!1,this.cache.add(s,o)),r=o}else if(e.isLine){let s="LineBasicMaterial:"+r.uuid,o=this.cache.get(s);o||(o=new ri,xi.prototype.copy.call(o,r),o.color.copy(r.color),o.map=r.map,this.cache.add(s,o)),r=o}if(i||n||a){let s="ClonedMaterial:"+r.uuid+":";i&&(s+="derivative-tangents:"),n&&(s+="vertex-colors:"),a&&(s+="flat-shading:");let o=this.cache.get(s);o||(o=r.clone(),n&&(o.vertexColors=!0),a&&(o.flatShading=!0),i&&(o.normalScale&&(o.normalScale.y*=-1),o.clearcoatNormalScale&&(o.clearcoatNormalScale.y*=-1)),this.cache.add(s,o),this.associations.set(o,this.associations.get(r))),r=o}e.material=r}getMaterialType(){return Ki}loadMaterial(e){let t=this,r=this.json,i=this.extensions,n=r.materials[e],a,s={},o=n.extensions||{},l=[];if(o[Sr.KHR_MATERIALS_UNLIT]){let u=i[Sr.KHR_MATERIALS_UNLIT];a=u.getMaterialType(),l.push(u.extendParams(s,n,t))}else{let u=n.pbrMetallicRoughness||{};if(s.color=new yt(1,1,1),s.opacity=1,Array.isArray(u.baseColorFactor)){let h=u.baseColorFactor;s.color.setRGB(h[0],h[1],h[2],Oi),s.opacity=h[3]}u.baseColorTexture!==void 0&&l.push(t.assignTexture(s,"map",u.baseColorTexture,Pr)),s.metalness=u.metallicFactor!==void 0?u.metallicFactor:1,s.roughness=u.roughnessFactor!==void 0?u.roughnessFactor:1,u.metallicRoughnessTexture!==void 0&&(l.push(t.assignTexture(s,"metalnessMap",u.metallicRoughnessTexture)),l.push(t.assignTexture(s,"roughnessMap",u.metallicRoughnessTexture))),a=this._invokeOne(function(h){return h.getMaterialType&&h.getMaterialType(e)}),l.push(Promise.all(this._invokeAll(function(h){return h.extendMaterialParams&&h.extendMaterialParams(e,s)})))}n.doubleSided===!0&&(s.side=Rt);let c=n.alphaMode||cm.OPAQUE;if(c===cm.BLEND?(s.transparent=!0,s.depthWrite=!1):(s.transparent=!1,c===cm.MASK&&(s.alphaTest=n.alphaCutoff!==void 0?n.alphaCutoff:.5)),n.normalTexture!==void 0&&a!==ti&&(l.push(t.assignTexture(s,"normalMap",n.normalTexture)),s.normalScale=new Xe(1,1),n.normalTexture.scale!==void 0)){let u=n.normalTexture.scale;s.normalScale.set(u,u)}if(n.occlusionTexture!==void 0&&a!==ti&&(l.push(t.assignTexture(s,"aoMap",n.occlusionTexture)),n.occlusionTexture.strength!==void 0&&(s.aoMapIntensity=n.occlusionTexture.strength)),n.emissiveFactor!==void 0&&a!==ti){let u=n.emissiveFactor;s.emissive=new yt().setRGB(u[0],u[1],u[2],Oi)}return n.emissiveTexture!==void 0&&a!==ti&&l.push(t.assignTexture(s,"emissiveMap",n.emissiveTexture,Pr)),Promise.all(l).then(function(){let u=new a(s);return n.name&&(u.name=n.name),xa(u,n),t.associations.set(u,{materials:e}),n.extensions&&Ns(i,u,n),u})}createUniqueName(e){let t=Vr.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(s){return r[Sr.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(s,t).then(function(o){return nx(o,s,t)})}let a=[];for(let s=0,o=e.length;s<o;s++){let l=e[s],c=p2(l),u=i[c];if(u)a.push(u.promise);else{let h;l.extensions&&l.extensions[Sr.KHR_DRACO_MESH_COMPRESSION]?h=n(l):h=nx(new ar,l,t),i[c]={primitive:l,promise:h},a.push(h)}}return Promise.all(a)}loadMesh(e){let t=this,r=this.json,i=this.extensions,n=r.meshes[e],a=n.primitives,s=[];for(let o=0,l=a.length;o<l;o++){let c=a[o].material===void 0?u2(this.cache):this.getDependency("material",a[o].material);s.push(c)}return s.push(t.loadGeometries(a)),Promise.all(s).then(function(o){let l=o.slice(0,o.length-1),c=o[o.length-1],u=[];for(let d=0,f=c.length;d<f;d++){let y=c[d],g=a[d],p,m=l[d];if(g.mode===_n.TRIANGLES||g.mode===_n.TRIANGLE_STRIP||g.mode===_n.TRIANGLE_FAN||g.mode===void 0)p=n.isSkinnedMesh===!0?new Qp(y,m):new hr(y,m),p.isSkinnedMesh===!0&&p.normalizeSkinWeights(),g.mode===_n.TRIANGLE_STRIP?p.geometry=Jv(p.geometry,bp):g.mode===_n.TRIANGLE_FAN&&(p.geometry=Jv(p.geometry,ju));else if(g.mode===_n.LINES)p=new Fi(y,m);else if(g.mode===_n.LINE_STRIP)p=new jn(y,m);else if(g.mode===_n.LINE_LOOP)p=new Ch(y,m);else if(g.mode===_n.POINTS)p=new Ih(y,m);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+g.mode);Object.keys(p.geometry.morphAttributes).length>0&&d2(p,n),p.name=t.createUniqueName(n.name||"mesh_"+e),xa(p,n),g.extensions&&Ns(i,p,g),t.assignFinalMaterial(p),u.push(p)}for(let d=0,f=u.length;d<f;d++)t.associations.set(u[d],{meshes:e,primitives:d});if(u.length===1)return n.extensions&&Ns(i,u[0],n),u[0];let h=new jr;n.extensions&&Ns(i,h,n),t.associations.set(h,{meshes:e});for(let d=0,f=u.length;d<f;d++)h.add(u[d]);return h})}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 li(Xu.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2e6):r.type==="orthographic"&&(t=new Oo(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar)),r.name&&(t.name=this.createUniqueName(r.name)),xa(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(),a=i,s=[],o=[];for(let l=0,c=a.length;l<c;l++){let u=a[l];if(u){s.push(u);let h=new Jt;n!==null&&h.fromArray(n.array,l*16),o.push(h)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[l])}return new Jp(s,o)})}loadAnimation(e){let t=this.json,r=this,i=t.animations[e],n=i.name?i.name:"animation_"+e,a=[],s=[],o=[],l=[],c=[];for(let u=0,h=i.channels.length;u<h;u++){let d=i.channels[u],f=i.samplers[d.sampler],y=d.target,g=y.node,p=i.parameters!==void 0?i.parameters[f.input]:f.input,m=i.parameters!==void 0?i.parameters[f.output]:f.output;y.node!==void 0&&(a.push(this.getDependency("node",g)),s.push(this.getDependency("accessor",p)),o.push(this.getDependency("accessor",m)),l.push(f),c.push(y))}return Promise.all([Promise.all(a),Promise.all(s),Promise.all(o),Promise.all(l),Promise.all(c)]).then(function(u){let h=u[0],d=u[1],f=u[2],y=u[3],g=u[4],p=[];for(let m=0,v=h.length;m<v;m++){let x=h[m],b=d[m],_=f[m],M=y[m],C=g[m];if(x===void 0)continue;x.updateMatrix&&x.updateMatrix();let S=r._createAnimationTracks(x,b,_,M,C);if(S)for(let w=0;w<S.length;w++)p.push(S[w])}return new Lo(n,void 0,p)})}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 a=r._getNodeRef(r.meshCache,i.mesh,n);return i.weights!==void 0&&a.traverse(function(s){if(s.isMesh)for(let o=0,l=i.weights.length;o<l;o++)s.morphTargetInfluences[o]=i.weights[o]}),a})}loadNode(e){let t=this.json,r=this,i=t.nodes[e],n=r._loadNodeShallow(e),a=[],s=i.children||[];for(let l=0,c=s.length;l<c;l++)a.push(r.getDependency("node",s[l]));let o=i.skin===void 0?Promise.resolve(null):r.getDependency("skin",i.skin);return Promise.all([n,Promise.all(a),o]).then(function(l){let c=l[0],u=l[1],h=l[2];h!==null&&c.traverse(function(d){d.isSkinnedMesh&&d.bind(h,m2)});for(let d=0,f=u.length;d<f;d++)c.add(u[d]);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],a=n.name?i.createUniqueName(n.name):"",s=[],o=i._invokeOne(function(l){return l.createNodeMesh&&l.createNodeMesh(e)});return o&&s.push(o),n.camera!==void 0&&s.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){s.push(l)}),this.nodeCache[e]=Promise.all(s).then(function(l){let c;if(n.isBone===!0?c=new vh:l.length>1?c=new jr:l.length===1?c=l[0]:c=new Ar,c!==l[0])for(let u=0,h=l.length;u<h;u++)c.add(l[u]);if(n.name&&(c.userData.name=n.name,c.name=a),xa(c,n),n.extensions&&Ns(r,c,n),n.matrix!==void 0){let u=new Jt;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 jr;r.name&&(n.name=i.createUniqueName(r.name)),xa(n,r),r.extensions&&Ns(t,n,r);let a=r.nodes||[],s=[];for(let o=0,l=a.length;o<l;o++)s.push(i.getDependency("node",a[o]));return Promise.all(s).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[h,d]of i.associations)(h instanceof xi||h instanceof ei)&&u.set(h,d);return c.traverse(h=>{let d=i.associations.get(h);d!=null&&u.set(h,d)}),u};return i.associations=l(n),n})}_createAnimationTracks(e,t,r,i,n){let a=[],s=e.name?e.name:e.uuid,o=[];za[n.path]===za.weights?e.traverse(function(h){h.morphTargetInfluences&&o.push(h.name?h.name:h.uuid)}):o.push(s);let l;switch(za[n.path]){case za.weights:l=vs;break;case za.rotation:l=xs;break;case za.position:case za.scale:l=_s;break;default:switch(r.itemSize){case 1:l=vs;break;case 2:case 3:default:l=_s;break}break}let c=i.interpolation!==void 0?c2[i.interpolation]:io,u=this._getArrayFromAccessor(r);for(let h=0,d=o.length;h<d;h++){let f=new l(o[h]+"."+za[n.path],t.array,u,c);i.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(f),a.push(f)}return a}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){let r=hm(t.constructor),i=new Float32Array(t.length);for(let n=0,a=t.length;n<a;n++)i[n]=t[n]*r;t=i}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(t){let r=this instanceof xs?l2:tx;return new r(this.times,this.values,this.getValueSize()/3,t)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}};function y2(e,t,r){let i=t.attributes,n=new Yr;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 ee(l[0],l[1],l[2]),new ee(c[0],c[1],c[2])),o.normalized){let u=hm(Bo[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 a=t.targets;if(a!==void 0){let o=new ee,l=new ee;for(let c=0,u=a.length;c<u;c++){let h=a[c];if(h.POSITION!==void 0){let d=r.json.accessors[h.POSITION],f=d.min,y=d.max;if(f!==void 0&&y!==void 0){if(l.setX(Math.max(Math.abs(f[0]),Math.abs(y[0]))),l.setY(Math.max(Math.abs(f[1]),Math.abs(y[1]))),l.setZ(Math.max(Math.abs(f[2]),Math.abs(y[2]))),d.normalized){let g=hm(Bo[d.componentType]);l.multiplyScalar(g)}o.max(l)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}n.expandByVector(o)}e.boundingBox=n;let s=new si;n.getCenter(s.center),s.radius=n.min.distanceTo(n.max)/2,e.boundingSphere=s}function nx(e,t,r){let i=t.attributes,n=[];function a(s,o){return r.getDependency("accessor",s).then(function(l){e.setAttribute(o,l)})}for(let s in i){let o=lm[s]||s.toLowerCase();o in e.attributes||n.push(a(i[s],o))}if(t.indices!==void 0&&!e.index){let s=r.getDependency("accessor",t.indices).then(function(o){e.setIndex(o)});n.push(s)}return _r.workingColorSpace!==Oi&&"COLOR_0"in i&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${_r.workingColorSpace}" not supported.`),xa(e,t),y2(e,t,r),Promise.all(n).then(function(){return t.targets!==void 0?h2(e,t.targets,r):e})}var vr=(e,t)=>()=>(t||(t={exports:{}},e(t.exports,t)),t.exports),ax=vr(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.VERSION=void 0,e.VERSION="9.0.1"}),Or=vr((e,t)=>{"use strict";var r=e&&e.__spreadArray||function(ne,_e){for(var oe=0,ce=_e.length,L=ne.length;oe<ce;oe++,L++)ne[L]=_e[oe];return ne};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(ne){return ne&&ne.length===0}e.isEmpty=i;function n(ne){return ne==null?[]:Object.keys(ne)}e.keys=n;function a(ne){for(var _e=[],oe=Object.keys(ne),ce=0;ce<oe.length;ce++)_e.push(ne[oe[ce]]);return _e}e.values=a;function s(ne,_e){for(var oe=[],ce=n(ne),L=0;L<ce.length;L++){var A=ce[L];oe.push(_e.call(null,ne[A],A))}return oe}e.mapValues=s;function o(ne,_e){for(var oe=[],ce=0;ce<ne.length;ce++)oe.push(_e.call(null,ne[ce],ce));return oe}e.map=o;function l(ne){for(var _e=[],oe=0;oe<ne.length;oe++){var ce=ne[oe];Array.isArray(ce)?_e=_e.concat(l(ce)):_e.push(ce)}return _e}e.flatten=l;function c(ne){return i(ne)?void 0:ne[0]}e.first=c;function u(ne){var _e=ne&&ne.length;return _e?ne[_e-1]:void 0}e.last=u;function h(ne,_e){if(Array.isArray(ne))for(var oe=0;oe<ne.length;oe++)_e.call(null,ne[oe],oe);else if(Q(ne))for(var ce=n(ne),oe=0;oe<ce.length;oe++){var L=ce[oe],A=ne[L];_e.call(null,A,L)}else throw Error("non exhaustive match")}e.forEach=h;function d(ne){return typeof ne=="string"}e.isString=d;function f(ne){return ne===void 0}e.isUndefined=f;function y(ne){return ne instanceof Function}e.isFunction=y;function g(ne,_e){return _e===void 0&&(_e=1),ne.slice(_e,ne.length)}e.drop=g;function p(ne,_e){return _e===void 0&&(_e=1),ne.slice(0,ne.length-_e)}e.dropRight=p;function m(ne,_e){var oe=[];if(Array.isArray(ne))for(var ce=0;ce<ne.length;ce++){var L=ne[ce];_e.call(null,L)&&oe.push(L)}return oe}e.filter=m;function v(ne,_e){return m(ne,function(oe){return!_e(oe)})}e.reject=v;function x(ne,_e){for(var oe=Object.keys(ne),ce={},L=0;L<oe.length;L++){var A=oe[L],O=ne[A];_e(O)&&(ce[A]=O)}return ce}e.pick=x;function b(ne,_e){return Q(ne)?ne.hasOwnProperty(_e):!1}e.has=b;function _(ne,_e){return S(ne,function(oe){return oe===_e})!==void 0}e.contains=_;function M(ne){for(var _e=[],oe=0;oe<ne.length;oe++)_e.push(ne[oe]);return _e}e.cloneArr=M;function C(ne){var _e={};for(var oe in ne)Object.prototype.hasOwnProperty.call(ne,oe)&&(_e[oe]=ne[oe]);return _e}e.cloneObj=C;function S(ne,_e){for(var oe=0;oe<ne.length;oe++){var ce=ne[oe];if(_e.call(null,ce))return ce}}e.find=S;function w(ne,_e){for(var oe=[],ce=0;ce<ne.length;ce++){var L=ne[ce];_e.call(null,L)&&oe.push(L)}return oe}e.findAll=w;function E(ne,_e,oe){for(var ce=Array.isArray(ne),L=ce?ne:a(ne),A=ce?[]:n(ne),O=oe,F=0;F<L.length;F++)O=_e.call(null,O,L[F],ce?F:A[F]);return O}e.reduce=E;function P(ne){return v(ne,function(_e){return _e==null})}e.compact=P;function N(ne,_e){_e===void 0&&(_e=function(ce){return ce});var oe=[];return E(ne,function(ce,L){var A=_e(L);return _(oe,A)?ce:(oe.push(A),ce.concat(L))},[])}e.uniq=N;function D(ne){for(var _e=[],oe=1;oe<arguments.length;oe++)_e[oe-1]=arguments[oe];var ce=[null],L=ce.concat(_e);return Function.bind.apply(ne,L)}e.partial=D;function B(ne){return Array.isArray(ne)}e.isArray=B;function J(ne){return ne instanceof RegExp}e.isRegExp=J;function Q(ne){return ne instanceof Object}e.isObject=Q;function j(ne,_e){for(var oe=0;oe<ne.length;oe++)if(!_e(ne[oe],oe))return!1;return!0}e.every=j;function k(ne,_e){return v(ne,function(oe){return _(_e,oe)})}e.difference=k;function H(ne,_e){for(var oe=0;oe<ne.length;oe++)if(_e(ne[oe]))return!0;return!1}e.some=H;function U(ne,_e){for(var oe=0;oe<ne.length;oe++)if(ne[oe]===_e)return oe;return-1}e.indexOf=U;function X(ne,_e){var oe=M(ne);return oe.sort(function(ce,L){return _e(ce)-_e(L)}),oe}e.sortBy=X;function W(ne,_e){if(ne.length!==_e.length)throw Error("can't zipObject with different number of keys and values!");for(var oe={},ce=0;ce<ne.length;ce++)oe[ne[ce]]=_e[ce];return oe}e.zipObject=W;function $(ne){for(var _e=[],oe=1;oe<arguments.length;oe++)_e[oe-1]=arguments[oe];for(var ce=0;ce<_e.length;ce++)for(var L=_e[ce],A=n(L),O=0;O<A.length;O++){var F=A[O];ne[F]=L[F]}return ne}e.assign=$;function G(ne){for(var _e=[],oe=1;oe<arguments.length;oe++)_e[oe-1]=arguments[oe];for(var ce=0;ce<_e.length;ce++)for(var L=_e[ce],A=n(L),O=0;O<A.length;O++){var F=A[O];b(ne,F)||(ne[F]=L[F])}return ne}e.assignNoOverwrite=G;function T(){for(var ne=[],_e=0;_e<arguments.length;_e++)ne[_e]=arguments[_e];return G.apply(void 0,r([{}],ne))}e.defaults=T;function I(ne,_e){var oe={};return h(ne,function(ce){var L=_e(ce),A=oe[L];A?A.push(ce):oe[L]=[ce]}),oe}e.groupBy=I;function V(ne,_e){for(var oe=C(ne),ce=n(_e),L=0;L<ce.length;L++){var A=ce[L],O=_e[A];oe[A]=O}return oe}e.merge=V;function K(){}e.NOOP=K;function ie(ne){return ne}e.IDENTITY=ie;function le(ne){for(var _e=[],oe=0;oe<ne.length;oe++){var ce=ne[oe];_e.push(ce!==void 0?ce:void 0)}return _e}e.packArray=le;function ae(ne){console&&console.error&&console.error("Error: "+ne)}e.PRINT_ERROR=ae;function de(ne){console&&console.warn&&console.warn("Warning: "+ne)}e.PRINT_WARNING=de;function z(){return typeof Map=="function"}e.isES2015MapSupported=z;function me(ne){return ne[ne.length-1]}e.peek=me;function we(ne){var _e=new Date().getTime(),oe=ne(),ce=new Date().getTime(),L=ce-_e;return{time:L,value:oe}}e.timer=we;function He(ne){function _e(){}_e.prototype=ne;var oe=new _e;function ce(){return typeof oe.bar}return ce(),ce(),ne}e.toFastProperties=He}),dm=vr((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(p){this.idx=p.idx,this.input=p.input,this.groupIdx=p.groupIdx},r.prototype.pattern=function(p){this.idx=0,this.input=p,this.groupIdx=0,this.consumeChar("/");var m=this.disjunction();this.consumeChar("/");for(var v={type:"Flags",loc:{begin:this.idx,end:p.length},global:!1,ignoreCase:!1,multiLine:!1,unicode:!1,sticky:!1};this.isRegExpFlag();)switch(this.popChar()){case"g":l(v,"global");break;case"i":l(v,"ignoreCase");break;case"m":l(v,"multiLine");break;case"u":l(v,"unicode");break;case"y":l(v,"sticky");break}if(this.idx!==this.input.length)throw Error("Redundant input: "+this.input.substring(this.idx));return{type:"Pattern",flags:v,value:m,loc:this.loc(0)}},r.prototype.disjunction=function(){var p=[],m=this.idx;for(p.push(this.alternative());this.peekChar()==="|";)this.consumeChar("|"),p.push(this.alternative());return{type:"Disjunction",value:p,loc:this.loc(m)}},r.prototype.alternative=function(){for(var p=[],m=this.idx;this.isTerm();)p.push(this.term());return{type:"Alternative",value:p,loc:this.loc(m)}},r.prototype.term=function(){return this.isAssertion()?this.assertion():this.atom()},r.prototype.assertion=function(){var p=this.idx;switch(this.popChar()){case"^":return{type:"StartAnchor",loc:this.loc(p)};case"$":return{type:"EndAnchor",loc:this.loc(p)};case"\\":switch(this.popChar()){case"b":return{type:"WordBoundary",loc:this.loc(p)};case"B":return{type:"NonWordBoundary",loc:this.loc(p)}}throw Error("Invalid Assertion Escape");case"(":this.consumeChar("?");var m;switch(this.popChar()){case"=":m="Lookahead";break;case"!":m="NegativeLookahead";break}c(m);var v=this.disjunction();return this.consumeChar(")"),{type:m,value:v,loc:this.loc(p)}}u()},r.prototype.quantifier=function(p){var m,v=this.idx;switch(this.popChar()){case"*":m={atLeast:0,atMost:1/0};break;case"+":m={atLeast:1,atMost:1/0};break;case"?":m={atLeast:0,atMost:1};break;case"{":var x=this.integerIncludingZero();switch(this.popChar()){case"}":m={atLeast:x,atMost:x};break;case",":var b;this.isDigit()?(b=this.integerIncludingZero(),m={atLeast:x,atMost:b}):m={atLeast:x,atMost:1/0},this.consumeChar("}");break}if(p===!0&&m===void 0)return;c(m);break}if(!(p===!0&&m===void 0))return c(m),this.peekChar(0)==="?"?(this.consumeChar("?"),m.greedy=!1):m.greedy=!0,m.type="Quantifier",m.loc=this.loc(v),m},r.prototype.atom=function(){var p,m=this.idx;switch(this.peekChar()){case".":p=this.dotAll();break;case"\\":p=this.atomEscape();break;case"[":p=this.characterClass();break;case"(":p=this.group();break}return p===void 0&&this.isPatternCharacter()&&(p=this.patternCharacter()),c(p),p.loc=this.loc(m),this.isQuantifier()&&(p.quantifier=this.quantifier()),p},r.prototype.dotAll=function(){return this.consumeChar("."),{type:"Set",complement:!0,value:[s(`
`),s("\r"),s("\u2028"),s("\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 p=this.positiveInteger();return{type:"GroupBackReference",value:p}},r.prototype.characterClassEscape=function(){var p,m=!1;switch(this.popChar()){case"d":p=d;break;case"D":p=d,m=!0;break;case"s":p=y;break;case"S":p=y,m=!0;break;case"w":p=f;break;case"W":p=f,m=!0;break}return c(p),{type:"Set",value:p,complement:m}},r.prototype.controlEscapeAtom=function(){var p;switch(this.popChar()){case"f":p=s("\f");break;case"n":p=s(`
`);break;case"r":p=s("\r");break;case"t":p=s(" ");break;case"v":p=s("\v");break}return c(p),{type:"Character",value:p}},r.prototype.controlLetterEscapeAtom=function(){this.consumeChar("c");var p=this.popChar();if(/[a-zA-Z]/.test(p)===!1)throw Error("Invalid ");var m=p.toUpperCase().charCodeAt(0)-64;return{type:"Character",value:m}},r.prototype.nulCharacterAtom=function(){return this.consumeChar("0"),{type:"Character",value:s("\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 p=this.popChar();return{type:"Character",value:s(p)}},r.prototype.classPatternCharacterAtom=function(){switch(this.peekChar()){case`
`:case"\r":case"\u2028":case"\u2029":case"\\":case"]":throw Error("TBD");default:var p=this.popChar();return{type:"Character",value:s(p)}}},r.prototype.characterClass=function(){var p=[],m=!1;for(this.consumeChar("["),this.peekChar(0)==="^"&&(this.consumeChar("^"),m=!0);this.isClassAtom();){var v=this.classAtom(),x=v.type==="Character";if(x&&this.isRangeDash()){this.consumeChar("-");var b=this.classAtom(),_=b.type==="Character";if(_){if(b.value<v.value)throw Error("Range out of order in character class");p.push({from:v.value,to:b.value})}else o(v.value,p),p.push(s("-")),o(b.value,p)}else o(v.value,p)}return this.consumeChar("]"),{type:"Set",complement:m,value:p}},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:s("\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 p=!0;switch(this.consumeChar("("),this.peekChar(0)){case"?":this.consumeChar("?"),this.consumeChar(":"),p=!1;break;default:this.groupIdx++;break}var m=this.disjunction();this.consumeChar(")");var v={type:"Group",capturing:p,value:m};return p&&(v.idx=this.groupIdx),v},r.prototype.positiveInteger=function(){var p=this.popChar();if(a.test(p)===!1)throw Error("Expecting a positive integer");for(;n.test(this.peekChar(0));)p+=this.popChar();return parseInt(p,10)},r.prototype.integerIncludingZero=function(){var p=this.popChar();if(n.test(p)===!1)throw Error("Expecting an integer");for(;n.test(this.peekChar(0));)p+=this.popChar();return parseInt(p,10)},r.prototype.patternCharacter=function(){var p=this.popChar();switch(p){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:s(p)}}},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(p){switch(p===void 0&&(p=0),this.peekChar(p)){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 p=this.saveState();try{return this.quantifier(!0)!==void 0}catch{return!1}finally{this.restoreState(p)}},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(p){for(var m="",v=0;v<p;v++){var x=this.popChar();if(i.test(x)===!1)throw Error("Expecting a HexDecimal digits");m+=x}var b=parseInt(m,16);return{type:"Character",value:b}},r.prototype.peekChar=function(p){return p===void 0&&(p=0),this.input[this.idx+p]},r.prototype.popChar=function(){var p=this.peekChar(0);return this.consumeChar(),p},r.prototype.consumeChar=function(p){if(p!==void 0&&this.input[this.idx]!==p)throw Error("Expected: '"+p+"' 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(p){return{begin:p,end:this.idx}};var i=/[0-9a-fA-F]/,n=/[0-9]/,a=/[1-9]/;function s(p){return p.charCodeAt(0)}function o(p,m){p.length!==void 0?p.forEach(function(v){m.push(v)}):m.push(p)}function l(p,m){if(p[m]===!0)throw"duplicate flag "+m;p[m]=!0}function c(p){if(p===void 0)throw Error("Internal Error - Should never get here!")}function u(){throw Error("Internal Error - Should never get here!")}var h,d=[];for(h=s("0");h<=s("9");h++)d.push(h);var f=[s("_")].concat(d);for(h=s("a");h<=s("z");h++)f.push(h);for(h=s("A");h<=s("Z");h++)f.push(h);var y=[s(" "),s("\f"),s(`
`),s("\r"),s(" "),s("\v"),s(" "),s("\xA0"),s("\u1680"),s("\u2000"),s("\u2001"),s("\u2002"),s("\u2003"),s("\u2004"),s("\u2005"),s("\u2006"),s("\u2007"),s("\u2008"),s("\u2009"),s("\u200A"),s("\u2028"),s("\u2029"),s("\u202F"),s("\u205F"),s("\u3000"),s("\uFEFF")];function g(){}return g.prototype.visitChildren=function(p){for(var m in p){var v=p[m];p.hasOwnProperty(m)&&(v.type!==void 0?this.visit(v):Array.isArray(v)&&v.forEach(function(x){this.visit(x)},this))}},g.prototype.visit=function(p){switch(p.type){case"Pattern":this.visitPattern(p);break;case"Flags":this.visitFlags(p);break;case"Disjunction":this.visitDisjunction(p);break;case"Alternative":this.visitAlternative(p);break;case"StartAnchor":this.visitStartAnchor(p);break;case"EndAnchor":this.visitEndAnchor(p);break;case"WordBoundary":this.visitWordBoundary(p);break;case"NonWordBoundary":this.visitNonWordBoundary(p);break;case"Lookahead":this.visitLookahead(p);break;case"NegativeLookahead":this.visitNegativeLookahead(p);break;case"Character":this.visitCharacter(p);break;case"Set":this.visitSet(p);break;case"Group":this.visitGroup(p);break;case"GroupBackReference":this.visitGroupBackReference(p);break;case"Quantifier":this.visitQuantifier(p);break}this.visitChildren(p)},g.prototype.visitPattern=function(p){},g.prototype.visitFlags=function(p){},g.prototype.visitDisjunction=function(p){},g.prototype.visitAlternative=function(p){},g.prototype.visitStartAnchor=function(p){},g.prototype.visitEndAnchor=function(p){},g.prototype.visitWordBoundary=function(p){},g.prototype.visitNonWordBoundary=function(p){},g.prototype.visitLookahead=function(p){},g.prototype.visitNegativeLookahead=function(p){},g.prototype.visitCharacter=function(p){},g.prototype.visitSet=function(p){},g.prototype.visitGroup=function(p){},g.prototype.visitGroupBackReference=function(p){},g.prototype.visitQuantifier=function(p){},{RegExpParser:r,BaseRegExpVisitor:g,VERSION:"0.5.0"}})}),pm=vr(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.clearRegExpParserCache=e.getRegExpAst=void 0;var t=dm(),r={},i=new t.RegExpParser;function n(s){var o=s.toString();if(r.hasOwnProperty(o))return r[o];var l=i.pattern(o);return r[o]=l,l}e.getRegExpAst=n;function a(){r={}}e.clearRegExpParserCache=a}),v2=vr(e=>{"use strict";var t=e&&e.__extends||(function(){var g=function(p,m){return g=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(v,x){v.__proto__=x}||function(v,x){for(var b in x)Object.prototype.hasOwnProperty.call(x,b)&&(v[b]=x[b])},g(p,m)};return function(p,m){if(typeof m!="function"&&m!==null)throw new TypeError("Class extends value "+String(m)+" is not a constructor or null");g(p,m);function v(){this.constructor=p}p.prototype=m===null?Object.create(m):(v.prototype=m.prototype,new v)}})();Object.defineProperty(e,"__esModule",{value:!0}),e.canMatchCharCode=e.firstCharOptimizedIndices=e.getOptimizedStartCodesIndices=e.failedOptimizationPrefixMsg=void 0;var r=dm(),i=Or(),n=pm(),a=sx(),s="Complement Sets are not supported for first char optimization";e.failedOptimizationPrefixMsg=`Unable to use "first char" lexer optimizations:
`;function o(g,p){p===void 0&&(p=!1);try{var m=n.getRegExpAst(g),v=l(m.value,{},m.flags.ignoreCase);return v}catch(b){if(b.message===s)p&&i.PRINT_WARNING(""+e.failedOptimizationPrefixMsg+(" Unable to optimize: < "+g.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 x="";p&&(x=`
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: < "+g.toString()+` >
`)+(" Using the regexp-to-ast library version: "+r.VERSION+`
`)+" Please open an issue at: https://github.com/bd82/regexp-to-ast/issues"+x)}}return[]}e.getOptimizedStartCodesIndices=o;function l(g,p,m){switch(g.type){case"Disjunction":for(var v=0;v<g.value.length;v++)l(g.value[v],p,m);break;case"Alternative":for(var x=g.value,v=0;v<x.length;v++){var b=x[v];switch(b.type){case"EndAnchor":case"GroupBackReference":case"Lookahead":case"NegativeLookahead":case"StartAnchor":case"WordBoundary":case"NonWordBoundary":continue}var _=b;switch(_.type){case"Character":c(_.value,p,m);break;case"Set":if(_.complement===!0)throw Error(s);i.forEach(_.value,function(S){if(typeof S=="number")c(S,p,m);else{var w=S;if(m===!0)for(var E=w.from;E<=w.to;E++)c(E,p,m);else{for(var E=w.from;E<=w.to&&E<a.minOptimizationVal;E++)c(E,p,m);if(w.to>=a.minOptimizationVal)for(var P=w.from>=a.minOptimizationVal?w.from:a.minOptimizationVal,N=w.to,D=a.charCodeToOptimizedIndex(P),B=a.charCodeToOptimizedIndex(N),J=D;J<=B;J++)p[J]=J}}});break;case"Group":l(_.value,p,m);break;default:throw Error("Non Exhaustive Match")}var M=_.quantifier!==void 0&&_.quantifier.atLeast===0;if(_.type==="Group"&&d(_)===!1||_.type!=="Group"&&M===!1)break}break;default:throw Error("non exhaustive match!")}return i.values(p)}e.firstCharOptimizedIndices=l;function c(g,p,m){var v=a.charCodeToOptimizedIndex(g);p[v]=v,m===!0&&u(g,p)}function u(g,p){var m=String.fromCharCode(g),v=m.toUpperCase();if(v!==m){var x=a.charCodeToOptimizedIndex(v.charCodeAt(0));p[x]=x}else{var b=m.toLowerCase();if(b!==m){var x=a.charCodeToOptimizedIndex(b.charCodeAt(0));p[x]=x}}}function h(g,p){return i.find(g.value,function(m){if(typeof m=="number")return i.contains(p,m);var v=m;return i.find(p,function(x){return v.from<=x&&x<=v.to})!==void 0})}function d(g){return g.quantifier&&g.quantifier.atLeast===0?!0:g.value?i.isArray(g.value)?i.every(g.value,d):d(g.value):!1}var f=(function(g){t(p,g);function p(m){var v=g.call(this)||this;return v.targetCharCodes=m,v.found=!1,v}return p.prototype.visitChildren=function(m){if(this.found!==!0){switch(m.type){case"Lookahead":this.visitLookahead(m);return;case"NegativeLookahead":this.visitNegativeLookahead(m);return}g.prototype.visitChildren.call(this,m)}},p.prototype.visitCharacter=function(m){i.contains(this.targetCharCodes,m.value)&&(this.found=!0)},p.prototype.visitSet=function(m){m.complement?h(m,this.targetCharCodes)===void 0&&(this.found=!0):h(m,this.targetCharCodes)!==void 0&&(this.found=!0)},p})(r.BaseRegExpVisitor);function y(g,p){if(p instanceof RegExp){var m=n.getRegExpAst(p),v=new f(g);return v.visit(m),v.found}else return i.find(p,function(x){return i.contains(g,x.charCodeAt(0))})!==void 0}e.canMatchCharCode=y}),sx=vr(e=>{"use strict";var t=e&&e.__extends||(function(){var T=function(I,V){return T=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(K,ie){K.__proto__=ie}||function(K,ie){for(var le in ie)Object.prototype.hasOwnProperty.call(ie,le)&&(K[le]=ie[le])},T(I,V)};return function(I,V){if(typeof V!="function"&&V!==null)throw new TypeError("Class extends value "+String(V)+" is not a constructor or null");T(I,V);function K(){this.constructor=I}I.prototype=V===null?Object.create(V):(K.prototype=V.prototype,new K)}})();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=dm(),i=hd(),n=Or(),a=v2(),s=pm(),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(T,I){I=n.defaults(I,{useSticky:e.SUPPORT_STICKY,debug:!1,safeMode:!1,positionTracking:"full",lineTerminatorCharacters:["\r",`
`],tracer:function(O,F){return F()}});var V=I.tracer;V("initCharCodeToOptimizedIndexMap",function(){G()});var K;V("Reject Lexer.NA",function(){K=n.reject(T,function(O){return O[o]===i.Lexer.NA})});var ie=!1,le;V("Transform Patterns",function(){ie=!1,le=n.map(K,function(O){var F=O[o];if(n.isRegExp(F)){var Y=F.source;return Y.length===1&&Y!=="^"&&Y!=="$"&&Y!=="."&&!F.ignoreCase?Y:Y.length===2&&Y[0]==="\\"&&!n.contains(["d","D","s","S","t","r","n","t","0","c","b","B","f","v","w","W"],Y[1])?Y[1]:I.useSticky?N(F):P(F)}else{if(n.isFunction(F))return ie=!0,{exec:F};if(n.has(F,"exec"))return ie=!0,F;if(typeof F=="string"){if(F.length===1)return F;var re=F.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),ue=new RegExp(re);return I.useSticky?N(ue):P(ue)}else throw Error("non exhaustive match")}})});var ae,de,z,me,we;V("misc mapping",function(){ae=n.map(K,function(O){return O.tokenTypeIdx}),de=n.map(K,function(O){var F=O.GROUP;if(F!==i.Lexer.SKIPPED){if(n.isString(F))return F;if(n.isUndefined(F))return!1;throw Error("non exhaustive match")}}),z=n.map(K,function(O){var F=O.LONGER_ALT;if(F){var Y=n.indexOf(K,F);return Y}}),me=n.map(K,function(O){return O.PUSH_MODE}),we=n.map(K,function(O){return n.has(O,"POP_MODE")})});var He;V("Line Terminator Handling",function(){var O=U(I.lineTerminatorCharacters);He=n.map(K,function(F){return!1}),I.positionTracking!=="onlyOffset"&&(He=n.map(K,function(F){if(n.has(F,"LINE_BREAKS"))return F.LINE_BREAKS;if(k(F,O)===!1)return a.canMatchCharCode(O,F.PATTERN)}))});var ne,_e,oe,ce;V("Misc Mapping #2",function(){ne=n.map(K,Q),_e=n.map(le,j),oe=n.reduce(K,function(O,F){var Y=F.GROUP;return n.isString(Y)&&Y!==i.Lexer.SKIPPED&&(O[Y]=[]),O},{}),ce=n.map(le,function(O,F){return{pattern:le[F],longerAlt:z[F],canLineTerminator:He[F],isCustom:ne[F],short:_e[F],group:de[F],push:me[F],pop:we[F],tokenTypeIdx:ae[F],tokenType:K[F]}})});var L=!0,A=[];return I.safeMode||V("First Char Optimization",function(){A=n.reduce(K,function(O,F,Y){if(typeof F.PATTERN=="string"){var re=F.PATTERN.charCodeAt(0),ue=$(re);X(O,ue,ce[Y])}else if(n.isArray(F.START_CHARS_HINT)){var se;n.forEach(F.START_CHARS_HINT,function(Pe){var Ce=typeof Pe=="string"?Pe.charCodeAt(0):Pe,je=$(Ce);se!==je&&(se=je,X(O,je,ce[Y]))})}else if(n.isRegExp(F.PATTERN))if(F.PATTERN.unicode)L=!1,I.ensureOptimizations&&n.PRINT_ERROR(""+a.failedOptimizationPrefixMsg+(" Unable to analyze < "+F.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 pe=a.getOptimizedStartCodesIndices(F.PATTERN,I.ensureOptimizations);n.isEmpty(pe)&&(L=!1),n.forEach(pe,function(Pe){X(O,Pe,ce[Y])})}else I.ensureOptimizations&&n.PRINT_ERROR(""+a.failedOptimizationPrefixMsg+(" TokenType: <"+F.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`),L=!1;return O},[])}),V("ArrayPacking",function(){A=n.packArray(A)}),{emptyGroups:oe,patternIdxToConfig:ce,charCodeToPatternIdxToConfig:A,hasCustom:ie,canBeOptimized:L}}e.analyzeTokenTypes=u;function h(T,I){var V=[],K=f(T);V=V.concat(K.errors);var ie=y(K.valid),le=ie.valid;return V=V.concat(ie.errors),V=V.concat(d(le)),V=V.concat(M(le)),V=V.concat(C(le,I)),V=V.concat(S(le)),V}e.validatePatterns=h;function d(T){var I=[],V=n.filter(T,function(K){return n.isRegExp(K[o])});return I=I.concat(p(V)),I=I.concat(x(V)),I=I.concat(b(V)),I=I.concat(_(V)),I=I.concat(m(V)),I}function f(T){var I=n.filter(T,function(ie){return!n.has(ie,o)}),V=n.map(I,function(ie){return{message:"Token Type: ->"+ie.name+"<- missing static 'PATTERN' property",type:i.LexerDefinitionErrorType.MISSING_PATTERN,tokenTypes:[ie]}}),K=n.difference(T,I);return{errors:V,valid:K}}e.findMissingPatterns=f;function y(T){var I=n.filter(T,function(ie){var le=ie[o];return!n.isRegExp(le)&&!n.isFunction(le)&&!n.has(le,"exec")&&!n.isString(le)}),V=n.map(I,function(ie){return{message:"Token Type: ->"+ie.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:[ie]}}),K=n.difference(T,I);return{errors:V,valid:K}}e.findInvalidPatterns=y;var g=/[^\\][\$]/;function p(T){var I=(function(ie){t(le,ie);function le(){var ae=ie!==null&&ie.apply(this,arguments)||this;return ae.found=!1,ae}return le.prototype.visitEndAnchor=function(ae){this.found=!0},le})(r.BaseRegExpVisitor),V=n.filter(T,function(ie){var le=ie[o];try{var ae=s.getRegExpAst(le),de=new I;return de.visit(ae),de.found}catch{return g.test(le.source)}}),K=n.map(V,function(ie){return{message:`Unexpected RegExp Anchor Error:
Token Type: ->`+ie.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:[ie]}});return K}e.findEndOfInputAnchor=p;function m(T){var I=n.filter(T,function(K){var ie=K[o];return ie.test("")}),V=n.map(I,function(K){return{message:"Token Type: ->"+K.name+"<- static 'PATTERN' must not match an empty string",type:i.LexerDefinitionErrorType.EMPTY_MATCH_PATTERN,tokenTypes:[K]}});return V}e.findEmptyMatchRegExps=m;var v=/[^\\[][\^]|^\^/;function x(T){var I=(function(ie){t(le,ie);function le(){var ae=ie!==null&&ie.apply(this,arguments)||this;return ae.found=!1,ae}return le.prototype.visitStartAnchor=function(ae){this.found=!0},le})(r.BaseRegExpVisitor),V=n.filter(T,function(ie){var le=ie[o];try{var ae=s.getRegExpAst(le),de=new I;return de.visit(ae),de.found}catch{return v.test(le.source)}}),K=n.map(V,function(ie){return{message:`Unexpected RegExp Anchor Error:
Token Type: ->`+ie.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:[ie]}});return K}e.findStartOfInputAnchor=x;function b(T){var I=n.filter(T,function(K){var ie=K[o];return ie instanceof RegExp&&(ie.multiline||ie.global)}),V=n.map(I,function(K){return{message:"Token Type: ->"+K.name+"<- static 'PATTERN' may NOT contain global('g') or multiline('m')",type:i.LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND,tokenTypes:[K]}});return V}e.findUnsupportedFlags=b;function _(T){var I=[],V=n.map(T,function(le){return n.reduce(T,function(ae,de){return le.PATTERN.source===de.PATTERN.source&&!n.contains(I,de)&&de.PATTERN!==i.Lexer.NA&&(I.push(de),ae.push(de)),ae},[])});V=n.compact(V);var K=n.filter(V,function(le){return le.length>1}),ie=n.map(K,function(le){var ae=n.map(le,function(z){return z.name}),de=n.first(le).PATTERN;return{message:"The same RegExp pattern ->"+de+"<-"+("has been used in all of the following Token Types: "+ae.join(", ")+" <-"),type:i.LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND,tokenTypes:le}});return ie}e.findDuplicatePatterns=_;function M(T){var I=n.filter(T,function(K){if(!n.has(K,"GROUP"))return!1;var ie=K.GROUP;return ie!==i.Lexer.SKIPPED&&ie!==i.Lexer.NA&&!n.isString(ie)}),V=n.map(I,function(K){return{message:"Token Type: ->"+K.name+"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",type:i.LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND,tokenTypes:[K]}});return V}e.findInvalidGroupType=M;function C(T,I){var V=n.filter(T,function(ie){return ie.PUSH_MODE!==void 0&&!n.contains(I,ie.PUSH_MODE)}),K=n.map(V,function(ie){var le="Token Type: ->"+ie.name+"<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->"+ie.PUSH_MODE+"<-which does not exist";return{message:le,type:i.LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST,tokenTypes:[ie]}});return K}e.findModesThatDoNotExist=C;function S(T){var I=[],V=n.reduce(T,function(K,ie,le){var ae=ie.PATTERN;return ae===i.Lexer.NA||(n.isString(ae)?K.push({str:ae,idx:le,tokenType:ie}):n.isRegExp(ae)&&E(ae)&&K.push({str:ae.source,idx:le,tokenType:ie})),K},[]);return n.forEach(T,function(K,ie){n.forEach(V,function(le){var ae=le.str,de=le.idx,z=le.tokenType;if(ie<de&&w(ae,K.PATTERN)){var me="Token: ->"+z.name+`<- can never be matched.
`+("Because it appears AFTER the Token Type ->"+K.name+"<-")+`in the lexer's definition.
See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;I.push({message:me,type:i.LexerDefinitionErrorType.UNREACHABLE_PATTERN,tokenTypes:[K,z]})}})}),I}e.findUnreachablePatterns=S;function w(T,I){if(n.isRegExp(I)){var V=I.exec(T);return V!==null&&V.index===0}else{if(n.isFunction(I))return I(T,0,[],{});if(n.has(I,"exec"))return I.exec(T,0,[],{});if(typeof I=="string")return I===T;throw Error("non exhaustive match")}}function E(T){var I=[".","\\","[","]","|","^","$","(",")","?","*","+","{"];return n.find(I,function(V){return T.source.indexOf(V)!==-1})===void 0}function P(T){var I=T.ignoreCase?"i":"";return new RegExp("^(?:"+T.source+")",I)}e.addStartOfInput=P;function N(T){var I=T.ignoreCase?"iy":"y";return new RegExp(""+T.source,I)}e.addStickyFlag=N;function D(T,I,V){var K=[];return n.has(T,e.DEFAULT_MODE)||K.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(T,e.MODES)||K.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(T,e.MODES)&&n.has(T,e.DEFAULT_MODE)&&!n.has(T.modes,T.defaultMode)&&K.push({message:"A MultiMode Lexer cannot be initialized with a "+e.DEFAULT_MODE+": <"+T.defaultMode+`>which does not exist
`,type:i.LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST}),n.has(T,e.MODES)&&n.forEach(T.modes,function(ie,le){n.forEach(ie,function(ae,de){n.isUndefined(ae)&&K.push({message:"A Lexer cannot be initialized using an undefined Token Type. Mode:"+("<"+le+"> at index: <"+de+`>
`),type:i.LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED})})}),K}e.performRuntimeChecks=D;function B(T,I,V){var K=[],ie=!1,le=n.compact(n.flatten(n.mapValues(T.modes,function(z){return z}))),ae=n.reject(le,function(z){return z[o]===i.Lexer.NA}),de=U(V);return I&&n.forEach(ae,function(z){var me=k(z,de);if(me!==!1){var we=H(z,me),He={message:we,type:me.issue,tokenType:z};K.push(He)}else n.has(z,"LINE_BREAKS")?z.LINE_BREAKS===!0&&(ie=!0):a.canMatchCharCode(de,z.PATTERN)&&(ie=!0)}),I&&!ie&&K.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}),K}e.performWarningRuntimeChecks=B;function J(T){var I={},V=n.keys(T);return n.forEach(V,function(K){var ie=T[K];if(n.isArray(ie))I[K]=[];else throw Error("non exhaustive match")}),I}e.cloneEmptyGroups=J;function Q(T){var I=T.PATTERN;if(n.isRegExp(I))return!1;if(n.isFunction(I)||n.has(I,"exec"))return!0;if(n.isString(I))return!1;throw Error("non exhaustive match")}e.isCustomPattern=Q;function j(T){return n.isString(T)&&T.length===1?T.charCodeAt(0):!1}e.isShortPattern=j,e.LineTerminatorOptimizedTester={test:function(T){for(var I=T.length,V=this.lastIndex;V<I;V++){var K=T.charCodeAt(V);if(K===10)return this.lastIndex=V+1,!0;if(K===13)return T.charCodeAt(V+1)===10?this.lastIndex=V+2:this.lastIndex=V+1,!0}return!1},lastIndex:0};function k(T,I){if(n.has(T,"LINE_BREAKS"))return!1;if(n.isRegExp(T.PATTERN)){try{a.canMatchCharCode(I,T.PATTERN)}catch(V){return{issue:i.LexerDefinitionErrorType.IDENTIFY_TERMINATOR,errMsg:V.message}}return!1}else{if(n.isString(T.PATTERN))return!1;if(Q(T))return{issue:i.LexerDefinitionErrorType.CUSTOM_LINE_BREAK};throw Error("non exhaustive match")}}function H(T,I){if(I.issue===i.LexerDefinitionErrorType.IDENTIFY_TERMINATOR)return`Warning: unable to identify line terminator usage in pattern.
`+(" The problem is in the <"+T.name+`> Token Type
`)+(" Root cause: "+I.errMsg+`.
`)+" For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR";if(I.issue===i.LexerDefinitionErrorType.CUSTOM_LINE_BREAK)return`Warning: A Custom Token Pattern should specify the <line_breaks> option.
`+(" The problem is in the <"+T.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=H;function U(T){var I=n.map(T,function(V){return n.isString(V)&&V.length>0?V.charCodeAt(0):V});return I}function X(T,I,V){T[I]===void 0?T[I]=[V]:T[I].push(V)}e.minOptimizationVal=256;var W=[];function $(T){return T<e.minOptimizationVal?T:W[T]}e.charCodeToOptimizedIndex=$;function G(){if(n.isEmpty(W)){W=new Array(65536);for(var T=0;T<65536;T++)W[T]=T>255?255+~~(T/255):T}}}),cc=vr(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=Or();function r(g,p){var m=g.tokenTypeIdx;return m===p.tokenTypeIdx?!0:p.isParent===!0&&p.categoryMatchesMap[m]===!0}e.tokenStructuredMatcher=r;function i(g,p){return g.tokenTypeIdx===p.tokenTypeIdx}e.tokenStructuredMatcherNoCategories=i,e.tokenShortNameIdx=1,e.tokenIdxToClass={};function n(g){var p=a(g);s(p),l(p),o(p),t.forEach(p,function(m){m.isParent=m.categoryMatches.length>0})}e.augmentTokenTypes=n;function a(g){for(var p=t.cloneArr(g),m=g,v=!0;v;){m=t.compact(t.flatten(t.map(m,function(b){return b.CATEGORIES})));var x=t.difference(m,p);p=p.concat(x),t.isEmpty(x)?v=!1:m=x}return p}e.expandCategories=a;function s(g){t.forEach(g,function(p){u(p)||(e.tokenIdxToClass[e.tokenShortNameIdx]=p,p.tokenTypeIdx=e.tokenShortNameIdx++),h(p)&&!t.isArray(p.CATEGORIES)&&(p.CATEGORIES=[p.CATEGORIES]),h(p)||(p.CATEGORIES=[]),d(p)||(p.categoryMatches=[]),f(p)||(p.categoryMatchesMap={})})}e.assignTokenDefaultProps=s;function o(g){t.forEach(g,function(p){p.categoryMatches=[],t.forEach(p.categoryMatchesMap,function(m,v){p.categoryMatches.push(e.tokenIdxToClass[v].tokenTypeIdx)})})}e.assignCategoriesTokensProp=o;function l(g){t.forEach(g,function(p){c([],p)})}e.assignCategoriesMapProp=l;function c(g,p){t.forEach(g,function(m){p.categoryMatchesMap[m.tokenTypeIdx]=!0}),t.forEach(p.CATEGORIES,function(m){var v=g.concat(p);t.contains(v,m)||c(v,m)})}e.singleAssignCategoriesToksMap=c;function u(g){return t.has(g,"tokenTypeIdx")}e.hasShortKeyProperty=u;function h(g){return t.has(g,"CATEGORIES")}e.hasCategoriesProperty=h;function d(g){return t.has(g,"categoryMatches")}e.hasExtendingTokensTypesProperty=d;function f(g){return t.has(g,"categoryMatchesMap")}e.hasExtendingTokensTypesMapProperty=f;function y(g){return t.has(g,"tokenTypeIdx")}e.isTokenType=y}),ox=vr(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,a){return"unexpected character: ->"+t.charAt(r)+"<- at offset: "+r+","+(" skipped "+i+" characters.")}}}),hd=vr(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.Lexer=e.LexerDefinitionErrorType=void 0;var t=sx(),r=Or(),i=cc(),n=ox(),a=pm(),s;(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"})(s=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,h){var d=this;if(h===void 0&&(h=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 h=="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,h);var f=this.config.traceInitPerf;f===!0?(this.traceInitMaxIdent=1/0,this.traceInitPerf=!0):typeof f=="number"&&(this.traceInitMaxIdent=f,this.traceInitPerf=!0),this.traceInitIndent=-1,this.TRACE_INIT("Lexer Constructor",function(){var y,g=!0;d.TRACE_INIT("Lexer Config handling",function(){if(d.config.lineTerminatorsPattern===o.lineTerminatorsPattern)d.config.lineTerminatorsPattern=t.LineTerminatorOptimizedTester;else if(d.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(h.safeMode&&h.ensureOptimizations)throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.');d.trackStartLines=/full|onlyStart/i.test(d.config.positionTracking),d.trackEndLines=/full/i.test(d.config.positionTracking),r.isArray(u)?(y={modes:{}},y.modes[t.DEFAULT_MODE]=r.cloneArr(u),y[t.DEFAULT_MODE]=t.DEFAULT_MODE):(g=!1,y=r.cloneObj(u))}),d.config.skipValidations===!1&&(d.TRACE_INIT("performRuntimeChecks",function(){d.lexerDefinitionErrors=d.lexerDefinitionErrors.concat(t.performRuntimeChecks(y,d.trackStartLines,d.config.lineTerminatorCharacters))}),d.TRACE_INIT("performWarningRuntimeChecks",function(){d.lexerDefinitionWarning=d.lexerDefinitionWarning.concat(t.performWarningRuntimeChecks(y,d.trackStartLines,d.config.lineTerminatorCharacters))})),y.modes=y.modes?y.modes:{},r.forEach(y.modes,function(x,b){y.modes[b]=r.reject(x,function(_){return r.isUndefined(_)})});var p=r.keys(y.modes);if(r.forEach(y.modes,function(x,b){d.TRACE_INIT("Mode: <"+b+"> processing",function(){if(d.modes.push(b),d.config.skipValidations===!1&&d.TRACE_INIT("validatePatterns",function(){d.lexerDefinitionErrors=d.lexerDefinitionErrors.concat(t.validatePatterns(x,p))}),r.isEmpty(d.lexerDefinitionErrors)){i.augmentTokenTypes(x);var _;d.TRACE_INIT("analyzeTokenTypes",function(){_=t.analyzeTokenTypes(x,{lineTerminatorCharacters:d.config.lineTerminatorCharacters,positionTracking:h.positionTracking,ensureOptimizations:h.ensureOptimizations,safeMode:h.safeMode,tracer:d.TRACE_INIT.bind(d)})}),d.patternIdxToConfig[b]=_.patternIdxToConfig,d.charCodeToPatternIdxToConfig[b]=_.charCodeToPatternIdxToConfig,d.emptyGroups=r.merge(d.emptyGroups,_.emptyGroups),d.hasCustom=_.hasCustom||d.hasCustom,d.canModeBeOptimized[b]=_.canBeOptimized}})}),d.defaultMode=y.defaultMode,!r.isEmpty(d.lexerDefinitionErrors)&&!d.config.deferDefinitionErrorsHandling){var m=r.map(d.lexerDefinitionErrors,function(x){return x.message}),v=m.join(`-----------------------
`);throw new Error(`Errors detected in definition of Lexer:
`+v)}r.forEach(d.lexerDefinitionWarning,function(x){r.PRINT_WARNING(x.message)}),d.TRACE_INIT("Choosing sub-methods implementations",function(){if(t.SUPPORT_STICKY?(d.chopInput=r.IDENTITY,d.match=d.matchWithTest):(d.updateLastIndex=r.NOOP,d.match=d.matchWithExec),g&&(d.handleModes=r.NOOP),d.trackStartLines===!1&&(d.computeNewColumn=r.IDENTITY),d.trackEndLines===!1&&(d.updateTokenEndLineColumnLocation=r.NOOP),/full/i.test(d.config.positionTracking))d.createTokenInstance=d.createFullToken;else if(/onlyStart/i.test(d.config.positionTracking))d.createTokenInstance=d.createStartOnlyToken;else if(/onlyOffset/i.test(d.config.positionTracking))d.createTokenInstance=d.createOffsetOnlyToken;else throw Error('Invalid <positionTracking> config option: "'+d.config.positionTracking+'"');d.hasCustom?(d.addToken=d.addTokenUsingPush,d.handlePayload=d.handlePayloadWithCustom):(d.addToken=d.addTokenUsingMemberAccess,d.handlePayload=d.handlePayloadNoCustom)}),d.TRACE_INIT("Failed Optimization Warnings",function(){var x=r.reduce(d.canModeBeOptimized,function(b,_,M){return _===!1&&b.push(M),b},[]);if(h.ensureOptimizations&&!r.isEmpty(x))throw Error("Lexer Modes: < "+x.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.`)}),d.TRACE_INIT("clearRegExpParserCache",function(){a.clearRegExpParserCache()}),d.TRACE_INIT("toFastProperties",function(){r.toFastProperties(d)})})}return c.prototype.tokenize=function(u,h){if(h===void 0&&(h=this.defaultMode),!r.isEmpty(this.lexerDefinitionErrors)){var d=r.map(this.lexerDefinitionErrors,function(g){return g.message}),f=d.join(`-----------------------
`);throw new Error(`Unable to Tokenize because Errors detected in definition of Lexer:
`+f)}var y=this.tokenizeInternal(u,h);return y},c.prototype.tokenizeInternal=function(u,h){var d=this,f,y,g,p,m,v,x,b,_,M,C,S,w,E,P,N=u,D=N.length,B=0,J=0,Q=this.hasCustom?0:Math.floor(u.length/10),j=new Array(Q),k=[],H=this.trackStartLines?1:void 0,U=this.trackStartLines?1:void 0,X=t.cloneEmptyGroups(this.emptyGroups),W=this.trackStartLines,$=this.config.lineTerminatorsPattern,G=0,T=[],I=[],V=[],K=[];Object.freeze(K);var ie=void 0;function le(){return T}function ae(Pe){var Ce=t.charCodeToOptimizedIndex(Pe),je=I[Ce];return je===void 0?K:je}var de=function(Pe){if(V.length===1&&Pe.tokenType.PUSH_MODE===void 0){var Ce=d.config.errorMessageProvider.buildUnableToPopLexerModeMessage(Pe);k.push({offset:Pe.startOffset,line:Pe.startLine!==void 0?Pe.startLine:void 0,column:Pe.startColumn!==void 0?Pe.startColumn:void 0,length:Pe.image.length,message:Ce})}else{V.pop();var je=r.last(V);T=d.patternIdxToConfig[je],I=d.charCodeToPatternIdxToConfig[je],G=T.length;var st=d.canModeBeOptimized[je]&&d.config.safeMode===!1;I&&st?ie=ae:ie=le}};function z(Pe){V.push(Pe),I=this.charCodeToPatternIdxToConfig[Pe],T=this.patternIdxToConfig[Pe],G=T.length,G=T.length;var Ce=this.canModeBeOptimized[Pe]&&this.config.safeMode===!1;I&&Ce?ie=ae:ie=le}z.call(this,h);for(var me;B<D;){m=null;var we=N.charCodeAt(B),He=ie(we),ne=He.length;for(f=0;f<ne;f++){me=He[f];var _e=me.pattern;v=null;var oe=me.short;if(oe!==!1?we===oe&&(m=_e):me.isCustom===!0?(P=_e.exec(N,B,j,X),P!==null?(m=P[0],P.payload!==void 0&&(v=P.payload)):m=null):(this.updateLastIndex(_e,B),m=this.match(_e,u,B)),m!==null){if(p=me.longerAlt,p!==void 0){var ce=T[p],L=ce.pattern;x=null,ce.isCustom===!0?(P=L.exec(N,B,j,X),P!==null?(g=P[0],P.payload!==void 0&&(x=P.payload)):g=null):(this.updateLastIndex(L,B),g=this.match(L,u,B)),g&&g.length>m.length&&(m=g,v=x,me=ce)}break}}if(m!==null){if(b=m.length,_=me.group,_!==void 0&&(M=me.tokenTypeIdx,C=this.createTokenInstance(m,B,M,me.tokenType,H,U,b),this.handlePayload(C,v),_===!1?J=this.addToken(j,J,C):X[_].push(C)),u=this.chopInput(u,b),B=B+b,U=this.computeNewColumn(U,b),W===!0&&me.canLineTerminator===!0){var A=0,O=void 0,F=void 0;$.lastIndex=0;do O=$.test(m),O===!0&&(F=$.lastIndex-1,A++);while(O===!0);A!==0&&(H=H+A,U=b-F,this.updateTokenEndLineColumnLocation(C,_,F,A,H,U,b))}this.handleModes(me,de,z,C)}else{for(var Y=B,re=H,ue=U,se=!1;!se&&B<D;)for(w=N.charCodeAt(B),u=this.chopInput(u,1),B++,y=0;y<G;y++){var pe=T[y],_e=pe.pattern,oe=pe.short;if(oe!==!1?N.charCodeAt(B)===oe&&(se=!0):pe.isCustom===!0?se=_e.exec(N,B,j,X)!==null:(this.updateLastIndex(_e,B),se=_e.exec(u)!==null),se===!0)break}S=B-Y,E=this.config.errorMessageProvider.buildUnexpectedCharactersMessage(N,Y,S,re,ue),k.push({offset:Y,line:re,column:ue,length:S,message:E})}}return this.hasCustom||(j.length=J),{tokens:j,groups:X,errors:k}},c.prototype.handleModes=function(u,h,d,f){if(u.pop===!0){var y=u.push;h(f),y!==void 0&&d.call(this,y)}else u.push!==void 0&&d.call(this,u.push)},c.prototype.chopInput=function(u,h){return u.substring(h)},c.prototype.updateLastIndex=function(u,h){u.lastIndex=h},c.prototype.updateTokenEndLineColumnLocation=function(u,h,d,f,y,g,p){var m,v;h!==void 0&&(m=d===p-1,v=m?-1:0,f===1&&m===!0||(u.endLine=y+v,u.endColumn=g-1+-v))},c.prototype.computeNewColumn=function(u,h){return u+h},c.prototype.createTokenInstance=function(){for(var u=[],h=0;h<arguments.length;h++)u[h]=arguments[h];return null},c.prototype.createOffsetOnlyToken=function(u,h,d,f){return{image:u,startOffset:h,tokenTypeIdx:d,tokenType:f}},c.prototype.createStartOnlyToken=function(u,h,d,f,y,g){return{image:u,startOffset:h,startLine:y,startColumn:g,tokenTypeIdx:d,tokenType:f}},c.prototype.createFullToken=function(u,h,d,f,y,g,p){return{image:u,startOffset:h,endOffset:h+p-1,startLine:y,endLine:y,startColumn:g,endColumn:g+p-1,tokenTypeIdx:d,tokenType:f}},c.prototype.addToken=function(u,h,d){return 666},c.prototype.addTokenUsingPush=function(u,h,d){return u.push(d),h},c.prototype.addTokenUsingMemberAccess=function(u,h,d){return u[h]=d,h++,h},c.prototype.handlePayload=function(u,h){},c.prototype.handlePayloadNoCustom=function(u,h){},c.prototype.handlePayloadWithCustom=function(u,h){h!==null&&(u.payload=h)},c.prototype.match=function(u,h,d){return null},c.prototype.matchWithTest=function(u,h,d){var f=u.test(h);return f===!0?h.substring(d,u.lastIndex):null},c.prototype.matchWithExec=function(u,h){var d=u.exec(h);return d!==null?d[0]:d},c.prototype.TRACE_INIT=function(u,h){if(this.traceInitPerf===!0){this.traceInitIndent++;var d=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent<this.traceInitMaxIdent&&console.log(d+"--> <"+u+">");var f=r.timer(h),y=f.time,g=f.value,p=y>10?console.warn:console.log;return this.traceInitIndent<this.traceInitMaxIdent&&p(d+"<-- <"+u+"> time: "+y+"ms"),this.traceInitIndent--,g}else return h()},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}),Ls=vr(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=Or(),r=hd(),i=cc();function n(b){return s(b)?b.LABEL:b.name}e.tokenLabel=n;function a(b){return b.name}e.tokenName=a;function s(b){return t.isString(b.LABEL)&&b.LABEL!==""}e.hasTokenLabel=s;var o="parent",l="categories",c="label",u="group",h="push_mode",d="pop_mode",f="longer_alt",y="line_breaks",g="start_chars_hint";function p(b){return m(b)}e.createToken=p;function m(b){var _=b.pattern,M={};if(M.name=b.name,t.isUndefined(_)||(M.PATTERN=_),t.has(b,o))throw`The parent property is no longer supported.
See: https://github.com/chevrotain/chevrotain/issues/564#issuecomment-349062346 for details.`;return t.has(b,l)&&(M.CATEGORIES=b[l]),i.augmentTokenTypes([M]),t.has(b,c)&&(M.LABEL=b[c]),t.has(b,u)&&(M.GROUP=b[u]),t.has(b,d)&&(M.POP_MODE=b[d]),t.has(b,h)&&(M.PUSH_MODE=b[h]),t.has(b,f)&&(M.LONGER_ALT=b[f]),t.has(b,y)&&(M.LINE_BREAKS=b[y]),t.has(b,g)&&(M.START_CHARS_HINT=b[g]),M}e.EOF=p({name:"EOF",pattern:r.Lexer.NA}),i.augmentTokenTypes([e.EOF]);function v(b,_,M,C,S,w,E,P){return{image:_,startOffset:M,endOffset:C,startLine:S,endLine:w,startColumn:E,endColumn:P,tokenTypeIdx:b.tokenTypeIdx,tokenType:b}}e.createTokenInstance=v;function x(b,_){return i.tokenStructuredMatcher(b,_)}e.tokenMatcher=x}),ln=vr(e=>{"use strict";var t=e&&e.__extends||(function(){var m=function(v,x){return m=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(b,_){b.__proto__=_}||function(b,_){for(var M in _)Object.prototype.hasOwnProperty.call(_,M)&&(b[M]=_[M])},m(v,x)};return function(v,x){if(typeof x!="function"&&x!==null)throw new TypeError("Class extends value "+String(x)+" is not a constructor or null");m(v,x);function b(){this.constructor=v}v.prototype=x===null?Object.create(x):(b.prototype=x.prototype,new b)}})();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=Or(),i=Ls(),n=(function(){function m(v){this._definition=v}return Object.defineProperty(m.prototype,"definition",{get:function(){return this._definition},set:function(v){this._definition=v},enumerable:!1,configurable:!0}),m.prototype.accept=function(v){v.visit(this),r.forEach(this.definition,function(x){x.accept(v)})},m})();e.AbstractProduction=n;var a=(function(m){t(v,m);function v(x){var b=m.call(this,[])||this;return b.idx=1,r.assign(b,r.pick(x,function(_){return _!==void 0})),b}return Object.defineProperty(v.prototype,"definition",{get:function(){return this.referencedRule!==void 0?this.referencedRule.definition:[]},set:function(x){},enumerable:!1,configurable:!0}),v.prototype.accept=function(x){x.visit(this)},v})(n);e.NonTerminal=a;var s=(function(m){t(v,m);function v(x){var b=m.call(this,x.definition)||this;return b.orgText="",r.assign(b,r.pick(x,function(_){return _!==void 0})),b}return v})(n);e.Rule=s;var o=(function(m){t(v,m);function v(x){var b=m.call(this,x.definition)||this;return b.ignoreAmbiguities=!1,r.assign(b,r.pick(x,function(_){return _!==void 0})),b}return v})(n);e.Alternative=o;var l=(function(m){t(v,m);function v(x){var b=m.call(this,x.definition)||this;return b.idx=1,r.assign(b,r.pick(x,function(_){return _!==void 0})),b}return v})(n);e.Option=l;var c=(function(m){t(v,m);function v(x){var b=m.call(this,x.definition)||this;return b.idx=1,r.assign(b,r.pick(x,function(_){return _!==void 0})),b}return v})(n);e.RepetitionMandatory=c;var u=(function(m){t(v,m);function v(x){var b=m.call(this,x.definition)||this;return b.idx=1,r.assign(b,r.pick(x,function(_){return _!==void 0})),b}return v})(n);e.RepetitionMandatoryWithSeparator=u;var h=(function(m){t(v,m);function v(x){var b=m.call(this,x.definition)||this;return b.idx=1,r.assign(b,r.pick(x,function(_){return _!==void 0})),b}return v})(n);e.Repetition=h;var d=(function(m){t(v,m);function v(x){var b=m.call(this,x.definition)||this;return b.idx=1,r.assign(b,r.pick(x,function(_){return _!==void 0})),b}return v})(n);e.RepetitionWithSeparator=d;var f=(function(m){t(v,m);function v(x){var b=m.call(this,x.definition)||this;return b.idx=1,b.ignoreAmbiguities=!1,b.hasPredicates=!1,r.assign(b,r.pick(x,function(_){return _!==void 0})),b}return Object.defineProperty(v.prototype,"definition",{get:function(){return this._definition},set:function(x){this._definition=x},enumerable:!1,configurable:!0}),v})(n);e.Alternation=f;var y=(function(){function m(v){this.idx=1,r.assign(this,r.pick(v,function(x){return x!==void 0}))}return m.prototype.accept=function(v){v.visit(this)},m})();e.Terminal=y;function g(m){return r.map(m,p)}e.serializeGrammar=g;function p(m){function v(_){return r.map(_,p)}if(m instanceof a)return{type:"NonTerminal",name:m.nonTerminalName,idx:m.idx};if(m instanceof o)return{type:"Alternative",definition:v(m.definition)};if(m instanceof l)return{type:"Option",idx:m.idx,definition:v(m.definition)};if(m instanceof c)return{type:"RepetitionMandatory",idx:m.idx,definition:v(m.definition)};if(m instanceof u)return{type:"RepetitionMandatoryWithSeparator",idx:m.idx,separator:p(new y({terminalType:m.separator})),definition:v(m.definition)};if(m instanceof d)return{type:"RepetitionWithSeparator",idx:m.idx,separator:p(new y({terminalType:m.separator})),definition:v(m.definition)};if(m instanceof h)return{type:"Repetition",idx:m.idx,definition:v(m.definition)};if(m instanceof f)return{type:"Alternation",idx:m.idx,definition:v(m.definition)};if(m instanceof y){var x={type:"Terminal",name:m.terminalType.name,label:i.tokenLabel(m.terminalType),idx:m.idx},b=m.terminalType.PATTERN;return m.terminalType.PATTERN&&(x.pattern=r.isRegExp(b)?b.source:b),x}else{if(m instanceof s)return{type:"Rule",name:m.name,orgText:m.orgText,definition:v(m.definition)};throw Error("non exhaustive match")}}e.serializeProduction=p}),fm=vr(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.RestWalker=void 0;var t=Or(),r=ln(),i=(function(){function a(){}return a.prototype.walk=function(s,o){var l=this;o===void 0&&(o=[]),t.forEach(s.definition,function(c,u){var h=t.drop(s.definition,u+1);if(c instanceof r.NonTerminal)l.walkProdRef(c,h,o);else if(c instanceof r.Terminal)l.walkTerminal(c,h,o);else if(c instanceof r.Alternative)l.walkFlat(c,h,o);else if(c instanceof r.Option)l.walkOption(c,h,o);else if(c instanceof r.RepetitionMandatory)l.walkAtLeastOne(c,h,o);else if(c instanceof r.RepetitionMandatoryWithSeparator)l.walkAtLeastOneSep(c,h,o);else if(c instanceof r.RepetitionWithSeparator)l.walkManySep(c,h,o);else if(c instanceof r.Repetition)l.walkMany(c,h,o);else if(c instanceof r.Alternation)l.walkOr(c,h,o);else throw Error("non exhaustive match")})},a.prototype.walkTerminal=function(s,o,l){},a.prototype.walkProdRef=function(s,o,l){},a.prototype.walkFlat=function(s,o,l){var c=o.concat(l);this.walk(s,c)},a.prototype.walkOption=function(s,o,l){var c=o.concat(l);this.walk(s,c)},a.prototype.walkAtLeastOne=function(s,o,l){var c=[new r.Option({definition:s.definition})].concat(o,l);this.walk(s,c)},a.prototype.walkAtLeastOneSep=function(s,o,l){var c=n(s,o,l);this.walk(s,c)},a.prototype.walkMany=function(s,o,l){var c=[new r.Option({definition:s.definition})].concat(o,l);this.walk(s,c)},a.prototype.walkManySep=function(s,o,l){var c=n(s,o,l);this.walk(s,c)},a.prototype.walkOr=function(s,o,l){var c=this,u=o.concat(l);t.forEach(s.definition,function(h){var d=new r.Alternative({definition:[h]});c.walk(d,u)})},a})();e.RestWalker=i;function n(a,s,o){var l=[new r.Option({definition:[new r.Terminal({terminalType:a.separator})].concat(a.definition)})],c=l.concat(s,o);return c}}),uc=vr(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.GAstVisitor=void 0;var t=ln(),r=(function(){function i(){}return i.prototype.visit=function(n){var a=n;switch(a.constructor){case t.NonTerminal:return this.visitNonTerminal(a);case t.Alternative:return this.visitAlternative(a);case t.Option:return this.visitOption(a);case t.RepetitionMandatory:return this.visitRepetitionMandatory(a);case t.RepetitionMandatoryWithSeparator:return this.visitRepetitionMandatoryWithSeparator(a);case t.RepetitionWithSeparator:return this.visitRepetitionWithSeparator(a);case t.Repetition:return this.visitRepetition(a);case t.Alternation:return this.visitAlternation(a);case t.Terminal:return this.visitTerminal(a);case t.Rule:return this.visitRule(a);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}),dd=vr(e=>{"use strict";var t=e&&e.__extends||(function(){var d=function(f,y){return d=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(g,p){g.__proto__=p}||function(g,p){for(var m in p)Object.prototype.hasOwnProperty.call(p,m)&&(g[m]=p[m])},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 g(){this.constructor=f}f.prototype=y===null?Object.create(y):(g.prototype=y.prototype,new g)}})();Object.defineProperty(e,"__esModule",{value:!0}),e.collectMethods=e.DslMethodsCollectorVisitor=e.getProductionDslName=e.isBranchingProd=e.isOptionalProd=e.isSequenceProd=void 0;var r=Or(),i=ln(),n=uc();function a(d){return d instanceof i.Alternative||d instanceof i.Option||d instanceof i.Repetition||d instanceof i.RepetitionMandatory||d instanceof i.RepetitionMandatoryWithSeparator||d instanceof i.RepetitionWithSeparator||d instanceof i.Terminal||d instanceof i.Rule}e.isSequenceProd=a;function s(d,f){f===void 0&&(f=[]);var y=d instanceof i.Option||d instanceof i.Repetition||d instanceof i.RepetitionWithSeparator;return y?!0:d instanceof i.Alternation?r.some(d.definition,function(g){return s(g,f)}):d instanceof i.NonTerminal&&r.contains(f,d)?!1:d instanceof i.AbstractProduction?(d instanceof i.NonTerminal&&f.push(d),r.every(d.definition,function(g){return s(g,f)})):!1}e.isOptionalProd=s;function o(d){return d instanceof i.Alternation}e.isBranchingProd=o;function l(d){if(d instanceof i.NonTerminal)return"SUBRULE";if(d instanceof i.Option)return"OPTION";if(d instanceof i.Alternation)return"OR";if(d instanceof i.RepetitionMandatory)return"AT_LEAST_ONE";if(d instanceof i.RepetitionMandatoryWithSeparator)return"AT_LEAST_ONE_SEP";if(d instanceof i.RepetitionWithSeparator)return"MANY_SEP";if(d instanceof i.Repetition)return"MANY";if(d instanceof i.Terminal)return"CONSUME";throw Error("non exhaustive match")}e.getProductionDslName=l;var c=(function(d){t(f,d);function f(){var y=d!==null&&d.apply(this,arguments)||this;return y.separator="-",y.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]},y}return f.prototype.reset=function(){this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}},f.prototype.visitTerminal=function(y){var g=y.terminalType.name+this.separator+"Terminal";r.has(this.dslMethods,g)||(this.dslMethods[g]=[]),this.dslMethods[g].push(y)},f.prototype.visitNonTerminal=function(y){var g=y.nonTerminalName+this.separator+"Terminal";r.has(this.dslMethods,g)||(this.dslMethods[g]=[]),this.dslMethods[g].push(y)},f.prototype.visitOption=function(y){this.dslMethods.option.push(y)},f.prototype.visitRepetitionWithSeparator=function(y){this.dslMethods.repetitionWithSeparator.push(y)},f.prototype.visitRepetitionMandatory=function(y){this.dslMethods.repetitionMandatory.push(y)},f.prototype.visitRepetitionMandatoryWithSeparator=function(y){this.dslMethods.repetitionMandatoryWithSeparator.push(y)},f.prototype.visitRepetition=function(y){this.dslMethods.repetition.push(y)},f.prototype.visitAlternation=function(y){this.dslMethods.alternation.push(y)},f})(n.GAstVisitor);e.DslMethodsCollectorVisitor=c;var u=new c;function h(d){u.reset(),d.accept(u);var f=u.dslMethods;return u.reset(),f}e.collectMethods=h}),lx=vr(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.firstForTerminal=e.firstForBranching=e.firstForSequence=e.first=void 0;var t=Or(),r=ln(),i=dd();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 a(l);if(i.isBranchingProd(l))return s(l);throw Error("non exhaustive match")}e.first=n;function a(l){for(var c=[],u=l.definition,h=0,d=u.length>h,f,y=!0;d&&y;)f=u[h],y=i.isOptionalProd(f),c=c.concat(n(f)),h=h+1,d=u.length>h;return t.uniq(c)}e.firstForSequence=a;function s(l){var c=t.map(l.definition,function(u){return n(u)});return t.uniq(t.flatten(c))}e.firstForBranching=s;function o(l){return[l.terminalType]}e.firstForTerminal=o}),cx=vr(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.IN=void 0,e.IN="_~IN~_"}),x2=vr(e=>{"use strict";var t=e&&e.__extends||(function(){var h=function(d,f){return h=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(y,g){y.__proto__=g}||function(y,g){for(var p in g)Object.prototype.hasOwnProperty.call(g,p)&&(y[p]=g[p])},h(d,f)};return function(d,f){if(typeof f!="function"&&f!==null)throw new TypeError("Class extends value "+String(f)+" is not a constructor or null");h(d,f);function y(){this.constructor=d}d.prototype=f===null?Object.create(f):(y.prototype=f.prototype,new y)}})();Object.defineProperty(e,"__esModule",{value:!0}),e.buildInProdFollowPrefix=e.buildBetweenProdsFollowPrefix=e.computeAllProdsFollows=e.ResyncFollowsWalker=void 0;var r=fm(),i=lx(),n=Or(),a=cx(),s=ln(),o=(function(h){t(d,h);function d(f){var y=h.call(this)||this;return y.topProd=f,y.follows={},y}return d.prototype.startWalking=function(){return this.walk(this.topProd),this.follows},d.prototype.walkTerminal=function(f,y,g){},d.prototype.walkProdRef=function(f,y,g){var p=c(f.referencedRule,f.idx)+this.topProd.name,m=y.concat(g),v=new s.Alternative({definition:m}),x=i.first(v);this.follows[p]=x},d})(r.RestWalker);e.ResyncFollowsWalker=o;function l(h){var d={};return n.forEach(h,function(f){var y=new o(f).startWalking();n.assign(d,y)}),d}e.computeAllProdsFollows=l;function c(h,d){return h.name+d+a.IN}e.buildBetweenProdsFollowPrefix=c;function u(h){var d=h.terminalType.name;return d+h.idx+a.IN}e.buildInProdFollowPrefix=u}),pd=vr(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.defaultGrammarValidatorErrorProvider=e.defaultGrammarResolverErrorProvider=e.defaultParserErrorProvider=void 0;var t=Ls(),r=Or(),i=Or(),n=ln(),a=dd();e.defaultParserErrorProvider={buildMismatchTokenMessage:function(s){var o=s.expected,l=s.actual,c=s.previous,u=s.ruleName,h=t.hasTokenLabel(o),d=h?"--> "+t.tokenLabel(o)+" <--":"token of type --> "+o.name+" <--",f="Expecting "+d+" but found --> '"+l.image+"' <--";return f},buildNotAllInputParsedMessage:function(s){var o=s.firstRedundant,l=s.ruleName;return"Redundant input, expecting EOF but found: "+o.image},buildNoViableAltMessage:function(s){var o=s.expectedPathsPerAlt,l=s.actual,c=s.previous,u=s.customUserDescription,h=s.ruleName,d="Expecting: ",f=i.first(l).image,y=`
but found: '`+f+"'";if(u)return d+u+y;var g=i.reduce(o,function(x,b){return x.concat(b)},[]),p=i.map(g,function(x){return"["+i.map(x,function(b){return t.tokenLabel(b)}).join(", ")+"]"}),m=i.map(p,function(x,b){return" "+(b+1)+". "+x}),v=`one of these possible Token sequences:
`+m.join(`
`);return d+v+y},buildEarlyExitMessage:function(s){var o=s.expectedIterationPaths,l=s.actual,c=s.customUserDescription,u=s.ruleName,h="Expecting: ",d=i.first(l).image,f=`
but found: '`+d+"'";if(c)return h+c+f;var y=i.map(o,function(p){return"["+i.map(p,function(m){return t.tokenLabel(m)}).join(",")+"]"}),g=`expecting at least one iteration which starts with one of these possible Token sequences::
`+("<"+y.join(" ,")+">");return h+g+f}},Object.freeze(e.defaultParserErrorProvider),e.defaultGrammarResolverErrorProvider={buildRuleNotFoundError:function(s,o){var l="Invalid grammar, reference to a rule which is not defined: ->"+o.nonTerminalName+`<-
inside top level rule: ->`+s.name+"<-";return l}},e.defaultGrammarValidatorErrorProvider={buildDuplicateFoundError:function(s,o){function l(p){return p instanceof n.Terminal?p.terminalType.name:p instanceof n.NonTerminal?p.nonTerminalName:""}var c=s.name,u=i.first(o),h=u.idx,d=a.getProductionDslName(u),f=l(u),y=h>0,g="->"+d+(y?h:"")+"<- "+(f?"with argument: ->"+f+"<-":"")+`
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 g=g.replace(/[ \t]+/g," "),g=g.replace(/\s\s+/g,`
`),g},buildNamespaceConflictError:function(s){var o=`Namespace conflict found in grammar.
`+("The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <"+s.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(s){var o=i.map(s.prefixPath,function(u){return t.tokenLabel(u)}).join(", "),l=s.alternation.idx===0?"":s.alternation.idx,c="Ambiguous alternatives: <"+s.ambiguityIndices.join(" ,")+`> due to common lookahead prefix
`+("in <OR"+l+"> inside <"+s.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(s){var o=i.map(s.prefixPath,function(u){return t.tokenLabel(u)}).join(", "),l=s.alternation.idx===0?"":s.alternation.idx,c="Ambiguous Alternatives Detected: <"+s.ambiguityIndices.join(" ,")+"> in <OR"+l+">"+(" inside <"+s.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(s){var o=a.getProductionDslName(s.repetition);s.repetition.idx!==0&&(o+=s.repetition.idx);var l="The repetition <"+o+"> within Rule <"+s.topLevelRule.name+`> can never consume any tokens.
This could lead to an infinite loop.`;return l},buildTokenNameError:function(s){return"deprecated"},buildEmptyAlternationError:function(s){var o="Ambiguous empty alternative: <"+(s.emptyChoiceIdx+1)+">"+(" in <OR"+s.alternation.idx+"> inside <"+s.topLevelRule.name+`> Rule.
`)+"Only the last alternative may be an empty alternative.";return o},buildTooManyAlternativesError:function(s){var o=`An Alternation cannot have more than 256 alternatives:
`+("<OR"+s.alternation.idx+"> inside <"+s.topLevelRule.name+`> Rule.
has `+(s.alternation.definition.length+1)+" alternatives.");return o},buildLeftRecursionError:function(s){var o=s.topLevelRule.name,l=r.map(s.leftRecursionPath,function(h){return h.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(s){return"deprecated"},buildDuplicateRuleNameError:function(s){var o;s.topLevelRule instanceof n.Rule?o=s.topLevelRule.name:o=s.topLevelRule;var l="Duplicate definition, rule: ->"+o+"<- is already defined in the grammar: ->"+s.grammarName+"<-";return l}}}),b2=vr(e=>{"use strict";var t=e&&e.__extends||(function(){var o=function(l,c){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(u,h){u.__proto__=h}||function(u,h){for(var d in h)Object.prototype.hasOwnProperty.call(h,d)&&(u[d]=h[d])},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=wn(),i=Or(),n=uc();function a(o,l){var c=new s(o,l);return c.resolveRefs(),c.errors}e.resolveGrammar=a;var s=(function(o){t(l,o);function l(c,u){var h=o.call(this)||this;return h.nameToTopRule=c,h.errMsgProvider=u,h.errors=[],h}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 h=this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel,c);this.errors.push({message:h,type:r.ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF,ruleName:this.currTopLevel.name,unresolvedRefName:c.nonTerminalName})}},l})(n.GAstVisitor);e.GastRefResolverVisitor=s}),fd=vr(e=>{"use strict";var t=e&&e.__extends||(function(){var p=function(m,v){return p=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(x,b){x.__proto__=b}||function(x,b){for(var _ in b)Object.prototype.hasOwnProperty.call(b,_)&&(x[_]=b[_])},p(m,v)};return function(m,v){if(typeof v!="function"&&v!==null)throw new TypeError("Class extends value "+String(v)+" is not a constructor or null");p(m,v);function x(){this.constructor=m}m.prototype=v===null?Object.create(v):(x.prototype=v.prototype,new x)}})();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=fm(),i=Or(),n=lx(),a=ln(),s=(function(p){t(m,p);function m(v,x){var b=p.call(this)||this;return b.topProd=v,b.path=x,b.possibleTokTypes=[],b.nextProductionName="",b.nextProductionOccurrence=0,b.found=!1,b.isAtEndOfPath=!1,b}return m.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},m.prototype.walk=function(v,x){x===void 0&&(x=[]),this.found||p.prototype.walk.call(this,v,x)},m.prototype.walkProdRef=function(v,x,b){if(v.referencedRule.name===this.nextProductionName&&v.idx===this.nextProductionOccurrence){var _=x.concat(b);this.updateExpectedNext(),this.walk(v.referencedRule,_)}},m.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())},m})(r.RestWalker);e.AbstractNextPossibleTokensWalker=s;var o=(function(p){t(m,p);function m(v,x){var b=p.call(this,v,x)||this;return b.path=x,b.nextTerminalName="",b.nextTerminalOccurrence=0,b.nextTerminalName=b.path.lastTok.name,b.nextTerminalOccurrence=b.path.lastTokOccurrence,b}return m.prototype.walkTerminal=function(v,x,b){if(this.isAtEndOfPath&&v.terminalType.name===this.nextTerminalName&&v.idx===this.nextTerminalOccurrence&&!this.found){var _=x.concat(b),M=new a.Alternative({definition:_});this.possibleTokTypes=n.first(M),this.found=!0}},m})(s);e.NextAfterTokenWalker=o;var l=(function(p){t(m,p);function m(v,x){var b=p.call(this)||this;return b.topRule=v,b.occurrence=x,b.result={token:void 0,occurrence:void 0,isEndOfRule:void 0},b}return m.prototype.startWalking=function(){return this.walk(this.topRule),this.result},m})(r.RestWalker);e.AbstractNextTerminalAfterProductionWalker=l;var c=(function(p){t(m,p);function m(){return p!==null&&p.apply(this,arguments)||this}return m.prototype.walkMany=function(v,x,b){if(v.idx===this.occurrence){var _=i.first(x.concat(b));this.result.isEndOfRule=_===void 0,_ instanceof a.Terminal&&(this.result.token=_.terminalType,this.result.occurrence=_.idx)}else p.prototype.walkMany.call(this,v,x,b)},m})(l);e.NextTerminalAfterManyWalker=c;var u=(function(p){t(m,p);function m(){return p!==null&&p.apply(this,arguments)||this}return m.prototype.walkManySep=function(v,x,b){if(v.idx===this.occurrence){var _=i.first(x.concat(b));this.result.isEndOfRule=_===void 0,_ instanceof a.Terminal&&(this.result.token=_.terminalType,this.result.occurrence=_.idx)}else p.prototype.walkManySep.call(this,v,x,b)},m})(l);e.NextTerminalAfterManySepWalker=u;var h=(function(p){t(m,p);function m(){return p!==null&&p.apply(this,arguments)||this}return m.prototype.walkAtLeastOne=function(v,x,b){if(v.idx===this.occurrence){var _=i.first(x.concat(b));this.result.isEndOfRule=_===void 0,_ instanceof a.Terminal&&(this.result.token=_.terminalType,this.result.occurrence=_.idx)}else p.prototype.walkAtLeastOne.call(this,v,x,b)},m})(l);e.NextTerminalAfterAtLeastOneWalker=h;var d=(function(p){t(m,p);function m(){return p!==null&&p.apply(this,arguments)||this}return m.prototype.walkAtLeastOneSep=function(v,x,b){if(v.idx===this.occurrence){var _=i.first(x.concat(b));this.result.isEndOfRule=_===void 0,_ instanceof a.Terminal&&(this.result.token=_.terminalType,this.result.occurrence=_.idx)}else p.prototype.walkAtLeastOneSep.call(this,v,x,b)},m})(l);e.NextTerminalAfterAtLeastOneSepWalker=d;function f(p,m,v){v===void 0&&(v=[]),v=i.cloneArr(v);var x=[],b=0;function _(w){return w.concat(i.drop(p,b+1))}function M(w){var E=f(_(w),m,v);return x.concat(E)}for(;v.length<m&&b<p.length;){var C=p[b];if(C instanceof a.Alternative||C instanceof a.NonTerminal)return M(C.definition);if(C instanceof a.Option)x=M(C.definition);else if(C instanceof a.RepetitionMandatory){var S=C.definition.concat([new a.Repetition({definition:C.definition})]);return M(S)}else if(C instanceof a.RepetitionMandatoryWithSeparator){var S=[new a.Alternative({definition:C.definition}),new a.Repetition({definition:[new a.Terminal({terminalType:C.separator})].concat(C.definition)})];return M(S)}else if(C instanceof a.RepetitionWithSeparator){var S=C.definition.concat([new a.Repetition({definition:[new a.Terminal({terminalType:C.separator})].concat(C.definition)})]);x=M(S)}else if(C instanceof a.Repetition){var S=C.definition.concat([new a.Repetition({definition:C.definition})]);x=M(S)}else{if(C instanceof a.Alternation)return i.forEach(C.definition,function(w){i.isEmpty(w.definition)===!1&&(x=M(w.definition))}),x;if(C instanceof a.Terminal)v.push(C.terminalType);else throw Error("non exhaustive match")}b++}return x.push({partialPath:v,suffixDef:i.drop(p,b)}),x}e.possiblePathsFrom=f;function y(p,m,v,x){var b="EXIT_NONE_TERMINAL",_=[b],M="EXIT_ALTERNATIVE",C=!1,S=m.length,w=S-x-1,E=[],P=[];for(P.push({idx:-1,def:p,ruleStack:[],occurrenceStack:[]});!i.isEmpty(P);){var N=P.pop();if(N===M){C&&i.last(P).idx<=w&&P.pop();continue}var D=N.def,B=N.idx,J=N.ruleStack,Q=N.occurrenceStack;if(!i.isEmpty(D)){var j=D[0];if(j===b){var k={idx:B,def:i.drop(D),ruleStack:i.dropRight(J),occurrenceStack:i.dropRight(Q)};P.push(k)}else if(j instanceof a.Terminal)if(B<S-1){var H=B+1,U=m[H];if(v(U,j.terminalType)){var k={idx:H,def:i.drop(D),ruleStack:J,occurrenceStack:Q};P.push(k)}}else if(B===S-1)E.push({nextTokenType:j.terminalType,nextTokenOccurrence:j.idx,ruleStack:J,occurrenceStack:Q}),C=!0;else throw Error("non exhaustive match");else if(j instanceof a.NonTerminal){var X=i.cloneArr(J);X.push(j.nonTerminalName);var W=i.cloneArr(Q);W.push(j.idx);var k={idx:B,def:j.definition.concat(_,i.drop(D)),ruleStack:X,occurrenceStack:W};P.push(k)}else if(j instanceof a.Option){var $={idx:B,def:i.drop(D),ruleStack:J,occurrenceStack:Q};P.push($),P.push(M);var G={idx:B,def:j.definition.concat(i.drop(D)),ruleStack:J,occurrenceStack:Q};P.push(G)}else if(j instanceof a.RepetitionMandatory){var T=new a.Repetition({definition:j.definition,idx:j.idx}),I=j.definition.concat([T],i.drop(D)),k={idx:B,def:I,ruleStack:J,occurrenceStack:Q};P.push(k)}else if(j instanceof a.RepetitionMandatoryWithSeparator){var V=new a.Terminal({terminalType:j.separator}),T=new a.Repetition({definition:[V].concat(j.definition),idx:j.idx}),I=j.definition.concat([T],i.drop(D)),k={idx:B,def:I,ruleStack:J,occurrenceStack:Q};P.push(k)}else if(j instanceof a.RepetitionWithSeparator){var $={idx:B,def:i.drop(D),ruleStack:J,occurrenceStack:Q};P.push($),P.push(M);var V=new a.Terminal({terminalType:j.separator}),K=new a.Repetition({definition:[V].concat(j.definition),idx:j.idx}),I=j.definition.concat([K],i.drop(D)),G={idx:B,def:I,ruleStack:J,occurrenceStack:Q};P.push(G)}else if(j instanceof a.Repetition){var $={idx:B,def:i.drop(D),ruleStack:J,occurrenceStack:Q};P.push($),P.push(M);var K=new a.Repetition({definition:j.definition,idx:j.idx}),I=j.definition.concat([K],i.drop(D)),G={idx:B,def:I,ruleStack:J,occurrenceStack:Q};P.push(G)}else if(j instanceof a.Alternation)for(var ie=j.definition.length-1;ie>=0;ie--){var le=j.definition[ie],ae={idx:B,def:le.definition.concat(i.drop(D)),ruleStack:J,occurrenceStack:Q};P.push(ae),P.push(M)}else if(j instanceof a.Alternative)P.push({idx:B,def:j.definition.concat(i.drop(D)),ruleStack:J,occurrenceStack:Q});else if(j instanceof a.Rule)P.push(g(j,B,J,Q));else throw Error("non exhaustive match")}}return E}e.nextPossibleTokensAfter=y;function g(p,m,v,x){var b=i.cloneArr(v);b.push(p.name);var _=i.cloneArr(x);return _.push(1),{idx:m,def:p.definition,ruleStack:b,occurrenceStack:_}}}),md=vr(e=>{"use strict";var t=e&&e.__extends||(function(){var w=function(E,P){return w=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(N,D){N.__proto__=D}||function(N,D){for(var B in D)Object.prototype.hasOwnProperty.call(D,B)&&(N[B]=D[B])},w(E,P)};return function(E,P){if(typeof P!="function"&&P!==null)throw new TypeError("Class extends value "+String(P)+" is not a constructor or null");w(E,P);function N(){this.constructor=E}E.prototype=P===null?Object.create(P):(N.prototype=P.prototype,new N)}})();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=Or(),i=fd(),n=fm(),a=cc(),s=ln(),o=uc(),l;(function(w){w[w.OPTION=0]="OPTION",w[w.REPETITION=1]="REPETITION",w[w.REPETITION_MANDATORY=2]="REPETITION_MANDATORY",w[w.REPETITION_MANDATORY_WITH_SEPARATOR=3]="REPETITION_MANDATORY_WITH_SEPARATOR",w[w.REPETITION_WITH_SEPARATOR=4]="REPETITION_WITH_SEPARATOR",w[w.ALTERNATION=5]="ALTERNATION"})(l=e.PROD_TYPE||(e.PROD_TYPE={}));function c(w){if(w instanceof s.Option)return l.OPTION;if(w instanceof s.Repetition)return l.REPETITION;if(w instanceof s.RepetitionMandatory)return l.REPETITION_MANDATORY;if(w instanceof s.RepetitionMandatoryWithSeparator)return l.REPETITION_MANDATORY_WITH_SEPARATOR;if(w instanceof s.RepetitionWithSeparator)return l.REPETITION_WITH_SEPARATOR;if(w instanceof s.Alternation)return l.ALTERNATION;throw Error("non exhaustive match")}e.getProdType=c;function u(w,E,P,N,D,B){var J=b(w,E,P),Q=S(J)?a.tokenStructuredMatcherNoCategories:a.tokenStructuredMatcher;return B(J,N,Q,D)}e.buildLookaheadFuncForOr=u;function h(w,E,P,N,D,B){var J=_(w,E,D,P),Q=S(J)?a.tokenStructuredMatcherNoCategories:a.tokenStructuredMatcher;return B(J[0],Q,N)}e.buildLookaheadFuncForOptionalProd=h;function d(w,E,P,N){var D=w.length,B=r.every(w,function(j){return r.every(j,function(k){return k.length===1})});if(E)return function(j){for(var k=r.map(j,function(K){return K.GATE}),H=0;H<D;H++){var U=w[H],X=U.length,W=k[H];if(!(W!==void 0&&W.call(this)===!1))e:for(var $=0;$<X;$++){for(var G=U[$],T=G.length,I=0;I<T;I++){var V=this.LA(I+1);if(P(V,G[I])===!1)continue e}return H}}};if(B&&!N){var J=r.map(w,function(j){return r.flatten(j)}),Q=r.reduce(J,function(j,k,H){return r.forEach(k,function(U){r.has(j,U.tokenTypeIdx)||(j[U.tokenTypeIdx]=H),r.forEach(U.categoryMatches,function(X){r.has(j,X)||(j[X]=H)})}),j},[]);return function(){var j=this.LA(1);return Q[j.tokenTypeIdx]}}else return function(){for(var j=0;j<D;j++){var k=w[j],H=k.length;e:for(var U=0;U<H;U++){for(var X=k[U],W=X.length,$=0;$<W;$++){var G=this.LA($+1);if(P(G,X[$])===!1)continue e}return j}}}}e.buildAlternativesLookAheadFunc=d;function f(w,E,P){var N=r.every(w,function(k){return k.length===1}),D=w.length;if(N&&!P){var B=r.flatten(w);if(B.length===1&&r.isEmpty(B[0].categoryMatches)){var J=B[0],Q=J.tokenTypeIdx;return function(){return this.LA(1).tokenTypeIdx===Q}}else{var j=r.reduce(B,function(k,H,U){return k[H.tokenTypeIdx]=!0,r.forEach(H.categoryMatches,function(X){k[X]=!0}),k},[]);return function(){var k=this.LA(1);return j[k.tokenTypeIdx]===!0}}}else return function(){e:for(var k=0;k<D;k++){for(var H=w[k],U=H.length,X=0;X<U;X++){var W=this.LA(X+1);if(E(W,H[X])===!1)continue e}return!0}return!1}}e.buildSingleAlternativeLookaheadFunction=f;var y=(function(w){t(E,w);function E(P,N,D){var B=w.call(this)||this;return B.topProd=P,B.targetOccurrence=N,B.targetProdType=D,B}return E.prototype.startWalking=function(){return this.walk(this.topProd),this.restDef},E.prototype.checkIsTarget=function(P,N,D,B){return P.idx===this.targetOccurrence&&this.targetProdType===N?(this.restDef=D.concat(B),!0):!1},E.prototype.walkOption=function(P,N,D){this.checkIsTarget(P,l.OPTION,N,D)||w.prototype.walkOption.call(this,P,N,D)},E.prototype.walkAtLeastOne=function(P,N,D){this.checkIsTarget(P,l.REPETITION_MANDATORY,N,D)||w.prototype.walkOption.call(this,P,N,D)},E.prototype.walkAtLeastOneSep=function(P,N,D){this.checkIsTarget(P,l.REPETITION_MANDATORY_WITH_SEPARATOR,N,D)||w.prototype.walkOption.call(this,P,N,D)},E.prototype.walkMany=function(P,N,D){this.checkIsTarget(P,l.REPETITION,N,D)||w.prototype.walkOption.call(this,P,N,D)},E.prototype.walkManySep=function(P,N,D){this.checkIsTarget(P,l.REPETITION_WITH_SEPARATOR,N,D)||w.prototype.walkOption.call(this,P,N,D)},E})(n.RestWalker),g=(function(w){t(E,w);function E(P,N,D){var B=w.call(this)||this;return B.targetOccurrence=P,B.targetProdType=N,B.targetRef=D,B.result=[],B}return E.prototype.checkIsTarget=function(P,N){P.idx===this.targetOccurrence&&this.targetProdType===N&&(this.targetRef===void 0||P===this.targetRef)&&(this.result=P.definition)},E.prototype.visitOption=function(P){this.checkIsTarget(P,l.OPTION)},E.prototype.visitRepetition=function(P){this.checkIsTarget(P,l.REPETITION)},E.prototype.visitRepetitionMandatory=function(P){this.checkIsTarget(P,l.REPETITION_MANDATORY)},E.prototype.visitRepetitionMandatoryWithSeparator=function(P){this.checkIsTarget(P,l.REPETITION_MANDATORY_WITH_SEPARATOR)},E.prototype.visitRepetitionWithSeparator=function(P){this.checkIsTarget(P,l.REPETITION_WITH_SEPARATOR)},E.prototype.visitAlternation=function(P){this.checkIsTarget(P,l.ALTERNATION)},E})(o.GAstVisitor);function p(w){for(var E=new Array(w),P=0;P<w;P++)E[P]=[];return E}function m(w){for(var E=[""],P=0;P<w.length;P++){for(var N=w[P],D=[],B=0;B<E.length;B++){var J=E[B];D.push(J+"_"+N.tokenTypeIdx);for(var Q=0;Q<N.categoryMatches.length;Q++){var j="_"+N.categoryMatches[Q];D.push(J+j)}}E=D}return E}function v(w,E,P){for(var N=0;N<w.length;N++)if(N!==P)for(var D=w[N],B=0;B<E.length;B++){var J=E[B];if(D[J]===!0)return!1}return!0}function x(w,E){for(var P=r.map(w,function(H){return i.possiblePathsFrom([H],1)}),N=p(P.length),D=r.map(P,function(H){var U={};return r.forEach(H,function(X){var W=m(X.partialPath);r.forEach(W,function($){U[$]=!0})}),U}),B=P,J=1;J<=E;J++){var Q=B;B=p(Q.length);for(var j=function(H){for(var U=Q[H],X=0;X<U.length;X++){var W=U[X].partialPath,$=U[X].suffixDef,G=m(W),T=v(D,G,H);if(T||r.isEmpty($)||W.length===E){var I=N[H];if(M(I,W)===!1){I.push(W);for(var V=0;V<G.length;V++){var K=G[V];D[H][K]=!0}}}else{var ie=i.possiblePathsFrom($,J+1,W);B[H]=B[H].concat(ie),r.forEach(ie,function(le){var ae=m(le.partialPath);r.forEach(ae,function(de){D[H][de]=!0})})}}},k=0;k<Q.length;k++)j(k)}return N}e.lookAheadSequenceFromAlternatives=x;function b(w,E,P,N){var D=new g(w,l.ALTERNATION,N);return E.accept(D),x(D.result,P)}e.getLookaheadPathsForOr=b;function _(w,E,P,N){var D=new g(w,P);E.accept(D);var B=D.result,J=new y(E,w,P),Q=J.startWalking(),j=new s.Alternative({definition:B}),k=new s.Alternative({definition:Q});return x([j,k],N)}e.getLookaheadPathsForOptionalProd=_;function M(w,E){e:for(var P=0;P<w.length;P++){var N=w[P];if(N.length===E.length){for(var D=0;D<N.length;D++){var B=E[D],J=N[D],Q=B===J||J.categoryMatchesMap[B.tokenTypeIdx]!==void 0;if(Q===!1)continue e}return!0}}return!1}e.containsPath=M;function C(w,E){return w.length<E.length&&r.every(w,function(P,N){var D=E[N];return P===D||D.categoryMatchesMap[P.tokenTypeIdx]})}e.isStrictPrefixOfPath=C;function S(w){return r.every(w,function(E){return r.every(E,function(P){return r.every(P,function(N){return r.isEmpty(N.categoryMatches)})})})}e.areTokenCategoriesNotUsed=S}),ux=vr(e=>{"use strict";var t=e&&e.__extends||(function(){var N=function(D,B){return N=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(J,Q){J.__proto__=Q}||function(J,Q){for(var j in Q)Object.prototype.hasOwnProperty.call(Q,j)&&(J[j]=Q[j])},N(D,B)};return function(D,B){if(typeof B!="function"&&B!==null)throw new TypeError("Class extends value "+String(B)+" is not a constructor or null");N(D,B);function J(){this.constructor=D}D.prototype=B===null?Object.create(B):(J.prototype=B.prototype,new J)}})();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=Or(),i=Or(),n=wn(),a=dd(),s=md(),o=fd(),l=ln(),c=uc();function u(N,D,B,J,Q){var j=r.map(N,function(T){return h(T,J)}),k=r.map(N,function(T){return m(T,T,J)}),H=[],U=[],X=[];i.every(k,i.isEmpty)&&(H=i.map(N,function(T){return b(T,J)}),U=i.map(N,function(T){return _(T,D,J)}),X=S(N,D,J));var W=P(N,B,J),$=i.map(N,function(T){return C(T,J)}),G=i.map(N,function(T){return g(T,N,Q,J)});return r.flatten(j.concat(X,k,H,U,W,$,G))}e.validateGrammar=u;function h(N,D){var B=new y;N.accept(B);var J=B.allProductions,Q=r.groupBy(J,d),j=r.pick(Q,function(H){return H.length>1}),k=r.map(r.values(j),function(H){var U=r.first(H),X=D.buildDuplicateFoundError(N,H),W=a.getProductionDslName(U),$={message:X,type:n.ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS,ruleName:N.name,dslName:W,occurrence:U.idx},G=f(U);return G&&($.parameter=G),$});return k}function d(N){return a.getProductionDslName(N)+"_#_"+N.idx+"_#_"+f(N)}e.identifyProductionForDuplicates=d;function f(N){return N instanceof l.Terminal?N.terminalType.name:N instanceof l.NonTerminal?N.nonTerminalName:""}var y=(function(N){t(D,N);function D(){var B=N!==null&&N.apply(this,arguments)||this;return B.allProductions=[],B}return D.prototype.visitNonTerminal=function(B){this.allProductions.push(B)},D.prototype.visitOption=function(B){this.allProductions.push(B)},D.prototype.visitRepetitionWithSeparator=function(B){this.allProductions.push(B)},D.prototype.visitRepetitionMandatory=function(B){this.allProductions.push(B)},D.prototype.visitRepetitionMandatoryWithSeparator=function(B){this.allProductions.push(B)},D.prototype.visitRepetition=function(B){this.allProductions.push(B)},D.prototype.visitAlternation=function(B){this.allProductions.push(B)},D.prototype.visitTerminal=function(B){this.allProductions.push(B)},D})(c.GAstVisitor);e.OccurrenceValidationCollector=y;function g(N,D,B,J){var Q=[],j=i.reduce(D,function(H,U){return U.name===N.name?H+1:H},0);if(j>1){var k=J.buildDuplicateRuleNameError({topLevelRule:N,grammarName:B});Q.push({message:k,type:n.ParserDefinitionErrorType.DUPLICATE_RULE_NAME,ruleName:N.name})}return Q}e.validateRuleDoesNotAlreadyExist=g;function p(N,D,B){var J=[],Q;return r.contains(D,N)||(Q="Invalid rule override, rule: ->"+N+"<- cannot be overridden in the grammar: ->"+B+"<-as it is not defined in any of the super grammars ",J.push({message:Q,type:n.ParserDefinitionErrorType.INVALID_RULE_OVERRIDE,ruleName:N})),J}e.validateRuleIsOverridden=p;function m(N,D,B,J){J===void 0&&(J=[]);var Q=[],j=v(D.definition);if(r.isEmpty(j))return[];var k=N.name,H=r.contains(j,N);H&&Q.push({message:B.buildLeftRecursionError({topLevelRule:N,leftRecursionPath:J}),type:n.ParserDefinitionErrorType.LEFT_RECURSION,ruleName:k});var U=r.difference(j,J.concat([N])),X=r.map(U,function(W){var $=r.cloneArr(J);return $.push(W),m(N,W,B,$)});return Q.concat(r.flatten(X))}e.validateNoLeftRecursion=m;function v(N){var D=[];if(r.isEmpty(N))return D;var B=r.first(N);if(B instanceof l.NonTerminal)D.push(B.referencedRule);else if(B instanceof l.Alternative||B instanceof l.Option||B instanceof l.RepetitionMandatory||B instanceof l.RepetitionMandatoryWithSeparator||B instanceof l.RepetitionWithSeparator||B instanceof l.Repetition)D=D.concat(v(B.definition));else if(B instanceof l.Alternation)D=r.flatten(r.map(B.definition,function(k){return v(k.definition)}));else if(!(B instanceof l.Terminal))throw Error("non exhaustive match");var J=a.isOptionalProd(B),Q=N.length>1;if(J&&Q){var j=r.drop(N);return D.concat(v(j))}else return D}e.getFirstNoneTerminal=v;var x=(function(N){t(D,N);function D(){var B=N!==null&&N.apply(this,arguments)||this;return B.alternations=[],B}return D.prototype.visitAlternation=function(B){this.alternations.push(B)},D})(c.GAstVisitor);function b(N,D){var B=new x;N.accept(B);var J=B.alternations,Q=r.reduce(J,function(j,k){var H=r.dropRight(k.definition),U=r.map(H,function(X,W){var $=o.nextPossibleTokensAfter([X],[],null,1);return r.isEmpty($)?{message:D.buildEmptyAlternationError({topLevelRule:N,alternation:k,emptyChoiceIdx:W}),type:n.ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT,ruleName:N.name,occurrence:k.idx,alternative:W+1}:null});return j.concat(r.compact(U))},[]);return Q}e.validateEmptyOrAlternative=b;function _(N,D,B){var J=new x;N.accept(J);var Q=J.alternations;Q=i.reject(Q,function(k){return k.ignoreAmbiguities===!0});var j=r.reduce(Q,function(k,H){var U=H.idx,X=H.maxLookahead||D,W=s.getLookaheadPathsForOr(U,N,X,H),$=w(W,H,N,B),G=E(W,H,N,B);return k.concat($,G)},[]);return j}e.validateAmbiguousAlternationAlternatives=_;var M=(function(N){t(D,N);function D(){var B=N!==null&&N.apply(this,arguments)||this;return B.allProductions=[],B}return D.prototype.visitRepetitionWithSeparator=function(B){this.allProductions.push(B)},D.prototype.visitRepetitionMandatory=function(B){this.allProductions.push(B)},D.prototype.visitRepetitionMandatoryWithSeparator=function(B){this.allProductions.push(B)},D.prototype.visitRepetition=function(B){this.allProductions.push(B)},D})(c.GAstVisitor);e.RepetionCollector=M;function C(N,D){var B=new x;N.accept(B);var J=B.alternations,Q=r.reduce(J,function(j,k){return k.definition.length>255&&j.push({message:D.buildTooManyAlternativesError({topLevelRule:N,alternation:k}),type:n.ParserDefinitionErrorType.TOO_MANY_ALTS,ruleName:N.name,occurrence:k.idx}),j},[]);return Q}e.validateTooManyAlts=C;function S(N,D,B){var J=[];return i.forEach(N,function(Q){var j=new M;Q.accept(j);var k=j.allProductions;i.forEach(k,function(H){var U=s.getProdType(H),X=H.maxLookahead||D,W=H.idx,$=s.getLookaheadPathsForOptionalProd(W,Q,U,X),G=$[0];if(i.isEmpty(i.flatten(G))){var T=B.buildEmptyRepetitionError({topLevelRule:Q,repetition:H});J.push({message:T,type:n.ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD,ruleName:Q.name})}})}),J}e.validateSomeNonEmptyLookaheadPath=S;function w(N,D,B,J){var Q=[],j=i.reduce(N,function(H,U,X){return D.definition[X].ignoreAmbiguities===!0||i.forEach(U,function(W){var $=[X];i.forEach(N,function(G,T){X!==T&&s.containsPath(G,W)&&D.definition[T].ignoreAmbiguities!==!0&&$.push(T)}),$.length>1&&!s.containsPath(Q,W)&&(Q.push(W),H.push({alts:$,path:W}))}),H},[]),k=r.map(j,function(H){var U=i.map(H.alts,function(W){return W+1}),X=J.buildAlternationAmbiguityError({topLevelRule:B,alternation:D,ambiguityIndices:U,prefixPath:H.path});return{message:X,type:n.ParserDefinitionErrorType.AMBIGUOUS_ALTS,ruleName:B.name,occurrence:D.idx,alternatives:[H.alts]}});return k}function E(N,D,B,J){var Q=[],j=i.reduce(N,function(k,H,U){var X=i.map(H,function(W){return{idx:U,path:W}});return k.concat(X)},[]);return i.forEach(j,function(k){var H=D.definition[k.idx];if(H.ignoreAmbiguities!==!0){var U=k.idx,X=k.path,W=i.findAll(j,function(G){return D.definition[G.idx].ignoreAmbiguities!==!0&&G.idx<U&&s.isStrictPrefixOfPath(G.path,X)}),$=i.map(W,function(G){var T=[G.idx+1,U+1],I=D.idx===0?"":D.idx,V=J.buildAlternationPrefixAmbiguityError({topLevelRule:B,alternation:D,ambiguityIndices:T,prefixPath:G.path});return{message:V,type:n.ParserDefinitionErrorType.AMBIGUOUS_PREFIX_ALTS,ruleName:B.name,occurrence:I,alternatives:T}});Q=Q.concat($)}}),Q}e.checkPrefixAlternativesAmbiguities=E;function P(N,D,B){var J=[],Q=i.map(D,function(j){return j.name});return i.forEach(N,function(j){var k=j.name;if(i.contains(Q,k)){var H=B.buildNamespaceConflictError(j);J.push({message:H,type:n.ParserDefinitionErrorType.CONFLICT_TOKENS_RULES_NAMESPACE,ruleName:k})}}),J}}),_2=vr(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.validateGrammar=e.resolveGrammar=void 0;var t=Or(),r=b2(),i=ux(),n=pd();function a(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=a;function s(o){return o=t.defaults(o,{errMsgProvider:n.defaultGrammarValidatorErrorProvider}),i.validateGrammar(o.rules,o.maxLookahead,o.tokenTypes,o.errMsgProvider,o.grammarName)}e.validateGrammar=s}),hc=vr(e=>{"use strict";var t=e&&e.__extends||(function(){var y=function(g,p){return y=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(m,v){m.__proto__=v}||function(m,v){for(var x in v)Object.prototype.hasOwnProperty.call(v,x)&&(m[x]=v[x])},y(g,p)};return function(g,p){if(typeof p!="function"&&p!==null)throw new TypeError("Class extends value "+String(p)+" is not a constructor or null");y(g,p);function m(){this.constructor=g}g.prototype=p===null?Object.create(p):(m.prototype=p.prototype,new m)}})();Object.defineProperty(e,"__esModule",{value:!0}),e.EarlyExitException=e.NotAllInputParsedException=e.NoViableAltException=e.MismatchedTokenException=e.isRecognitionException=void 0;var r=Or(),i="MismatchedTokenException",n="NoViableAltException",a="EarlyExitException",s="NotAllInputParsedException",o=[i,n,a,s];Object.freeze(o);function l(y){return r.contains(o,y.name)}e.isRecognitionException=l;var c=(function(y){t(g,y);function g(p,m){var v=this.constructor,x=y.call(this,p)||this;return x.token=m,x.resyncedTokens=[],Object.setPrototypeOf(x,v.prototype),Error.captureStackTrace&&Error.captureStackTrace(x,x.constructor),x}return g})(Error),u=(function(y){t(g,y);function g(p,m,v){var x=y.call(this,p,m)||this;return x.previousToken=v,x.name=i,x}return g})(c);e.MismatchedTokenException=u;var h=(function(y){t(g,y);function g(p,m,v){var x=y.call(this,p,m)||this;return x.previousToken=v,x.name=n,x}return g})(c);e.NoViableAltException=h;var d=(function(y){t(g,y);function g(p,m){var v=y.call(this,p,m)||this;return v.name=s,v}return g})(c);e.NotAllInputParsedException=d;var f=(function(y){t(g,y);function g(p,m,v){var x=y.call(this,p,m)||this;return x.previousToken=v,x.name=a,x}return g})(c);e.EarlyExitException=f}),hx=vr(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=Ls(),r=Or(),i=hc(),n=cx(),a=wn();e.EOF_FOLLOW_KEY={},e.IN_RULE_RECOVERY_EXCEPTION="InRuleRecoveryException";function s(c){this.name=e.IN_RULE_RECOVERY_EXCEPTION,this.message=c}e.InRuleRecoveryException=s,s.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:a.DEFAULT_PARSER_CONFIG.recoveryEnabled,this.recoveryEnabled&&(this.attemptInRepetitionRecovery=l)},c.prototype.getTokenToInsert=function(u){var h=t.createTokenInstance(u,"",NaN,NaN,NaN,NaN,NaN,NaN);return h.isInsertedInRecovery=!0,h},c.prototype.canTokenTypeBeInsertedInRecovery=function(u){return!0},c.prototype.tryInRepetitionRecovery=function(u,h,d,f){for(var y=this,g=this.findReSyncTokenType(),p=this.exportLexerState(),m=[],v=!1,x=this.LA(1),b=this.LA(1),_=function(){var M=y.LA(0),C=y.errorMessageProvider.buildMismatchTokenMessage({expected:f,actual:x,previous:M,ruleName:y.getCurrRuleFullName()}),S=new i.MismatchedTokenException(C,x,y.LA(0));S.resyncedTokens=r.dropRight(m),y.SAVE_ERROR(S)};!v;)if(this.tokenMatcher(b,f)){_();return}else if(d.call(this)){_(),u.apply(this,h);return}else this.tokenMatcher(b,g)?v=!0:(b=this.SKIP_TOKEN(),this.addToResyncTokens(b,m));this.importLexerState(p)},c.prototype.shouldInRepetitionRecoveryBeTried=function(u,h,d){return!(d===!1||u===void 0||h===void 0||this.tokenMatcher(this.LA(1),u)||this.isBackTracking()||this.canPerformInRuleRecovery(u,this.getFollowsForInRuleRecovery(u,h)))},c.prototype.getFollowsForInRuleRecovery=function(u,h){var d=this.getCurrentGrammarPath(u,h),f=this.getNextPossibleTokenTypes(d);return f},c.prototype.tryInRuleRecovery=function(u,h){if(this.canRecoverWithSingleTokenInsertion(u,h)){var d=this.getTokenToInsert(u);return d}if(this.canRecoverWithSingleTokenDeletion(u)){var f=this.SKIP_TOKEN();return this.consumeToken(),f}throw new s("sad sad panda")},c.prototype.canPerformInRuleRecovery=function(u,h){return this.canRecoverWithSingleTokenInsertion(u,h)||this.canRecoverWithSingleTokenDeletion(u)},c.prototype.canRecoverWithSingleTokenInsertion=function(u,h){var d=this;if(!this.canTokenTypeBeInsertedInRecovery(u)||r.isEmpty(h))return!1;var f=this.LA(1),y=r.find(h,function(g){return d.tokenMatcher(f,g)})!==void 0;return y},c.prototype.canRecoverWithSingleTokenDeletion=function(u){var h=this.tokenMatcher(this.LA(2),u);return h},c.prototype.isInCurrentRuleReSyncSet=function(u){var h=this.getCurrFollowKey(),d=this.getFollowSetFromFollowKey(h);return r.contains(d,u)},c.prototype.findReSyncTokenType=function(){for(var u=this.flattenFollowSet(),h=this.LA(1),d=2;;){var f=h.tokenType;if(r.contains(u,f))return f;h=this.LA(d),d++}},c.prototype.getCurrFollowKey=function(){if(this.RULE_STACK.length===1)return e.EOF_FOLLOW_KEY;var u=this.getLastExplicitRuleShortName(),h=this.getLastExplicitRuleOccurrenceIndex(),d=this.getPreviousExplicitRuleShortName();return{ruleName:this.shortRuleNameToFullName(u),idxInCallingRule:h,inRule:this.shortRuleNameToFullName(d)}},c.prototype.buildFullFollowKeyStack=function(){var u=this,h=this.RULE_STACK,d=this.RULE_OCCURRENCE_STACK;return r.map(h,function(f,y){return y===0?e.EOF_FOLLOW_KEY:{ruleName:u.shortRuleNameToFullName(f),idxInCallingRule:d[y],inRule:u.shortRuleNameToFullName(h[y-1])}})},c.prototype.flattenFollowSet=function(){var u=this,h=r.map(this.buildFullFollowKeyStack(),function(d){return u.getFollowSetFromFollowKey(d)});return r.flatten(h)},c.prototype.getFollowSetFromFollowKey=function(u){if(u===e.EOF_FOLLOW_KEY)return[t.EOF];var h=u.ruleName+u.idxInCallingRule+n.IN+u.inRule;return this.resyncFollows[h]},c.prototype.addToResyncTokens=function(u,h){return this.tokenMatcher(u,t.EOF)||h.push(u),h},c.prototype.reSyncTo=function(u){for(var h=[],d=this.LA(1);this.tokenMatcher(d,u)===!1;)d=this.SKIP_TOKEN(),this.addToResyncTokens(d,h);return r.dropRight(h)},c.prototype.attemptInRepetitionRecovery=function(u,h,d,f,y,g,p){},c.prototype.getCurrentGrammarPath=function(u,h){var d=this.getHumanReadableRuleStack(),f=r.cloneArr(this.RULE_OCCURRENCE_STACK),y={ruleStack:d,occurrenceStack:f,lastTok:u,lastTokOccurrence:h};return y},c.prototype.getHumanReadableRuleStack=function(){var u=this;return r.map(this.RULE_STACK,function(h){return u.shortRuleNameToFullName(h)})},c})();e.Recoverable=o;function l(c,u,h,d,f,y,g){var p=this.getKeyForAutomaticLookahead(d,f),m=this.firstAfterRepMap[p];if(m===void 0){var v=this.getCurrRuleFullName(),x=this.getGAstProductions()[v],b=new y(x,f);m=b.startWalking(),this.firstAfterRepMap[p]=m}var _=m.token,M=m.occurrence,C=m.isEndOfRule;this.RULE_STACK.length===1&&C&&_===void 0&&(_=t.EOF,M=1),this.shouldInRepetitionRecoveryBeTried(_,M,g)&&this.tryInRepetitionRecovery(c,u,h,_)}e.attemptInRepetitionRecovery=l}),mm=vr(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,a){return a|n|i}e.getKeyForAutomaticLookahead=t;var r=32-e.BITS_FOR_ALT_IDX}),w2=vr(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.LooksAhead=void 0;var t=md(),r=Or(),i=wn(),n=mm(),a=dd(),s=(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 h=a.collectMethods(u),d=h.alternation,f=h.repetition,y=h.option,g=h.repetitionMandatory,p=h.repetitionMandatoryWithSeparator,m=h.repetitionWithSeparator;r.forEach(d,function(v){var x=v.idx===0?"":v.idx;c.TRACE_INIT(""+a.getProductionDslName(v)+x,function(){var b=t.buildLookaheadFuncForOr(v.idx,u,v.maxLookahead||c.maxLookahead,v.hasPredicates,c.dynamicTokensEnabled,c.lookAheadBuilderForAlternatives),_=n.getKeyForAutomaticLookahead(c.fullRuleNameToShort[u.name],n.OR_IDX,v.idx);c.setLaFuncCache(_,b)})}),r.forEach(f,function(v){c.computeLookaheadFunc(u,v.idx,n.MANY_IDX,t.PROD_TYPE.REPETITION,v.maxLookahead,a.getProductionDslName(v))}),r.forEach(y,function(v){c.computeLookaheadFunc(u,v.idx,n.OPTION_IDX,t.PROD_TYPE.OPTION,v.maxLookahead,a.getProductionDslName(v))}),r.forEach(g,function(v){c.computeLookaheadFunc(u,v.idx,n.AT_LEAST_ONE_IDX,t.PROD_TYPE.REPETITION_MANDATORY,v.maxLookahead,a.getProductionDslName(v))}),r.forEach(p,function(v){c.computeLookaheadFunc(u,v.idx,n.AT_LEAST_ONE_SEP_IDX,t.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR,v.maxLookahead,a.getProductionDslName(v))}),r.forEach(m,function(v){c.computeLookaheadFunc(u,v.idx,n.MANY_SEP_IDX,t.PROD_TYPE.REPETITION_WITH_SEPARATOR,v.maxLookahead,a.getProductionDslName(v))})})})},o.prototype.computeLookaheadFunc=function(l,c,u,h,d,f){var y=this;this.TRACE_INIT(""+f+(c===0?"":c),function(){var g=t.buildLookaheadFuncForOptionalProd(c,l,d||y.maxLookahead,y.dynamicTokensEnabled,h,y.lookAheadBuilderForOptional),p=n.getKeyForAutomaticLookahead(y.fullRuleNameToShort[l.name],u,c);y.setLaFuncCache(p,g)})},o.prototype.lookAheadBuilderForOptional=function(l,c,u){return t.buildSingleAlternativeLookaheadFunction(l,c,u)},o.prototype.lookAheadBuilderForAlternatives=function(l,c,u,h){return t.buildAlternativesLookAheadFunc(l,c,u,h)},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=s}),E2=vr(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.addNoneTerminalToCst=e.addTerminalToCst=e.setNodeLocationFull=e.setNodeLocationOnlyOffset=void 0;function t(a,s){isNaN(a.startOffset)===!0?(a.startOffset=s.startOffset,a.endOffset=s.endOffset):a.endOffset<s.endOffset&&(a.endOffset=s.endOffset)}e.setNodeLocationOnlyOffset=t;function r(a,s){isNaN(a.startOffset)===!0?(a.startOffset=s.startOffset,a.startColumn=s.startColumn,a.startLine=s.startLine,a.endOffset=s.endOffset,a.endColumn=s.endColumn,a.endLine=s.endLine):a.endOffset<s.endOffset&&(a.endOffset=s.endOffset,a.endColumn=s.endColumn,a.endLine=s.endLine)}e.setNodeLocationFull=r;function i(a,s,o){a.children[o]===void 0?a.children[o]=[s]:a.children[o].push(s)}e.addTerminalToCst=i;function n(a,s,o){a.children[s]===void 0?a.children[s]=[o]:a.children[s].push(o)}e.addNoneTerminalToCst=n}),dx=vr(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.defineNameProp=e.functionName=e.classNameFromInstance=void 0;var t=Or();function r(s){return n(s.constructor)}e.classNameFromInstance=r;var i="name";function n(s){var o=s.name;return o||"anonymous"}e.functionName=n;function a(s,o){var l=Object.getOwnPropertyDescriptor(s,i);return t.isUndefined(l)||l.configurable?(Object.defineProperty(s,i,{enumerable:!1,configurable:!0,writable:!1,value:o}),!0):!1}e.defineNameProp=a}),M2=vr(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=Or(),r=dx();function i(h,d){for(var f=t.keys(h),y=f.length,g=0;g<y;g++)for(var p=f[g],m=h[p],v=m.length,x=0;x<v;x++){var b=m[x];b.tokenTypeIdx===void 0&&this[b.name](b.children,d)}}e.defaultVisit=i;function n(h,d){var f=function(){};r.defineNameProp(f,h+"BaseSemantics");var y={visit:function(g,p){if(t.isArray(g)&&(g=g[0]),!t.isUndefined(g))return this[g.name](g.children,p)},validateVisitor:function(){var g=o(this,d);if(!t.isEmpty(g)){var p=t.map(g,function(m){return m.msg});throw Error("Errors Detected in CST Visitor <"+r.functionName(this.constructor)+`>:
`+(""+p.join(`
`).replace(/\n/g,`
`)))}}};return f.prototype=y,f.prototype.constructor=f,f._RULE_NAMES=d,f}e.createBaseSemanticVisitorConstructor=n;function a(h,d,f){var y=function(){};r.defineNameProp(y,h+"BaseSemanticsWithDefaults");var g=Object.create(f.prototype);return t.forEach(d,function(p){g[p]=i}),y.prototype=g,y.prototype.constructor=y,y}e.createBaseVisitorConstructorWithDefaults=a;var s;(function(h){h[h.REDUNDANT_METHOD=0]="REDUNDANT_METHOD",h[h.MISSING_METHOD=1]="MISSING_METHOD"})(s=e.CstVisitorDefinitionError||(e.CstVisitorDefinitionError={}));function o(h,d){var f=l(h,d),y=u(h,d);return f.concat(y)}e.validateVisitor=o;function l(h,d){var f=t.map(d,function(y){if(!t.isFunction(h[y]))return{msg:"Missing visitor method: <"+y+"> on "+r.functionName(h.constructor)+" CST Visitor.",type:s.MISSING_METHOD,methodName:y}});return t.compact(f)}e.validateMissingCstMethods=l;var c=["constructor","visit","validateVisitor"];function u(h,d){var f=[];for(var y in h)t.isFunction(h[y])&&!t.contains(c,y)&&!t.contains(d,y)&&f.push({msg:"Redundant visitor method: <"+y+"> on "+r.functionName(h.constructor)+` CST Visitor
There is no Grammar Rule corresponding to this method's name.
`,type:s.REDUNDANT_METHOD,methodName:y});return f}e.validateRedundantMethods=u}),S2=vr(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.TreeBuilder=void 0;var t=E2(),r=Or(),i=M2(),n=wn(),a=(function(){function s(){}return s.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+'"')},s.prototype.setInitialNodeLocationOnlyOffsetRecovery=function(o){o.location={startOffset:NaN,endOffset:NaN}},s.prototype.setInitialNodeLocationOnlyOffsetRegular=function(o){o.location={startOffset:this.LA(1).startOffset,endOffset:NaN}},s.prototype.setInitialNodeLocationFullRecovery=function(o){o.location={startOffset:NaN,startLine:NaN,startColumn:NaN,endOffset:NaN,endLine:NaN,endColumn:NaN}},s.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}},s.prototype.cstInvocationStateUpdate=function(o,l){var c={name:o,children:{}};this.setInitialNodeLocation(c),this.CST_STACK.push(c)},s.prototype.cstFinallyStateUpdate=function(){this.CST_STACK.pop()},s.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)},s.prototype.cstPostRuleOnlyOffset=function(o){var l=this.LA(0),c=o.location;c.startOffset<=l.startOffset?c.endOffset=l.endOffset:c.startOffset=NaN},s.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)},s.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)},s.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},s.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},s.prototype.getLastExplicitRuleShortName=function(){var o=this.RULE_STACK;return o[o.length-1]},s.prototype.getPreviousExplicitRuleShortName=function(){var o=this.RULE_STACK;return o[o.length-2]},s.prototype.getLastExplicitRuleOccurrenceIndex=function(){var o=this.RULE_OCCURRENCE_STACK;return o[o.length-1]},s})();e.TreeBuilder=a}),T2=vr(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.LexerAdapter=void 0;var t=wn(),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 a=this.currIdx+n;return a<0||this.tokVectorLength<=a?t.END_OF_FILE:this.tokVector[a]},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}),A2=vr(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.RecognizerApi=void 0;var t=Or(),r=hc(),i=wn(),n=pd(),a=ux(),s=ln(),o=(function(){function l(){}return l.prototype.ACTION=function(c){return c.call(this)},l.prototype.consume=function(c,u,h){return this.consumeInternal(u,c,h)},l.prototype.subrule=function(c,u,h){return this.subruleInternal(u,c,h)},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,h){if(h===void 0&&(h=i.DEFAULT_RULE_CONFIG),t.contains(this.definedRulesNames,c)){var d=n.defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({topLevelRule:c,grammarName:this.className}),f={message:d,type:i.ParserDefinitionErrorType.DUPLICATE_RULE_NAME,ruleName:c};this.definitionErrors.push(f)}this.definedRulesNames.push(c);var y=this.defineRule(c,u,h);return this[c]=y,y},l.prototype.OVERRIDE_RULE=function(c,u,h){h===void 0&&(h=i.DEFAULT_RULE_CONFIG);var d=[];d=d.concat(a.validateRuleIsOverridden(c,this.definedRulesNames,this.className)),this.definitionErrors=this.definitionErrors.concat(d);var f=this.defineRule(c,u,h);return this[c]=f,f},l.prototype.BACKTRACK=function(c,u){return function(){this.isBackTrackingStack.push(1);var h=this.saveRecogState();try{return c.apply(this,u),!0}catch(d){if(r.isRecognitionException(d))return!1;throw d}finally{this.reloadRecogState(h),this.isBackTrackingStack.pop()}}},l.prototype.getGAstProductions=function(){return this.gastProductionsCache},l.prototype.getSerializedGastProductions=function(){return s.serializeGrammar(t.values(this.gastProductionsCache))},l})();e.RecognizerApi=o}),C2=vr(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.RecognizerEngine=void 0;var t=Or(),r=mm(),i=hc(),n=md(),a=fd(),s=wn(),o=hx(),l=Ls(),c=cc(),u=dx(),h=(function(){function d(){}return d.prototype.initRecognizerEngine=function(f,y){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(y,"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(f)){if(t.isEmpty(f))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 f[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(f))this.tokensMap=t.reduce(f,function(v,x){return v[x.name]=x,v},{});else if(t.has(f,"modes")&&t.every(t.flatten(t.values(f.modes)),c.isTokenType)){var g=t.flatten(t.values(f.modes)),p=t.uniq(g);this.tokensMap=t.reduce(p,function(v,x){return v[x.name]=x,v},{})}else if(t.isObject(f))this.tokensMap=t.cloneObj(f);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 m=t.every(t.values(f),function(v){return t.isEmpty(v.categoryMatches)});this.tokenMatcher=m?c.tokenStructuredMatcherNoCategories:c.tokenStructuredMatcher,c.augmentTokenTypes(t.values(this.tokensMap))},d.prototype.defineRule=function(f,y,g){if(this.selfAnalysisDone)throw Error("Grammar rule <"+f+`> 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 p=t.has(g,"resyncEnabled")?g.resyncEnabled:s.DEFAULT_RULE_CONFIG.resyncEnabled,m=t.has(g,"recoveryValueFunc")?g.recoveryValueFunc:s.DEFAULT_RULE_CONFIG.recoveryValueFunc,v=this.ruleShortNameIdx<<r.BITS_FOR_METHOD_TYPE+r.BITS_FOR_OCCURRENCE_IDX;this.ruleShortNameIdx++,this.shortRuleNameToFull[v]=f,this.fullRuleNameToShort[f]=v;function x(M){try{if(this.outputCst===!0){y.apply(this,M);var C=this.CST_STACK[this.CST_STACK.length-1];return this.cstPostRule(C),C}else return y.apply(this,M)}catch(S){return this.invokeRuleCatch(S,p,m)}finally{this.ruleFinallyStateUpdate()}}var b=function(M,C){return M===void 0&&(M=0),this.ruleInvocationStateUpdate(v,f,M),x.call(this,C)},_="ruleName";return b[_]=f,b.originalGrammarAction=y,b},d.prototype.invokeRuleCatch=function(f,y,g){var p=this.RULE_STACK.length===1,m=y&&!this.isBackTracking()&&this.recoveryEnabled;if(i.isRecognitionException(f)){var v=f;if(m){var x=this.findReSyncTokenType();if(this.isInCurrentRuleReSyncSet(x))if(v.resyncedTokens=this.reSyncTo(x),this.outputCst){var b=this.CST_STACK[this.CST_STACK.length-1];return b.recoveredNode=!0,b}else return g();else{if(this.outputCst){var b=this.CST_STACK[this.CST_STACK.length-1];b.recoveredNode=!0,v.partialCstResult=b}throw v}}else{if(p)return this.moveToTerminatedState(),g();throw v}}else throw f},d.prototype.optionInternal=function(f,y){var g=this.getKeyForAutomaticLookahead(r.OPTION_IDX,y);return this.optionInternalLogic(f,y,g)},d.prototype.optionInternalLogic=function(f,y,g){var p=this,m=this.getLaFuncFromCache(g),v,x;if(f.DEF!==void 0){if(v=f.DEF,x=f.GATE,x!==void 0){var b=m;m=function(){return x.call(p)&&b.call(p)}}}else v=f;if(m.call(this)===!0)return v.call(this)},d.prototype.atLeastOneInternal=function(f,y){var g=this.getKeyForAutomaticLookahead(r.AT_LEAST_ONE_IDX,f);return this.atLeastOneInternalLogic(f,y,g)},d.prototype.atLeastOneInternalLogic=function(f,y,g){var p=this,m=this.getLaFuncFromCache(g),v,x;if(y.DEF!==void 0){if(v=y.DEF,x=y.GATE,x!==void 0){var b=m;m=function(){return x.call(p)&&b.call(p)}}}else v=y;if(m.call(this)===!0)for(var _=this.doSingleRepetition(v);m.call(this)===!0&&_===!0;)_=this.doSingleRepetition(v);else throw this.raiseEarlyExitException(f,n.PROD_TYPE.REPETITION_MANDATORY,y.ERR_MSG);this.attemptInRepetitionRecovery(this.atLeastOneInternal,[f,y],m,r.AT_LEAST_ONE_IDX,f,a.NextTerminalAfterAtLeastOneWalker)},d.prototype.atLeastOneSepFirstInternal=function(f,y){var g=this.getKeyForAutomaticLookahead(r.AT_LEAST_ONE_SEP_IDX,f);this.atLeastOneSepFirstInternalLogic(f,y,g)},d.prototype.atLeastOneSepFirstInternalLogic=function(f,y,g){var p=this,m=y.DEF,v=y.SEP,x=this.getLaFuncFromCache(g);if(x.call(this)===!0){m.call(this);for(var b=function(){return p.tokenMatcher(p.LA(1),v)};this.tokenMatcher(this.LA(1),v)===!0;)this.CONSUME(v),m.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[f,v,b,m,a.NextTerminalAfterAtLeastOneSepWalker],b,r.AT_LEAST_ONE_SEP_IDX,f,a.NextTerminalAfterAtLeastOneSepWalker)}else throw this.raiseEarlyExitException(f,n.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR,y.ERR_MSG)},d.prototype.manyInternal=function(f,y){var g=this.getKeyForAutomaticLookahead(r.MANY_IDX,f);return this.manyInternalLogic(f,y,g)},d.prototype.manyInternalLogic=function(f,y,g){var p=this,m=this.getLaFuncFromCache(g),v,x;if(y.DEF!==void 0){if(v=y.DEF,x=y.GATE,x!==void 0){var b=m;m=function(){return x.call(p)&&b.call(p)}}}else v=y;for(var _=!0;m.call(this)===!0&&_===!0;)_=this.doSingleRepetition(v);this.attemptInRepetitionRecovery(this.manyInternal,[f,y],m,r.MANY_IDX,f,a.NextTerminalAfterManyWalker,_)},d.prototype.manySepFirstInternal=function(f,y){var g=this.getKeyForAutomaticLookahead(r.MANY_SEP_IDX,f);this.manySepFirstInternalLogic(f,y,g)},d.prototype.manySepFirstInternalLogic=function(f,y,g){var p=this,m=y.DEF,v=y.SEP,x=this.getLaFuncFromCache(g);if(x.call(this)===!0){m.call(this);for(var b=function(){return p.tokenMatcher(p.LA(1),v)};this.tokenMatcher(this.LA(1),v)===!0;)this.CONSUME(v),m.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[f,v,b,m,a.NextTerminalAfterManySepWalker],b,r.MANY_SEP_IDX,f,a.NextTerminalAfterManySepWalker)}},d.prototype.repetitionSepSecondInternal=function(f,y,g,p,m){for(;g();)this.CONSUME(y),p.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[f,y,g,p,m],g,r.AT_LEAST_ONE_SEP_IDX,f,m)},d.prototype.doSingleRepetition=function(f){var y=this.getLexerPosition();f.call(this);var g=this.getLexerPosition();return g>y},d.prototype.orInternal=function(f,y){var g=this.getKeyForAutomaticLookahead(r.OR_IDX,y),p=t.isArray(f)?f:f.DEF,m=this.getLaFuncFromCache(g),v=m.call(this,p);if(v!==void 0){var x=p[v];return x.ALT.call(this)}this.raiseNoAltException(y,f.ERR_MSG)},d.prototype.ruleFinallyStateUpdate=function(){if(this.RULE_STACK.pop(),this.RULE_OCCURRENCE_STACK.pop(),this.cstFinallyStateUpdate(),this.RULE_STACK.length===0&&this.isAtEndOfInput()===!1){var f=this.LA(1),y=this.errorMessageProvider.buildNotAllInputParsedMessage({firstRedundant:f,ruleName:this.getCurrRuleFullName()});this.SAVE_ERROR(new i.NotAllInputParsedException(y,f))}},d.prototype.subruleInternal=function(f,y,g){var p;try{var m=g!==void 0?g.ARGS:void 0;return p=f.call(this,y,m),this.cstPostNonTerminal(p,g!==void 0&&g.LABEL!==void 0?g.LABEL:f.ruleName),p}catch(v){this.subruleInternalError(v,g,f.ruleName)}},d.prototype.subruleInternalError=function(f,y,g){throw i.isRecognitionException(f)&&f.partialCstResult!==void 0&&(this.cstPostNonTerminal(f.partialCstResult,y!==void 0&&y.LABEL!==void 0?y.LABEL:g),delete f.partialCstResult),f},d.prototype.consumeInternal=function(f,y,g){var p;try{var m=this.LA(1);this.tokenMatcher(m,f)===!0?(this.consumeToken(),p=m):this.consumeInternalError(f,m,g)}catch(v){p=this.consumeInternalRecovery(f,y,v)}return this.cstPostTerminal(g!==void 0&&g.LABEL!==void 0?g.LABEL:f.name,p),p},d.prototype.consumeInternalError=function(f,y,g){var p,m=this.LA(0);throw g!==void 0&&g.ERR_MSG?p=g.ERR_MSG:p=this.errorMessageProvider.buildMismatchTokenMessage({expected:f,actual:y,previous:m,ruleName:this.getCurrRuleFullName()}),this.SAVE_ERROR(new i.MismatchedTokenException(p,y,m))},d.prototype.consumeInternalRecovery=function(f,y,g){if(this.recoveryEnabled&&g.name==="MismatchedTokenException"&&!this.isBackTracking()){var p=this.getFollowsForInRuleRecovery(f,y);try{return this.tryInRuleRecovery(f,p)}catch(m){throw m.name===o.IN_RULE_RECOVERY_EXCEPTION?g:m}}else throw g},d.prototype.saveRecogState=function(){var f=this.errors,y=t.cloneArr(this.RULE_STACK);return{errors:f,lexerState:this.exportLexerState(),RULE_STACK:y,CST_STACK:this.CST_STACK}},d.prototype.reloadRecogState=function(f){this.errors=f.errors,this.importLexerState(f.lexerState),this.RULE_STACK=f.RULE_STACK},d.prototype.ruleInvocationStateUpdate=function(f,y,g){this.RULE_OCCURRENCE_STACK.push(g),this.RULE_STACK.push(f),this.cstInvocationStateUpdate(y,f)},d.prototype.isBackTracking=function(){return this.isBackTrackingStack.length!==0},d.prototype.getCurrRuleFullName=function(){var f=this.getLastExplicitRuleShortName();return this.shortRuleNameToFull[f]},d.prototype.shortRuleNameToFullName=function(f){return this.shortRuleNameToFull[f]},d.prototype.isAtEndOfInput=function(){return this.tokenMatcher(this.LA(1),l.EOF)},d.prototype.reset=function(){this.resetLexerState(),this.isBackTrackingStack=[],this.errors=[],this.RULE_STACK=[],this.CST_STACK=[],this.RULE_OCCURRENCE_STACK=[]},d})();e.RecognizerEngine=h}),R2=vr(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ErrorHandler=void 0;var t=hc(),r=Or(),i=md(),n=wn(),a=(function(){function s(){}return s.prototype.initErrorHandler=function(o){this._errors=[],this.errorMessageProvider=r.has(o,"errorMessageProvider")?o.errorMessageProvider:n.DEFAULT_PARSER_CONFIG.errorMessageProvider},s.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(s.prototype,"errors",{get:function(){return r.cloneArr(this._errors)},set:function(o){this._errors=o},enumerable:!1,configurable:!0}),s.prototype.raiseEarlyExitException=function(o,l,c){for(var u=this.getCurrRuleFullName(),h=this.getGAstProductions()[u],d=i.getLookaheadPathsForOptionalProd(o,h,l,this.maxLookahead),f=d[0],y=[],g=1;g<=this.maxLookahead;g++)y.push(this.LA(g));var p=this.errorMessageProvider.buildEarlyExitMessage({expectedIterationPaths:f,actual:y,previous:this.LA(0),customUserDescription:c,ruleName:u});throw this.SAVE_ERROR(new t.EarlyExitException(p,this.LA(1),this.LA(0)))},s.prototype.raiseNoAltException=function(o,l){for(var c=this.getCurrRuleFullName(),u=this.getGAstProductions()[c],h=i.getLookaheadPathsForOr(o,u,this.maxLookahead),d=[],f=1;f<=this.maxLookahead;f++)d.push(this.LA(f));var y=this.LA(0),g=this.errorMessageProvider.buildNoViableAltMessage({expectedPathsPerAlt:h,actual:d,previous:y,customUserDescription:l,ruleName:this.getCurrRuleFullName()});throw this.SAVE_ERROR(new t.NoViableAltException(g,this.LA(1),y))},s})();e.ErrorHandler=a}),P2=vr(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.ContentAssist=void 0;var t=fd(),r=Or(),i=(function(){function n(){}return n.prototype.initContentAssist=function(){},n.prototype.computeContentAssist=function(a,s){var o=this.gastProductionsCache[a];if(r.isUndefined(o))throw Error("Rule ->"+a+"<- does not exist in this grammar.");return t.nextPossibleTokensAfter([o],s,this.tokenMatcher,this.maxLookahead)},n.prototype.getNextPossibleTokenTypes=function(a){var s=r.first(a.ruleStack),o=this.getGAstProductions(),l=o[s],c=new t.NextAfterTokenWalker(l,a).startWalking();return c},n})();e.ContentAssist=i}),I2=vr(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.GastRecorder=void 0;var t=Or(),r=ln(),i=hd(),n=cc(),a=Ls(),s=wn(),o=mm(),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,h=a.createToken({name:"RECORDING_PHASE_TOKEN",pattern:i.Lexer.NA});n.augmentTokenTypes([h]);var d=a.createTokenInstance(h,`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(d);var f={name:`This CSTNode indicates the Parser is in Recording Phase
See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,children:{}},y=(function(){function x(){}return x.prototype.initGastRecorder=function(b){this.recordingProdStack=[],this.RECORDING_PHASE=!1},x.prototype.enableRecording=function(){var b=this;this.RECORDING_PHASE=!0,this.TRACE_INIT("Enable Recording",function(){for(var _=function(C){var S=C>0?C:"";b["CONSUME"+S]=function(w,E){return this.consumeInternalRecord(w,C,E)},b["SUBRULE"+S]=function(w,E){return this.subruleInternalRecord(w,C,E)},b["OPTION"+S]=function(w){return this.optionInternalRecord(w,C)},b["OR"+S]=function(w){return this.orInternalRecord(w,C)},b["MANY"+S]=function(w){this.manyInternalRecord(C,w)},b["MANY_SEP"+S]=function(w){this.manySepFirstInternalRecord(C,w)},b["AT_LEAST_ONE"+S]=function(w){this.atLeastOneInternalRecord(C,w)},b["AT_LEAST_ONE_SEP"+S]=function(w){this.atLeastOneSepFirstInternalRecord(C,w)}},M=0;M<10;M++)_(M);b.consume=function(C,S,w){return this.consumeInternalRecord(S,C,w)},b.subrule=function(C,S,w){return this.subruleInternalRecord(S,C,w)},b.option=function(C,S){return this.optionInternalRecord(S,C)},b.or=function(C,S){return this.orInternalRecord(S,C)},b.many=function(C,S){this.manyInternalRecord(C,S)},b.atLeastOne=function(C,S){this.atLeastOneInternalRecord(C,S)},b.ACTION=b.ACTION_RECORD,b.BACKTRACK=b.BACKTRACK_RECORD,b.LA=b.LA_RECORD})},x.prototype.disableRecording=function(){var b=this;this.RECORDING_PHASE=!1,this.TRACE_INIT("Deleting Recording methods",function(){for(var _=0;_<10;_++){var M=_>0?_:"";delete b["CONSUME"+M],delete b["SUBRULE"+M],delete b["OPTION"+M],delete b["OR"+M],delete b["MANY"+M],delete b["MANY_SEP"+M],delete b["AT_LEAST_ONE"+M],delete b["AT_LEAST_ONE_SEP"+M]}delete b.consume,delete b.subrule,delete b.option,delete b.or,delete b.many,delete b.atLeastOne,delete b.ACTION,delete b.BACKTRACK,delete b.LA})},x.prototype.ACTION_RECORD=function(b){},x.prototype.BACKTRACK_RECORD=function(b,_){return function(){return!0}},x.prototype.LA_RECORD=function(b){return s.END_OF_FILE},x.prototype.topLevelRuleRecord=function(b,_){try{var M=new r.Rule({definition:[],name:b});return M.name=b,this.recordingProdStack.push(M),_.call(this),this.recordingProdStack.pop(),M}catch(C){if(C.KNOWN_RECORDER_ERROR!==!0)try{C.message=C.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 C}throw C}},x.prototype.optionInternalRecord=function(b,_){return g.call(this,r.Option,b,_)},x.prototype.atLeastOneInternalRecord=function(b,_){g.call(this,r.RepetitionMandatory,_,b)},x.prototype.atLeastOneSepFirstInternalRecord=function(b,_){g.call(this,r.RepetitionMandatoryWithSeparator,_,b,c)},x.prototype.manyInternalRecord=function(b,_){g.call(this,r.Repetition,_,b)},x.prototype.manySepFirstInternalRecord=function(b,_){g.call(this,r.RepetitionWithSeparator,_,b,c)},x.prototype.orInternalRecord=function(b,_){return p.call(this,b,_)},x.prototype.subruleInternalRecord=function(b,_,M){if(v(_),!b||t.has(b,"ruleName")===!1){var C=new Error("<SUBRULE"+m(_)+"> argument is invalid"+(" expecting a Parser method reference but got: <"+JSON.stringify(b)+">")+(`
inside top level rule: <`+this.recordingProdStack[0].name+">"));throw C.KNOWN_RECORDER_ERROR=!0,C}var S=t.peek(this.recordingProdStack),w=b.ruleName,E=new r.NonTerminal({idx:_,nonTerminalName:w,referencedRule:void 0});return S.definition.push(E),this.outputCst?f:l},x.prototype.consumeInternalRecord=function(b,_,M){if(v(_),!n.hasShortKeyProperty(b)){var C=new Error("<CONSUME"+m(_)+"> argument is invalid"+(" expecting a TokenType reference but got: <"+JSON.stringify(b)+">")+(`
inside top level rule: <`+this.recordingProdStack[0].name+">"));throw C.KNOWN_RECORDER_ERROR=!0,C}var S=t.peek(this.recordingProdStack),w=new r.Terminal({idx:_,terminalType:b});return S.definition.push(w),d},x})();e.GastRecorder=y;function g(x,b,_,M){M===void 0&&(M=!1),v(_);var C=t.peek(this.recordingProdStack),S=t.isFunction(b)?b:b.DEF,w=new x({definition:[],idx:_});return M&&(w.separator=b.SEP),t.has(b,"MAX_LOOKAHEAD")&&(w.maxLookahead=b.MAX_LOOKAHEAD),this.recordingProdStack.push(w),S.call(this),C.definition.push(w),this.recordingProdStack.pop(),l}function p(x,b){var _=this;v(b);var M=t.peek(this.recordingProdStack),C=t.isArray(x)===!1,S=C===!1?x:x.DEF,w=new r.Alternation({definition:[],idx:b,ignoreAmbiguities:C&&x.IGNORE_AMBIGUITIES===!0});t.has(x,"MAX_LOOKAHEAD")&&(w.maxLookahead=x.MAX_LOOKAHEAD);var E=t.some(S,function(P){return t.isFunction(P.GATE)});return w.hasPredicates=E,M.definition.push(w),t.forEach(S,function(P){var N=new r.Alternative({definition:[]});w.definition.push(N),t.has(P,"IGNORE_AMBIGUITIES")?N.ignoreAmbiguities=P.IGNORE_AMBIGUITIES:t.has(P,"GATE")&&(N.ignoreAmbiguities=!0),_.recordingProdStack.push(N),P.ALT.call(_),_.recordingProdStack.pop()}),l}function m(x){return x===0?"":""+x}function v(x){if(x<0||x>u){var b=new Error("Invalid DSL Method idx value: <"+x+`>
`+("Idx value must be a none negative value smaller than "+(u+1)));throw b.KNOWN_RECORDER_ERROR=!0,b}}}),N2=vr(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.PerformanceTracer=void 0;var t=Or(),r=wn(),i=(function(){function n(){}return n.prototype.initPerformanceTracer=function(a){if(t.has(a,"traceInitPerf")){var s=a.traceInitPerf,o=typeof s=="number";this.traceInitMaxIdent=o?s:1/0,this.traceInitPerf=o?s>0:s}else this.traceInitMaxIdent=0,this.traceInitPerf=r.DEFAULT_PARSER_CONFIG.traceInitPerf;this.traceInitIndent=-1},n.prototype.TRACE_INIT=function(a,s){if(this.traceInitPerf===!0){this.traceInitIndent++;var o=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent<this.traceInitMaxIdent&&console.log(o+"--> <"+a+">");var l=t.timer(s),c=l.time,u=l.value,h=c>10?console.warn:console.log;return this.traceInitIndent<this.traceInitMaxIdent&&h(o+"<-- <"+a+"> time: "+c+"ms"),this.traceInitIndent--,u}else return s()},n})();e.PerformanceTracer=i}),L2=vr(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.applyMixins=void 0;function t(r,i){i.forEach(function(n){var a=n.prototype;Object.getOwnPropertyNames(a).forEach(function(s){if(s!=="constructor"){var o=Object.getOwnPropertyDescriptor(a,s);o&&(o.get||o.set)?Object.defineProperty(r.prototype,s,o):r.prototype[s]=n.prototype[s]}})})}e.applyMixins=t}),wn=vr(e=>{"use strict";var t=e&&e.__extends||(function(){var C=function(S,w){return C=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(E,P){E.__proto__=P}||function(E,P){for(var N in P)Object.prototype.hasOwnProperty.call(P,N)&&(E[N]=P[N])},C(S,w)};return function(S,w){if(typeof w!="function"&&w!==null)throw new TypeError("Class extends value "+String(w)+" is not a constructor or null");C(S,w);function E(){this.constructor=S}S.prototype=w===null?Object.create(w):(E.prototype=w.prototype,new E)}})();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=Or(),i=x2(),n=Ls(),a=pd(),s=_2(),o=hx(),l=w2(),c=S2(),u=T2(),h=A2(),d=C2(),f=R2(),y=P2(),g=I2(),p=N2(),m=L2();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:a.defaultParserErrorProvider,nodeLocationTracking:"none",traceInitPerf:!1,skipValidations:!1}),e.DEFAULT_RULE_CONFIG=Object.freeze({recoveryValueFunc:function(){},resyncEnabled:!0});var v;(function(C){C[C.INVALID_RULE_NAME=0]="INVALID_RULE_NAME",C[C.DUPLICATE_RULE_NAME=1]="DUPLICATE_RULE_NAME",C[C.INVALID_RULE_OVERRIDE=2]="INVALID_RULE_OVERRIDE",C[C.DUPLICATE_PRODUCTIONS=3]="DUPLICATE_PRODUCTIONS",C[C.UNRESOLVED_SUBRULE_REF=4]="UNRESOLVED_SUBRULE_REF",C[C.LEFT_RECURSION=5]="LEFT_RECURSION",C[C.NONE_LAST_EMPTY_ALT=6]="NONE_LAST_EMPTY_ALT",C[C.AMBIGUOUS_ALTS=7]="AMBIGUOUS_ALTS",C[C.CONFLICT_TOKENS_RULES_NAMESPACE=8]="CONFLICT_TOKENS_RULES_NAMESPACE",C[C.INVALID_TOKEN_NAME=9]="INVALID_TOKEN_NAME",C[C.NO_NON_EMPTY_LOOKAHEAD=10]="NO_NON_EMPTY_LOOKAHEAD",C[C.AMBIGUOUS_PREFIX_ALTS=11]="AMBIGUOUS_PREFIX_ALTS",C[C.TOO_MANY_ALTS=12]="TOO_MANY_ALTS"})(v=e.ParserDefinitionErrorType||(e.ParserDefinitionErrorType={}));function x(C){return C===void 0&&(C=void 0),function(){return C}}e.EMPTY_ALT=x;var b=(function(){function C(S,w){this.definitionErrors=[],this.selfAnalysisDone=!1;var E=this;if(E.initErrorHandler(w),E.initLexerAdapter(),E.initLooksAhead(w),E.initRecognizerEngine(S,w),E.initRecoverable(w),E.initTreeBuilder(w),E.initContentAssist(),E.initGastRecorder(w),E.initPerformanceTracer(w),r.has(w,"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(w,"skipValidations")?w.skipValidations:e.DEFAULT_PARSER_CONFIG.skipValidations}return C.performSelfAnalysis=function(S){throw Error("The **static** `performSelfAnalysis` method has been deprecated. \nUse the **instance** method with the same name instead.")},C.prototype.performSelfAnalysis=function(){var S=this;this.TRACE_INIT("performSelfAnalysis",function(){var w;S.selfAnalysisDone=!0;var E=S.className;S.TRACE_INIT("toFastProps",function(){r.toFastProperties(S)}),S.TRACE_INIT("Grammar Recording",function(){try{S.enableRecording(),r.forEach(S.definedRulesNames,function(N){var D=S[N],B=D.originalGrammarAction,J=void 0;S.TRACE_INIT(N+" Rule",function(){J=S.topLevelRuleRecord(N,B)}),S.gastProductionsCache[N]=J})}finally{S.disableRecording()}});var P=[];if(S.TRACE_INIT("Grammar Resolving",function(){P=s.resolveGrammar({rules:r.values(S.gastProductionsCache)}),S.definitionErrors=S.definitionErrors.concat(P)}),S.TRACE_INIT("Grammar Validations",function(){if(r.isEmpty(P)&&S.skipValidations===!1){var N=s.validateGrammar({rules:r.values(S.gastProductionsCache),maxLookahead:S.maxLookahead,tokenTypes:r.values(S.tokensMap),errMsgProvider:a.defaultGrammarValidatorErrorProvider,grammarName:E});S.definitionErrors=S.definitionErrors.concat(N)}}),r.isEmpty(S.definitionErrors)&&(S.recoveryEnabled&&S.TRACE_INIT("computeAllProdsFollows",function(){var N=i.computeAllProdsFollows(r.values(S.gastProductionsCache));S.resyncFollows=N}),S.TRACE_INIT("ComputeLookaheadFunctions",function(){S.preComputeLookaheadFunctions(r.values(S.gastProductionsCache))})),!C.DEFER_DEFINITION_ERRORS_HANDLING&&!r.isEmpty(S.definitionErrors))throw w=r.map(S.definitionErrors,function(N){return N.message}),new Error(`Parser Definition Errors detected:
`+w.join(`
-------------------------------
`))})},C.DEFER_DEFINITION_ERRORS_HANDLING=!1,C})();e.Parser=b,m.applyMixins(b,[o.Recoverable,l.LooksAhead,c.TreeBuilder,u.LexerAdapter,d.RecognizerEngine,h.RecognizerApi,f.ErrorHandler,y.ContentAssist,g.GastRecorder,p.PerformanceTracer]);var _=(function(C){t(S,C);function S(w,E){E===void 0&&(E=e.DEFAULT_PARSER_CONFIG);var P=this,N=r.cloneObj(E);return N.outputCst=!0,P=C.call(this,w,N)||this,P}return S})(b);e.CstParser=_;var M=(function(C){t(S,C);function S(w,E){E===void 0&&(E=e.DEFAULT_PARSER_CONFIG);var P=this,N=r.cloneObj(E);return N.outputCst=!1,P=C.call(this,w,N)||this,P}return S})(b);e.EmbeddedActionsParser=M}),O2=vr(e=>{"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createSyntaxDiagramsCode=void 0;var t=ax();function r(i,n){var a=n===void 0?{}:n,s=a.resourceBase,o=s===void 0?"https://unpkg.com/chevrotain@"+t.VERSION+"/diagrams/":s,l=a.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>
`,h=`
<link rel='stylesheet' href='`+c+`'>
`,d=`
<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>
`,f=`
<div id="diagrams" align="center"></div>
`,y=`
<script>
window.serializedGrammar = `+JSON.stringify(i,null," ")+`;
<\/script>
`,g=`
<script>
var diagramsDiv = document.getElementById("diagrams");
main.drawDiagramsFromSerializedGrammar(serializedGrammar, diagramsDiv);
<\/script>
`;return u+h+d+f+y+g}e.createSyntaxDiagramsCode=r}),D2=vr(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=ax();Object.defineProperty(e,"VERSION",{enumerable:!0,get:function(){return t.VERSION}});var r=wn();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=hd();Object.defineProperty(e,"Lexer",{enumerable:!0,get:function(){return i.Lexer}}),Object.defineProperty(e,"LexerDefinitionErrorType",{enumerable:!0,get:function(){return i.LexerDefinitionErrorType}});var n=Ls();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 a=pd();Object.defineProperty(e,"defaultParserErrorProvider",{enumerable:!0,get:function(){return a.defaultParserErrorProvider}});var s=hc();Object.defineProperty(e,"EarlyExitException",{enumerable:!0,get:function(){return s.EarlyExitException}}),Object.defineProperty(e,"isRecognitionException",{enumerable:!0,get:function(){return s.isRecognitionException}}),Object.defineProperty(e,"MismatchedTokenException",{enumerable:!0,get:function(){return s.MismatchedTokenException}}),Object.defineProperty(e,"NotAllInputParsedException",{enumerable:!0,get:function(){return s.NotAllInputParsedException}}),Object.defineProperty(e,"NoViableAltException",{enumerable:!0,get:function(){return s.NoViableAltException}});var o=ox();Object.defineProperty(e,"defaultLexerErrorProvider",{enumerable:!0,get:function(){return o.defaultLexerErrorProvider}});var l=ln();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=ln();Object.defineProperty(e,"serializeGrammar",{enumerable:!0,get:function(){return c.serializeGrammar}}),Object.defineProperty(e,"serializeProduction",{enumerable:!0,get:function(){return c.serializeProduction}});var u=uc();Object.defineProperty(e,"GAstVisitor",{enumerable:!0,get:function(){return u.GAstVisitor}});function h(){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=h;var d=O2();Object.defineProperty(e,"createSyntaxDiagramsCode",{enumerable:!0,get:function(){return d.createSyntaxDiagramsCode}});var f=(function(){function y(){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 y})();e.Parser=f}),dc=D2(),k2=class extends fi{constructor(e){super(e)}load(e,t,r,i){let n=this,a=n.path===""?va.extractUrlBase(e):n.path,s=new bn(n.manager);s.setPath(n.path),s.setRequestHeader(n.requestHeader),s.setWithCredentials(n.withCredentials),s.load(e,function(o){try{t(n.parse(o,a))}catch(l){i?i(l):console.error(l),n.manager.itemError(e)}},r,i)}parse(e,t){let r={};function i(L){let A=n(),O=new U2(A.tokens),F=new B2(A.tokenVocabulary),Y=a(F.getBaseCstVisitorConstructor()),re=O.lex(L);F.input=re.tokens;let ue=F.vrml();if(F.errors.length>0)throw console.error(F.errors),Error("THREE.VRMLLoader: Parsing errors detected.");return Y.visit(ue)}function n(){let L=dc.createToken,A=L({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]*/}),O=L({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:A}),F=["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"],Y=L({name:"Version",pattern:/#VRML.*/,longer_alt:O}),re=L({name:"NodeName",pattern:new RegExp(F.join("|")),longer_alt:O}),ue=L({name:"DEF",pattern:/DEF/,longer_alt:O}),se=L({name:"USE",pattern:/USE/,longer_alt:O}),pe=L({name:"ROUTE",pattern:/ROUTE/,longer_alt:O}),Pe=L({name:"TO",pattern:/TO/,longer_alt:O}),Ce=L({name:"StringLiteral",pattern:/"(?:[^\\"\n\r]|\\[bfnrtv"\\/]|\\u[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F])*"/}),je=L({name:"HexLiteral",pattern:/0[xX][0-9a-fA-F]+/}),st=L({name:"NumberLiteral",pattern:/[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?/}),Pt=L({name:"TrueLiteral",pattern:/TRUE/}),ut=L({name:"FalseLiteral",pattern:/FALSE/}),ot=L({name:"NullLiteral",pattern:/NULL/}),tt=L({name:"LSquare",pattern:/\[/}),Ht=L({name:"RSquare",pattern:/]/}),fe=L({name:"LCurly",pattern:/{/}),qe=L({name:"RCurly",pattern:/}/}),Ue=L({name:"Comment",pattern:/#.*/,group:dc.Lexer.SKIPPED}),Ie=[L({name:"WhiteSpace",pattern:/[ ,\s]/,group:dc.Lexer.SKIPPED}),re,ue,se,pe,Pe,Pt,ut,ot,Y,O,A,Ce,je,st,tt,Ht,fe,qe,Ue],mt={};for(let lt=0,Ut=Ie.length;lt<Ut;lt++){let xt=Ie[lt];mt[xt.name]=xt}return{tokens:Ie,tokenVocabulary:mt}}function a(L){class A extends L{constructor(){super(),this.validateVisitor()}vrml(Y){let re={version:this.visit(Y.version),nodes:[],routes:[]};for(let ue=0,se=Y.node.length;ue<se;ue++){let pe=Y.node[ue];re.nodes.push(this.visit(pe))}if(Y.route)for(let ue=0,se=Y.route.length;ue<se;ue++){let pe=Y.route[ue];re.routes.push(this.visit(pe))}return re}version(Y){return Y.Version[0].image}node(Y){let re={name:Y.NodeName[0].image,fields:[]};if(Y.field)for(let ue=0,se=Y.field.length;ue<se;ue++){let pe=Y.field[ue];re.fields.push(this.visit(pe))}return Y.def&&(re.DEF=this.visit(Y.def[0])),re}field(Y){let re={name:Y.Identifier[0].image,type:null,values:null},ue;return Y.singleFieldValue&&(ue=this.visit(Y.singleFieldValue[0])),Y.multiFieldValue&&(ue=this.visit(Y.multiFieldValue[0])),re.type=ue.type,re.values=ue.values,re}def(Y){return(Y.Identifier||Y.NodeName)[0].image}use(Y){return{USE:(Y.Identifier||Y.NodeName)[0].image}}singleFieldValue(Y){return O(this,Y)}multiFieldValue(Y){return O(this,Y)}route(Y){return{FROM:Y.RouteIdentifier[0].image,TO:Y.RouteIdentifier[1].image}}}function O(F,Y){let re={type:null,values:[]};if(Y.node){re.type="node";for(let ue=0,se=Y.node.length;ue<se;ue++){let pe=Y.node[ue];re.values.push(F.visit(pe))}}if(Y.use){re.type="use";for(let ue=0,se=Y.use.length;ue<se;ue++){let pe=Y.use[ue];re.values.push(F.visit(pe))}}if(Y.StringLiteral){re.type="string";for(let ue=0,se=Y.StringLiteral.length;ue<se;ue++){let pe=Y.StringLiteral[ue];re.values.push(pe.image.replace(/'|"/g,""))}}if(Y.NumberLiteral){re.type="number";for(let ue=0,se=Y.NumberLiteral.length;ue<se;ue++){let pe=Y.NumberLiteral[ue];re.values.push(parseFloat(pe.image))}}if(Y.HexLiteral){re.type="hex";for(let ue=0,se=Y.HexLiteral.length;ue<se;ue++){let pe=Y.HexLiteral[ue];re.values.push(pe.image)}}if(Y.TrueLiteral){re.type="boolean";for(let ue=0,se=Y.TrueLiteral.length;ue<se;ue++)Y.TrueLiteral[ue].image==="TRUE"&&re.values.push(!0)}if(Y.FalseLiteral){re.type="boolean";for(let ue=0,se=Y.FalseLiteral.length;ue<se;ue++)Y.FalseLiteral[ue].image==="FALSE"&&re.values.push(!1)}return Y.NullLiteral&&(re.type="null",Y.NullLiteral.forEach(function(){re.values.push(null)})),re}return new A}function s(L){let A=L.nodes,O=new us;for(let F=0,Y=A.length;F<Y;F++){let re=A[F];o(re)}for(let F=0,Y=A.length;F<Y;F++){let re=A[F],ue=l(re);ue instanceof Ar&&O.add(ue),re.name==="WorldInfo"&&(O.userData.worldInfo=ue)}return O}function o(L){L.DEF&&(r[L.DEF]=L);let A=L.fields;for(let O=0,F=A.length;O<F;O++){let Y=A[O];if(Y.type==="node"){let re=Y.values;for(let ue=0,se=re.length;ue<se;ue++)o(re[ue])}}}function l(L){return L.USE?J(L.USE):(L.build!==void 0||(L.build=c(L)),L.build)}function c(L){let A=L.name,O;switch(A){case"Anchor":case"Group":case"Transform":case"Collision":O=u(L);break;case"Background":O=h(L);break;case"Shape":O=d(L);break;case"Appearance":O=f(L);break;case"Material":O=y(L);break;case"ImageTexture":O=v(L);break;case"PixelTexture":O=m(L);break;case"TextureTransform":O=x(L);break;case"IndexedFaceSet":O=M(L);break;case"IndexedLineSet":O=C(L);break;case"PointSet":O=S(L);break;case"Box":O=w(L);break;case"Cone":O=E(L);break;case"Cylinder":O=P(L);break;case"Sphere":O=N(L);break;case"ElevationGrid":O=D(L);break;case"Extrusion":O=B(L);break;case"Color":case"Coordinate":case"Normal":case"TextureCoordinate":O=b(L);break;case"WorldInfo":O=_(L);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:",A);break}return O!==void 0&&L.DEF!==void 0&&O.hasOwnProperty("name")===!0&&(O.name=L.DEF),O}function u(L){let A=new jr,O=L.fields;for(let F=0,Y=O.length;F<Y;F++){let re=O[F],ue=re.name,se=re.values;switch(ue){case"bboxCenter":break;case"bboxSize":break;case"center":break;case"children":Q(se,A);break;case"description":break;case"collide":break;case"parameter":break;case"rotation":let pe=new ee(se[0],se[1],se[2]).normalize(),Pe=se[3];A.quaternion.setFromAxisAngle(pe,Pe);break;case"scale":A.scale.set(se[0],se[1],se[2]);break;case"scaleOrientation":break;case"translation":A.position.set(se[0],se[1],se[2]);break;case"proxy":break;case"url":break;default:console.warn("THREE.VRMLLoader: Unknown field:",ue);break}}return A}function h(L){let A=new jr,O,F,Y,re,ue=L.fields;for(let pe=0,Pe=ue.length;pe<Pe;pe++){let Ce=ue[pe],je=Ce.name,st=Ce.values;switch(je){case"groundAngle":O=st;break;case"groundColor":F=st;break;case"backUrl":break;case"bottomUrl":break;case"frontUrl":break;case"leftUrl":break;case"rightUrl":break;case"topUrl":break;case"skyAngle":Y=st;break;case"skyColor":re=st;break;default:console.warn("THREE.VRMLLoader: Unknown field:",je);break}}let se=1e4;if(re){let pe=new Ua(se,32,16),Pe=new ti({fog:!1,side:_t,depthWrite:!1,depthTest:!1});re.length>3?(_e(pe,se,Y,He(re),!0),Pe.vertexColors=!0):Pe.color.setRGB(re[0],re[1],re[2],Pr);let Ce=new hr(pe,Pe);A.add(Ce)}if(F&&F.length>0){let pe=new Ua(se,32,16,0,2*Math.PI,.5*Math.PI,1.5*Math.PI),Pe=new ti({fog:!1,side:_t,vertexColors:!0,depthWrite:!1,depthTest:!1});_e(pe,se,O,He(F),!1);let Ce=new hr(pe,Pe);A.add(Ce)}return A.renderOrder=-1/0,A}function d(L){let A=L.fields,O=new ti({name:fi.DEFAULT_MATERIAL_NAME,color:0}),F;for(let re=0,ue=A.length;re<ue;re++){let se=A[re],pe=se.name,Pe=se.values;switch(pe){case"appearance":Pe[0]!==null&&(O=l(Pe[0]));break;case"geometry":Pe[0]!==null&&(F=l(Pe[0]));break;default:console.warn("THREE.VRMLLoader: Unknown field:",pe);break}}let Y;if(F&&F.attributes.position){let re=F._type;if(re==="points"){let ue=new Yl({name:fi.DEFAULT_MATERIAL_NAME,color:16777215,opacity:O.opacity,transparent:O.transparent});F.attributes.color!==void 0?ue.vertexColors=!0:O.isMeshPhongMaterial&&ue.color.copy(O.emissive),Y=new Ih(F,ue)}else if(re==="line"){let ue=new ri({name:fi.DEFAULT_MATERIAL_NAME,color:16777215,opacity:O.opacity,transparent:O.transparent});F.attributes.color!==void 0?ue.vertexColors=!0:O.isMeshPhongMaterial&&ue.color.copy(O.emissive),Y=new Fi(F,ue)}else F._solid!==void 0&&(O.side=F._solid?it:Rt),F.attributes.color!==void 0&&(O.vertexColors=!0),Y=new hr(F,O)}else Y=new Ar,Y.visible=!1;return Y}function f(L){let A=new wf,O,F=L.fields;for(let Y=0,re=F.length;Y<re;Y++){let ue=F[Y],se=ue.name,pe=ue.values;switch(se){case"material":if(pe[0]!==null){let Ce=l(pe[0]);Ce.diffuseColor&&A.color.copy(Ce.diffuseColor),Ce.emissiveColor&&A.emissive.copy(Ce.emissiveColor),Ce.shininess&&(A.shininess=Ce.shininess),Ce.specularColor&&A.specular.copy(Ce.specularColor),Ce.transparency&&(A.opacity=1-Ce.transparency),Ce.transparency>0&&(A.transparent=!0)}else A=new ti({name:fi.DEFAULT_MATERIAL_NAME,color:0});break;case"texture":let Pe=pe[0];Pe!==null&&(Pe.name==="ImageTexture"||Pe.name==="PixelTexture")&&(A.map=l(Pe));break;case"textureTransform":pe[0]!==null&&(O=l(pe[0]));break;default:console.warn("THREE.VRMLLoader: Unknown field:",se);break}}if(A.map){if(A.map.__type){switch(A.map.__type){case Un.INTENSITY_ALPHA:A.opacity=1;break;case Un.RGB:A.color.set(16777215);break;case Un.RGBA:A.color.set(16777215),A.opacity=1;break;default:}delete A.map.__type}O&&(A.map.center.copy(O.center),A.map.rotation=O.rotation,A.map.repeat.copy(O.scale),A.map.offset.copy(O.translation))}return A}function y(L){let A={},O=L.fields;for(let F=0,Y=O.length;F<Y;F++){let re=O[F],ue=re.name,se=re.values;switch(ue){case"ambientIntensity":break;case"diffuseColor":A.diffuseColor=new yt().setRGB(se[0],se[1],se[2],Pr);break;case"emissiveColor":A.emissiveColor=new yt().setRGB(se[0],se[1],se[2],Pr);break;case"shininess":A.shininess=se[0];break;case"specularColor":A.specularColor=new yt().setRGB(se[0],se[1],se[2],Pr);break;case"transparency":A.transparency=se[0];break;default:console.warn("THREE.VRMLLoader: Unknown field:",ue);break}}return A}function g(L,A,O){let F;switch(A){case Un.INTENSITY:F=parseInt(L),O.r=F,O.g=F,O.b=F,O.a=1;break;case Un.INTENSITY_ALPHA:F=parseInt("0x"+L.substring(2,4)),O.r=F,O.g=F,O.b=F,O.a=parseInt("0x"+L.substring(4,6));break;case Un.RGB:O.r=parseInt("0x"+L.substring(2,4)),O.g=parseInt("0x"+L.substring(4,6)),O.b=parseInt("0x"+L.substring(6,8)),O.a=1;break;case Un.RGBA:O.r=parseInt("0x"+L.substring(2,4)),O.g=parseInt("0x"+L.substring(4,6)),O.b=parseInt("0x"+L.substring(6,8)),O.a=parseInt("0x"+L.substring(8,10));break;default:}}function p(L){let A;switch(L){case 1:A=Un.INTENSITY;break;case 2:A=Un.INTENSITY_ALPHA;break;case 3:A=Un.RGB;break;case 4:A=Un.RGBA;break;default:}return A}function m(L){let A,O=Ni,F=Ni,Y=L.fields;for(let re=0,ue=Y.length;re<ue;re++){let se=Y[re],pe=se.name,Pe=se.values;switch(pe){case"image":let Ce=Pe[0],je=Pe[1],st=Pe[2],Pt=p(st),ut=new Uint8Array(4*Ce*je),ot={r:0,g:0,b:0,a:0};for(let tt=3,Ht=0,fe=Pe.length;tt<fe;tt++,Ht++){g(Pe[tt],Pt,ot);let qe=Ht*4;ut[qe+0]=ot.r,ut[qe+1]=ot.g,ut[qe+2]=ot.b,ut[qe+3]=ot.a}A=new sn(ut,Ce,je),A.colorSpace=Pr,A.needsUpdate=!0,A.__type=Pt;break;case"repeatS":Pe[0]===!1&&(O=Ri);break;case"repeatT":Pe[0]===!1&&(F=Ri);break;default:console.warn("THREE.VRMLLoader: Unknown field:",pe);break}}return A&&(A.wrapS=O,A.wrapT=F),A}function v(L){let A,O=Ni,F=Ni,Y=L.fields;for(let re=0,ue=Y.length;re<ue;re++){let se=Y[re],pe=se.name,Pe=se.values;switch(pe){case"url":let Ce=Pe[0];Ce&&(A=oe.load(Ce));break;case"repeatS":Pe[0]===!1&&(O=Ri);break;case"repeatT":Pe[0]===!1&&(F=Ri);break;default:console.warn("THREE.VRMLLoader: Unknown field:",pe);break}}return A&&(A.wrapS=O,A.wrapT=F,A.colorSpace=Pr),A}function x(L){let A={center:new Xe,rotation:new Xe,scale:new Xe,translation:new Xe},O=L.fields;for(let F=0,Y=O.length;F<Y;F++){let re=O[F],ue=re.name,se=re.values;switch(ue){case"center":A.center.set(se[0],se[1]);break;case"rotation":A.rotation=se[0];break;case"scale":A.scale.set(se[0],se[1]);break;case"translation":A.translation.set(se[0],se[1]);break;default:console.warn("THREE.VRMLLoader: Unknown field:",ue);break}}return A}function b(L){return L.fields[0].values}function _(L){let A={},O=L.fields;for(let F=0,Y=O.length;F<Y;F++){let re=O[F],ue=re.name,se=re.values;switch(ue){case"title":A.title=se[0];break;case"info":A.info=se;break;default:console.warn("THREE.VRMLLoader: Unknown field:",ue);break}}return A}function M(L){let A,O,F,Y,re=!0,ue=!0,se=0,pe,Pe,Ce,je,st=!0,Pt=!0,ut=L.fields;for(let Ie=0,mt=ut.length;Ie<mt;Ie++){let lt=ut[Ie],Ut=lt.name,xt=lt.values;switch(Ut){case"color":let Dt=xt[0];Dt!==null&&(A=l(Dt));break;case"coord":let gt=xt[0];gt!==null&&(O=l(gt));break;case"normal":let Vt=xt[0];Vt!==null&&(F=l(Vt));break;case"texCoord":let $e=xt[0];$e!==null&&(Y=l($e));break;case"ccw":re=xt[0];break;case"colorIndex":pe=xt;break;case"colorPerVertex":st=xt[0];break;case"convex":break;case"coordIndex":Pe=xt;break;case"creaseAngle":se=xt[0];break;case"normalIndex":Ce=xt;break;case"normalPerVertex":Pt=xt[0];break;case"solid":ue=xt[0];break;case"texCoordIndex":je=xt;break;default:console.warn("THREE.VRMLLoader: Unknown field:",Ut);break}}if(Pe===void 0)return console.warn("THREE.VRMLLoader: Missing coordIndex."),new ar;let ot=j(Pe,re),tt,Ht,fe;if(A){if(st===!0)if(pe&&pe.length>0){let Ie=j(pe,re);tt=K(ot,Ie,A,3)}else tt=ae(ot,new Mt(A,3));else if(pe&&pe.length>0){let Ie=H(A,pe),mt=k(Ie,Pe);tt=ie(ot,mt)}else{let Ie=k(A,Pe);tt=ie(ot,Ie)}ne(tt)}if(F)if(Pt===!0)if(Ce&&Ce.length>0){let Ie=j(Ce,re);Ht=K(ot,Ie,F,3)}else Ht=ae(ot,new Mt(F,3));else if(Ce&&Ce.length>0){let Ie=H(F,Ce),mt=k(Ie,Pe);Ht=ie(ot,mt)}else{let Ie=k(F,Pe);Ht=ie(ot,Ie)}else Ht=me(ot,O,se);if(Y)if(je&&je.length>0){let Ie=j(je,re);fe=K(ot,Ie,Y,2)}else fe=ae(ot,new Mt(Y,2));let qe=new ar,Ue=ae(ot,new Mt(O,3));return qe.setAttribute("position",Ue),qe.setAttribute("normal",Ht),tt&&qe.setAttribute("color",tt),fe&&qe.setAttribute("uv",fe),qe._solid=ue,qe._type="mesh",qe}function C(L){let A,O,F,Y,re=!0,ue=L.fields;for(let je=0,st=ue.length;je<st;je++){let Pt=ue[je],ut=Pt.name,ot=Pt.values;switch(ut){case"color":let tt=ot[0];tt!==null&&(A=l(tt));break;case"coord":let Ht=ot[0];Ht!==null&&(O=l(Ht));break;case"colorIndex":F=ot;break;case"colorPerVertex":re=ot[0];break;case"coordIndex":Y=ot;break;default:console.warn("THREE.VRMLLoader: Unknown field:",ut);break}}let se,pe=U(Y);if(A){if(re===!0)if(F.length>0){let je=U(F);se=K(pe,je,A,3)}else se=ae(pe,new Mt(A,3));else if(F.length>0){let je=H(A,F),st=X(je,Y);se=le(pe,st)}else{let je=X(A,Y);se=le(pe,je)}ne(se)}let Pe=new ar,Ce=ae(pe,new Mt(O,3));return Pe.setAttribute("position",Ce),se&&Pe.setAttribute("color",se),Pe._type="line",Pe}function S(L){let A,O,F=L.fields;for(let re=0,ue=F.length;re<ue;re++){let se=F[re],pe=se.name,Pe=se.values;switch(pe){case"color":let Ce=Pe[0];Ce!==null&&(A=l(Ce));break;case"coord":let je=Pe[0];je!==null&&(O=l(je));break;default:console.warn("THREE.VRMLLoader: Unknown field:",pe);break}}let Y=new ar;if(Y.setAttribute("position",new Mt(O,3)),A){let re=new Mt(A,3);ne(re),Y.setAttribute("color",re)}return Y._type="points",Y}function w(L){let A=new ee(2,2,2),O=L.fields;for(let F=0,Y=O.length;F<Y;F++){let re=O[F],ue=re.name,se=re.values;switch(ue){case"size":A.x=se[0],A.y=se[1],A.z=se[2];break;default:console.warn("THREE.VRMLLoader: Unknown field:",ue);break}}return new da(A.x,A.y,A.z)}function E(L){let A=1,O=2,F=!1,Y=L.fields;for(let re=0,ue=Y.length;re<ue;re++){let se=Y[re],pe=se.name,Pe=se.values;switch(pe){case"bottom":F=!Pe[0];break;case"bottomRadius":A=Pe[0];break;case"height":O=Pe[0];break;case"side":break;default:console.warn("THREE.VRMLLoader: Unknown field:",pe);break}}return new gf(A,O,16,1,F)}function P(L){let A=1,O=2,F=L.fields;for(let Y=0,re=F.length;Y<re;Y++){let ue=F[Y],se=ue.name,pe=ue.values;switch(se){case"bottom":break;case"radius":A=pe[0];break;case"height":O=pe[0];break;case"side":break;case"top":break;default:console.warn("THREE.VRMLLoader: Unknown field:",se);break}}return new Zl(A,A,O,16,1)}function N(L){let A=1,O=L.fields;for(let F=0,Y=O.length;F<Y;F++){let re=O[F],ue=re.name,se=re.values;switch(ue){case"radius":A=se[0];break;default:console.warn("THREE.VRMLLoader: Unknown field:",ue);break}}return new Ua(A,16,16)}function D(L){let A,O,F,Y,re=!0,ue=!0,se=!0,pe=!0,Pe=0,Ce=2,je=2,st=1,Pt=1,ut=L.fields;for(let xt=0,Dt=ut.length;xt<Dt;xt++){let gt=ut[xt],Vt=gt.name,$e=gt.values;switch(Vt){case"color":let Tr=$e[0];Tr!==null&&(A=l(Tr));break;case"normal":let ni=$e[0];ni!==null&&(O=l(ni));break;case"texCoord":let $r=$e[0];$r!==null&&(F=l($r));break;case"height":Y=$e;break;case"ccw":pe=$e[0];break;case"colorPerVertex":re=$e[0];break;case"creaseAngle":Pe=$e[0];break;case"normalPerVertex":ue=$e[0];break;case"solid":se=$e[0];break;case"xDimension":Ce=$e[0];break;case"xSpacing":st=$e[0];break;case"zDimension":je=$e[0];break;case"zSpacing":Pt=$e[0];break;default:console.warn("THREE.VRMLLoader: Unknown field:",Vt);break}}let ot=[],tt=[],Ht=[],fe=[];for(let xt=0;xt<je;xt++)for(let Dt=0;Dt<Ce;Dt++){let gt=xt*Ce+Dt,Vt=st*xt,$e=Y[gt],Tr=Pt*Dt;if(ot.push(Vt,$e,Tr),A&&re===!0){let ni=A[gt*3+0],$r=A[gt*3+1],qn=A[gt*3+2];Ht.push(ni,$r,qn)}if(O&&ue===!0){let ni=O[gt*3+0],$r=O[gt*3+1],qn=O[gt*3+2];tt.push(ni,$r,qn)}if(F){let ni=F[gt*2+0],$r=F[gt*2+1];fe.push(ni,$r)}else fe.push(xt/(Ce-1),Dt/(je-1))}let qe=[];for(let xt=0;xt<Ce-1;xt++)for(let Dt=0;Dt<je-1;Dt++){let gt=xt+Dt*Ce,Vt=xt+(Dt+1)*Ce,$e=xt+1+(Dt+1)*Ce,Tr=xt+1+Dt*Ce;pe===!0?(qe.push(gt,$e,Vt),qe.push($e,gt,Tr)):(qe.push(gt,Vt,$e),qe.push($e,Tr,gt))}let Ue=ae(qe,new Mt(ot,3)),Ie=ae(qe,new Mt(fe,2)),mt,lt;if(A){if(re===!1){for(let xt=0;xt<Ce-1;xt++)for(let Dt=0;Dt<je-1;Dt++){let gt=xt+Dt*(Ce-1),Vt=A[gt*3+0],$e=A[gt*3+1],Tr=A[gt*3+2];Ht.push(Vt,$e,Tr),Ht.push(Vt,$e,Tr),Ht.push(Vt,$e,Tr),Ht.push(Vt,$e,Tr),Ht.push(Vt,$e,Tr),Ht.push(Vt,$e,Tr)}mt=new Mt(Ht,3)}else mt=ae(qe,new Mt(Ht,3));ne(mt)}if(O)if(ue===!1){for(let xt=0;xt<Ce-1;xt++)for(let Dt=0;Dt<je-1;Dt++){let gt=xt+Dt*(Ce-1),Vt=O[gt*3+0],$e=O[gt*3+1],Tr=O[gt*3+2];tt.push(Vt,$e,Tr),tt.push(Vt,$e,Tr),tt.push(Vt,$e,Tr),tt.push(Vt,$e,Tr),tt.push(Vt,$e,Tr),tt.push(Vt,$e,Tr)}lt=new Mt(tt,3)}else lt=ae(qe,new Mt(tt,3));else lt=me(qe,ot,Pe);let Ut=new ar;return Ut.setAttribute("position",Ue),Ut.setAttribute("normal",lt),Ut.setAttribute("uv",Ie),mt&&Ut.setAttribute("color",mt),Ut._solid=se,Ut._type="mesh",Ut}function B(L){let A=[1,1,1,-1,-1,-1,-1,1,1,1],O=[0,0,0,0,1,0],F,Y,re=!0,ue=!0,se=0,pe=!0,Pe=!0,Ce=L.fields;for(let Ut=0,xt=Ce.length;Ut<xt;Ut++){let Dt=Ce[Ut],gt=Dt.name,Vt=Dt.values;switch(gt){case"beginCap":re=Vt[0];break;case"ccw":ue=Vt[0];break;case"convex":break;case"creaseAngle":se=Vt[0];break;case"crossSection":A=Vt;break;case"endCap":pe=Vt[0];break;case"orientation":Y=Vt;break;case"scale":F=Vt;break;case"solid":Pe=Vt[0];break;case"spine":O=Vt;break;default:console.warn("THREE.VRMLLoader: Unknown field:",gt);break}}let je=A[0]===A[A.length-2]&&A[1]===A[A.length-1],st=[],Pt=new ee,ut=new ee,ot=new ee,tt=new ee,Ht=new di;for(let Ut=0,xt=0,Dt=0,gt=O.length;Ut<gt;Ut+=3,xt+=2,Dt+=4){Pt.fromArray(O,Ut),ut.x=F?F[xt+0]:1,ut.y=1,ut.z=F?F[xt+1]:1,ot.x=Y?Y[Dt+0]:0,ot.y=Y?Y[Dt+1]:0,ot.z=Y?Y[Dt+2]:1;let Vt=Y?Y[Dt+3]:0;for(let $e=0,Tr=A.length;$e<Tr;$e+=2)tt.x=A[$e+0],tt.y=0,tt.z=A[$e+1],tt.multiply(ut),Ht.setFromAxisAngle(ot,Vt),tt.applyQuaternion(Ht),tt.add(Pt),st.push(tt.x,tt.y,tt.z)}let fe=[],qe=O.length/3,Ue=A.length/2;for(let Ut=0;Ut<qe-1;Ut++)for(let xt=0;xt<Ue-1;xt++){let Dt=xt+Ut*Ue,gt=xt+1+Ut*Ue,Vt=xt+(Ut+1)*Ue,$e=xt+1+(Ut+1)*Ue;xt===Ue-2&&je===!0&&(gt=Ut*Ue,$e=(Ut+1)*Ue),ue===!0?(fe.push(Dt,gt,Vt),fe.push(Vt,gt,$e)):(fe.push(Dt,Vt,gt),fe.push(Vt,$e,gt))}if(re===!0||pe===!0){let Ut=[];for(let gt=0,Vt=A.length;gt<Vt;gt+=2)Ut.push(new Xe(A[gt],A[gt+1]));let xt=ma.triangulateShape(Ut,[]),Dt=[];for(let gt=0,Vt=xt.length;gt<Vt;gt++){let $e=xt[gt];Dt.push($e[0],$e[1],$e[2])}if(re===!0)for(let gt=0,Vt=Dt.length;gt<Vt;gt+=3)ue===!0?fe.push(Dt[gt+0],Dt[gt+1],Dt[gt+2]):fe.push(Dt[gt+0],Dt[gt+2],Dt[gt+1]);if(pe===!0){let gt=Ue*(qe-1);for(let Vt=0,$e=Dt.length;Vt<$e;Vt+=3)ue===!0?fe.push(gt+Dt[Vt+0],gt+Dt[Vt+2],gt+Dt[Vt+1]):fe.push(gt+Dt[Vt+0],gt+Dt[Vt+1],gt+Dt[Vt+2])}}let Ie=ae(fe,new Mt(st,3)),mt=me(fe,st,se),lt=new ar;return lt.setAttribute("position",Ie),lt.setAttribute("normal",mt),lt._solid=Pe,lt._type="mesh",lt}function J(L){let A=r[L],O=l(A);return O.isObject3D||O.isMaterial?O.clone():O}function Q(L,A){for(let O=0,F=L.length;O<F;O++){let Y=l(L[O]);Y instanceof Ar&&A.add(Y)}}function j(L,A){let O=[],F=0;for(let Y=0,re=L.length;Y<re;Y++){let ue=L[F],se=L[Y+(A?1:2)],pe=L[Y+(A?2:1)];O.push(ue,se,pe),(L[Y+3]===-1||Y+3>=re)&&(Y+=3,F=Y+1)}return O}function k(L,A){let O=[],F=0;for(let Y=0,re=A.length;Y<re;Y++){let ue=F*3,se=L[ue],pe=L[ue+1],Pe=L[ue+2];O.push(se,pe,Pe),(A[Y+3]===-1||Y+3>=re)&&(Y+=3,F++)}return O}function H(L,A){let O=[];for(let F=0,Y=A.length;F<Y;F++){let re=A[F]*3,ue=L[re],se=L[re+1],pe=L[re+2];O.push(ue,se,pe)}return O}function U(L){let A=[];for(let O=0,F=L.length;O<F;O++){let Y=L[O],re=L[O+1];A.push(Y,re),(L[O+2]===-1||O+2>=F)&&(O+=2)}return A}function X(L,A){let O=[],F=0;for(let Y=0,re=A.length;Y<re;Y++){let ue=F*3,se=L[ue],pe=L[ue+1],Pe=L[ue+2];O.push(se,pe,Pe),(A[Y+2]===-1||Y+2>=re)&&(Y+=2,F++)}return O}let W=new ee,$=new ee,G=new ee,T=new Xe,I=new Xe,V=new Xe;function K(L,A,O,F){let Y=[];for(let re=0,ue=L.length;re<ue;re+=3){let se=A[re],pe=A[re+1],Pe=A[re+2];F===2?(T.fromArray(O,se*F),I.fromArray(O,pe*F),V.fromArray(O,Pe*F),Y.push(T.x,T.y),Y.push(I.x,I.y),Y.push(V.x,V.y)):(W.fromArray(O,se*F),$.fromArray(O,pe*F),G.fromArray(O,Pe*F),Y.push(W.x,W.y,W.z),Y.push($.x,$.y,$.z),Y.push(G.x,G.y,G.z))}return new Mt(Y,F)}function ie(L,A){let O=[];for(let F=0,Y=0,re=L.length;F<re;F+=3,Y++)W.fromArray(A,Y*3),O.push(W.x,W.y,W.z),O.push(W.x,W.y,W.z),O.push(W.x,W.y,W.z);return new Mt(O,3)}function le(L,A){let O=[];for(let F=0,Y=0,re=L.length;F<re;F+=2,Y++)W.fromArray(A,Y*3),O.push(W.x,W.y,W.z),O.push(W.x,W.y,W.z);return new Mt(O,3)}function ae(L,A){let O=A.array,F=A.itemSize,Y=new O.constructor(L.length*F),re=0,ue=0;for(let se=0,pe=L.length;se<pe;se++){re=L[se]*F;for(let Pe=0;Pe<F;Pe++)Y[ue++]=O[re++]}return new Mt(Y,F)}let de=new ee,z=new ee;function me(L,A,O){let F=[],Y={};for(let ue=0,se=L.length;ue<se;ue+=3){let pe=L[ue],Pe=L[ue+1],Ce=L[ue+2],je=new z2(pe,Pe,Ce);W.fromArray(A,pe*3),$.fromArray(A,Pe*3),G.fromArray(A,Ce*3),z.subVectors(G,$),de.subVectors(W,$),z.cross(de),z.normalize(),je.normal.copy(z),Y[pe]===void 0&&(Y[pe]=[]),Y[Pe]===void 0&&(Y[Pe]=[]),Y[Ce]===void 0&&(Y[Ce]=[]),Y[pe].push(je.normal),Y[Pe].push(je.normal),Y[Ce].push(je.normal),F.push(je)}let re=[];for(let ue=0,se=F.length;ue<se;ue++){let pe=F[ue],Pe=we(Y[pe.a],pe.normal,O),Ce=we(Y[pe.b],pe.normal,O),je=we(Y[pe.c],pe.normal,O);W.fromArray(A,pe.a*3),$.fromArray(A,pe.b*3),G.fromArray(A,pe.c*3),re.push(Pe.x,Pe.y,Pe.z),re.push(Ce.x,Ce.y,Ce.z),re.push(je.x,je.y,je.z)}return new Mt(re,3)}function we(L,A,O){let F=new ee;if(O===0)F.copy(A);else for(let Y=0,re=L.length;Y<re;Y++)L[Y].angleTo(A)<O&&F.add(L[Y]);return F.normalize()}function He(L){let A=[];for(let O=0,F=L.length;O<F;O+=3)A.push(new yt(L[O],L[O+1],L[O+2]));return A}function ne(L){let A=new yt;for(let O=0;O<L.count;O++)A.fromBufferAttribute(L,O),_r.toWorkingColorSpace(A,Pr),L.setXYZ(O,A.r,A.g,A.b)}function _e(L,A,O,F,Y){let re=[],ue=Y===!0?0:Math.PI;for(let st=0,Pt=F.length;st<Pt;st++){let ut=st===0?0:O[st-1];ut=Y===!0?ut:ue-ut;let ot=new ee;ot.setFromSphericalCoords(A,ut,0),re.push(ot)}let se=L.index,pe=L.attributes.position,Pe=new Mr(new Float32Array(L.attributes.position.count*3),3),Ce=new ee,je=new yt;for(let st=0;st<se.count;st++){let Pt=se.getX(st);Ce.fromBufferAttribute(pe,Pt);let ut,ot,tt=1;for(let qe=1;qe<re.length;qe++){ut=qe-1,ot=qe;let Ue=re[ut],Ie=re[ot];if(Y===!0){if(Ce.y<=Ue.y&&Ce.y>Ie.y){tt=Math.abs(Ue.y-Ce.y)/Math.abs(Ue.y-Ie.y);break}}else if(Ce.y>=Ue.y&&Ce.y<Ie.y){tt=Math.abs(Ue.y-Ce.y)/Math.abs(Ue.y-Ie.y);break}}let Ht=F[ut],fe=F[ot];je.copy(Ht).lerp(fe,tt),_r.toWorkingColorSpace(je,Pr),Pe.setXYZ(Pt,je.r,je.g,je.b)}L.setAttribute("color",Pe)}let oe=new If(this.manager);if(oe.setPath(this.resourcePath||t).setCrossOrigin(this.crossOrigin),e.indexOf("#VRML V2.0")===-1)throw Error("THREE.VRMLLexer: Version of VRML asset not supported.");let ce=i(e);return s(ce)}},U2=class{constructor(e){this.lexer=new dc.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}},F2=dc.CstParser,B2=class extends F2{constructor(e){super(e);let t=this,r=e.Version,i=e.LCurly,n=e.RCurly,a=e.LSquare,s=e.RSquare,o=e.Identifier,l=e.RouteIdentifier,c=e.StringLiteral,u=e.HexLiteral,h=e.NumberLiteral,d=e.TrueLiteral,f=e.FalseLiteral,y=e.NullLiteral,g=e.DEF,p=e.USE,m=e.ROUTE,v=e.TO,x=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(x),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(g),t.OR([{ALT:function(){t.CONSUME(o)}},{ALT:function(){t.CONSUME(x)}}])}),t.RULE("use",function(){t.CONSUME(p),t.OR([{ALT:function(){t.CONSUME(o)}},{ALT:function(){t.CONSUME(x)}}])}),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(h)}},{ALT:function(){t.CONSUME(d)}},{ALT:function(){t.CONSUME(f)}},{ALT:function(){t.CONSUME(y)}}])})}),t.RULE("multiFieldValue",function(){t.CONSUME(a),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(h)}},{ALT:function(){t.CONSUME(y)}}])}),t.CONSUME(s)}),t.RULE("route",function(){t.CONSUME(m),t.CONSUME(l),t.CONSUME(v),t.CONSUME2(l)}),this.performSelfAnalysis()}},z2=class{constructor(e,t,r){this.a=e,this.b=t,this.c=r,this.normal=new ee}},Un={INTENSITY:1,INTENSITY_ALPHA:2,RGB:3,RGBA:4},G2=class extends us{constructor(){super();let e=new da;e.deleteAttribute("uv");let t=new Ki({side:_t}),r=new Ki,i=new jh(16777215,900,28,2);i.position.set(.418,16.199,.3),this.add(i);let n=new hr(e,t);n.position.set(-.757,13.219,.717),n.scale.set(31.713,28.305,28.591),this.add(n);let a=new hr(e,r);a.position.set(-10.906,2.009,1.846),a.rotation.set(0,-.195,0),a.scale.set(2.328,7.905,4.651),this.add(a);let s=new hr(e,r);s.position.set(-5.607,-.754,-.758),s.rotation.set(0,.994,0),s.scale.set(1.97,1.534,3.955),this.add(s);let o=new hr(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 hr(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 hr(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 hr(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 h=new hr(e,zo(50));h.position.set(-16.116,14.37,8.208),h.scale.set(.1,2.428,2.739),this.add(h);let d=new hr(e,zo(50));d.position.set(-16.109,18.021,-8.207),d.scale.set(.1,2.425,2.751),this.add(d);let f=new hr(e,zo(17));f.position.set(14.904,12.198,-1.832),f.scale.set(.15,4.265,6.331),this.add(f);let y=new hr(e,zo(43));y.position.set(-.462,8.89,14.52),y.scale.set(4.38,5.441,.088),this.add(y);let g=new hr(e,zo(20));g.position.set(3.235,11.486,-12.541),g.scale.set(2.5,2,.1),this.add(g);let p=new hr(e,zo(100));p.position.set(0,20,0),p.scale.set(1,.1,1),this.add(p)}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 zo(e){let t=new ti;return t.color.setScalar(e),t}var pc=new ee;function En(e,t,r,i,n,a){let s=2*Math.PI*n/4,o=Math.max(a-2*n,0),l=Math.PI/4;pc.copy(t),pc[i]=0,pc.normalize();let c=.5*s/(s+o),u=1-pc.angleTo(e)/l;return Math.sign(pc[r])===1?u*c:o/(s+o)+c+c*(1-u)}var V2=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 a=this.toNonIndexed();this.index=null,this.attributes.position=a.attributes.position,this.attributes.normal=a.attributes.normal,this.attributes.uv=a.attributes.uv;let s=new ee,o=new ee,l=new ee(e,t,r).divideScalar(2).subScalar(n),c=this.attributes.position.array,u=this.attributes.normal.array,h=this.attributes.uv.array,d=c.length/6,f=new ee,y=.5/i;for(let g=0,p=0;g<c.length;g+=3,p+=2)switch(s.fromArray(c,g),o.copy(s),o.x-=Math.sign(o.x)*y,o.y-=Math.sign(o.y)*y,o.z-=Math.sign(o.z)*y,o.normalize(),c[g+0]=l.x*Math.sign(s.x)+o.x*n,c[g+1]=l.y*Math.sign(s.y)+o.y*n,c[g+2]=l.z*Math.sign(s.z)+o.z*n,u[g+0]=o.x,u[g+1]=o.y,u[g+2]=o.z,Math.floor(g/d)){case 0:f.set(1,0,0),h[p+0]=En(f,o,"z","y",n,r),h[p+1]=1-En(f,o,"y","z",n,t);break;case 1:f.set(-1,0,0),h[p+0]=1-En(f,o,"z","y",n,r),h[p+1]=1-En(f,o,"y","z",n,t);break;case 2:f.set(0,1,0),h[p+0]=1-En(f,o,"x","z",n,e),h[p+1]=En(f,o,"z","x",n,r);break;case 3:f.set(0,-1,0),h[p+0]=1-En(f,o,"x","z",n,e),h[p+1]=1-En(f,o,"z","x",n,r);break;case 4:f.set(0,0,1),h[p+0]=1-En(f,o,"x","y",n,e),h[p+1]=1-En(f,o,"y","x",n,t);break;case 5:f.set(0,0,-1),h[p+0]=En(f,o,"x","y",n,e),h[p+1]=1-En(f,o,"y","x",n,t);break}}},gd={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;
}`},Os=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(){}},H2=new Oo(-1,1,1,-1,0,1),W2=class extends ar{constructor(){super(),this.setAttribute("position",new Mt([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new Mt([0,2,0,0,2,0],2))}},j2=new W2,yd=class{constructor(e){this._mesh=new hr(j2,e)}dispose(){this._mesh.geometry.dispose()}render(e){e.render(this._mesh,H2)}get material(){return this._mesh.material}set material(e){this._mesh.material=e}},X2=class extends Os{constructor(e,t){super(),this.textureID=t!==void 0?t:"tDiffuse",e instanceof oi?(this.uniforms=e.uniforms,this.material=e):e&&(this.uniforms=xn.clone(e.uniforms),this.material=new oi({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 yd(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()}},px=class extends Os{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 a,s;this.inverse?(a=0,s=1):(a=1,s=0),n.buffers.stencil.setTest(!0),n.buffers.stencil.setOp(i.REPLACE,i.REPLACE,i.REPLACE),n.buffers.stencil.setFunc(i.ALWAYS,a,4294967295),n.buffers.stencil.setClear(s),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)}},Y2=class extends Os{constructor(){super(),this.needsSwap=!1}render(e){e.state.buffers.stencil.setLocked(!1),e.state.buffers.stencil.setTest(!1)}},q2=class{constructor(e,t){if(this.renderer=e,this._pixelRatio=e.getPixelRatio(),t===void 0){let r=e.getSize(new Xe);this._width=r.width,this._height=r.height,t=new Pi(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:yn}),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 X2(gd),this.copyPass.material.blending=Ft,this.clock=new Ff}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 a=this.passes[i];if(a.enabled!==!1){if(a.renderToScreen=this.renderToScreen&&this.isLastEnabledPass(i),a.render(this.renderer,this.writeBuffer,this.readBuffer,e,r),a.needsSwap){if(r){let s=this.renderer.getContext(),o=this.renderer.state.buffers.stencil;o.setFunc(s.NOTEQUAL,1,4294967295),this.copyPass.render(this.renderer,this.writeBuffer,this.readBuffer,e),o.setFunc(s.EQUAL,1,4294967295)}this.swapBuffers()}px!==void 0&&(a instanceof px?r=!0:a instanceof Y2&&(r=!1))}}this.renderer.setRenderTarget(t)}reset(e){if(e===void 0){let t=this.renderer.getSize(new Xe);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()}},K2=class extends Os{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 yt}render(e,t,r){let i=e.autoClear;e.autoClear=!1;let n,a;this.overrideMaterial!==null&&(a=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=a),e.autoClear=i}},vd={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 Xe},cameraNear:{value:null},cameraFar:{value:null},cameraProjectionMatrix:{value:new Jt},cameraProjectionMatrixInverse:{value:new Jt},cameraWorldMatrix:{value:new Jt},radius:{value:.25},distanceExponent:{value:1},thickness:{value:1},distanceFallOff:{value:1},scale:{value:1},sceneBoxMin:{value:new ee(-1,-1,-1)},sceneBoxMax:{value:new ee(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;
}`},xd={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 );
}`},gm={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 Z2(e=5){let t=Math.floor(e)%2===0?Math.floor(e)+1:Math.floor(e),r=Q2(t),i=r.length,n=new Uint8Array(i*4);for(let s=0;s<i;++s){let o=r[s],l=2*Math.PI*o/i,c=new ee(Math.cos(l),Math.sin(l),0).normalize();n[s*4]=(c.x*.5+.5)*255,n[s*4+1]=(c.y*.5+.5)*255,n[s*4+2]=127,n[s*4+3]=255}let a=new sn(n,t,t);return a.wrapS=Ni,a.wrapT=Ni,a.needsUpdate=!0,a}function Q2(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),a=t-1;for(let s=1;s<=r;){if(n===-1&&a===t?(a=t-2,n=0):(a===t&&(a=0),n<0&&(n=t-1)),i[n*t+a]!==0){a-=2,n++;continue}else i[n*t+a]=s++;a++,n--}return i}var bd={name:"PoissonDenoiseShader",defines:{SAMPLES:16,SAMPLE_VECTORS:fx(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 Xe},cameraProjectionMatrixInverse:{value:new Jt},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 fx(e,t,r){let i=J2(e,t,r),n="vec3[SAMPLES](";for(let a=0;a<e;a++){let s=i[a];n+=`vec3(${s.x}, ${s.y}, ${s.z})${a<e-1?",":")"}`}return n}function J2(e,t,r){let i=[];for(let n=0;n<e;n++){let a=2*Math.PI*t*n/e,s=Math.pow(n/(e-1),r);i.push(new ee(Math.cos(a),Math.sin(a),s))}return i}var $2=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,a=.5*(Math.sqrt(3)-1),s=(e+t)*a,o=Math.floor(e+s),l=Math.floor(t+s),c=(3-Math.sqrt(3))/6,u=(o+l)*c,h=o-u,d=l-u,f=e-h,y=t-d,g,p;f>y?(g=1,p=0):(g=0,p=1);let m=f-g+c,v=y-p+c,x=f-1+2*c,b=y-1+2*c,_=o&255,M=l&255,C=this.perm[_+this.perm[M]]%12,S=this.perm[_+g+this.perm[M+p]]%12,w=this.perm[_+1+this.perm[M+1]]%12,E=.5-f*f-y*y;E<0?r=0:(E*=E,r=E*E*this.dot(this.grad3[C],f,y));let P=.5-m*m-v*v;P<0?i=0:(P*=P,i=P*P*this.dot(this.grad3[S],m,v));let N=.5-x*x-b*b;return N<0?n=0:(N*=N,n=N*N*this.dot(this.grad3[w],x,b)),70*(r+i+n)}noise3d(e,t,r){let i,n,a,s,o=(e+t+r)*.3333333333333333,l=Math.floor(e+o),c=Math.floor(t+o),u=Math.floor(r+o),h=1/6,d=(l+c+u)*h,f=l-d,y=c-d,g=u-d,p=e-f,m=t-y,v=r-g,x,b,_,M,C,S;p>=m?m>=v?(x=1,b=0,_=0,M=1,C=1,S=0):p>=v?(x=1,b=0,_=0,M=1,C=0,S=1):(x=0,b=0,_=1,M=1,C=0,S=1):m<v?(x=0,b=0,_=1,M=0,C=1,S=1):p<v?(x=0,b=1,_=0,M=0,C=1,S=1):(x=0,b=1,_=0,M=1,C=1,S=0);let w=p-x+h,E=m-b+h,P=v-_+h,N=p-M+2*h,D=m-C+2*h,B=v-S+2*h,J=p-1+3*h,Q=m-1+3*h,j=v-1+3*h,k=l&255,H=c&255,U=u&255,X=this.perm[k+this.perm[H+this.perm[U]]]%12,W=this.perm[k+x+this.perm[H+b+this.perm[U+_]]]%12,$=this.perm[k+M+this.perm[H+C+this.perm[U+S]]]%12,G=this.perm[k+1+this.perm[H+1+this.perm[U+1]]]%12,T=.6-p*p-m*m-v*v;T<0?i=0:(T*=T,i=T*T*this.dot3(this.grad3[X],p,m,v));let I=.6-w*w-E*E-P*P;I<0?n=0:(I*=I,n=I*I*this.dot3(this.grad3[W],w,E,P));let V=.6-N*N-D*D-B*B;V<0?a=0:(V*=V,a=V*V*this.dot3(this.grad3[$],N,D,B));let K=.6-J*J-Q*Q-j*j;return K<0?s=0:(K*=K,s=K*K*this.dot3(this.grad3[G],J,Q,j)),32*(i+n+a+s)}noise4d(e,t,r,i){let n=this.grad4,a=this.simplex,s=this.perm,o=(Math.sqrt(5)-1)/4,l=(5-Math.sqrt(5))/20,c,u,h,d,f,y=(e+t+r+i)*o,g=Math.floor(e+y),p=Math.floor(t+y),m=Math.floor(r+y),v=Math.floor(i+y),x=(g+p+m+v)*l,b=g-x,_=p-x,M=m-x,C=v-x,S=e-b,w=t-_,E=r-M,P=i-C,N=S>w?32:0,D=S>E?16:0,B=w>E?8:0,J=S>P?4:0,Q=w>P?2:0,j=E>P?1:0,k=N+D+B+J+Q+j,H=a[k][0]>=3?1:0,U=a[k][1]>=3?1:0,X=a[k][2]>=3?1:0,W=a[k][3]>=3?1:0,$=a[k][0]>=2?1:0,G=a[k][1]>=2?1:0,T=a[k][2]>=2?1:0,I=a[k][3]>=2?1:0,V=a[k][0]>=1?1:0,K=a[k][1]>=1?1:0,ie=a[k][2]>=1?1:0,le=a[k][3]>=1?1:0,ae=S-H+l,de=w-U+l,z=E-X+l,me=P-W+l,we=S-$+2*l,He=w-G+2*l,ne=E-T+2*l,_e=P-I+2*l,oe=S-V+3*l,ce=w-K+3*l,L=E-ie+3*l,A=P-le+3*l,O=S-1+4*l,F=w-1+4*l,Y=E-1+4*l,re=P-1+4*l,ue=g&255,se=p&255,pe=m&255,Pe=v&255,Ce=s[ue+s[se+s[pe+s[Pe]]]]%32,je=s[ue+H+s[se+U+s[pe+X+s[Pe+W]]]]%32,st=s[ue+$+s[se+G+s[pe+T+s[Pe+I]]]]%32,Pt=s[ue+V+s[se+K+s[pe+ie+s[Pe+le]]]]%32,ut=s[ue+1+s[se+1+s[pe+1+s[Pe+1]]]]%32,ot=.6-S*S-w*w-E*E-P*P;ot<0?c=0:(ot*=ot,c=ot*ot*this.dot4(n[Ce],S,w,E,P));let tt=.6-ae*ae-de*de-z*z-me*me;tt<0?u=0:(tt*=tt,u=tt*tt*this.dot4(n[je],ae,de,z,me));let Ht=.6-we*we-He*He-ne*ne-_e*_e;Ht<0?h=0:(Ht*=Ht,h=Ht*Ht*this.dot4(n[st],we,He,ne,_e));let fe=.6-oe*oe-ce*ce-L*L-A*A;fe<0?d=0:(fe*=fe,d=fe*fe*this.dot4(n[Pt],oe,ce,L,A));let qe=.6-O*O-F*F-Y*Y-re*re;return qe<0?f=0:(qe*=qe,f=qe*qe*this.dot4(n[ut],O,F,Y,re)),27*(c+u+h+d+f)}},ym=class Qa extends Os{constructor(t,r,i,n,a,s,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=Z2(),this.pdNoiseTexture=this.generateNoise(),this.gtaoRenderTarget=new Pi(this.width,this.height,{type:yn}),this.pdRenderTarget=this.gtaoRenderTarget.clone(),this.gtaoMaterial=new oi({defines:Object.assign({},vd.defines),uniforms:xn.clone(vd.uniforms),vertexShader:vd.vertexShader,fragmentShader:vd.fragmentShader,blending:Ft,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 Ef,this.normalMaterial.blending=Ft,this.pdMaterial=new oi({defines:Object.assign({},bd.defines),uniforms:xn.clone(bd.uniforms),vertexShader:bd.vertexShader,fragmentShader:bd.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 oi({defines:Object.assign({},xd.defines),uniforms:xn.clone(xd.uniforms),vertexShader:xd.vertexShader,fragmentShader:xd.fragmentShader,blending:Ft}),this.depthRenderMaterial.uniforms.cameraNear.value=this.camera.near,this.depthRenderMaterial.uniforms.cameraFar.value=this.camera.far,this.copyMaterial=new oi({uniforms:xn.clone(gd.uniforms),vertexShader:gd.vertexShader,fragmentShader:gd.fragmentShader,transparent:!0,depthTest:!1,depthWrite:!1,blendSrc:eu,blendDst:fn,blendEquation:Gt,blendSrcAlpha:$c,blendDstAlpha:fn,blendEquationAlpha:Gt}),this.blendMaterial=new oi({uniforms:xn.clone(gm.uniforms),vertexShader:gm.vertexShader,fragmentShader:gm.fragmentShader,transparent:!0,depthTest:!1,depthWrite:!1,blending:cr,blendSrc:eu,blendDst:fn,blendEquation:Gt,blendSrcAlpha:$c,blendDstAlpha:fn,blendEquationAlpha:Gt}),this.fsQuad=new yd(null),this.originalClearColor=new yt,this.setGBuffer(a?a.depthTexture:void 0,a?a.normalTexture:void 0),s!==void 0&&this.updateGtaoMaterial(s),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 Oh,this.depthTexture.format=Ra,this.depthTexture.type=Ca,this.normalRenderTarget=new Pi(this.width,this.height,{minFilter:Kr,magFilter:Kr,type:yn,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=fx(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 Qa.OUTPUT.Off:break;case Qa.OUTPUT.Diffuse:this.copyMaterial.uniforms.tDiffuse.value=i.texture,this.copyMaterial.blending=Ft,this.renderPass(t,this.copyMaterial,this.renderToScreen?null:r);break;case Qa.OUTPUT.AO:this.copyMaterial.uniforms.tDiffuse.value=this.gtaoRenderTarget.texture,this.copyMaterial.blending=Ft,this.renderPass(t,this.copyMaterial,this.renderToScreen?null:r);break;case Qa.OUTPUT.Denoise:this.copyMaterial.uniforms.tDiffuse.value=this.pdRenderTarget.texture,this.copyMaterial.blending=Ft,this.renderPass(t,this.copyMaterial,this.renderToScreen?null:r);break;case Qa.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 Qa.OUTPUT.Normal:this.copyMaterial.uniforms.tDiffuse.value=this.normalRenderTarget.texture,this.copyMaterial.blending=Ft,this.renderPass(t,this.copyMaterial,this.renderToScreen?null:r);break;case Qa.OUTPUT.Default:this.copyMaterial.uniforms.tDiffuse.value=i.texture,this.copyMaterial.blending=Ft,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,a){t.getClearColor(this.originalClearColor);let s=t.getClearAlpha(),o=t.autoClear;t.setRenderTarget(i),t.autoClear=!1,n!=null&&(t.setClearColor(n),t.setClearAlpha(a||0),t.clear()),this.fsQuad.material=r,this.fsQuad.render(t),t.autoClear=o,t.setClearColor(this.originalClearColor),t.setClearAlpha(s)}renderOverride(t,r,i,n,a){t.getClearColor(this.originalClearColor);let s=t.getClearAlpha(),o=t.autoClear;t.setRenderTarget(i),t.autoClear=!1,n=r.clearColor||n,a=r.clearAlpha||a,n!=null&&(t.setClearColor(n),t.setClearAlpha(a||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(s)}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 $2,i=t*t*4,n=new Uint8Array(i);for(let s=0;s<t;s++)for(let o=0;o<t;o++){let l=s,c=o;n[(s*t+o)*4]=(r.noise(l,c)*.5+.5)*255,n[(s*t+o)*4+1]=(r.noise(l+t,c)*.5+.5)*255,n[(s*t+o)*4+2]=(r.noise(l,c+t)*.5+.5)*255,n[(s*t+o)*4+3]=(r.noise(l+t,c+t)*.5+.5)*255}let a=new sn(n,t,t,Li,gn);return a.wrapS=Ni,a.wrapT=Ni,a.needsUpdate=!0,a}};ym.OUTPUT={Off:-1,Default:0,Diffuse:1,Depth:2,Normal:3,AO:4,Denoise:5};var eP={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
}`},tP=class extends Os{constructor(){super();let e=eP;this.uniforms=xn.clone(e.uniforms),this.material=new _f({name:e.name,uniforms:this.uniforms,vertexShader:e.vertexShader,fragmentShader:e.fragmentShader}),this.fsQuad=new yd(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={},_r.getTransfer(this._outputColorSpace)===kr&&(this.material.defines.SRGB_TRANSFER=""),this._toneMapping===np?this.material.defines.LINEAR_TONE_MAPPING="":this._toneMapping===ap?this.material.defines.REINHARD_TONE_MAPPING="":this._toneMapping===sp?this.material.defines.CINEON_TONE_MAPPING="":this._toneMapping===lu?this.material.defines.ACES_FILMIC_TONE_MAPPING="":this._toneMapping===op?this.material.defines.AGX_TONE_MAPPING="":this._toneMapping===lp&&(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()}},_d={name:"SMAAEdgesShader",defines:{SMAA_THRESHOLD:"0.1"},uniforms:{tDiffuse:{value:null},resolution:{value:new Xe(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 );
}`},wd={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 Xe(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 ) );
}`},vm={name:"SMAABlendShader",uniforms:{tDiffuse:{value:null},tColor:{value:null},resolution:{value:new Xe(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 );
}`},rP=class extends Os{constructor(e,t){super(),this.edgesRT=new Pi(e,t,{depthBuffer:!1,type:yn}),this.edgesRT.texture.name="SMAAPass.edges",this.weightsRT=new Pi(e,t,{depthBuffer:!1,type:yn}),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 ei,this.areaTexture.name="SMAAPass.area",this.areaTexture.image=i,this.areaTexture.minFilter=Zr,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 ei,this.searchTexture.name="SMAAPass.search",this.searchTexture.image=n,this.searchTexture.magFilter=Kr,this.searchTexture.minFilter=Kr,this.searchTexture.generateMipmaps=!1,this.searchTexture.flipY=!1,this.uniformsEdges=xn.clone(_d.uniforms),this.uniformsEdges.resolution.value.set(1/e,1/t),this.materialEdges=new oi({defines:Object.assign({},_d.defines),uniforms:this.uniformsEdges,vertexShader:_d.vertexShader,fragmentShader:_d.fragmentShader}),this.uniformsWeights=xn.clone(wd.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 oi({defines:Object.assign({},wd.defines),uniforms:this.uniformsWeights,vertexShader:wd.vertexShader,fragmentShader:wd.fragmentShader}),this.uniformsBlend=xn.clone(vm.uniforms),this.uniformsBlend.resolution.value.set(1/e,1/t),this.uniformsBlend.tDiffuse.value=this.weightsRT.texture,this.materialBlend=new oi({uniforms:this.uniformsBlend,vertexShader:vm.vertexShader,fragmentShader:vm.fragmentShader}),this.fsQuad=new yd(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()}},FN=Qt(Ye()),BN=Qt(Ct()),iP=Qt(It()),zN=Qt(wt()),GN=Qt(at());function mx(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 VN=Object.freeze({side:2,depthWrite:!0,transparent:!1,opacity:1}),gx=e=>e&&typeof e=="object"&&!Array.isArray(e)?e.quoted:e;function yx(e,t,r,i){for(let n of["uuid","tstamp"]){let a=gx(e.find(s=>Array.isArray(s)&&gx(s[0])===n)?.[1]);if(typeof a=="string"&&a||typeof a=="number"&&Number.isFinite(a))return String(a)}if(!Number.isSafeInteger(r)||r<0||!Number.isSafeInteger(i)||i<0)throw TypeError("Choose bounded source pad occurrences.");return`display-pad:${r}:${i}`}function vx(e,t=0,r=t){let i=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY,a=0;for(let s of e)Number.isFinite(s)&&(s<i&&(i=s),s>n&&(n=s),a+=1);return a?{minimum:i,maximum:n,count:a}:{minimum:t,maximum:r,count:0}}var nP=new Set(["signal","power","mixed","jumper"]);function aP(e){return!e.name||e.name.includes("*")?!1:e.name.endsWith(".Cu")||nP.has(e.kind.toLowerCase())}function sP(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 oP(e,t=[],r=[]){let i=[...e].filter(aP).map(c=>c.name),n=[...new Set(r)].filter(c=>c.endsWith(".Cu")&&!c.includes("*")),a=new Set(n),s=i.length>0&&i.every(c=>a.has(c))?[...n,...i.filter(c=>!a.has(c))]:i,o=new Set(s),l=[...new Set(t)].filter(c=>c.endsWith(".Cu")&&!c.includes("*")&&!o.has(c)).sort(sP);return[...s,...l]}var lP=.015;function Ds(e){return Array.isArray(e)}function*cP(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 uP(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(Ds)??[]}function Br(e,t){return e.find(r=>Ds(r)&&r[0]===t)}function Xn(e,t){return e.filter(r=>Ds(r)&&r[0]===t)}function ui(e,t,r=0){let i=Number(Ed(e?.[t]));return Number.isFinite(i)?i:r}function Ed(e){return e&&typeof e=="object"&&!Array.isArray(e)&&!(e instanceof Float64Array)?e.quoted:typeof e=="string"||typeof e=="number"?e:void 0}function Ur(e,t,r=""){let i=Ed(e?.[t]);return typeof i=="string"?i:typeof i=="number"?String(i):r}function mi(e,t){let r=e?Br(e,t):void 0;if(!(!r||r.length<3))return[ui(r,1),ui(r,2)]}function xm(e,t,r){let i=Br(Br(e??[],t)??[],"xyz");return i?[ui(i,1,r[0]),ui(i,2,r[1]),ui(i,3,r[2])]:r}function xx(e){let t=e?Br(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 Xn(t,"xy").map(i=>[ui(i,1),ui(i,2)])}function fc(e,t){return Ur(Br(e,"uuid"),1,Ur(Br(e,"tstamp"),1,t))}function mc(e,t="F.Cu"){return Ur(Br(e,"layer"),1,Ur(Br(e,"layers"),1,t))}function bx(e,t){return Ur(Xn(e,"property").find(r=>Ur(r,1).toLowerCase()===t.toLowerCase()),2)}function hP(e,t,r){let i=e[0],n=-r*Math.PI/180,a=Math.cos(n),s=Math.sin(n);return[t[0]+i*a-e[1]*s,t[1]+i*s+e[1]*a]}function _x(e,t,r){let[i,n]=e,[a,s]=t,[o,l]=r,c=2*(i*(s-l)+a*(l-n)+o*(n-s));if(Math.abs(c)<1e-9)return null;let u=((i*i+n*n)*(s-l)+(a*a+s*s)*(l-n)+(o*o+l*l)*(n-s))/c,h=((i*i+n*n)*(o-a)+(a*a+s*s)*(i-o)+(o*o+l*l)*(a-i))/c,d=Math.atan2(n-h,i-u),f=Math.atan2(s-h,a-u),y=Math.atan2(l-h,o-u),g=Math.PI*2,p=b=>(b%g+g)%g,m=p(f-d),v=p(y-d),x=m<=v?v:v-g;return{center:[u,h],radius:Math.hypot(i-u,n-h),sweep:x,startAngle:d}}function wx(e,t,r){let i=_x(e,t,r);if(!i)return[e,r];let{steps:n}=mx(i.radius,i.sweep);return Array.from({length:n+1},(a,s)=>{let o=i.startAngle+i.sweep*s/n;return[i.center[0]+i.radius*Math.cos(o),i.center[1]+i.radius*Math.sin(o)]})}function dP(e,t){let r=Math.hypot(t[0]-e[0],t[1]-e[1]);return Array.from({length:65},(i,n)=>{let a=Math.PI*2*n/64;return[e[0]+r*Math.cos(a),e[1]+r*Math.sin(a)]})}function Ex(e,t,r,i){let n=Ur(e,0),a=mc(e,"Dwgs.User"),s=Br(e,"stroke"),o=ui(Br(s??e,"width"),1,.12),l=r??(h=>h),c,u;if(n.endsWith("_line")){let h=mi(e,"start"),d=mi(e,"end");if(!h||!d)return null;c="line",u=[l(h),l(d)]}else if(n.endsWith("_arc")){let h=mi(e,"start"),d=mi(e,"mid"),f=mi(e,"end");if(!h||!d||!f)return null;c="arc",u=wx(h,d,f).map(l)}else if(n.endsWith("_circle")){let h=mi(e,"center"),d=mi(e,"end");if(!h||!d)return null;c="circle",u=dP(h,d).map(l)}else if(n.endsWith("_rect")){let h=mi(e,"start"),d=mi(e,"end");if(!h||!d)return null;c="rect",u=[l(h),l([d[0],h[1]]),l(d),l([h[0],d[1]]),l(h)]}else if(n.endsWith("_poly"))c="poly",u=xx(e).map(l),u.length>2&&u.push(u[0]);else return null;return{id:t,type:c,points:u,layer:a,width:o,ref:i}}function ks(e,t){return Math.hypot(e[0]-t[0],e[1]-t[1])<=lP}function gc(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 Mx(e,t="Edge.Cuts"){let r=[],i=[];for(e.filter(n=>n.layer===t).forEach(n=>{let a=n.points;a.length>2&&ks(a[0],a[a.length-1])?r.push(a):a.length>1&&i.push([...a])});i.length;){let n=i.shift(),a=!0;for(;a&&!ks(n[0],n[n.length-1]);){a=!1;for(let s=0;s<i.length;s+=1){let o=i[s];if(ks(n[n.length-1],o[0]))n.push(...o.slice(1));else if(ks(n[n.length-1],o[o.length-1]))n.push(...o.slice(0,-1).reverse());else if(ks(n[0],o[o.length-1]))n.unshift(...o.slice(0,-1));else if(ks(n[0],o[0]))n.unshift(...o.slice(1).reverse());else continue;i.splice(s,1),a=!0;break}}n.length>2&&ks(n[0],n[n.length-1])&&(n[n.length-1]=n[0],r.push(n))}return r.sort((n,a)=>Math.abs(gc(a))-Math.abs(gc(n)))}function pP(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 Sx(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 Tx(e){if(!e.length)return{minX:0,minY:0,maxX:100,maxY:70};let t=vx(e.map(i=>i[0])),r=vx(e.map(i=>i[1]));return{minX:t.minimum,minY:r.minimum,maxX:t.maximum,maxY:r.maximum}}function fP(e,t,r={}){let i=t||uP(cP(e));if(i[0]!=="kicad_pcb")throw new Error("The selected file is not a KiCad PCB document.");let n=[],a=[],s=[],o=[],l=[],c=[],u=new Set,h=[],d=new Set,f=[],y=[],g={};for(let j of i)Ds(j)&&j[0]==="net"&&(g[Ur(j,1)]=Ur(j,2));let p=j=>{let k=Br(j,"net"),H=Ur(k,1),U=Ur(k,2)||Ur(Br(j,"net_name"),1)||g[H]||(/^\d+$/.test(H)?"":H);return U&&(g[H||U]=U),U||void 0},m=-1;for(let j of i){if(!Ds(j)||!j.length)continue;let k=Ur(j,0);if((k==="footprint"||k==="module")&&m++,k==="layers")j.slice(1).filter(Ds).forEach(H=>{let U=Ur(H,1);U&&!U.includes("*")&&f.push({id:ui(H,0,f.length),name:U,kind:Ur(H,2)||"user",userName:Ur(H,3)||void 0}),U.endsWith(".Cu")&&!U.includes("*")&&d.add(U)});else if(k==="setup"){let H=Br(j,"stackup");Xn(H??[],"layer").forEach(U=>{let X=Ur(U,1);if(!X)return;let W=Br(U,"thickness"),$=Br(U,"epsilon_r"),G=Br(U,"loss_tangent");y.push({name:X,type:Ur(Br(U,"type"),1,"unknown"),thickness:W?ui(W,1):void 0,material:Ur(Br(U,"material"),1)||void 0,epsilonR:$?ui($,1):void 0,lossTangent:G?ui(G,1):void 0}),X.endsWith(".Cu")&&d.add(X)})}else if(k==="segment"||k==="arc"){let H=ui(Br(j,"width"),1,.25),U=mc(j),X=p(j),W=fc(j,`track-${n.length+1}`);if(k==="arc"){let G=mi(j,"start"),T=mi(j,"mid"),I=mi(j,"end"),V=G&&T&&I?_x(G,T,I):null;V&&mx(V.radius,V.sweep).limited&&a.length<100&&a.push("Saved copper arc "+W+" exceeds the 512-segment/5 \xC2\xB5m chord budget and is shown approximately.")}let $=k==="arc"?wx(mi(j,"start")??[0,0],mi(j,"mid")??[0,0],mi(j,"end")??[0,0]):[mi(j,"start"),mi(j,"end")].filter(Boolean);for(let G=0;G<$.length-1;G+=1)n.push({id:$.length>2?`${W}:${G}`:W,start:$[G],end:$[G+1],width:H,layer:U,net:X});d.add(U)}else if(k==="via"){let H=mi(j,"at");if(!H)continue;let U=Br(j,"layers")?.slice(1).map(Ed).filter(X=>typeof X=="string")??["F.Cu","B.Cu"];s.push({id:fc(j,`via-${s.length+1}`),at:H,size:ui(Br(j,"size"),1,.8),drill:ui(Br(j,"drill"),1,.4),layers:U,net:p(j)})}else if(k==="zone"){let H=mc(j),U=Xn(j,"filled_polygon");(U.length?U:Xn(j,"polygon")).forEach((X,W)=>{let $=Br(X,"pts"),G=$?.[1]instanceof Float64Array?$[1].length/2:0;for(let K of $||[])Ds(K)&&Ur(K,0)==="xy"&&G++;if(G<3)return;let T=mc(X,H),I=p(j);if(d.add(T),u.add(T),r.zonePoints===!1)return;let V=xx(X);c.push({id:`${fc(j,`zone-${c.length+1}`)}:${W}`,points:V,layer:T,net:I})})}else if(k.startsWith("gr_")){let H=Ex(j,fc(j,`drawing-${h.length+1}`));H&&h.push(H)}else if(k==="footprint"||k==="module"){let H=mi(j,"at")??[0,0],U=Br(j,"at"),X=ui(U,3),W=mc(j),$=W.startsWith("B."),G=z=>hP(z,H,X),T=bx(j,"Reference")||Ur(Xn(j,"fp_text").find(z=>Ur(z,1)==="reference"),2)||`REF${l.length+1}`,I=bx(j,"Value")||Ur(Xn(j,"fp_text").find(z=>Ur(z,1)==="value"),2)||"",V=[],K=[];Xn(j,"pad").forEach((z,me)=>{let we=mi(z,"at")??[0,0];K.push(we);let He=Br(z,"size"),ne=Br(z,"layers")?.slice(1).map(Ed).filter(A=>typeof A=="string")??[W],_e=ne.includes("F.Cu")||ne.includes("*.Cu")?$?"B.Cu":"F.Cu":ne.find(A=>A.endsWith(".Cu"))??W,oe=Br(z,"drill"),ce=Ur(oe,1)==="oval"?ui(oe,2):ui(oe,1),L={id:yx(z,T,m,me),name:Ur(z,1,String(me+1)),at:G(we),width:ui(He,1,1),height:ui(He,2,1),rotation:ui(Br(z,"at"),3),shape:Ur(z,3,"rect"),drill:ce,layers:ne,layer:_e,net:p(z),ref:T};o.push(L),V.push(L),ne.filter(A=>A.endsWith(".Cu")&&!A.includes("*")).forEach(A=>d.add(A))});for(let z of["fp_line","fp_arc","fp_circle","fp_rect","fp_poly"])Xn(j,z).forEach((me,we)=>{let He=Ex(me,`${T}:${z}:${we}`,G,T);He&&h.push(He)});let ie=Tx(K),le=K.length?Math.max(ie.maxX-ie.minX+2.5,2.5):5,ae=K.length?Math.max(ie.maxY-ie.minY+2.5,2.5):5,de=Br(j,"model");l.push({id:fc(j,`component-${T}`),ref:T,value:I,library:Ur(j,1),at:H,width:le,height:ae,rotation:X,layer:W,model:!!de,modelPath:Ur(de,1),modelPaths:Xn(j,"model").map(z=>Ur(z,1)).filter(Boolean),modelOffset:xm(de,"offset",[0,0,0]),modelScale:xm(de,"scale",[1,1,1]),modelRotation:xm(de,"rotate",[0,0,0])}),d.add(W==="B.Cu"?"B.Cu":"F.Cu")}}let v=Mx(h),x=v[0]??n.flatMap(j=>[j.start,j.end]).concat(o.map(j=>j.at)),b=Tx(x),_=new Set(f.map(j=>j.name)),M=Math.max(-1,...f.map(j=>j.id))+1;[...n.map(j=>j.layer),...o.flatMap(j=>j.layers),...u,...h.map(j=>j.layer)].forEach(j=>{!j||j.includes("*")||_.has(j)||(_.add(j),f.push({id:M++,name:j,kind:j.endsWith(".Cu")?"signal":"user"}))});let C=oP(f,d,y.map(j=>j.name)),S=[],w=[];f.forEach(j=>{let k=pP(j);if(!k)return;let H=j.userName||j.name;if(k==="bend"){h.filter(U=>U.layer===j.name&&U.points.length>=2).forEach((U,X)=>{w.push({id:`bend:${U.id}`,name:`${H} ${X+1}`,points:U.points,sourceLayer:j.name,radiusMm:Sx(H,"radius"),angleDeg:Sx(H,"angle")})});return}Mx(h,j.name).forEach((U,X)=>{S.push({id:`region:${j.id}:${X}`,name:`${H}${X?` ${X+1}`:""}`,kind:k,outline:U,sourceLayer:j.name,source:"kicad-user-layer"})})});let E=v[0]??[],P=Math.abs(gc(E)),N=S.filter(j=>j.kind==="flex").reduce((j,k)=>j+Math.abs(gc(k.outline)),0),D=N>0,B=S.some(j=>j.kind==="rigid"),J=D?!B&&P>0&&N>=P*.92?"flex":"rigid-flex":"rigid",Q=[...S];return E.length&&J!=="flex"&&!Q.some(j=>j.kind==="rigid"&&Math.abs(gc(j.outline))>=P*.92)&&Q.unshift({id:"region:implicit-rigid-board",name:"Rigid board",kind:"rigid",outline:E,sourceLayer:"Edge.Cuts",source:"implicit-board-outline"}),{width:Math.max(b.maxX-b.minX,1),height:Math.max(b.maxY-b.minY,1),bounds:b,outlineLoops:v,tracks:n,geometryWarnings:a,vias:s,pads:o,components:l,zones:c,drawings:h,layers:C,layerDefinitions:f,stackup:y,nets:g,technology:J,regions:Q,bendLines:w}}var HN=Qt(zt()),Ax=e=>e&&(e.type==="Component"||typeof e.library=="string"),Go=e=>{for(let t=e;t;t=t.parent)if(!t.visible)return!1;return!0},bm=(e,t)=>{if(typeof e!="string"||!e||e.length>128||/[\x00-\x1f\x7f]/.test(e))throw new TypeError("Choose a bounded "+t+".");return e},Cx={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 mP(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 a=Math.floor((n?n.count:i.count)/3);if(!a||a>5e4)throw new Error("Selected mesh exceeds the 50,000-triangle face-selection budget.");let s=Math.ceil((t.drawRange?.start||0)/3),o=Math.min(a,Math.floor(((t.drawRange?.start||0)+(Number.isFinite(t.drawRange?.count)?t.drawRange.count:a*3))/3));if(!Number.isInteger(r)||r<s||r>=o)throw new Error("Choose a visible triangle face.");let l=T=>new e.Vector3().fromBufferAttribute(i,n?n.getX(T):T),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 h=t.boundingBox.getSize(new e.Vector3).length(),d=Math.max(1e-7,h*1e-7),f=u.dot(c[0]),y=t.groups||[];if(y.length>256)throw new Error("Selected mesh exceeds the 256 material-group face budget.");let g=new Int32Array(a);g.fill(-1);for(let T of y){if(!Number.isInteger(T.start)||!Number.isInteger(T.count)||T.start<0||T.count<0||T.start%3||T.count%3||!Number.isInteger(T.materialIndex)||T.materialIndex<0||T.materialIndex>1e6)throw new Error("Unsupported triangle material groups.");for(let I=T.start/3;I<Math.min(a,(T.start+T.count)/3);I++){if(g[I]!==-1)throw new Error("Overlapping material groups make the selected face ambiguous.");g[I]=T.materialIndex}}let p=T=>g[T],m=p(r);if(y.length&&m===-1)throw new Error("The selected face has no supported material group.");let v=T=>[T.x,T.y,T.z].map(I=>Math.round(I/d)).join(","),x=(T,I)=>T<I?T+"|"+I:I+"|"+T,b=new Map,_=new Map,M=new e.Vector3,C=new e.Vector3;for(let T=s;T<o;T++){if(p(T)!==m)continue;let I=[l(T*3),l(T*3+1),l(T*3+2)];if(I.some(le=>!Number.isFinite(le.x)||!Number.isFinite(le.y)||!Number.isFinite(le.z)||Math.abs(u.dot(le)-f)>d))continue;let V=M.subVectors(I[1],I[0]).cross(C.subVectors(I[2],I[0]));if(V.lengthSq()<1e-20||V.normalize().dot(u)<.99999)continue;let K=I.map(v),ie=[x(K[0],K[1]),x(K[1],K[2]),x(K[2],K[0])];b.set(T,{points:I,edges:ie});for(let le of ie){let ae=_.get(le)||[];ae.push(T),_.set(le,ae)}}let S=[r],w=new Set(S),E=new Set,P=new Set;for(let T=0;T<S.length;T++){let I=S[T],V=b.get(I);if(V){E.add(I);for(let K of V.edges)if(!P.has(K)){P.add(K);for(let ie of _.get(K)||[])w.has(ie)||(w.add(ie),S.push(ie))}}}if(!E.size)throw new Error("No connected planar face was found.");let N=new e.Vector3(Math.abs(u.x)<.9?1:0,Math.abs(u.x)<.9?0:1,0);N.addScaledVector(u,-N.dot(u)).normalize();let D=new e.Vector3().crossVectors(u,N).normalize(),B=1/0,J=-1/0,Q=1/0,j=-1/0,k=0,H=[];for(let T of E){let I=b.get(T).points;k+=new e.Vector3().subVectors(I[1],I[0]).cross(new e.Vector3().subVectors(I[2],I[0])).length()/2;for(let V of I){let K=V.dot(N),ie=V.dot(D);B=Math.min(B,K),J=Math.max(J,K),Q=Math.min(Q,ie),j=Math.max(j,ie),H.push(V)}}let U=J-B,X=j-Q;if(!(U>d&&X>d&&k>d*d))throw new Error("The selected face is too small for a display.");let W=new Float32Array(H.length*3),$=new Float32Array(H.length*2);H.forEach((T,I)=>{W.set([T.x,T.y,T.z],I*3),$.set([(T.dot(N)-B)/U,(T.dot(D)-Q)/X],I*2)});let G=u.clone().multiplyScalar(f).addScaledVector(N,(B+J)/2).addScaledVector(D,(Q+j)/2);return{positions:W,uvs:$,normal:u,u:N,v:D,center:G,width:U,height:X,area:k,triangles:E.size,faceIndex:Math.min(...E),faceIndices:[...E]}}function gP(e,{scene:t,objects:r,document:i=globalThis.document,invalidate:n=()=>{},onError:a=()=>{}}){if(!t?.add||typeof r!="function"||!i?.createElement)throw new TypeError("Choose a 3D scene, saved component meshes and document.");let s=new e.Group;s.name="Scripted demo surfaces",t.add(s);let o="demo-face-"+Math.random().toString(36).slice(2)+"-",l=new Map,c=new Map,u=0,h=!1,d=null,f=null,y=0,g=0,p=()=>{if(h)throw new Error("Demo surfaces have been disposed.")};function m(T,I){T.updateWorldMatrix(!0,!1);let V=T.matrixWorld.clone();if(T.isInstancedMesh){if(!Number.isInteger(I)||I<0||I>=T.count)return null;let K=new e.Matrix4;if(T.getMatrixAt(I,K),Math.abs(K.determinant())<1e-15)return null;V.multiply(K)}return Math.abs(V.determinant())<1e-15?null:V}function v(T,I){return T?.isInstancedMesh?T.userData.records?.[I]:T?.userData.record}function x(T,I,V){if(!r().includes(T)||!Go(T)||T.isSkinnedMesh)throw new Error("Choose a visible static component face.");let K=v(T,I),ie=m(T,I);if(!Ax(K)||!ie)throw new Error("Choose a visible component body, not a pad or board surface.");let le=mP(e,T.geometry,V),ae=le.normal.clone().applyMatrix3(new e.Matrix3().getNormalMatrix(ie)).normalize(),de=new e.Vector3().applyMatrix4(ie),z=le.u.clone().multiplyScalar(le.width).applyMatrix4(ie).sub(de),me=le.v.clone().multiplyScalar(le.height).applyMatrix4(ie).sub(de);return{object:T,instanceId:I,record:K,geometry:T.geometry,patch:le,normal:ae,width:z.length(),height:me.length(),key:T.uuid+":"+I+":"+le.faceIndex}}function b(T){let I=[...l.values()].reduce((K,ie)=>K+ie.patch.triangles,0);for(;l.size>=128||I+T.patch.triangles>1e5;){let K=[...l].find(([,ie])=>![...c.values()].some(le=>le.face===ie));if(!K)throw new Error("Selected demo faces exceed the geometry budget.");I-=K[1].patch.triangles,l.delete(K[0])}let V=o+ ++u;return T.token=V,l.set(V,T),_(T)}function _(T){let I=m(T.object,T.instanceId);return I?Object.freeze({token:T.token,shape:"face",uuid:String(T.record.uuid||T.record.id||""),reference:String(T.record.ref||""),center:T.patch.center.clone().applyMatrix4(I).toArray(),normal:T.patch.normal.clone().applyMatrix3(new e.Matrix3().getNormalMatrix(I)).normalize().toArray(),up:T.patch.v.clone().transformDirection(I).toArray(),right:T.patch.u.clone().transformDirection(I).toArray(),width:T.width,height:T.height,triangles:T.patch.triangles}):null}function M(T){if(p(),!T||!Number.isInteger(T.faceIndex))throw new Error("Select a component triangle face.");return b(x(T.object,T.instanceId,T.faceIndex))}function C(T){if(!T||typeof T!="object"||!Cx[T.face||"top"])throw new TypeError("Choose a saved component and top/bottom/front/back/left/right face.");let I=T.uuid===void 0?null:bm(T.uuid,"component UUID"),V=T.reference===void 0?null:bm(T.reference,"component reference");if(!I&&!V)throw new TypeError("A demo face needs a component UUID or unique reference.");let K=[],ie=new Set,le=0;for(let ae of r()){let de=ae.userData.records||[ae.userData.record];for(let z=0;z<de.length;z++){if(++le>2e5)throw new Error("Component face lookup exceeds its record budget.");let me=de[z];if(!Ax(me)||I&&I!==(me.uuid||me.id)||V&&V!==me.ref)continue;let we=ae.isInstancedMesh?z:void 0;if(!Go(ae)||!m(ae,we))continue;let He=String(me.uuid||me.id||"")+"|"+String(me.ref||"")+"|"+JSON.stringify(me.at||[]);ie.add(He),K.push({object:ae,instanceId:we})}}if(ie.size!==1)throw new Error("The component anchor is absent or ambiguous.");return K}function S(T){let I=C(T),V=new e.Vector3(...Cx[T.face||"top"]),K=null,ie=25e4;for(let le of I){let ae=le.object.geometry,de=ae?.getAttribute?.("position"),z=ae?.index;if(!de||le.object.isSkinnedMesh||ae.morphAttributes?.position?.length)continue;let me=Math.floor((z?z.count:de.count)/3);if(me>5e4)throw new Error("Selected mesh exceeds the 50,000-triangle face-selection budget.");let we=m(le.object,le.instanceId),He=new e.Matrix3().getNormalMatrix(we),ne=new Set,_e=Math.ceil((ae.drawRange?.start||0)/3),oe=Math.min(me,Math.floor(((ae.drawRange?.start||0)+(Number.isFinite(ae.drawRange?.count)?ae.drawRange.count:me*3))/3));for(let ce=_e;ce<oe;ce++){if(ne.has(ce))continue;let L=new e.Vector3().fromBufferAttribute(de,z?z.getX(ce*3):ce*3),A=new e.Vector3().fromBufferAttribute(de,z?z.getX(ce*3+1):ce*3+1),O=new e.Vector3().fromBufferAttribute(de,z?z.getX(ce*3+2):ce*3+2);if(A.sub(L).cross(O.sub(L)).normalize().applyMatrix3(He).normalize().dot(V)<.9999)continue;if((ie-=me)<0)throw new Error("Automatic face selection exceeds its triangle-work budget. Select an actual face manually.");let F=x(le.object,le.instanceId,ce);for(let pe of F.patch.faceIndices)ne.add(pe);let Y=m(F.object,F.instanceId),re=new e.Vector3().applyMatrix4(Y),ue=F.patch.u.clone().multiplyScalar(F.patch.width).applyMatrix4(Y).sub(re),se=F.patch.v.clone().multiplyScalar(F.patch.height).applyMatrix4(Y).sub(re);F.worldArea=F.patch.area*ue.cross(se).length()/(F.patch.width*F.patch.height),F.depth=F.patch.center.clone().applyMatrix4(Y).dot(V),(!K||F.depth>K.depth+1e-5||Math.abs(F.depth-K.depth)<=1e-5&&F.worldArea>K.worldArea)&&(K=F)}}if(!K)throw new Error("This component has no supported planar face in that direction. Select an actual face instead.");return b(K)}function w(T){let I=T.face||T.anchor&&S(T.anchor),V=typeof I=="string"?I:I?.token,K=l.get(V);if(!K)throw new Error("The selected face belongs to another or closed 3D view. Select it again.");if(!r().includes(K.object)||!Go(K.object)||K.object.geometry!==K.geometry||!m(K.object,K.instanceId))throw new Error("The selected source geometry is no longer available. Select it again.");return K}function E(T,I,V,K,ie={}){if(typeof d=="function")try{d({id:T.id,type:I,...I==="change"?{value:T.value}:{},...K?{uv:{x:K.x,y:K.y}}:{},source:"pointer",originalEvent:V,...ie})}catch(le){d=null;try{a(le)}catch{}}}function P(T){let I=T.width??(T.kind==="led"?32:128),V=T.height??(T.kind==="led"?32:T.kind==="button"?64:128);if(!Number.isInteger(I)||!Number.isInteger(V)||I<1||V<1||I>1024||V>1024)throw new TypeError("Demo canvases need integer dimensions from 1 to 1024.");return{width:I,height:V}}function N(T){if(T.kind==="led"&&!T.canvas){T.material.color.set(T.color).multiplyScalar(T.on?T.brightness:.025);return}let I=T.canvas.getContext("2d");if(!I)throw new Error("Canvas drawing is unavailable.");T.kind!=="display"&&(I.clearRect(0,0,T.canvas.width,T.canvas.height),T.kind==="led"?(I.fillStyle=T.color,I.fillRect(0,0,T.canvas.width,T.canvas.height),T.material.color.setScalar(T.on?T.brightness:.025)):(I.fillStyle=T.pressed?"#77d4df":"#182f3e",I.fillRect(0,0,T.canvas.width,T.canvas.height),I.fillStyle=T.pressed?"#10202c":"#e1eaf3",I.textAlign="center",I.textBaseline="middle",I.font="600 "+Math.max(9,Math.round(T.canvas.height*.22))+"px system-ui",I.fillText(T.kind==="knob"?String(T.value):T.label,T.canvas.width/2,T.canvas.height/2,T.canvas.width-8)),T.texture.needsUpdate=!0)}function D(T){if(T.bindings){let K=!1;for(let ie of T.bindings){let le=m(ie.object,ie.instanceId);ie.mesh.visible=r().includes(ie.object)&&ie.object.geometry===ie.geometry&&Go(ie.object)&&!!le,ie.mesh.visible&&(ie.mesh.matrix.copy(le),ie.mesh.matrixWorldNeedsUpdate=!0,K=!0)}return K}let I=T.face,V=m(I.object,I.instanceId);if(T.mesh.visible=r().includes(I.object)&&I.object.geometry===I.geometry&&Go(I.object)&&!!V,T.mesh.visible){let K=I.patch.normal.clone().applyMatrix3(new e.Matrix3().getNormalMatrix(V)).normalize(),ie=Math.max(1e-5,Math.min(.006,Math.min(I.width,I.height)*.002));T.mesh.matrix.copy(V),T.mesh.matrix.elements[12]+=K.x*ie,T.mesh.matrix.elements[13]+=K.y*ie,T.mesh.matrix.elements[14]+=K.z*ie,T.mesh.matrixWorldNeedsUpdate=!0}return!T.mesh.visible&&f?.entry===T&&X("cancel",null),T.mesh.visible}function B(T){if(!(!c.has(T.id)||c.get(T.id)!==T)&&(f?.entry===T&&X("cancel",null),c.get(T.id)===T)){c.delete(T.id),y-=T.pixels,g-=T.triangles;for(let I of T.meshes||[T.mesh])I.removeFromParent();T.texture?.dispose(),T.material.dispose(),T.bindings||T.mesh.geometry.dispose(),n()}}function J(T){if(typeof T!="string"||T.length>64||!/^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/i.test(T)&&!Object.hasOwn(e.Color.NAMES,T.toLowerCase()))throw new TypeError("Choose a hex or named LED color.");return"#"+new e.Color(T).getHexString()}function Q(T,I={}){let V={on:I.on===void 0?T.on:!!I.on,color:I.color===void 0?T.color:J(I.color),brightness:I.brightness===void 0?T.brightness:I.brightness};if(!Number.isFinite(V.brightness)||V.brightness<0||V.brightness>1)throw new TypeError("Choose LED brightness from 0 to 1.");Object.assign(T,V),N(T),n()}function j(T){let I=new e.Box3;for(let ie of T.bindings){let le=m(ie.object,ie.instanceId);le&&(ie.geometry.boundingBox||ie.geometry.computeBoundingBox(),I.union(ie.geometry.boundingBox.clone().applyMatrix4(le)))}if(I.isEmpty())return null;let V=I.getSize(new e.Vector3),K=T.bindings[0].record;return{shape:"component",uuid:String(K.uuid||K.id||""),reference:String(K.ref||""),center:I.getCenter(new e.Vector3).toArray(),normal:null,width:V.x,height:V.y,triangles:T.triangles}}function k(T,I){let V=C(I.anchor),K=c.get(T),ie=V.reduce((z,me)=>{let we=me.object.geometry;if(me.object.isSkinnedMesh||we.morphAttributes?.position?.length)throw new Error("LED body binding requires static geometry.");return z+Math.floor((we.index?.count||we.getAttribute("position")?.count||0)/3)},0);if(!ie||ie>5e4||c.size-(K?1:0)>=64||g-(K?.triangles||0)+ie>1e5)throw new Error("LED component geometry exceeds the demo surface budget.");let le=J(I.color||"#59f3a5");if(I.brightness!==void 0&&(!Number.isFinite(I.brightness)||I.brightness<0||I.brightness>1))throw new TypeError("Choose LED brightness from 0 to 1.");let ae=new e.MeshBasicMaterial({color:16777215,depthTest:!0,depthWrite:!0,toneMapped:!1,polygonOffset:!0,polygonOffsetFactor:-1,polygonOffsetUnits:-2}),de={id:T,kind:"led",bindings:V,material:ae,pixels:0,triangles:ie,on:!1,brightness:1,color:le};for(let z of V)z.geometry=z.object.geometry,z.record=v(z.object,z.instanceId),z.mesh=new e.Mesh(z.geometry,ae),z.mesh.matrixAutoUpdate=!1,z.mesh.userData.demoSurface=T,z.mesh.renderOrder=10;de.meshes=V.map(z=>z.mesh),Q(de,I),K&&B(K),c.set(T,de),g+=ie;for(let z of de.meshes)s.add(z);return D(de),n(),{get face(){return j(de)},getFace(){return j(de)},setLED(z){if(p(),c.get(T)!==de)throw new Error("LED surface is closed.");Q(de,z)},update(){return p(),D(de)},setValue(){throw new Error("An LED uses setLED().")},isAvailable(){return!h&&c.get(T)===de&&D(de)},dispose(){B(de)}}}function H(T,I={}){if(p(),bm(T,"demo surface ID"),!["led","display","button","knob"].includes(I.kind))throw new TypeError("Choose an LED, display, button or knob.");if(I.kind==="led"&&!I.face&&I.anchor&&!I.anchor.face)return k(T,I);let V=w(I),K=c.get(T),ie=P(I),le=ie.width*ie.height;if(c.size-(K?1:0)>=64||y-(K?.pixels||0)+le>4194304||g-(K?.triangles||0)+V.patch.triangles>1e5)throw new Error("Demo surfaces exceed their canvas or geometry budget.");if([...c.values()].some(O=>O!==K&&O.face?.key===V.key))throw new Error("This geometry face already has a demo surface.");let ae=I.kind==="led"?J(I.color||"#59f3a5"):"#59f3a5";if(I.brightness!==void 0&&(!Number.isFinite(I.brightness)||I.brightness<0||I.brightness>1))throw new TypeError("Choose LED brightness from 0 to 1.");let de=i.createElement("canvas");de.width=ie.width,de.height=ie.height;let z=I.kind==="display"?i.createElement("canvas"):de;z.width=ie.width,z.height=ie.height;let me=new e.CanvasTexture(z);me.colorSpace=e.SRGBColorSpace,me.minFilter=e.LinearFilter,me.magFilter=I.mode==="matrix"?e.NearestFilter:e.LinearFilter,me.generateMipmaps=!1;let we=new e.BufferGeometry;we.setAttribute("position",new e.BufferAttribute(V.patch.positions.slice(),3)),we.setAttribute("uv",new e.BufferAttribute(V.patch.uvs.slice(),2)),we.computeVertexNormals();let He=new e.MeshBasicMaterial({map:me,color:16777215,side:e.FrontSide,depthTest:!0,depthWrite:!0,toneMapped:!1,polygonOffset:!0,polygonOffsetFactor:-1,polygonOffsetUnits:-2}),ne=new e.Mesh(we,He);ne.matrixAutoUpdate=!1,ne.userData.demoSurface=T,ne.renderOrder=10;let _e=I.min??0,oe=I.max??100,ce=I.step??1;if(![_e,oe,ce].every(Number.isFinite)||oe<=_e||ce<=0)throw me.dispose(),He.dispose(),we.dispose(),new TypeError("Choose a finite increasing knob range and positive step.");let L=O=>Math.max(_e,Math.min(oe,_e+Math.round((O-_e)/ce)*ce)),A={id:T,kind:I.kind,face:V,canvas:de,uploadCanvas:z,texture:me,material:He,mesh:ne,pixels:le,triangles:V.patch.triangles,min:_e,max:oe,step:ce,clamp:L,value:L(Number.isFinite(I.value)?I.value:_e),pressed:!1,color:ae,on:!!I.on,brightness:Number.isFinite(I.brightness)?Math.max(0,Math.min(1,I.brightness)):1,label:typeof I.label=="string"?I.label.slice(0,64):T};try{N(A)}catch(O){throw me.dispose(),He.dispose(),we.dispose(),O}return K&&B(K),c.set(T,A),y+=le,g+=V.patch.triangles,s.add(ne),D(A),n(),{canvas:de,get face(){return _(V)},getFace(){return _(V)},update(){if(p(),c.get(T)!==A)throw new Error("Demo surface is closed.");let O=P({width:de.width,height:de.height}),F=O.width*O.height;if(y-A.pixels+F>4194304)throw new Error("Demo surfaces exceed their canvas budget.");if(A.kind==="display"){let Y=de.getContext("2d");if(!Y)throw new Error("Canvas drawing is unavailable.");try{Y.getImageData(0,0,1,1)}catch(ue){let se=new Error("Display graphics must be CORS-enabled and origin-clean before upload.");throw se.cause=ue,se}let re=z.getContext("2d");if(!re)throw new Error("Canvas upload is unavailable.");z.width!==de.width&&(z.width=de.width),z.height!==de.height&&(z.height=de.height),re.clearRect(0,0,z.width,z.height),re.drawImage(de,0,0)}return y+=F-A.pixels,A.pixels=F,me.needsUpdate=!0,n(),D(A)},setLED(O={}){if(p(),A.kind!=="led"||c.get(T)!==A)throw new Error("Choose an active LED surface.");Q(A,O)},setValue(O){if(p(),!Number.isFinite(O)||c.get(T)!==A)throw new TypeError("Choose a finite active control value.");return A.value=A.clamp(O),A.kind==="button"&&(A.pressed=!!A.value),N(A),n(),A.value},isAvailable(){return!h&&c.get(T)===A&&D(A)},dispose(){B(A)}}}function U(T){let I=T?.object?.userData?.demoSurface&&c.get(T.object.userData.demoSurface);return I&&Go(T.object)&&(I.mesh===T.object||I.meshes?.includes(T.object))&&D(I)?I:null}function X(T,I){let V=f;return V?(f=null,V.entry.pressed=!1,N(V.entry),n(),E(V.entry,"release",I,V.uv,{cancelled:T==="cancel"}),!0):!1}function W(T,I,V={}){if(h)return!1;if(I==="release"||I==="cancel")return!f||V.pointerId!==void 0&&V.pointerId!==f.pointerId?!1:X(I,V);if(I==="move"){if(!f||V.pointerId!==void 0&&V.pointerId!==f.pointerId)return!1;let ie=f.entry;if(ie.kind==="knob"&&Number.isFinite(V.clientY)){let le=ie.clamp(f.startValue+(f.startY-V.clientY)*ie.step);le!==ie.value&&(ie.value=le,N(ie),n(),E(ie,"change",V,T?.uv||f.uv))}return!0}if(I!=="press"||f)return!1;let K=U(T);return!K||K.kind==="led"?!1:(f={entry:K,pointerId:V.pointerId,startY:Number.isFinite(V.clientY)?V.clientY:0,startValue:K.value,uv:T.uv?{x:T.uv.x,y:T.uv.y}:void 0},K.pressed=!0,N(K),n(),E(K,"press",V,f.uv),!0)}function $(){if(!h)for(let T of c.values())D(T)}function G(){if(!h){X("cancel",null);for(let T of[...c.values()])B(T);h=!0,l.clear(),d=null,s.removeFromParent()}}return{selectFace:M,createSurface:H,setInputHandler(T){if(h&&T===null){d=null;return}if(p(),T!==null&&typeof T!="function")throw new TypeError("Choose an input callback or null.");T===null&&X("cancel",null),d=T},getPickables(){return $(),[...c.values()].flatMap(T=>T.meshes||[T.mesh]).filter(T=>T.visible)},getFace(T){let I=c.get(T);return I?I.bindings?j(I):_(I.face):null},objects(){return this.getPickables()},isHit(T){return!!U(T)},pointer:W,sync:$,get hasActivePointer(){return!!f},dispose:G}}function yP(e){let t=c=>{let u=e?.[c];if(!Array.isArray(u)||u.length!==3||!u.every(h=>typeof h=="number"&&Number.isFinite(h)&&Math.abs(h)<=1e7))throw new TypeError("Choose finite bounded 3D camera vectors.");return[...u]},r=t("position"),i=t("target"),n=t("up"),a=r.map((c,u)=>c-i[u]),s=Math.hypot(...a),o=Math.hypot(...n),l=[a[1]*n[2]-a[2]*n[1],a[2]*n[0]-a[0]*n[2],a[0]*n[1]-a[1]*n[0]];if(s<1e-4||o<1e-8||Math.hypot(...l)<s*o*1e-6)throw new TypeError("Choose a nondegenerate 3D camera direction and up vector.");return{position:r,target:i,up:n}}function Rx(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,a=Math.atan(Math.tan(n)*r);return e*Math.max(1,i)/Math.sin(Math.min(n,a))}function Px(e,t,r,i,n=.85,a=[0,1,0]){if(!Array.isArray(e)||e.length!==3||e.some(p=>!Number.isFinite(p)||p<0)||!Array.isArray(t)||t.length!==3||t.some(p=>!Number.isFinite(p))||!Array.isArray(a)||a.length!==3||a.some(p=>!Number.isFinite(p))||Math.hypot(...a)<1e-10||!(i>0&&Number.isFinite(i))||!(r>0&&r<180)||!(n>0&&n<1))return null;let s=Math.hypot(...t);if(s<1e-10)return null;let o=t.map(p=>p/s),l=(p,m)=>[p[1]*m[2]-p[2]*m[1],p[2]*m[0]-p[0]*m[2],p[0]*m[1]-p[1]*m[0]],c=(p,m)=>p.reduce((v,x,b)=>v+x*m[b],0),u=l(a,o);Math.hypot(...u)<1e-8&&(u=l(Math.abs(o[2])<.9?[0,0,1]:[0,1,0],o));let h=Math.hypot(...u);u=u.map(p=>p/h);let d=l(o,u),f=Math.tan(r*Math.PI/360)*n,y=f*i,g=.01;for(let p of[-1,1])for(let m of[-1,1])for(let v of[-1,1]){let x=[p*e[0]/2,m*e[1]/2,v*e[2]/2],b=c(x,o);g=Math.max(g,b+Math.abs(c(x,u))/y,b+Math.abs(c(x,d))/f,b+.01)}return g}function vP(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,h)=>u>t[h]))return null;let a=e.map((u,h)=>(u+t[h])/2),s=e.map((u,h)=>Math.max(h===2?1:8,t[h]-u)),o=r==="B.Cu"?-1:1,l=[0,1,0],c=Px(s,[0,0,o],i,n,.55,l);return c===null?null:{target:a,position:[a[0],a[1],a[2]+o*c],up:l}}var yc=e=>e&&typeof e=="object"&&!Array.isArray(e)?e.quoted:e,xP=e=>Array.isArray(e)?yc(e[0]):void 0,_m=(e,t)=>(Array.isArray(e)?e:[]).filter(r=>xP(r)===t),wm=(e,t)=>_m(e,t)[0],Vo=e=>Number.isFinite(e)&&e>0;function bP(e={},t=[],r=1.6){let i=[],n=new Map,a=0,s=C=>{i.length<64?i.push(C):a++},o=[...new Set((e.layers||[]).filter(C=>typeof C=="string"&&/^(?:F|B|In[1-9]\d*)\.Cu$/.test(C)))],l=o.slice(0,64);o.length>64&&s("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:[],h=Vo(r)?r:1.6;Vo(r)||s("Board thickness is unavailable; copper elevation uses an estimated 1.6 mm board depth.");let d=u.filter(C=>c.has(C.name)),f=new Map(d.filter(C=>Vo(C.thickness)).map(C=>[C.name,C.thickness])),y=l.filter(C=>!f.has(C));y.length&&s(`Saved copper thickness is unavailable for ${y.join(", ")}; 0.035 mm is used for display only.`);let g=C=>/^dielectric\b/i.test(C.name||"")||/^(core|prepreg|dielectric)$/i.test(C.type||""),p=l.length>0&&d.length===l.length&&d.every((C,S)=>C.name===l[S]&&Vo(C.thickness))&&u.every(C=>!(c.has(C.name)||g(C))||Vo(C.thickness)),m;if(p){let C=0,S=new Map;for(let w of u){let E=Vo(w.thickness)?w.thickness:0;c.has(w.name)&&S.set(w.name,h/2-C-E/2),C+=E}Math.abs(C-h)>Math.max(1e-6,h*1e-6)?s("Saved stackup thickness differs from board depth; copper elevations are estimated uniformly."):m=l.map(w=>({name:w,z:S.get(w),thickness:f.get(w)}))}let v=!!m;if(!m){p||s("Complete saved stackup depths are unavailable; copper elevations are estimated uniformly across the board.");let C=f.get(l[0])||.035,S=f.get(l.at(-1))||.035;m=l.map((w,E)=>({name:w,thickness:f.get(w)||.035,z:l.length<2?0:h/2-C/2-E/(l.length-1)*(h-(C+S)/2)}))}let x=new Map(m.map(C=>[C.name,C])),b=new Map,_=new Set,M=0;for(let C of _m(t,"via")){if((wm(C,"at")?.length||0)<3)continue;M++;let S=String(yc(wm(C,"uuid")?.[1])||yc(wm(C,"tstamp")?.[1])||`via-${M}`);b.has(S)&&_.add(S),b.set(S,C)}for(let C of e.vias||[]){let S=b.get(C.id),w=_m(S,"layers"),E=w.length===1?w[0].slice(1).map(yc):[],P=W=>s(`Via ${C.id}: ${W}; span omitted.`);if(!S||_.has(C.id)||E.length!==2||E.some(W=>typeof W!="string"||!x.has(W))||E[0]===E[1]){P("saved copper endpoint pair is absent, ambiguous or unknown");continue}let N=S.slice(1).filter(W=>!Array.isArray(W)).map(yc),D=N.filter(W=>["through","blind","buried","micro"].includes(W));if(D.length>1||N.some(W=>!["through","blind","buried","micro","locked"].includes(W))){P("saved via type is ambiguous or unsupported");continue}let B=E.map(W=>l.indexOf(W)).sort((W,$)=>W-$),J=l[B[0]],Q=l[B[1]],j=J==="F.Cu"&&Q==="B.Cu",k=D[0]||"through",H=[J,Q].filter(W=>W==="F.Cu"||W==="B.Cu").length;if(k==="through"&&!j||k!=="through"&&j||k==="micro"&&B[1]-B[0]!==1||k==="buried"&&H!==0){P("saved via type does not agree with its layer endpoints");continue}let U=x.get(J),X=x.get(Q);n.set(C.id,{zMin:Math.min(U.z,X.z),zMax:Math.max(U.z,X.z),from:J,to:Q,through:j,type:k==="blind"&&H===0?"buried":k})}return a&&i.push(`${a} additional saved-geometry diagnostics omitted.`),{layers:m,byLayer:x,viaSpans:n,warnings:i,savedDepths:v}}var vc=e=>typeof e=="number"&&Number.isFinite(e)&&Math.abs(e)<=1e4,Fn=(e,t)=>Math.abs(e-t)<=1e-9;function _P(e){let t=e.customPrimitives;if(e.customAnchor!=="rect"||!Array.isArray(t)||t.length!==3||!vc(e.width)||!vc(e.height)||e.width<=0||e.height<=0)return null;let r=t.filter(p=>p?.shape==="circle"),i=t.filter(p=>p?.shape==="polygon");if(r.length!==2||i.length!==1)return null;let n=e.width/2,a=e.height/2;for(let p of r)if(!Array.isArray(p.center)||p.center.length!==2||!p.center.every(vc)||!vc(p.radius)||!Fn(p.radius,n)||!Fn(p.center[0],0))return null;if(!(Fn(r[0].center[1],a)&&Fn(r[1].center[1],-a)||Fn(r[1].center[1],a)&&Fn(r[0].center[1],-a)))return null;let s=i[0].points;if(!Array.isArray(s)||s.length<4||s.length>5||!s.every(p=>Array.isArray(p)&&p.length===2&&p.every(vc)))return null;if(s.length===5){if(!s[0].every((p,m)=>Fn(p,s[4][m])))return null;s=s.slice(0,4)}let o=s.some(p=>Fn(p[0],n))?1:s.some(p=>Fn(p[0],-n))?-1:0;if(!o)return null;let l=[[0,-a-n],[o*n,-a-n],[o*n,a+n],[0,a+n]],c=new Set;for(let p of s){let m=l.findIndex(v=>v.every((x,b)=>Fn(x,p[b])));if(m<0||c.has(m))return null;c.add(m)}let u=s.map(p=>l.findIndex(m=>m.every((v,x)=>Fn(v,p[x]))));if(!u.every((p,m)=>(u[(m+1)%4]-p+4)%4===(u[1]-u[0]+4)%4)||![1,3].includes((u[1]-u[0]+4)%4))return null;let h=Math.ceil(Math.PI/Math.acos(Math.max(-1,1-.0025/n))),d=Math.min(128,Math.max(64,Math.ceil(h/4)*4)),f=d/4,y=[];for(let p=0;p<=f;p++){let m=Math.PI/2+p*Math.PI/2/f;y.push([n*Math.cos(m),a+n*Math.sin(m)])}for(let p=0;p<=f;p++){let m=Math.PI+p*Math.PI/2/f;y.push([n*Math.cos(m),-a+n*Math.sin(m)])}if(y.push([n,-a-n],[n,a+n]),o<0){for(let p of y)p[0]=-p[0];y.reverse()}y.push([...y[0]]);let g=n*(1-Math.cos(Math.PI/d));return{outline:y,tessellation:{error:g,limited:g>.00250000000025,tolerance:.0025}}}var Ix=1e4,Nx=16,Md=1e-10,Lx=e=>typeof e=="number"&&Number.isFinite(e)&&e>0&&e<=Ix,Sd=e=>typeof e=="number"&&Number.isFinite(e)&&Math.abs(e)<=Ix;function wP(e){let t=[];for(let r of e){let i=t.at(-1);(!i||Math.hypot(r[0]-i[0],r[1]-i[1])>Md)&&t.push(r)}return t.length>1&&Math.hypot(t[0][0]-t.at(-1)[0],t[0][1]-t.at(-1)[1])<=Md&&t.pop(),t.push([...t[0]]),t}function Td(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 a=[],s=[[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<=Nx;l++){let c=(-.5+o*.5+l*.5/Nx)*Math.PI;a.push([s[o][0]+r*Math.cos(c),s[o][1]+r*Math.sin(c)])}return wP(a)}function Em(e,t,r,i){return!Lx(t)||!Lx(r)?null:e==="rect"?Td(t,r,0):e==="oval"?Td(t,r,Math.min(t,r)/2):e==="circle"?Math.abs(t-r)<=Md*Math.max(1,t,r)?Td(t,r,t/2):null:e==="roundrect"&&typeof i=="number"&&Number.isFinite(i)&&i>=0&&i<=.5?Td(t,r,Math.min(t,r)*i):null}function Mm(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=Em(e.drillShape,t,r);if(!i)return null;let n=e.drillOffset??[0,0];if(!Array.isArray(n)||n.length!==2||!n.every(Sd))return null;let a=i.map(([s,o])=>[s+n[0],o+n[1]]).reverse();return a.every(s=>s.every(Sd))?a:null}function EP(e){if(!e||typeof e!="object")return null;let t=e.shape,r=t==="custom"?_P(e):null,i=r?.outline||Em(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=Mm(e),!n||!n.every(a=>Ox(i,a)))?null:{shape:t,outline:i,drill:n,...r?{tessellation:r.tessellation}:{}}}function Ox(e,[t,r],i=!1){let n=!1;for(let a=0,s=e.length-2;a<e.length-1;s=a++){let[o,l]=e[s],[c,u]=e[a],h=c-o,d=u-l,f=((t-o)*h+(r-l)*d)/(h*h+d*d),y=Math.max(0,Math.min(1,f));if(Math.hypot(t-(o+y*h),r-(l+y*d))<=Md)return i;l>r!=u>r&&t<(c-o)*(r-l)/(u-l)+o&&(n=!n)}return n}function MP(e){if(e?.padType!=="np_thru_hole")return!1;let t=Em(e.shape,e.width,e.height,e.roundrectRatio??e.roundrect_rratio),r=Mm(e);return!!(t&&r&&t.every(i=>Ox(r,i,!0)))}var hi=e=>e&&typeof e=="object"&&!Array.isArray(e)?e.quoted:e,cn=(e,t)=>e.find(r=>Array.isArray(r)&&hi(r[0])===t);function SP(e){let t=cn(e,"primitives");if(!t||t.length>17)return null;let r=[],i=(n,a)=>{let s=cn(n,a)?.slice(1).map(hi);return s?.length===2&&s.every(Sd)?s:null};for(let n of t.slice(1)){if(!Array.isArray(n)||hi(cn(n,"fill")?.[1])!=="yes"||hi(cn(n,"width")?.[1])!==0)return null;if(hi(n[0])==="gr_circle"){let a=i(n,"center"),s=i(n,"end");if(!a||!s)return null;r.push({shape:"circle",center:a,radius:Math.hypot(s[0]-a[0],s[1]-a[1])})}else if(hi(n[0])==="gr_poly"){let a=cn(n,"pts");if(!a||a.length<4||a.length>17)return null;let s=[];for(let o of a.slice(1)){if(!Array.isArray(o)||hi(o[0])!=="xy")return null;let l=o.slice(1).map(hi);if(l.length!==2||!l.every(Sd))return null;s.push(l)}r.push({shape:"polygon",points:s})}else return null}return r}function TP(e){let t=new Map,r=new Set,i=0;if(!Array.isArray(e)||hi(e[0])!=="kicad_pcb"||e.length>1e6)return t;let n=-1;for(let a of e){if(!Array.isArray(a)||!["footprint","module"].includes(hi(a[0]))||(n++,a.length>1e6))continue;let s=a.find(l=>Array.isArray(l)&&hi(l[0])==="property"&&hi(l[1])==="Reference")?.[2],o=-1;for(let l of a){if(!Array.isArray(l)||hi(l[0])!=="pad"||(o++,l.length>1e4))continue;if(++i>2e5)return t;let c=yx(l,hi(s),n,o);if(typeof c!="string"||!c||c.length>128)continue;if(r.has(c)){t.delete(c);continue}r.add(c);let u=cn(l,"roundrect_rratio")?.[1],h=cn(l,"drill"),d={type:"Pad",padType:String(hi(l[2])||""),uuid:c,ownerUuid:hi(cn(a,"uuid")?.[1]??cn(a,"tstamp")?.[1]),pinNumber:String(hi(l[1])??""),pinName:String(hi(cn(l,"pinfunction")?.[1])??"")};if(typeof u=="number"&&(d.roundrectRatio=u),hi(l[3])==="custom"&&(d.customAnchor=hi(cn(cn(l,"options")||[],"anchor")?.[1]),d.customPrimitives=SP(l)),h){let f=hi(h[1])==="oval";d.drillShape=f?"oval":"circle",d.drillWidth=h[f?2:1],d.drillHeight=f?h[3]:d.drillWidth;let y=cn(h,"offset");y&&(d.drillOffset=[y[1],y[2]])}if(t.set(c,d),t.size>=2e5)return t}}return t}var Ho=Math.PI*2,Sm=1e-9,xc=.0025,gi=e=>typeof e=="number"&&Number.isFinite(e);function Ad(e,{tolerance:t=xc,min:r=24,max:i=128}={}){if(!gi(e)||e<=0||!gi(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))),a=n>0?Math.ceil(Ho/n):i,s=Math.min(i,Math.max(r,Math.ceil(a/4)*4)),o=e*(1-Math.cos(Math.PI/s));return{segments:s,error:o,limited:o>t*1.0000000001,tolerance:t}}function AP(e,t,{world:r,z:i,thickness:n}){if(!Array.isArray(t)||typeof r!="function"||!gi(i)||!gi(n)||n<=0)throw Error("Invalid copper stroke batch parameters.");let a=t.filter(g=>gi(g.width)&&g.width>0&&Array.isArray(g.start)&&Array.isArray(g.end)&&g.start.length===2&&g.end.length===2&&[...g.start,...g.end].every(gi)),s=t.length-a.length;if(!a.length)return{batches:[],tracks:a,invalid:s,plan:null,triangles:0};let o=[12,16,24,32,48,64,96,128],l=new Map,c=new Map,u=[],h=0,d=!1;for(let g of a){let p=c.get(g.width);if(!p){let v=Ad(g.width/2,{min:12});p=o.find(x=>x>=v.segments)||128,c.set(g.width,p)}let m=g.width/2*(1-Math.cos(Math.PI/p));h=Math.max(h,m),d||=m>xc*1.0000000001,l.has(p)||l.set(p,[]),l.get(p).push(g)}let f=a.filter(g=>Math.hypot(g.end[0]-g.start[0],g.end[1]-g.start[1])>1e-12);f.length&&u.push({part:"core",records:f,geometry:new e.BoxGeometry(1,1,1),place(g,p){let m=r(p.start),v=r(p.end);g.position.set((m[0]+v[0])/2,(m[1]+v[1])/2,i),g.rotation.set(0,0,Math.atan2(v[1]-m[1],v[0]-m[0])),g.scale.set(Math.hypot(v[0]-m[0],v[1]-m[1]),p.width,n)}});for(let[g,p]of[...l].sort((m,v)=>m[0]-v[0])){let m=new e.CylinderGeometry(1,1,1,g/2,1,!1,0,Math.PI);m.rotateX(Math.PI/2);for(let v of["start","end"])u.push({part:v+"-"+g,records:p,geometry:m,place(x,b){let[_,M]=r(b[v]),C=r(b.start),S=r(b.end);x.position.set(_,M,i),x.rotation.set(0,0,Math.atan2(S[1]-C[1],S[0]-C[0])+(v==="start"?Math.PI:0)),x.scale.set(b.width/2,b.width/2,n)}})}let y={segments:Math.max(...l.keys()),error:h,limited:d,tolerance:xc};return{batches:u,tracks:a,invalid:s,plan:y,triangles:u.reduce((g,p)=>g+(p.geometry.index?.count||p.geometry.getAttribute("position").count)/3*p.records.length,0)}}function CP(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=Ad(r,{min:64}),n=i.segments/4,a=[],s=e/2,o=t/2,l=[[s-r,-o+r],[s-r,o-r],[-s+r,o-r],[-s+r,-o+r]];for(let c=0;c<4;c++)for(let u=0;u<=n;u++){let h=(-.5+c*.5+u*.5/n)*Math.PI,d=[l[c][0]+r*Math.cos(h),l[c][1]+r*Math.sin(h)],f=a.at(-1);(!f||Math.hypot(d[0]-f[0],d[1]-f[1])>Sm)&&a.push(d)}return Math.hypot(a[0][0]-a.at(-1)[0],a[0][1]-a.at(-1)[1])<Sm&&a.pop(),a.push([...a[0]]),a}function Dx(e,t,r,i){return CP(t,r,e==="rect"?0:e==="roundrect"?Math.min(t,r)*i:Math.min(t,r)/2)}function Tm(e){if(!Mm(e))return null;let t=e.drillWidth??e.drill,r=e.drillHeight??(e.drillShape==="circle"?t:void 0),i=e.drillOffset||[0,0];return Dx(e.drillShape,t,r,0).map(([n,a])=>[n+i[0],a+i[1]]).reverse()}function RP(e,t){let r=0;for(let i=0;i<e.length-1;i++){let n=e[i],a=e[i+1],s=(a[0]-n[0])*(t[1]-n[1])-(a[1]-n[1])*(t[0]-n[0]);if(Math.abs(s)<1e-12)return!1;let o=Math.sign(s);if(r&&o!==r)return!1;r=o}return!0}function kx(e){let t=EP(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>xc*1.0000000001}}}let r=e.roundrectRatio??e.roundrect_rratio,i=Dx(e.shape,e.width,e.height,r),n=e.drill||e.drillWidth||e.drillHeight?Tm(e):null,a=[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),s=a.map(o=>Ad(o,{min:64}));return n&&n.some(o=>!RP(i,o))?{...t,tessellation:{error:Math.max(0,...a.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,...s.map(o=>o.error)),limited:s.some(o=>o.limited)}}}function PP(e,t,r){if(!Array.isArray(t)||t.length<4||!t.every(o=>Array.isArray(o)&&o.length===2&&o.every(gi))||!gi(r)||r<=0||Math.hypot(t[0][0]-t.at(-1)[0],t[0][1]-t.at(-1)[1])>Sm)throw Error("Invalid saved drill wall.");let i=t.length-1,n=[],a=[];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;a.push(o*2,u*2,o*2+1,u*2,u*2+1,o*2+1)}let s=new e.BufferGeometry;return s.setAttribute("position",new e.Float32BufferAttribute(n,3)),s.setIndex(a),s.computeVertexNormals(),s}function IP(e,t,r=.035,i){if(!["F.Cu","B.Cu"].includes(e)||!gi(t)||t<=0||!gi(r)||r<=0||i!==void 0&&!gi(i))throw Error("Invalid outer copper placement.");let n=e==="F.Cu"?1:-1,a=.001,s=i??n*(t/2-r/2),o=s+n*a;return{center:o,sourceCenter:s,base:o-r/2,thickness:r,displayOffset:a}}function NP(e,t){if(!["F.Cu","B.Cu"].includes(e)||!gi(t?.base)||!gi(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 LP(e,t){if(!gi(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&&gi(o.z)&&gi(o.thickness)&&o.thickness>0,a=n(r)?r.z-r.thickness/2:e/2,s=n(i)?i.z+i.thickness/2:-e/2;if(!gi(a-s)||a<=s)throw Error("Outer copper inner faces do not enclose a valid substrate.");return{top:a,bottom:s,depth:a-s,missingOuterDepths:!n(r)||!n(i)}}var Us=e=>e&&typeof e=="object"&&!Array.isArray(e)?e.quoted:e,bc=(e,t)=>e.find(r=>Array.isArray(r)&&Us(r[0])===t),Am=(e,t)=>{let r=bc(e,t),i=r?.slice(1,3).map(Us);return i?.length===2&&i.every(gi)?i:null};function OP(e,t,r){let i=t[0]-e[0],n=t[1]-e[1],a=r[0]-e[0],s=r[1]-e[1],o=2*(i*s-n*a);if(Math.abs(o)<1e-12)return null;let l=i*i+n*n,c=a*a+s*s,u=[e[0]+(l*s-c*n)/o,e[1]+(c*i-l*a)/o],h=Math.atan2(e[1]-u[1],e[0]-u[0]),d=p=>(p%Ho+Ho)%Ho,f=d(Math.atan2(r[1]-u[1],r[0]-u[0])-h),y=d(Math.atan2(t[1]-u[1],t[0]-u[0])-h),g=Math.hypot(e[0]-u[0],e[1]-u[1]);return u.every(gi)&&gi(g)?{center:u,radius:g,start:h,sweep:y<=f?f:f-Ho}:null}function DP(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,a=new Map,s=new Set,o=Math.max(0,r-e.length);for(let h of e){let d=String(h.id||"").replace(/:\d+$/,"");n.has(d)||n.set(d,[]),n.get(d).push(h)}let l=(h,d)=>h&&d&&Math.hypot(h[0]-d[0],h[1]-d[1])<1e-6;for(let h of t){if(!Array.isArray(h)||Us(h[0])!=="arc")continue;let d=Am(h,"start"),f=Am(h,"mid"),y=Am(h,"end"),g=Us(bc(h,"uuid")?.[1])??Us(bc(h,"tstamp")?.[1]),p=Us(bc(h,"layer")?.[1]),m=Us(bc(h,"width")?.[1]);if(!d||!f||!y)continue;let v=typeof g=="string"&&n.has(g)?[[g,n.get(g)]]:[...n].filter(([,E])=>E[0].layer===p&&E[0].width===m&&l(E[0].start,d)&&l(E.at(-1).end,y));if(v.length!==1){i.push("A saved copper arc could not be matched unambiguously; existing parsed segments are retained.");continue}let[x,b]=v[0];if(s.has(x)){a.delete(x),i.push("Duplicate saved copper arc identity retained without refinement.");continue}s.add(x);let _=OP(d,f,y);if(!_){i.push("Degenerate saved copper arc retained without refinement.");continue}let M=Ad(_.radius,{min:24,max:4096}),C=Math.max(b.length,2,Math.ceil(M.segments*Math.abs(_.sweep)/Ho)),S=Math.max(0,C-b.length);if(M.limited||S>o){i.push("Saved copper arc refinement reached its geometric error or segment budget; parsed segments are retained.");continue}o-=S;let w=Array.from({length:C+1},(E,P)=>{let N=_.start+_.sweep*P/C;return[_.center[0]+_.radius*Math.cos(N),_.center[1]+_.radius*Math.sin(N)]});w[0]=d,w[C]=y,a.set(x,Array.from({length:C},(E,P)=>({...b[Math.min(b.length-1,Math.floor(P*b.length/C))],...typeof g=="string"?{uuid:g}:{},start:w[P],end:w[P+1]})))}let c=[],u=new Set;for(let h of e){let d=String(h.id||"").replace(/:\d+$/,"");a.has(d)?u.has(d)||(c.push(...a.get(d)),u.add(d)):c.push(h)}return{tracks:c,warnings:[...new Set(i)],tolerance:xc}}var Ux=e=>encodeURIComponent(e?.trim()||"global");function Wo(e,t,r){return`spike:${e}:${Ux(t)}:${Ux(r)}`}function Fx(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 kP(e,t){let r=e.map(()=>!0),i=Fx(e);if(!Array.isArray(t))return r;let n=new Map;for(let a of t)typeof a?.reference!="string"||!a.reference||typeof a.populated!="boolean"||n.set(a.reference,n.has(a.reference)?null:a.populated);for(let[a,s]of n){let o=i.get(a);o!=null&&s!=null&&(r[o]=s)}return r}function UP(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 a=t.get(n.ref)||[],s=n.layer?.startsWith("B.")?"B":"F",o=[],l=null;for(let _ of[s+".Fab",s+".CrtYd"]){let M=a.filter(C=>C.layer===_&&C.points).map(C=>C.points);if(o=M.flat(),l=FP(M),o.length)break}if(!o.length)for(let _ of a.filter(M=>M.at&&M.width>0&&M.height>0)){let M=-(_.rotation||0)*Math.PI/180,C=Math.cos(M),S=Math.sin(M);for(let w of[-_.width/2,_.width/2])for(let E of[-_.height/2,_.height/2])o.push([_.at[0]+w*C-E*S,_.at[1]+w*S+E*C])}let c=(n.rotation||0)*Math.PI/180,u=Math.cos(c),h=Math.sin(c),d=o.filter(_=>_?.length>=2&&_.every(Number.isFinite)).map(([_,M])=>(_-=n.at[0],M-=n.at[1],[_*u-M*h,_*h+M*u]));if(!d.length)continue;let f=1/0,y=1/0,g=-1/0,p=-1/0;for(let[_,M]of d)f=Math.min(f,_),y=Math.min(y,M),g=Math.max(g,_),p=Math.max(p,M);let m=g-f,v=p-y;if(!(m>1e-6&&v>1e-6))continue;let x=(f+g)/2,b=(y+p)/2;if(l){let _=l.map(([S,w])=>(S-=n.at[0],w-=n.at[1],[S*u-w*h,S*h+w*u]));if(!Bx([x,b],_))continue;let M=0,C=1;for(let S=0;S<30;S++){let w=(M+C)/2,E=[[-1,-1],[1,-1],[1,1],[-1,1]].map(([P,N])=>[x+P*m*w/2,b+N*v*w/2]);E.every(P=>Bx(P,_))&&!E.some((P,N)=>_.some((D,B)=>BP(P,E[(N+1)%4],D,_[(B+1)%_.length])))?M=w:C=w}if(m*=M,v*=M,!(m>1e-6&&v>1e-6))continue}i.set(n,{at:[n.at[0]+x*u+b*h,n.at[1]-x*h+b*u],width:m,height:v,rotation:c})}return i}var _c=(e,t)=>Math.hypot(e[0]-t[0],e[1]-t[1])<1e-5;function FP(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(;!_c(i[0],i.at(-1));){let n=t.findIndex(s=>_c(i.at(-1),s[0])||_c(i.at(-1),s.at(-1)));if(n<0)break;let a=t.splice(n,1)[0];_c(i.at(-1),a[0])||a.reverse(),i.push(...a.slice(1))}i.length>3&&_c(i[0],i.at(-1))&&r.push(i.slice(0,-1))}return r.length===1?r[0]:r.length?[]:null}function Bx(e,t){let r=!1;for(let i=0,n=t.length-1;i<t.length;n=i++){let a=t[i],s=t[n];a[1]>e[1]!=s[1]>e[1]&&e[0]<(s[0]-a[0])*(e[1]-a[1])/(s[1]-a[1])+a[0]&&(r=!r)}return r}function BP(e,t,r,i){let n=(a,s,o)=>(s[0]-a[0])*(o[1]-a[1])-(s[1]-a[1])*(o[0]-a[0]);return n(e,t,r)*n(e,t,i)<-1e-12&&n(r,i,e)*n(r,i,t)<-1e-12}function zP(e,{objects:t,camera:r,rect:i,positionToWorld:n}){let a=s=>s?.type==="Component"||typeof s?.library=="string";return function(s){if(!s||typeof s!="object")return null;let o=i();if(!(o.width>0&&o.height>0))return null;let l=y=>(y.project(r),![y.x,y.y,y.z].every(Number.isFinite)||Math.abs(y.x)>1||Math.abs(y.y)>1||y.z<-1||y.z>1?null:{x:o.left+(y.x+1)*o.width/2,y:o.top+(1-y.y)*o.height/2,visible:!0});if(s.position){let{x:y,y:g}=s.position;return![y,g].every(p=>typeof p=="number"&&Number.isFinite(p)&&Math.abs(p)<=1e6)||!["front","back",void 0].includes(s.side)?null:l(n({x:y,y:g},s.side))}let c=y=>typeof y=="string"&&y.length>0&&y.length<=500&&!/[\x00-\x1f\x7f]/.test(y);if(!["uuid","reference","pinNumber","net"].some(y=>c(s[y]))||["uuid","reference","pinNumber","net"].some(y=>s[y]!==void 0&&!c(s[y]))||s.pinNumber&&!s.uuid&&!s.reference)return null;let u=new Map,h=new e.Matrix4,d=new e.Matrix4;for(let y of t()){let g=!0;for(let m=y;m;m=m.parent)m.visible||(g=!1);if(!g)continue;let p=y.userData.records||[y.userData.record];for(let m=0;m<p.length;m++){let v=p[m];if(!v)continue;let x=v.uuid||v.id;if(s.uuid&&s.uuid!==x&&!(s.pinNumber&&s.uuid===v.ownerUuid)&&!(typeof x=="string"&&x.replace(/:\d+$/,"")===s.uuid)||s.reference&&v.ref!==s.reference||s.pinNumber&&String(v.pinNumber??v.name??"")!==s.pinNumber||s.net&&v.net!==s.net||s.reference&&!s.uuid&&!s.pinNumber&&!s.net&&!a(v)||(y.updateWorldMatrix(!0,!1),y.geometry?.boundingBox||y.geometry?.computeBoundingBox(),!y.geometry?.boundingBox))continue;let b=y.geometry.boundingBox.clone();if(y.isInstancedMesh){if(y.getMatrixAt(m,d),d.determinant()===0)continue;h.multiplyMatrices(y.matrixWorld,d),b.applyMatrix4(h)}else b.applyMatrix4(y.matrixWorld);if(b.isEmpty())continue;let _=x||v.ref;_&&(u.has(_)?u.get(_).union(b):u.set(_,b))}}if(!s.net&&u.size!==1)return null;let f=[...u.values()].map(y=>l(y.getCenter(new e.Vector3))).filter(Boolean);return f.sort((y,g)=>Math.hypot(y.x-o.left-o.width/2,y.y-o.top-o.height/2)-Math.hypot(g.x-o.left-o.width/2,g.y-o.top-o.height/2)),f[0]||null}}function Cm(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 GP(e,t){let r=new Map,i=new Map,n=new Map,a=new Map,s={owned:[]},o="",l=v=>Array.isArray(v)?v:[v];function c(){for(let[v,x]of r){v.material=x.material,v.isInstancedMesh&&(v.instanceColor!==x.instanceColor&&v.dispose?.(),v.instanceColor=x.instanceColor,v.customDepthMaterial=x.depth,v.customDistanceMaterial=x.distance);for(let b of x.owned)b.dispose()}for(let v of s.owned)v.dispose();s.owned.length=0,i.clear(),n.clear(),a.clear(),r.clear(),o=""}function u(v){if(r.has(v))return r.get(v);let x={material:v.material,instanceColor:v.instanceColor,depth:v.customDepthMaterial,distance:v.customDistanceMaterial,owned:[]};return r.set(v,x),x}function h(v,x){let b=v.clone();return b.onBeforeCompile=v.onBeforeCompile,b.customProgramCacheKey=()=>v.customProgramCacheKey(),x.owned.push(b),b}function d(v,x,b){if(v.has(x))return v.get(x);let _=h(x,s);return b(_),v.set(x,_),_}function f(v,x,b=!1){if(b&&i.has(v))return i.get(v);let _=h(v,b?s:x),M=v.onBeforeCompile;return _.userData??={},_.userData.selectionOpacityCap=.24,_.opacity=Math.min(v.opacity??1,.24),_.transparent=!0,_.depthWrite=!1,_.onBeforeCompile=(C,S)=>{M?.call(_,C,S),C.fragmentShader=C.fragmentShader.replace("#include <opaque_fragment>",`outgoingLight = vec3(dot(outgoingLight, vec3(0.2126, 0.7152, 0.0722))) * 0.24;
#include <opaque_fragment>`)},_.customProgramCacheKey=()=>v.customProgramCacheKey()+":selection-grey",b&&i.set(v,_),_}function y(v){return v.accent||(v.accent=l(v.material).map(x=>d(a,x,b=>{b.color?.setHex(6547182),b.emissive?.setHex(1201756),b.metalness=0,b.roughness=.55}))),Array.isArray(v.material)?v.accent:v.accent[0]}function g(v,x,b=!1,_=!1){let M=v.onBeforeCompile,C=v.customProgramCacheKey(),S=b?v:h(v,x);return b&&x.owned.push(S),_&&(S.transparent=!0,S.depthWrite=!1),S.onBeforeCompile=(w,E)=>{M?.call(S,w,E),w.vertexShader=w.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`),w.vertexShader=w.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")),w.fragmentShader=w.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;"+(_?" diffuseColor.a *= 0.24;":"")+` }
#include <opaque_fragment>`)},S.customProgramCacheKey=()=>C+":selection-instances-v1"+(_?":translucent-context":""),S}function p(v,x,b=null,_={}){let M=Cm(_),C=_.expanded===!0,S=_.netContext===!0,w=M.mode+":"+M.color+":"+C+":"+S,E=M.mode==="dim"&&S,P=D=>v(D)&&!(E&&(D?.type==="Component"||typeof D?.library=="string"));if(!x){c();return}o&&o!==w&&c(),o=w;let N=M.mode==="dim"&&M.color==="accent";for(let D of t()){if(!D.material)continue;let B=u(D),J=D.userData.records,Q=D.userData.identity?.startsWith("spike:via-barrel:"),j=N&&!Q&&!E;if(Q&&M.mode!=="isolate"&&!((C||S)&&M.mode==="dim")){D.material=B.material,D.instanceColor!==B.instanceColor&&(D.instanceColor=B.instanceColor);continue}if(D.isInstancedMesh&&J){if(j){B.white||(B.white=l(B.material).map(U=>{let X=h(U,B);return X.color?.setHex(16777215),X}),D.instanceColor=B.instanceColor?.clone()||null),D.material=Array.isArray(B.material)?B.white:B.white[0];let k=l(B.material)[0].color||new e.Color(16777215),H=new e.Color;for(let U=0;U<J.length;U++){if(B.instanceColor?H.fromArray(B.instanceColor.array,U*3).multiply(k):H.copy(k),b?.(J[U]))H.setHex(6547182);else if(!v(J[U])){let X=(H.r*.2126+H.g*.7152+H.b*.0722)*.24;H.setRGB(X,X,X)}D.setColorAt(U,H)}}else{B.instances||(B.instances=l(B.material).map(H=>g(H,B,!1,M.mode==="dim"&&(S||Q&&C))),D.instanceColor=B.instanceColor?.clone()||null,M.mode==="isolate"&&(D.customDepthMaterial=g(B.depth||new e.MeshDepthMaterial({depthPacking:e.RGBADepthPacking}),B,!B.depth),D.customDistanceMaterial=g(B.distance||new e.MeshDistanceMaterial,B,!B.distance))),D.material=Array.isArray(B.material)?B.instances:B.instances[0];let k=new e.Color;for(let H=0;H<J.length;H++){B.instanceColor?k.fromArray(B.instanceColor.array,H*3):k.setHex(16777215);let U=J[H],X=P(U);!X&&M.mode==="isolate"?k.setRGB(-1e30,-1e30,-1e30):!Q&&M.color==="accent"&&b?.(U)?k.setRGB(-1e20,-1e20,-1e20):!X&&M.mode==="dim"&&k.setRGB(-k.r-1,-k.g-1,-k.b-1),D.setColorAt(H,k)}}D.instanceColor&&(D.instanceColor.needsUpdate=!0)}else M.mode==="isolate"&&D.userData.record&&D.userData.record.type!=="Board"&&!v(D.userData.record)?(B.hidden||(B.hidden=l(B.material).map(k=>d(n,k,H=>{H.visible=!1}))),D.material=Array.isArray(B.material)?B.hidden:B.hidden[0]):!Q&&M.color==="accent"&&b?.(D.userData.record)?D.material=y(B):P(D.userData.record)||M.mode!=="dim"?D.material=B.material:(B.dim||(B.dim=l(B.material).map(k=>f(k,B,!D.isInstancedMesh))),D.material=Array.isArray(B.material)?B.dim:B.dim[0])}}function m(v,x){let b=v.isInstancedMesh&&v.instanceColor;return b&&Number.isInteger(x)&&b.array[x*3]<-1e25?!1:l(v.material).some(_=>_&&_.visible!==!1)}return{update:p,restore:c,dispose:c,isVisible:m,stats:()=>({capturedObjects:r.size,sharedDimMaterials:i.size})}}var VP=Object.freeze(["realistic","layers","translucent"]);function zx(e){if(!VP.includes(e))throw new TypeError("Choose realistic, layers or translucent appearance.");return e}function HP(){let e=new Map,t=new Map,r=!1,i=!1,n={substrate:.12,component:.22,zone:.08,silkscreen:.45};function a(c){return Array.isArray(c)?c:[c]}function s(c,u){if(!c||!c.clone)return c;let h=t.get(c);if(h||(h=new Map,t.set(c,h)),h.has(u))return h.get(u);let d=c.clone();return d.onBeforeCompile=c.onBeforeCompile,d.customProgramCacheKey=()=>c.customProgramCacheKey(),d.transparent=!0,d.opacity=(Number.isFinite(c.opacity)?c.opacity:1)*n[u],d.depthWrite=!1,d.forceSinglePass=!0,d.needsUpdate=!0,h.set(u,d),d}function o(c,u){let h=a(u.material).map(d=>s(d,u.role));c.material=Array.isArray(u.material)?h:h[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 h={material:c.material,role:u};e.set(c,h),r&&o(c,h)},setEnabled(c){if(i)return!1;let u=!!c;if(u===r)return r;if(u||l(),r=u,r)for(let[h,d]of e)o(h,d);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 Rm(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 WP(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,a=0,s=i.findIndex(u=>u.name==="F.Cu"),o=i.findIndex(u=>u.name==="B.Cu"),l=s>=0&&o>s&&i.slice(s,o+1).every(u=>Number.isFinite(u.thickness)&&u.thickness>=0);if(l)for(let u of i){let h=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-a-h/2)}a+=h}let c=l&&r.every(u=>n.has(u))&&Math.abs(a-t)<1e-6&&r.every((u,h)=>!h||n.get(r[h-1])>n.get(u));return r.map((u,h)=>({name:u,internal:h>0&&h<r.length-1,z:h===0?t/2+.025:h===r.length-1?-t/2-.025:c?n.get(u):t/2-h*t/(r.length-1),basis:h===0||h===r.length-1?"outer-surface":c?"saved-stackup":"illustrative"}))}function jP(e,t){let r=!1,i=!1,n=0,a=0;return{request(){if(!i&&(n++,!r)){r=!0;try{t()}catch(s){throw r=!1,s}}},flush(){i||!r||(r=!1,a++,e())},dispose(){i=!0,r=!1},stats(){return{requestCount:n,flushCount:a,pending:r}}}}function Gx({request:e,cancel:t,render:r,canRender:i=()=>!0,state:n={}}){let a={documentVisible:!0,intersecting:!0,hasSize:!0,contextAvailable:!0,...n},s=null,o=!1,l=!1,c=0,u=0,h=0,d=0,f=0,y=0,g=0,p=()=>!l&&a.documentVisible&&a.intersecting&&a.hasSize&&a.contextAvailable&&i();function m(){s!==null&&(t(s),s=null,f++)}function v(){!o||s!==null||!p()||(u++,s=e(()=>{if(s=null,!p()){y++;return}o&&(o=!1,h++,r())}))}return{invalidate(){l||(c++,o=!0,p()?v():d++)},setState(x){if(l)return;let b=p();Object.assign(a,x),p()?(b||(g++,o=!0),v()):m()},stats(){return{...a,paused:!p(),dirty:o,pending:s!==null,requestCount:c,scheduledFrames:u,renderCallbacks:h,suppressedInvalidations:d,cancelledFrames:f,skippedFrames:y,resumeCount:g}},dispose(){l||(l=!0,m(),o=!1)}}}function Vx(e,t,r=globalThis.IntersectionObserver){if(typeof r!="function")return null;let i;try{return i=new r(n=>{let a=n.find(s=>s.target===t);a&&e.setState({intersecting:!!a.isIntersecting&&a.intersectionRatio!==0})}),i.observe(t),i}catch{return i?.disconnect(),e.setState({intersecting:!0}),null}}function XP(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 YP(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 qP(e,t){return t.size>0&&!["references","uuids"].some(r=>Array.isArray(e[r])&&e[r].some(i=>typeof i=="string"&&i))}function KP(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 ZP(e,t){let r=new Set,i=0,n=0,a=0;for(let s of e){let o=!0;for(let c=s;c;c=c.parent)if(!c.visible){o=!1;break}if(!o||!s.geometry?.attributes?.position?.count)continue;a++;let l=(c,u)=>{i++,!(!t(c)||s.isInstancedMesh&&Number.isInteger(u)&&!KP(s,u))&&(n++,r.add(c?.ref?"part:"+c.ref:c?.uuid||c?.id||s.uuid+":"+u))};Array.isArray(s.userData.records)?s.userData.records.forEach(l):l(s.userData.record)}return{matched:r.size,matchedRecords:n,visitedRecords:i,visibleObjects:a}}function Cd(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 QP(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),a=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?a.add(l):typeof o=="string"&&!/^\d+$/.test(o)&&a.add(o)}let s=new Set;for(let o of t.pads||[])a.has(o.net)&&o.ref&&s.add(o.ref);return o=>!!(o&&(i.has(o.ref)||a.has(o.net)||n.has(o.uuid)||n.has(o.id)||typeof o.id=="string"&&n.has(o.id.split(":")[0])||s.has(o.ref)&&(o.type==="Component"||typeof o.library=="string")))}function Hx(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),a=!!(n&&!r&&t.size===1&&Math.hypot(i.clientX-n[0],i.clientY-n[1])<e);return t.delete(i.pointerId),a},cancel(i){t.delete(i.pointerId),r=!0}}}function JP(e,{later:t=setTimeout,clear:r=clearTimeout,delay:i=550,limit:n=8}={}){let a=new Set,s=null,o=null,l=!1,c=()=>{s!==null&&r(s),s=null};return{down(u){a.size||(l=!1),a.add(u.pointerId),c(),!(u.pointerType!=="touch"||a.size!==1)&&(o={pointerId:u.pointerId,clientX:u.clientX,clientY:u.clientY},s=t(()=>{s=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(),a.delete(u.pointerId),l},isHeld(){return l},dispose(){c(),a.clear(),o=null}}}function $P(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 eI(e,{scene:t,renderer:r,extent:i,bottom:n,constrained:a=!1}){let s=new e.ShadowMaterial({color:0,opacity:.18,depthWrite:!1}),o=new e.Mesh(new e.PlaneGeometry(i*6,i*6),s);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(h=>{h.isDirectionalLight&&h.castShadow&&c.push(h)});function u(h,{fast:d=!1}={}){for(let[y,g]of l)y.castShadow=h||g;o.visible=h,t.environmentIntensity=h?1:.65,r.toneMappingExposure=h?1.05:1;let f=h&&!a&&!d?2048:1024;for(let y of c)y.shadow.mapSize.x!==f&&(y.shadow.map?.dispose(),y.shadow.map=null,y.shadow.mapSize.set(f,f),y.shadow.needsUpdate=!0);r.shadowMap.needsUpdate=!0}return{apply:u,addCaster(h){l.set(h,h.castShadow),h.castShadow=o.visible||h.castShadow},get enabled(){return o.visible},dispose(){for(let[h,d]of l)h.castShadow=d;l.clear(),t.remove(o),o.geometry.dispose(),s.dispose()}}}function Pm(e,t,r=1,i=4096){let n=Number.isFinite(e)&&e>0?e:1,a=Number.isFinite(t)&&t>0?t:1,s=Number.isFinite(r)&&r>0?r:1,o=Number.isFinite(i)&&i>0?i:4096;return Math.min(s,3,Math.sqrt(4e6/n/a),o/n,o/a)}function Im(e){return["low","balanced","high","presentation","photoreal-fast"].includes(e)?e:"balanced"}function tI({maxTextureSize:e=4096,maxRenderbufferSize:t=e,deviceMemory:r,hardwareConcurrency:i=0,floatTargets:n=!1,android:a=!1}={}){let s=Math.min(...[e,t].map(u=>Number.isFinite(u)&&u>0?u:4096)),o=Number.isFinite(r)&&r>0?r:null,l=s<=4096||o!==null&&o<=2,c=!l&&n&&s>=8192&&(o!==null?o>=6:s>=16384&&i>=8);return{tier:l?"constrained":c?"premium":"standard",constrained:l,premium:c,maxDimension:s,defaultQuality:a&&c?"high":"balanced",highMaxPixels:l?1e6:c?3e6:2e6}}function Wx(e,t,r=1,i=4096,n="balanced",a=!1){let s=Im(n),o=Number.isFinite(e)&&e>0?e:1,l=Number.isFinite(t)&&t>0?t:1,c=a&&typeof a=="object"?a:null,u=c?c.constrained:a,h=s==="high"||s==="presentation",d=s==="photoreal-fast"?1e6:s==="presentation"?u?1e6:c?.premium?4e6:3e6:s==="high"?c?c.highMaxPixels:u?1e6:2e6:s==="low"||u?1e6:2e6,f=Math.min(Pm(o,l,s==="presentation"&&!u?Math.max(1.5,r):r,i),Math.sqrt(d/o/l)),y=Math.floor(o*f)*Math.floor(l*f),g=h?96:s==="low"?12:48;return{quality:s,ratio:f,width:Math.max(1,Math.floor(o*f)),height:Math.max(1,Math.floor(l*f)),pixels:y,maxPixels:d,estimatedBytes:y*g+(s==="low"?0:2*(s==="presentation"&&!u?2048:1024)**2*4)}}function rI(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 iI(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 wc=Object.freeze({coatedCopper:1459761,exposedCopper:12954220});function nI(e,t,r,i){let n=0,a=0;for(let s=0;s<3;s++)n+=((r[s]+i[s])/2-e[s])*t[s],a+=(i[s]-r[s])/2*Math.abs(t[s]);return n-a}function aI(e,t,r){let i=Number.isFinite(e)&&e>0?e:1,n=Number.isFinite(t)&&t>0?t:1,a=Number.isFinite(r)?r:i-n,s=Math.max(.005,a*.5);return{near:s,far:Math.max(10,i+n*4,s+1)}}var sI=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)),Yn=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 oI(e){let t=e.onBeforeCompile;e.onBeforeCompile=function(i,n){t?.call(this,i,n);let a="#include <logdepthbuf_fragment>";if(!i.fragmentShader.includes(a))throw Error("Unsupported occlusion depth shader.");i.fragmentShader=i.fragmentShader.replace(a,"")};let r=e.customProgramCacheKey;e.customProgramCacheKey=function(){return r.call(this)+"|perspective-occlusion-depth-v1"}}var lI=2e5,cI=6e5;function Nm(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>cI||e.triangles.length>lI)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 jx(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 Lm(e,t=i=>i,r={}){let i=Nm(e),n=r.palette;if(n!==void 0&&(!Array.isArray(n)||n.length!==4||n.some(_=>!Array.isArray(_)||_.length!==3||_.some(M=>!Number.isFinite(M)||M<0||M>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 a=new jr,s=new jr,o=1/0,l=-1/0;for(let _ of i.values)_!==null&&(o=Math.min(o,_),l=Math.max(l,_));r.range&&(o=r.range[0],l=r.range[1]);let c=[],u=[],h=[],d=[],f=[new yt(2639291),new yt(52179),new yt(16769114),new yt(15154225)],y=_=>Number.isFinite(l-o)?(_-o)/(l-o):(_/2-o/2)/(l/2-o/2),g=_=>l>o?Math.max(0,Math.min(1,y(_))):.5,p=_=>{let M=g(_)*3,C=Math.min(2,Math.floor(M)),S=M-C;if(n){let w=n[C].map((E,P)=>Math.round(E+(n[C+1][P]-E)*S)/255);return new yt().setRGB(...w,Pr)}return f[C].clone().lerp(f[C+1],S)};i.triangles.forEach((_,M)=>{let C=i.nodal?_.map(N=>i.values[N]):_.map(()=>i.values[M]);if(C.some(N=>N===null))return;let S=_.map(N=>t(i.points[N]));if(S.some(N=>!Array.isArray(N)||N.length!==3||!N.every(D=>Number.isFinite(D)&&Number.isFinite(Math.fround(D)))))throw new Error("Invalid result coordinate mapping.");let w=new ee(...S[0]),E=new ee(...S[1]),P=new ee(...S[2]);E.clone().sub(w).cross(P.clone().sub(w)).lengthSq()!==0&&(S.forEach((N,D)=>{c.push(...N);let B=p(C[D]);u.push(B.r,B.g,B.b),r.range&&d.push(y(C[D]))}),h.push(M))});let m=new ar;m.setAttribute("position",new Mt(c,3)),m.setAttribute("color",new Mt(u,3)),r.range&&m.setAttribute("resultScalar",new Mt(d,1)),m.computeBoundingSphere();let v=new ti({vertexColors:!0,toneMapped:!1,side:Rt,transparent:!0,opacity:.85,depthWrite:!1,polygonOffset:!0,polygonOffsetFactor:-2,polygonOffsetUnits:-2}),x=new hr(m,v);a.add(x,s);function b(_){if(!_||_.object!==x||_.faceIndex==null)return null;let M=h[_.faceIndex],C=i.triangles[M];if(!C)return null;let S=C.map(D=>new ee(...t(i.points[D]))),w=new ee;if(ua.getBarycoord(_.point,...S,w),![w.x,w.y,w.z].every(Number.isFinite))return null;let E=C.map(D=>i.points[D]),P=D=>E[0][D]*w.x+E[1][D]*w.y+E[2][D]*w.z,N=i.nodal?i.values[C[0]]*w.x+i.values[C[1]]*w.y+i.values[C[2]]*w.z:i.values[M];return{x:P(0),y:P(1),z:P(2),value:N,unit:String(i.unit||""),method:i.nodal?"nodal barycentric interpolation":"saved cell value",triangle:M}}return{group:a,mesh:x,surface:i,min:o,max:l,range:Number.isFinite(o)&&Number.isFinite(l)?[o,l]:null,sample:b,setOpacity(_){Number.isFinite(_)&&(v.opacity=Math.max(0,Math.min(1,_)),x.visible=v.opacity>0)},setProbes(_=[]){if(jx(s),!Array.isArray(_))return;let M=Math.max((m.boundingSphere?.radius||1)*.012,.001);for(let C of _.slice(0,100)){if(![C.x,C.y,C.z].every(Number.isFinite))continue;let S=new hr(new Ua(M,12,8),new ti({color:16777215,depthTest:!1}));if(S.position.set(...t([C.x,C.y,C.z])),S.renderOrder=10,S.userData.label=String(C.label||""),s.add(S),C.label){let w=document.createElement("canvas");w.width=256,w.height=64;let E=w.getContext("2d");if(E){E.fillStyle="#101d28",E.fillRect(0,0,256,64),E.fillStyle="#fff",E.font="bold 32px system-ui",E.textBaseline="middle",E.fillText(String(C.label).slice(0,12),8,32,240);let P=new Lh(w);P.colorSpace=Pr;let N=new qp(new dh({map:P,depthTest:!1}));N.position.copy(S.position).add(new ee(0,0,M*4)),N.scale.set(M*12,M*3,1),N.renderOrder=11,s.add(N)}}}},dispose(){jx(a),a.removeFromParent()}}}function uI(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 a=document.createElement("div");a.className="shell";let s=document.createElement("div");s.className="bar";let o=document.createElement("span");o.className="title",s.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"),a.append(s,l,c,u),i.append(n,a),e.append(r);let h;try{h=new sd({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()}}}h.outputColorSpace=Pr,h.domElement.setAttribute("role","img"),h.domElement.setAttribute("aria-label","3D saved result surface"),l.append(h.domElement);let d=new us;d.background=new yt(1056040);let f=new li(45,1,.001,1e6);f.up.set(0,0,1);let y=new sm(f,h.domElement);y.enableDamping=!0;let g=null,p=!0,m=0,v=.85,x=[],b=new Xe,_=new ic;function M(G=!1){if(!p||!g)return;let T=new Yr().setFromObject(g.mesh),I=T.getBoundingSphere(new si);if(T.isEmpty())return;let V=Math.max(I.radius,.001),K=V/Math.sin(Xu.degToRad(f.fov/2))*1.25/Math.min(f.aspect,1);y.target.copy(I.center),f.position.copy(I.center).add(new ee(...G?[0,-1e-6,1]:[1,-1,1]).normalize().multiplyScalar(K)),f.near=Math.max(V*1e-5,1e-6),f.far=K+V*1e3,f.updateProjectionMatrix(),y.minDistance=V*.005,y.maxDistance=V*1e3,y.update()}function C(G){if(!p)return;let T=Lm(G,([I,V,K])=>[I,-V,K]);g?.dispose(),g=T,d.add(T.group),T.setOpacity(v),T.setProbes(x),o.textContent=String(G.title||"Saved result surface"),c.textContent=`${G.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(T.min)?` \xB7 ${T.min.toPrecision(5)}\u2013${T.max.toPrecision(5)} ${G.unit||""}`:" \xB7 no valid samples"}`,u.textContent="Click a colored surface to probe.",M()}let S=(G,T)=>{let I=document.createElement("button");I.textContent=G,I.type="button",I.addEventListener("click",T),s.append(I)};S("Fit",()=>M()),S("Top",()=>M(!0));let w=document.createElement("label");w.textContent="Opacity";let E=document.createElement("input");E.type="range",E.min="0",E.max="1",E.step=".05",E.value=String(v),E.setAttribute("aria-label","Result surface opacity"),w.append(E),s.append(w);let P=G=>{!p||!Number.isFinite(G)||(v=Math.max(0,Math.min(1,G)),E.value=String(v),g?.setOpacity(v))};E.addEventListener("input",()=>P(Number(E.value)));function N(G){if(!g||!g.mesh.visible)return null;let T=h.domElement.getBoundingClientRect();return!T.width||!T.height?null:(b.set((G.clientX-T.left)/T.width*2-1,-(G.clientY-T.top)/T.height*2+1),_.setFromCamera(b,f),g.sample(_.intersectObject(g.mesh,!1)[0]))}let D=null,B=G=>{D={id:G.pointerId,x:G.clientX,y:G.clientY,moved:!1}},J=G=>{D&&(D.id!==G.pointerId||Math.hypot(G.clientX-D.x,G.clientY-D.y)>5)&&(D.moved=!0),t.onHover?.(N(G))},Q=G=>{let T=D&&D.id===G.pointerId&&!D.moved&&(G.button===0||G.pointerType==="touch");if(D=null,!T)return;let I=N(G);I&&(u.textContent=`${I.value.toPrecision(6)} ${I.unit} at (${I.x.toFixed(3)}, ${I.y.toFixed(3)}, ${I.z.toFixed(3)}) \xB7 ${I.method}`,t.onProbe?.(I))},j=()=>{D=null},k=()=>t.onHover?.(null);for(let[G,T]of[["pointerdown",B],["pointermove",J],["pointerup",Q],["pointercancel",j],["pointerleave",k]])h.domElement.addEventListener(G,T);let H=()=>{if(!p)return;let G=Math.max(l.clientWidth,1),T=Math.max(l.clientHeight,1),I=Pm(G,T,globalThis.devicePixelRatio,h.capabilities.maxTextureSize);h.getPixelRatio()!==I&&h.setPixelRatio(I),h.setSize(G,T,!1),f.aspect=G/T,f.updateProjectionMatrix()},U=new ResizeObserver(H);U.observe(l),H();let X=G=>{G.preventDefault(),c.textContent="3D graphics context lost. Reopen this view to restore rendering.",p=!1,cancelAnimationFrame(m)};h.domElement.addEventListener("webglcontextlost",X);let W=G=>{r.style.background=G?"#101d28":"#f3f7f5",r.style.color=G?"#e7f3ef":"#172e36",d.background.setHex(G?1056040:15988725)};W(t.dark!==!1);try{C(t.surface)}catch(G){throw U.disconnect(),y.dispose(),h.dispose(),r.remove(),G}let $=()=>{p&&(m=requestAnimationFrame($),y.update(),h.render(d,f))};return $(),{host:r,setSurface:C,setOpacity:P,setTheme:W,fit:M,setProbes(G){x=Array.isArray(G)?G:[],g?.setProbes(x)},dispose(){p=!1,cancelAnimationFrame(m),U.disconnect(),y.dispose(),g?.dispose(),h.domElement.removeEventListener("webglcontextlost",X);for(let[G,T]of[["pointerdown",B],["pointermove",J],["pointerup",Q],["pointercancel",j],["pointerleave",k]])h.domElement.removeEventListener(G,T);h.dispose(),r.remove()}}}var Xx=Object.freeze([[26,64,115],[20,136,156],[107,196,151],[255,225,112]].map(e=>Object.freeze(e))),Yx=Object.freeze({wayricad:Xx,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 Om(e="wayricad"){if(typeof e!="string"||!Object.hasOwn(Yx,e))throw new TypeError("Choose wayricad, viridis, inferno or grayscale palette.");return Yx[e]}function qx(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 hI=1e4,dI=2e5,Dm="Source XYZ translated by the saved bounds center; +Z up; no PCB registration",Kx=e=>Array.isArray(e)&&e.length===3&&e.every(t=>Number.isFinite(t)&&Number.isFinite(Math.fround(t)));function km(e,t){return Object.assign(new Error(e),{code:t,fallback:"2d"})}function Zx(){return new DOMException("Saved result view was aborted.","AbortError")}function Qx(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 pI(e){let[t,r,i]=e,n=r.map((s,o)=>s-t[o]),a=i.map((s,o)=>s-t[o]);return Math.hypot(n[1]*a[2]-n[2]*a[1],n[2]*a[0]-n[0]*a[2],n[0]*a[1]-n[1]*a[0])>0}function Um(e,{contextPrimitives:t=[],coordinateUnit:r="source units",range:i,palette:n="wayricad"}={}){let a=Om(n),s=Nm(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(s.zKnown!==!0)throw km("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>hI)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,h=0,d=0,f=0;if(s.triangles.forEach((g,p)=>{if((s.nodal?g.map(m=>s.values[m]):[s.values[p]]).some(m=>m===null)||!pI(g.map(m=>s.points[m]))){h++;return}u++;for(let m of g)Qx(o,s.points[m])}),!u)throw km("No valid saved triangles with known field values. Missing samples remain holes in the 2D field view.","NO_SAVED_FIELD_VALUES");for(let g of t){let p=g?.points;if(!["line","polygon"].includes(g?.type)||!Array.isArray(p)||p.length<(g.type==="polygon"?3:2)||!p.every(Kx)){f++;continue}if(d+=p.length,d>dI)throw new TypeError("Saved context exceeds 200,000 explicit XYZ points.");let m=p.map(v=>[...v]);l.push({type:g.type,points:m}),m.forEach(v=>Qx(o,v))}f&&c.push(f+" context primitives without supported explicit XYZ geometry were omitted; no elevation was invented."),h&&c.push(h+" triangles with missing values or degenerate geometry remain unrendered.");let y=o.min.map((g,p)=>g/2+o.max[p]/2);if(o.max.some((g,p)=>g-o.min[p]>1e7))throw km("Saved geometry exceeds the bounded 3D coordinate span. Use the 2D field view.","SAVED_GEOMETRY_RANGE");return{surface:s,context:l,bounds:o,origin:y,palette:n,stops:a,range:i?[...i]:qx(s.values),coordinateUnit:r||"source units",coordinateConvention:Dm,renderedTriangles:u,omittedTriangles:h,diagnostics:c}}function Jx(e,t=Xx){let r=e.mesh.material,i=r.clone(),n=r.onBeforeCompile,a=r.customProgramCacheKey(),s=!1,o=i;i.vertexColors=!1,i.onBeforeCompile=(u,h)=>{if(n.call(i,u,h),!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(d=>new ee(...d.map(f=>f/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=()=>a+":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 s||!o?!1:(e.mesh.material=r,o.dispose(),o=null,!0)},dispose(){s||(s=!0,o&&r.dispose())}};return e.mesh.geometry.getAttribute("resultScalar").array.every(Number.isFinite)||c.useFallback(),c}function fI(e,t={}){let r=Um(e,t),i=u=>u.map((h,d)=>h-r.origin[d]),n=Lm(r.surface,i,{palette:r.stops,range:r.range}),a=Jx(n,r.stops),s=new jr,o=[];a.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 h=u.points;for(let d=1;d<h.length;d++)o.push(...i(h[d-1]),...i(h[d]));u.type==="polygon"&&o.push(...i(h.at(-1)),...i(h[0]))}if(o.length){let u=new ar;u.setAttribute("position",new Mt(o,3)),l=new Fi(u,new ri({color:8886951,transparent:!0,opacity:.65})),s.add(l)}s.add(n.group)}catch(u){throw a.dispose(),n.dispose(),l?.geometry.dispose(),l?.material.dispose(),u}return{group:s,overlay:n,prepared:r,contextMesh:l,scalarAppearance:a,dispose(){c||(c=!0,a.dispose(),n.dispose(),l?.geometry.dispose(),l?.material.dispose(),s.clear(),s.removeFromParent())}}}function mI(e){let t=u=>{let h=e?.[u];if(!Kx(h)||h.some(d=>Math.abs(d)>1e12))throw new TypeError("Choose finite bounded source-view camera vectors.");return[...h]},r=t("position"),i=t("target"),n=t("up"),a=r.map((u,h)=>u-i[h]),s=Math.hypot(...a),o=Math.hypot(...n);if(!(s>0)||!(o>0))throw new TypeError("Choose a nondegenerate source-view camera.");let l=a.map(u=>u/s),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 gI(e,t,r={}){if(r.signal?.aborted)throw Zx();let i=e?.ownerDocument;if(!i||typeof e.append!="function")throw new TypeError("Choose a saved result viewer container.");let n,a;try{n=Um(t,r)}catch(G){if(G.fallback!=="2d")throw G;a=G}n&&r.range!==void 0&&(r={...r,range:[...n.range]});let s=i.createElement("div"),o=i.createElement("div"),l=i.createElement("div"),c=i.createElement("div");s.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"),s.append(o,l,c),e.append(s);let u=G=>{s.style.background=G?"#101d28":"#f3f7f5",s.style.color=G?"#e7f3ef":"#172e36"};u(r.dark!==!1);let h=G=>{let T=!1;l.textContent=G.message,o.hidden=!0;let I=()=>{T||(T=!0,r.signal?.removeEventListener("abort",I),s.remove())};r.signal?.addEventListener("abort",I,{once:!0});let V={host:s,unavailable:!0,diagnostic:{code:G.code||"WEBGL_UNAVAILABLE",message:G.message,fallback:"2d"},setSurface(K){return Um(K,r),!1},setTheme:u,setOpacity(){},fit(){return!1},getCameraState(){return null},setCameraState(){return!1},getRenderStats(){return{unavailable:!0,renderCount:0,coordinateConvention:Dm,coordinateUnit:r.coordinateUnit||"source units"}},dispose:I};try{r.onDiagnostics?.([G.message])}catch(K){throw I(),K}return V};if(a)return h(a);let d;try{d=new sd({antialias:!0,alpha:!1})}catch{return h(new Error("3D graphics are unavailable on this device. Use the 2D field view."))}let f=!0,y=null,g=.85,p=0,m=0,v=!1,x=null,b=null,_=null,M=null,C=new us,S=new li(45,1,.001,1e3);S.up.set(0,0,1),d.outputColorSpace=Pr,d.domElement.style.cssText="display:block;width:100%;height:100%;touch-action:none",d.domElement.setAttribute("role","img"),d.domElement.setAttribute("aria-label","3D saved field in source XYZ coordinates"),o.append(d.domElement);let w=[],E=new Xe,P=new ic,N=Hx(),D=(G,T,I)=>{G.addEventListener(T,I),w.push(()=>G.removeEventListener(T,I))},B=()=>o.clientWidth>0&&o.clientHeight>0,J=()=>{f&&(_.setState({documentVisible:!i.hidden,hasSize:B()}),_.invalidate())};d.debug.onShaderError=()=>{v=!0};function Q(){if(f){M.update(),v=!1;try{if(d.render(C,S),v)throw new Error("Saved scalar color shader failed.");p++}catch(G){if(y?.scalarAppearance.useFallback()){m++,y.prepared.diagnostics.push("Scalar color mapping is unavailable; vertex-color interpolation is active. Probe values remain exact."),H(y.prepared),r.onDiagnostics?.([...y.prepared.diagnostics]),v=!1;try{if(d.render(C,S),v)throw G;p++}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 j(){if(!y)return;let G=Math.max(y.sphere.radius,1e-12),T=S.position.distanceTo(y.sphere.center);S.near=Math.max(G*1e-7,(T-G)*.5,1e-15),S.far=Math.max(T+G*4,S.near*2),S.updateProjectionMatrix()}function k(G=!1){if(!f||!y||new Yr().setFromObject(y.group).isEmpty())return!1;let T=y.sphere,I=Math.max(T.radius,1e-12),V=Rx(I,S.fov,S.aspect,1.2);return M.target.copy(T.center),S.position.copy(T.center).add(new ee(...G?[0,-1e-6,1]:[1,-1,1]).normalize().multiplyScalar(V)),j(),M.minDistance=I*1e-4,M.maxDistance=I*100,M.update(),J(),!0}function H(G){l.textContent="Independent saved field \xB7 "+G.coordinateUnit+" \xB7 source XYZ, +Z up \xB7 saved Z"+(G.surface.zBasis?" ("+String(G.surface.zBasis).slice(0,160)+")":"")+" \xB7 no PCB registration"+(G.context.length?" \xB7 retained source context":"")+" \xB7 "+G.renderedTriangles+" colored triangles \xB7 "+G.range.map(T=>Number(T.toPrecision(6))).join(" \u2013 ")+(G.surface.unit?" "+String(G.surface.unit).slice(0,80):"")+(y?.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 U(G,{retainCamera:T=!1}={}){if(!f)return!1;let I=fI(G,r);I.overlay.setOpacity(g),C.add(I.group),I.sphere=new Yr().setFromObject(I.group).getBoundingSphere(new si);let V=y;return y=I,V?.dispose(),H(y.prepared),T?j():k(),r.onDiagnostics?.([...y.prepared.diagnostics]),J(),!0}function X(){if(!f)return;let G=B();if(_.setState({hasSize:G}),!G){J();return}let T=o.clientWidth,I=o.clientHeight,V=Pm(T,I,globalThis.devicePixelRatio,d.capabilities.maxTextureSize);d.getPixelRatio()!==V&&d.setPixelRatio(V),d.setSize(T,I,!1),S.aspect=T/I,S.updateProjectionMatrix(),J()}function W(G){if(!y?.overlay.mesh.visible)return null;let T=d.domElement.getBoundingClientRect();return!T.width||!T.height?null:(E.set((G.clientX-T.left)/T.width*2-1,-(G.clientY-T.top)/T.height*2+1),P.setFromCamera(E,S),y.overlay.sample(P.intersectObject(y.overlay.mesh,!1)[0]))}function $(){if(f){f=!1,_?.dispose(),x?.disconnect(),b?.disconnect();for(let G of w)G();w.length=0,r.signal?.removeEventListener("abort",$),M?.dispose(),y?.dispose(),y=null,C.clear(),d.dispose(),d.domElement.width=d.domElement.height=1,s.remove()}}try{if(M=new sm(S,d.domElement),M.enableDamping=!1,_=Gx({request:G=>requestAnimationFrame(G),cancel:G=>cancelAnimationFrame(G),render:Q,canRender:()=>f&&!i.hidden&&B(),state:{documentVisible:!i.hidden,hasSize:B()}}),D(M,"change",()=>{j(),J()}),D(i,"visibilitychange",()=>{_.setState({documentVisible:!i.hidden}),i.hidden||J()}),D(d.domElement,"pointerdown",G=>N.down(G)),D(d.domElement,"pointermove",G=>{N.move(G),r.onHover&&r.onHover(W(G))}),D(d.domElement,"pointerup",G=>{if(!N.up(G)||G.button!==0&&G.pointerType!=="touch")return;let T=W(G);T&&(c.textContent=T.value.toPrecision(6)+" "+T.unit+" at source XYZ ("+[T.x,T.y,T.z].map(I=>Number(I.toPrecision(7))).join(", ")+") "+y.prepared.coordinateUnit+" \xB7 "+T.method,r.onProbe?.(T))}),D(d.domElement,"pointercancel",G=>N.cancel(G)),D(d.domElement,"pointerleave",()=>r.onHover?.(null)),D(d.domElement,"webglcontextlost",G=>{G.preventDefault(),_.setState({contextAvailable:!1}),l.textContent="3D graphics context interrupted. Saved field geometry is retained."}),D(d.domElement,"webglcontextrestored",()=>{_.setState({contextAvailable:!0}),y&&H(y.prepared),J()}),typeof ResizeObserver=="function"?(x=new ResizeObserver(X),x.observe(o)):i.defaultView&&D(i.defaultView,"resize",X),b=Vx(_,o),r.signal?.addEventListener("abort",$,{once:!0}),C.background=new yt(r.dark!==!1?1056040:15988725),X(),U(n.surface),r.signal?.aborted)throw $(),Zx()}catch(G){throw $(),G}return{host:s,unavailable:!1,setSurface:U,setPalette(G){if(Om(G),!f)return!1;let T=r;r={...r,palette:G};try{return U(y.prepared.surface,{retainCamera:!0})}catch(I){throw r=T,I}},setProbes(G){y?.overlay.setProbes(G),J()},setTheme(G){f&&(u(!!G),C.background.setHex(G?1056040:15988725),J())},setOpacity(G){if(f){if(!Number.isFinite(G)||G<0||G>1)throw new TypeError("Choose result opacity between 0 and 1.");g=G,y.overlay.setOpacity(G),J()}},fit:k,getCameraState(){return{position:S.position.toArray(),target:M.target.toArray(),up:S.up.toArray()}},setCameraState(G){if(!f)return!1;let T=mI(G);S.position.fromArray(T.position),M.target.fromArray(T.target),S.up.fromArray(T.up);let I=S.position.distanceTo(M.target);return M.minDistance=Math.min(M.minDistance,I),M.maxDistance=Math.max(M.maxDistance,I),M.update(),J(),!0},getRenderStats(){let G=y?.prepared;return{unavailable:!1,renderCount:p,renderActivity:{..._.stats(),observesIntersection:!!b},drawCalls:d.info.render.calls,gpuTextures:d.info.memory.textures,renderedTriangles:G?.renderedTriangles||0,omittedTriangles:G?.omittedTriangles||0,contextPrimitives:G?.context.length||0,range:G?[...G.range]:null,palette:G?.palette||"wayricad",colorInterpolation:y?.scalarAppearance.mode||null,scalarColorFallbacks:m,coordinateUnit:G?.coordinateUnit||r.coordinateUnit||"source units",coordinateConvention:Dm,sourceOrigin:G?[...G.origin]:null,sourceBounds:G?{min:[...G.bounds.min],max:[...G.bounds.max]}:null}},dispose:$}}function Ec(e){return Object.assign(new Error(e),{code:"UNSUPPORTED_RESULT_REGISTRATION"})}function yI(e,{bounds:t,thickness:r,layers:i=[]},n={}){let a=Nm(e),s=a.zBasis,o=a.layer??n.layer??null;if(n.layer!==void 0&&a.layer!==void 0&&n.layer!==a.layer)throw Ec("Selected layer does not match the saved result layer.");if(o!==null&&(typeof o!="string"||!i.includes(o)))throw Ec("Saved result layer is not present on this board.");if(s!=null&&!["front-depth","board-center"].includes(s))throw Ec("Saved result elevation basis is unsupported; use the standalone result scene.");if(a.zKnown===!0?!["front-depth","board-center"].includes(s):!["F.Cu","B.Cu"].includes(a.layer))throw Ec("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:Om(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,h=([f,y,g])=>[f-c,u-y,a.zKnown===!0?s==="front-depth"?r/2-g:g:a.layer==="F.Cu"?r/2:-r/2],d=n.range?[...n.range]:l?qx(a.values):null;if(l&&!d)throw Ec("No known saved field values are available for placement.");return{surface:a,transform:h,stops:l,palette:n.palette??null,layer:o,basis:a.zKnown===!0?s:a.layer,flat:a.zKnown!==!0,range:d,throughBoard:n.throughBoard!==!1}}function vI(e,t,r={}){let i=yI(e,t,r),n=Lm(i.surface,i.transform,{...i.range?{range:i.range}:{},...i.stops?{palette:i.stops}:{}}),a=n.sample;n.sample=c=>{let u=a(c);return u?{...u,overlayOwner:r.owner}:null};let s=null,o=!1;try{n.mesh.material.depthTest=!i.throughBoard,n.mesh.renderOrder=i.throughBoard?20:0,i.stops&&(s=Jx(n,i.stops))}catch(c){throw s?.dispose(),n.dispose(),c}let l=[];return s?.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:s,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 s?.useFallback()?(l.push("Scalar color mapping is unavailable; vertex-color interpolation is active. Probe values remain exact."),!0):!1},dispose(){o||(o=!0,s?.dispose(),n.dispose())}}}function xI(e,{scene:t,invalidate:r=()=>{},isActive:i=()=>!0}={}){let n=null,a,s=l=>l?.owner===void 0||l.owner===a,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 s(c)?(n?.dispose(),n=null,a=void 0,r(),o("Overlay cleared.")):o("Overlay belongs to another owner.");let u;try{u=vI(l,e,c)}catch(d){if(d.code==="UNSUPPORTED_RESULT_REGISTRATION")return o(d.message);throw d}t.add(u.overlay.group);let h=n;return n=u,a=c.owner,h?.dispose(),r(),n.state()},setAnalysisProbes(l,c={}){return!n||!s(c)?!1:(n.overlay.setProbes(l),r(),!0)},setAnalysisOpacity(l,c={}){return!n||!s(c)?!1:(n.overlay.setOpacity(l),r(),!0)},useColorFallback(){return n?.useColorFallback()||!1},dispose(){n?.dispose(),n=null,a=void 0}}}var Mn=e=>e&&typeof e=="object"&&!Array.isArray(e)?e.quoted:e,Rd=e=>Array.isArray(e)?String(Mn(e[0])):"",Fm=(e,t)=>e.filter(r=>Rd(r)===t),Ga=(e,t)=>Fm(e,t)[0],Mc=(e,t,r)=>(t[0]-e[0])*(r[1]-e[1])-(t[1]-e[1])*(r[0]-e[0]),Sc=(e,t,r)=>Math.abs(Mc(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 bI(e,t,r,i){let n=Mc(e,t,r),a=Mc(e,t,i),s=Mc(r,i,e),o=Mc(r,i,t);return n*a<0&&s*o<0||Sc(e,t,r)||Sc(e,t,i)||Sc(r,i,e)||Sc(r,i,t)}function $x(e,t){let r=!1;for(let i=0,n=t.length-1;i<t.length;n=i++){let a=t[i],s=t[n];if(Sc(a,s,e))return!1;a[1]>e[1]!=s[1]>e[1]&&e[0]<(s[0]-a[0])*(e[1]-a[1])/(s[1]-a[1])+a[0]&&(r=!r)}return r}function _I(e,t,r=[]){if(!Array.isArray(e)||e.length<3||!Array.isArray(t)||t.length<3||e.some(i=>!i.every(Number.isFinite)||!$x(i,t)||r.some(n=>$x(i,n))))return!1;for(let i of[t,...r])for(let n=0;n<e.length;n++)for(let a=0;a<i.length;a++)if(bI(e[n],e[(n+1)%e.length],i[a],i[(a+1)%i.length]))return!1;return!0}function wI(e,{maxContours:t=1e5}={}){if(!Number.isSafeInteger(t)||t<1)throw TypeError("Invalid zone contour index limit.");let r=new Map;for(let h of e)Rd(h)==="net"&&r.set(Mn(h[1]),String(Mn(h[2])||""));let i=new Map,n=0,a=0,s=0,o=0,l=0,c=0,u=0;for(let h of e){if(Rd(h)!=="zone")continue;let d=Fm(h,"filled_polygon"),f=d.length>0;f||n++;let y=Ga(h,"layers")?.slice(1).map(Mn)??[Mn(Ga(h,"layer")?.[1])],g=Mn(Ga(h,"uuid")?.[1])||Mn(Ga(h,"tstamp")?.[1]),p=Mn(Ga(h,"net")?.[1]),m=String(Mn(Ga(h,"net_name")?.[1])||r.get(p)||(typeof p=="string"?p:""));for(let v of f?d:Fm(h,"polygon")){let x=Ga(v,"pts")||[],b=x[1]instanceof Float64Array?x[1].length/2:0,_=!1;for(let C of x)Rd(C)==="xy"&&((!Number.isFinite(Number(Mn(C[1])))||!Number.isFinite(Number(Mn(C[2]))))&&(_=!0),b++);if(_||b<3){o++;continue}let M=Mn(Ga(v,"layer")?.[1]);for(let C of M?[M]:y){if(typeof C!="string")continue;if(a>=t){l++;continue}let S={id:String(g||"saved-zone-"+a),net:m,layer:C,filled:f,size:b,contour:a,sourcePoints:x};i.has(C)||i.set(C,[]),i.get(C).push(S),a++,s+=b,C.endsWith(".Cu")?c++:u++}}}return{forLayer:h=>i.get(h)||[],stats:()=>({contours:a,copperContours:c,nonCopperContours:u,points:s,unfilled:n,invalid:o,omitted:l,layers:i.size,retainsCoordinateCopies:!1})}}var Pd=e=>e&&["x","y","z"].every(t=>typeof e[t]=="number"&&Number.isFinite(e[t])),jo=e=>({x:e.x,y:e.y,z:e.z,approximate:!!e.approximate});function EI(e,t){if(!Pd(e)||!Pd(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:jo(e),to:jo(t),delta:r,distance:i,approximate:!!(e.approximate||t.approximate)}:null}function Bm(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 MI=class{constructor(){this.pending=null,this.records=[],this.selected=null,this.nextId=1}add(e){if(!Pd(e))return null;if(!this.pending)return this.pending=jo(e),this.selected=null,{pending:this.pending};let t=EI(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?jo(this.pending):null,records:this.records.map(e=>({...e,from:jo(e.from),to:jo(e.to),delta:{...e.delta}})),selected:this.selected?.id??null}}};function SI(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 a=null,s=(o,l,c)=>{let u=Math.hypot(l.x-e.x,l.y-e.y);u<=n&&(!a||u<a.distance)&&(a={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(Pd))continue;let[l,c]=o,u=r(l),h=r(c);if(!u||!h||![u.x,u.y,u.z,h.x,h.y,h.z].every(Number.isFinite)||u.z<-1||u.z>1||h.z<-1||h.z>1)continue;if(i==="corners"){s(l,u,"mesh vertex"),s(c,h,"mesh vertex");continue}let d=h.x-u.x,f=h.y-u.y,y=d*d+f*f;if(y<1e-10)continue;let g=Math.max(0,Math.min(1,((e.x-u.x)*d+(e.y-u.y)*f)/y)),p=Number.isFinite(u.w)&&u.w>0?u.w:1,m=Number.isFinite(h.w)&&h.w>0?h.w:1,v=g*p/((1-g)*m+g*p);s({x:l.x+(c.x-l.x)*v,y:l.y+(c.y-l.y)*v,z:l.z+(c.z-l.z)*v},{x:u.x+d*g,y:u.y+f*g},"mesh edge")}return a}var Id=[{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 TI(e){let t=e===!0?"top":e===!1?"iso":e;return Id.find(r=>r.id===t)||Id.at(-1)}function AI({onChange:e=()=>{}}={}){let t=!1,r=0,i=-1,n=null,a=new Set,s=new WeakSet,o=new Map;function l(m){let v=m.source?.data,x=0,b=_=>{Number.isFinite(_?.width)&&Number.isFinite(_?.height)&&(x+=Math.ceil(_.width*_.height*4*(_.data?.BYTES_PER_ELEMENT||1)*(m.generateMipmaps?4/3:1)))};if(Array.isArray(v))for(let _ of v)b(_);else b(v);return x}function c(){for(let[m,v]of o)if(m.instanceMatrix?.array!==v.matrix||m.instanceColor?.array!==v.color||m.boneMatrices!==v.bones||m.isTexture&&l(m)!==v.textureBytes)return!1;return!0}function u(m){return!m||typeof m!="object"||typeof m.dispose!="function"||(t?h(m):a.has(m)||(a.add(m),r++,e())),m}function h(m){s.has(m)||(s.add(m),m.dispose(),m.isTexture&&m.source?.data?.close?.())}function d(m,v=!1){let x=new Set,b=M=>{M&&typeof M.dispose=="function"&&!a.has(M)&&x.add(M)},_=M=>{if(!(!M||v&&a.has(M))){for(let C in M)Object.hasOwn(M,C)&&M[C]?.isTexture&&b(M[C]);b(M)}};return m?.traverse?.(M=>{if(M.isInstancedMesh&&b(M),b(M.geometry),Array.isArray(M.material))for(let C of M.material)_(C);else _(M.material);M.skeleton&&b(M.skeleton)}),x}function f(m,v=1/0,x=1/0,b=!1){let _=d(m,b),M=b&&!_.size&&i===r&&c()?n:p(_);if(!t&&(M.retainedGeometryBytes>v||M.retainedTextureBytes>x)){for(let C of _)h(C);throw Error("Decoded model geometry or textures exceed this device\u2019s memory budget.")}for(let C of _)u(C);return t||(M!==n&&y(),n=M,i=r),m}function y(){for(let m of a)if(m.isInstancedMesh||m.boneMatrices||m.isTexture){let v=o.get(m);v||(v={},o.set(m,v)),v.matrix=m.instanceMatrix?.array,v.color=m.instanceColor?.array,v.bones=m.boneMatrices,m.isTexture&&(v.textureBytes=l(m))}}function g(){if(!t){t=!0;for(let m of a)h(m);a.clear(),o.clear(),n=null,i=-1}}function p(m){let v=new Set,x=0,b=0,_=0,M=S=>{let w=S?.buffer;w&&!v.has(w)&&(v.add(w),x+=w.byteLength)},C=S=>{if(S.isTexture&&(b++,_+=l(S)),S.isInstancedMesh&&(M(S.instanceMatrix?.array),M(S.instanceColor?.array)),S.boneMatrices&&M(S.boneMatrices),S.isBufferGeometry){let w=E=>M(E?.array||E?.data?.array);for(let E in S.attributes)Object.hasOwn(S.attributes,E)&&w(S.attributes[E]);for(let E in S.morphAttributes)if(Object.hasOwn(S.morphAttributes,E))for(let P of S.morphAttributes[E])w(P);w(S.index)}};for(let S of a)C(S);if(m)for(let S of m)C(S);return{retainedResources:a.size+(m?.size||0),retainedGeometryBytes:x,retainedTextures:b,retainedTextureBytes:_}}return{track:u,retain:f,dispose:g,stats:()=>p(),discard(m){for(let v of d(m))h(v)},retainClone:(m,v,x)=>f(m,v,x,!0)}}function CI({onPick:e,onContextMenu:t,isHeld:r=()=>!1},i=6){let n=Hx(i);return{down:a=>n.down(a),move:a=>n.move(a),cancel:a=>n.cancel(a),up(a,{select:s=!0}={}){let o=n.up(a);return s&&o&&!r()&&(a.button===0?e(a):a.button===2&&t(a)),o},context(a){a.preventDefault?.(),a.button!==2&&!r()&&t(a)}}}var eb=e=>{let t=Math.max(0,Math.min(1,e));return t*t*(3-2*t)};function Xo(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:eb(t/35),layers:eb((t-35)/65)}}function RI({request:e,cancel:t,now:r=()=>performance.now(),update:i,canRun:n=()=>!0,reducedMotion:a=()=>!1,settle:s=()=>{}}){let o=0,l=0,c=null,u=0,h=!1;function d(){!h&&c===null&&o!==l&&n()&&(u=r(),c=e(f))}function f(y){if(c=null,h||!n())return;let g=Math.max(1,Math.min(64,y-u));u=y,o+=(l-o)*(1-Math.exp(-g/85)),Math.abs(l-o)<.04&&(o=l),i(o),!h&&(o!==l?c=e(f):s(o))}return{set(y,{immediate:g=!1}={}){return h||(l=Xo(y).amount,g||a()?(c!==null&&t(c),c=null,o=l,i(o),h||s(o)):d()),l},resume:d,get:()=>o,target:()=>l,running:()=>c!==null,dispose(){h=!0,c!==null&&t(c),c=null}}}function PI(e,t,{maxGap:r=4,componentLift:i=8}={}){let n=[...t.layers||[]].filter(p=>typeof p.name=="string"&&Number.isFinite(p.z)).sort((p,m)=>m.z-p.z).slice(0,64),a=new Map(n.map((p,m)=>[p.name,(n.length-1)/2-m])),s=new WeakMap,o=new WeakMap,l=0,c=p=>{let m=Xo(l).layers;return m===0?0:(a.get(p)||0)*r*m},u=p=>c(p)+(p==="B.Cu"?-1:1)*i*Xo(l).components,h=p=>n.reduce((m,v)=>!m||Math.abs(v.z-p)<Math.abs(m.z-p)?v:m,null)?.name;function d(p,m){s.has(p)||s.set(p,p.position.z),p.position.z=s.get(p)+c(m),p.updateMatrix?.()}function f(p,m){s.has(p)||s.set(p,p.position.z),p.position.z=s.get(p)+u(m),p.updateMatrix?.()}function y(p,m){if(!p?.isInstancedMesh||!m||!(m.zMax>m.zMin))return;o.has(p)||o.set(p,p.instanceMatrix.array.slice());let v=o.get(p),x=c(h(m.zMin)),b=c(h(m.zMax)),_=(m.zMax-m.zMin+b-x)/(m.zMax-m.zMin),M=new e.Matrix4,C=new e.Vector3(1,1,_);for(let S=0;S<p.count;S++)M.fromArray(v,S*16),M.elements[14]+=x,M.scale(C),p.setMatrixAt(S,M);p.instanceMatrix.needsUpdate=!0,p.computeBoundingSphere?.(),p.computeBoundingBox?.()}function g(p){p.traverse(m=>{m.geometry&&(m.userData.explodeSpan?y(m,m.userData.explodeSpan):d(m,m.userData.layer||m.userData.record?.layer))})}return{offset:c,componentOffset:u,component:f,layer:d,barrels:y,overlay:g,set(p){return l=Xo(p).amount,l},get:()=>l,phases:()=>Xo(l),span:()=>r*Xo(l).layers*Math.max(0,n.length-1),layers:n.map(p=>p.name)}}function II(){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 NI(e,{scene:t,objects:r,visible:i=()=>!0,colorForLayer:n=()=>7534079,maxInstances:a=5e4,maxMeshes:s=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,h="",d=0,f=0,y=!1,g={sourceScans:0,recordScans:0,transformSyncs:0};function p(_,M=!1,C=!1,S="accent",w=!1){let E=[_,M,C,S,w].join("|");if(c.has(E))return c.get(E);let P={color:w||_==="through"?12954220:S==="source"?n(_):7534079,transparent:!0,opacity:M?.14:.95,depthTest:!1,depthWrite:!1,toneMapped:!1},N=C?new e.LineBasicMaterial(P):new e.MeshBasicMaterial({...P,side:e.DoubleSide});return c.set(E,N),N}function m(){for(let _ of l.values())o.remove(_.mesh),_.mesh.dispose?.(),_.edge&&(o.remove(_.edge),_.edge.geometry.dispose());l.clear();for(let _ of c.values())_.dispose();c.clear(),d=0,f=0,y=!1,h=""}function v(_,{color:M="accent"}={}){let C=JSON.stringify([[..._].sort(),M]);if(!_.size){l.size&&m();return}C!==h&&(m(),h=C);for(let S of l.values())S.mesh.visible=!1,S.edge&&(S.edge.visible=!1);for(let S of r()){if(g.sourceScans++,S.userData?.record?.type==="Component")continue;let w=S.userData?.identity||"",E=S.userData?.record?.type==="Zone",P=w.startsWith("spike:via-barrel:");if(!S.geometry?.attributes?.position||!E&&!/^spike:(copper-track|copper-pad|via-barrel):/.test(w))continue;let N=E?S.userData.record.layer:decodeURIComponent(w.split(":")[2]||"");if(!i(S,N))continue;let D=l.get(S);if(!D){if(l.size>=s){y=!0;continue}let B=S.userData.records,J=[],Q=Math.max(0,a-d);if(S.isInstancedMesh&&B){for(let H=0;H<Math.min(B.length,S.count);H++)if(g.recordScans++,_.has(B[H].net)){if(J.length>=Q){y=!0;break}J.push(H)}}else _.has(S.userData.record?.net)&&J.push(null);if(!J.length)continue;let j=Math.max(0,a-d);if(J.length>j&&(J.length=j,y=!0),!J.length)continue;let k=S.isInstancedMesh?new e.InstancedMesh(S.geometry,p(N,!1,!1,M,P),J.length):new e.Mesh(S.geometry,p(N,E,!1,M,P));if(k.matrixAutoUpdate=!1,k.renderOrder=201,k.frustumCulled=!1,o.add(k),D={mesh:k,indices:J,edge:null,layer:N},E)if(S.geometry.attributes.position.count*6+f<=2e5){let H=new e.LineSegments(new e.EdgesGeometry(S.geometry,1),p(N,!1,!0,M));f+=H.geometry.attributes.position.count,H.matrixAutoUpdate=!1,H.renderOrder=202,H.frustumCulled=!1,o.add(H),D.edge=H}else y=!0;l.set(S,D),d+=J.length}x(S,D)}}function x(_,M){if(g.transformSyncs++,_.updateWorldMatrix(!0,!1),M.mesh.matrix.copy(_.matrixWorld),M.mesh.matrixWorldNeedsUpdate=!0,M.mesh.visible=!0,_.isInstancedMesh){for(let C=0;C<M.indices.length;C++)_.getMatrixAt(M.indices[C],u),M.mesh.setMatrixAt(C,u);M.mesh.instanceMatrix.needsUpdate=!0}M.edge&&(M.edge.matrix.copy(_.matrixWorld),M.edge.matrixWorldNeedsUpdate=!0,M.edge.visible=!0)}function b(){for(let[_,M]of l)M.mesh.visible=i(_,M.layer),M.edge&&(M.edge.visible=M.mesh.visible),M.mesh.visible&&x(_,M)}return{update:v,syncTransforms:b,clear:m,stats:()=>{let _=0,M=0;for(let C of l.values())C.mesh.visible&&(_++,M+=C.indices.length);return{meshes:_,instances:M,retainedMeshes:l.size,limited:y,throughBoard:!0,...g}},dispose(){m(),t.remove(o)}}}function Tc(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 tb(e,t,r){return["cap","wall"].map(i=>zm(new e.MeshStandardMaterial({...r,...Tc(t,i)}),t,i))}function zm(e,t,r="all"){let i=Tc(t,r);if(!i.polygonOffset)return e;let n=e.onBeforeCompile,a=e.customProgramCacheKey();return e.onBeforeCompile=function(s,o){n?.call(this,s,o),this.polygonOffset=!o?.capabilities?.logarithmicDepthBuffer;let l="#include <logdepthbuf_fragment>";if(!s.fragmentShader.includes(l))throw Error("Unsupported copper depth shader.");s.fragmentShader=s.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=()=>a+"|copper-log-depth-v1:"+t+":"+r,e}var rb=e=>e&&typeof e=="object"&&!Array.isArray(e)?e.quoted:e,Nd=e=>Array.isArray(e)?String(rb(e[0])):"",LI=(e,t)=>Array.isArray(e)?e.find(r=>Nd(r)===t):void 0,Gm=e=>["F.SilkS","B.SilkS"].includes(rb(LI(e,"layer")?.[1]));function OI(e){let t=[e[0]];for(let r of e.slice(1)){let i=Nd(r);if(["version","generator","layers"].includes(i)||Gm(r)&&i.startsWith("gr_"))t.push(r);else if(i==="footprint"){let n=r.filter((a,s)=>s<2||["at","layer","uuid","tstamp"].includes(Nd(a))||Gm(a)&&["fp_line","fp_arc","fp_rect","fp_circle","fp_poly","fp_text","fp_curve","property"].includes(Nd(a)));n.some(a=>Gm(a))&&t.push(n)}}return t}function DI(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),a=i?524288:1048576,s=Math.min(16,n/e,n/t,Math.sqrt(a/e/t)),o=Math.max(1,Math.floor(e*s)),l=Math.max(1,Math.floor(t*s));return{width:o,height:l,scale:Math.min(o/e,l/t),pixels:o*l,maxPixels:a}}function ib(e,t,r,i,n,a){let s=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 h=s({x:c[0],y:c[1]});u?e.lineTo(h.x,h.y):e.moveTo(h.x,h.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=s(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((h,d,f)=>e.fillText(h,0,(d-(f.length-1)/2)*u*(l.lineSpacing||1.5))),e.restore();continue}if(e.beginPath(),l.type==="arc"){let c=a?.(l.start,l.mid,l.end);if(c){let u=s(c);e.arc(u.x,u.y,c.r*o,c.start,c.end,c.ccw)}}else if(l.type==="circle"){let c=s(l);e.arc(c.x,c.y,l.r*o,0,2*Math.PI)}else{for(let[c,u]of(l.points||[]).entries()){let h=s(u);c?e.lineTo(h.x,h.y):e.moveTo(h.x,h.y)}l.type==="polygon"&&e.closePath()}l.fill&&e.fill(),l.stroke!==!1&&e.stroke(),e.restore()}e.restore()}function Vm(e,t,r,i,n,a,s=.2){t.updateMatrixWorld();let o=[];for(let g of[-1,1])for(let p of[-1,1])for(let m of[-1,1])o.push(new e.Vector3(m,p,g).unproject(t));let l=[];for(let g=0;g<8;g++)for(let p of[1,2,4]){let m=g^p;if(m<g)continue;let v=o[g],x=o[m],b=x.z-v.z;if(Math.abs(b)<1e-12)continue;let _=(r-v.z)/b;_>=0&&_<=1&&l.push({x:v.x+(x.x-v.x)*_+n,y:a-v.y-(x.y-v.y)*_})}if(!l.length)return null;let c=Math.max(i.minX,Math.min(...l.map(g=>g.x))),u=Math.min(i.maxX,Math.max(...l.map(g=>g.x))),h=Math.max(i.minY,Math.min(...l.map(g=>g.y))),d=Math.min(i.maxY,Math.max(...l.map(g=>g.y)));if(u-c<1e-6||d-h<1e-6)return null;let f=(u-c)*s,y=(d-h)*s;return{minX:Math.max(i.minX,c-f),maxX:Math.min(i.maxX,u+f),minY:Math.max(i.minY,h-y),maxY:Math.min(i.maxY,d+y)}}function nb(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),a=i?1048576:4194304,s=Math.min(n/e,n/t,Math.sqrt(a/e/t)),o=Math.max(1,Math.floor(e*s)),l=Math.max(1,Math.floor(t*s));return{width:o,height:l,scale:Math.min(o/e,l/t),pixels:o*l,maxPixels:a}}function kI(e,{camera:t,document:r,bounds:i,centerX:n,centerY:a,graphics:s,resources:o,invalidate:l,arcThrough:c,setTimer:u=setTimeout,clearTimer:h=clearTimeout,onError:d=()=>{}}){let f=[],y=!1,g=null,p=null,m=!1,v=0;function x(_){_.crop=null,_.scale=null,_.mesh.material.map=_.base,_.mesh.position.set(0,0,_.z),_.mesh.scale.set(1,1,1)}function b(){if(g=null,!(y||m)){if(r.hidden){p=null;return}for(let _ of f){if(!_.mesh.visible||!_.mesh.parent?.visible||(_.front?t.position.z<=_.z:t.position.z>=_.z))continue;let M=Vm(e,t,_.z,i,n,a);if(!M)continue;let C=M.maxX-M.minX,S=M.maxY-M.minY,w=nb(C,S,s.maxDimension,s.constrained);if(w)try{let E=Math.floor(Math.min(s.constrained?1024:2048,s.maxDimension));_.texture||(_.canvas.width=_.canvas.height=E);let P=_.canvas.getContext("2d");if(!P)continue;P.clearRect(0,0,E,E),ib(P,_.primitives,M,w,_.clips,c),v++,_.texture||(_.texture=o.track(new e.CanvasTexture(_.canvas)),_.texture.colorSpace=e.SRGBColorSpace,_.texture.anisotropy=_.base.anisotropy),_.texture.repeat.set(w.width/E,w.height/E),_.texture.offset.set(0,1-w.height/E),_.texture.needsUpdate=!0,_.mesh.material.map=_.texture,_.crop=M,_.scale=w.scale,_.mesh.scale.set(C/(i.maxX-i.minX),S/(i.maxY-i.minY),1),_.mesh.position.set((M.minX+M.maxX)/2-n,a-(M.minY+M.maxY)/2,_.z)}catch(E){x(_),d(E)}}l()}}return{add(_,M,C,S){f.push({mesh:_,primitives:M,clips:C,front:S,z:_.position.z,base:_.material.map,canvas:r.createElement("canvas"),texture:null})},sync({moving:_=!1}={}){if(y)return;for(let S of f)S.z=S.mesh.position.z;if(_){g!==null&&h(g),g=null;for(let S of f){if(S.crop){let w=Vm(e,t,S.z,i,n,a,0),E=S.crop;(!w||w.minX<E.minX||w.maxX>E.maxX||w.minY<E.minY||w.maxY>E.maxY)&&x(S)}S.mesh.material.map=S.crop?S.texture:S.base}m=!0,p=null;return}m=!1;for(let S of f){let w=S.crop?S.texture:S.base;S.mesh.material.map!==w&&(S.mesh.material.map=w)}t.updateMatrixWorld();let M=[...t.matrixWorld.elements,...t.projectionMatrix.elements,...f.flatMap(S=>[S.mesh.visible&&S.mesh.parent?.visible?1:0,S.z])];if(p&&M.every((S,w)=>Math.abs(S-p[w])<=1e-5*Math.max(1,Math.abs(S),Math.abs(p[w]))))return;p=M;let C=!1;for(let S of f){if(!S.mesh.visible||!S.mesh.parent?.visible||(S.front?t.position.z<=S.z:t.position.z>=S.z))continue;let w=Vm(e,t,S.z,i,n,a,0),E=S.crop;if(!(w&&E&&w.minX>=E.minX&&w.maxX<=E.maxX&&w.minY>=E.minY&&w.maxY<=E.maxY)){x(S),C=!0;continue}let P=nb(w.maxX-w.minX,w.maxY-w.minY,s.maxDimension,s.constrained);P&&P.scale>S.scale*1.5&&(C=!0)}C&&g===null&&(g=u(b,100))},stats:()=>({repaints:v,moving:m,pending:g!==null,detailTextures:f.filter(_=>_.texture).length}),dispose(){if(!y){y=!0,g!==null&&h(g),g=null;for(let _ of f)x(_),_.canvas.width=_.canvas.height=1;f.length=0}}}}var UI=DR(sm),Ld=e=>Number.parseInt(globalThis.KiCadLayerColors.hexFor(e).slice(1),16),FI=`
: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 Hm(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,a){return!r.includes(n)&&!(i==="top"&&a?.startsWith("B."))&&!(i==="bottom"&&a?.startsWith("F."))}}}function Ac(e,t){let r=new Co;return e.forEach((i,n)=>{let[a,s]=t(i);n===0?r.moveTo(a,s):r.lineTo(a,s)}),r}function BI(e,t){let r=e.outlineLoops?.filter(a=>a.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;Ac(i,t).getPoints().forEach((a,s)=>{s===0?n.moveTo(a.x,a.y):n.lineTo(a.x,a.y)});for(let a of r.slice(1))n.holes.push(Ac(a,t));return n}function Cc(e,t,r,i,n,a){if(!i.length)return null;let s=new bh(t,r,i.length),o=new Ar;return i.forEach((l,c)=>{n(o,l),o.updateMatrix(),s.setMatrixAt(c,o.matrix)}),s.instanceMatrix.needsUpdate=!0,s.userData.records=i,s.userData.identity=a,e.add(s),s}function zI(e,t,r={}){r||={};let i=zx(r.appearance??"realistic"),n=r.dark!==!1,a=r.sourceSnapshot?(r.sourceParser||globalThis.KiCadDesignDiff).preparedFile(r.sourceSnapshot,r.sourceKey,t):globalThis.KiCadDesignDiff.parse(t),s=wI(a),o=fP(t,a,{zonePoints:!1}),l=TP(a),c=o.pads.map(R=>({...R,...l.get(R.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 h=document.createElement("div");h.dataset.theme=n?"dark":"light",h.dataset.embedded=r.embedded===!0&&typeof r.onDiagnostics=="function"?"true":"false";let d=h.attachShadow({mode:"open"}),f=document.createElement("style");f.textContent=FI;let y=document.createElement("div");y.className="shell";let g=document.createElement("div");g.className="bar",g.setAttribute("role","toolbar"),g.setAttribute("aria-label","3D tools");let p=document.createElement("div");p.className="stage";let m=document.createElement("div");m.className="canvas";let v=document.createElement("div");v.className="hint",v.textContent="Drag to orbit \xB7 right-drag to pan \xB7 wheel to zoom \xB7 click to inspect";let x=document.createElement("div");x.className="inspector",x.hidden=!0;let b=document.createElement("div");b.className="menu",b.hidden=!0;let _=document.createElement("div");_.className="notice",_.textContent="Material preview \xB7 mask openings follow saved pad layer flags \xB7 footprint stand-ins where linked models are unavailable.";let M=document.createElement("div");M.className="quality-notice",M.hidden=!0,M.setAttribute("role","status"),p.append(M),p.append(m,x,b),y.append(g,p,v,_),d.append(f,y),e.append(h);let C=document.createElement("strong");C.className="title",C.textContent="3D VIEW";let S=document.createElement("span");S.className="detail",S.textContent=`${o.width.toFixed(1)} \xD7 ${o.height.toFixed(1)} mm \xB7 ${o.components.length} parts \xB7 ${o.tracks.length} tracks`;let w=document.createElement("span");w.className="spacer";function E(R,q,he,Fe=R){let ze=document.createElement("button");if(ze.type="button",ze.title=Fe,ze.setAttribute("aria-label",Fe),he){let vt=document.createElementNS("http://www.w3.org/2000/svg","svg"),At=document.createElementNS("http://www.w3.org/2000/svg","path");vt.setAttribute("viewBox","0 0 24 24"),vt.setAttribute("fill","none"),vt.setAttribute("stroke","currentColor"),vt.setAttribute("stroke-width","1.6"),vt.setAttribute("stroke-linecap","round"),vt.setAttribute("stroke-linejoin","round"),vt.setAttribute("aria-hidden","true"),At.setAttribute("d",he),vt.append(At),ze.append(vt)}let Ve=document.createElement("span");return Ve.textContent=R,ze.append(Ve),ze.addEventListener("click",()=>{q(),Ie()}),g.append(ze),ze}let P=document.createElement("section");P.className="visibility-options",P.id="display-options",P.hidden=!0,P.setAttribute("aria-label","3D display settings"),p.append(P);let N=document.createElement("div");N.className="display-heading",N.append(document.createTextNode("Display"));let D=document.createElement("button");D.type="button",D.textContent="\xD7",D.title="Close display settings",D.setAttribute("aria-label","Close display settings"),D.onclick=()=>H(!1,!0),N.append(D);let B=document.createElement("fieldset"),J=document.createElement("legend");J.textContent="Rendering",B.append(J);let Q=document.createElement("fieldset"),j=document.createElement("legend");j.textContent="Visible geometry",Q.append(j),P.append(N,B,Q);function k(){if(y.clientHeight&&h.style.setProperty("--tools-panel-height",Math.max(72,Math.min(280,y.clientHeight-50))+"px"),h.dataset.embedded!=="true")return;let R=p.getBoundingClientRect(),q=g.getBoundingClientRect(),he=Math.min(Math.max(8,Math.ceil(q.bottom-R.top+6)),Math.max(8,R.height-180));h.style.setProperty("--tools-bottom",he+"px")}function H(R,q=!1){R&&(k(),typeof Gs<"u"&&(Gs.open=!1)),P.hidden=!R,$o.setAttribute("aria-expanded",String(R)),q&&$o.focus()}function U(R,q,he){let Fe=document.createElement("label"),ze=document.createElement("input");return ze.type="checkbox",ze.checked=q,ze.addEventListener("change",()=>{he(ze.checked),Ie()}),Fe.append(ze,document.createTextNode(R)),Q.append(Fe),ze}g.append(C,S,w);let X="pocket-kivi:3d-quality:v1",W="balanced",$=!1;try{let R=localStorage.getItem(X);["low","balanced","high"].includes(R)&&(W=R,$=!0)}catch{}r.quality&&(W=Im(r.quality));let G=document.createElement("label");G.className="quality-label";let T=document.createElement("span");T.textContent="Quality";let I=document.createElement("select");I.setAttribute("aria-label","3D rendering quality"),I.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[R,q]of[["low","Low"],["balanced","Balanced"],["high","High"],["photoreal-fast","Photoreal Fast"],["presentation","Presentation"]]){let he=document.createElement("option");he.value=R,he.textContent=q,I.append(he)}I.value=W,G.append(T,I);let V=(o.bounds.minX+o.bounds.maxX)/2,K=(o.bounds.minY+o.bounds.maxY)/2,ie=([R,q])=>[R-V,K-q],le=([R,q])=>[R,-q],ae=Nt(),de=(R,q)=>ae.get(JSON.stringify([R.outline,R.drill||null,q]),()=>new Wh(z(R),{depth:q,bevelEnabled:!1,curveSegments:8})),z=R=>{let q=new fa;return Ac(R.outline,le).getPoints().forEach((he,Fe)=>Fe?q.lineTo(he.x,he.y):q.moveTo(he.x,he.y)),R.drill&&q.holes.push(Ac(R.drill,le)),q},me=Math.max(1,o.width),we=Math.max(1,o.height),He=Math.max(me,we),ne=o.stackup?.filter(R=>Number.isFinite(R.thickness)).reduce((R,q)=>R+q.thickness,0)||1.6,_e=ne/2,oe=-_e,ce=new us;ce.background=new yt(n?1382432:15199217);let L=null,A=AI({onChange:()=>L?.invalidate()}),O=new li(45,1,.1,Math.max(3e3,He*30));O.up.set(0,0,1);let F=new sd({antialias:!1,logarithmicDepthBuffer:!0,alpha:!1,powerPreference:"high-performance"}),Y=F.getContext(),re=tI({maxTextureSize:F.capabilities.maxTextureSize,maxRenderbufferSize:Y.getParameter(Y.MAX_RENDERBUFFER_SIZE),deviceMemory:globalThis.navigator?.deviceMemory,hardwareConcurrency:globalThis.navigator?.hardwareConcurrency,floatTargets:F.extensions.has("EXT_color_buffer_float"),android:/Android/i.test(globalThis.navigator?.userAgent||"")});L=XP(Y);let ue=(re.constrained?32:re.premium?96:64)*1024*1024,se=(re.constrained?32:64)*1024*1024,pe={budgetBytes:se,retainedBytes:0,renderedContours:0,vertices:0,rejected:0},Pe=(re.constrained?16:re.premium?64:32)*1024*1024,Ce=rt(re.constrained?8192:32768),je=De(re.constrained,o.components.length);!$&&!r.quality&&(W=re.defaultQuality);let st=!0,Pt=!1,ut=0,ot=null,tt=W,Ht=!1;function fe(){ce.background.setHex(h.dataset.theme==="dark"?1513237:16250350)}let qe=()=>m.clientWidth>0&&m.clientHeight>0,Ue=Gx({request:R=>requestAnimationFrame(R),cancel:R=>cancelAnimationFrame(R),render:lN,canRender:()=>st&&!Pt&&!document.hidden&&qe(),state:{documentVisible:!document.hidden,hasSize:qe()}});function Ie(){st&&(Ue.setState({documentVisible:!document.hidden,hasSize:qe()}),Ue.invalidate())}function mt(R,q=!1){M.replaceChildren(document.createTextNode(R)),M.hidden=!1;let he=document.createElement("button");if(he.type="button",he.textContent="Dismiss",he.onclick=()=>{M.hidden=!0},M.append(he),q){let Fe=document.createElement("button");Fe.type="button",Fe.textContent="Retry graphics",Fe.onclick=()=>F.forceContextRestore(),M.append(Fe)}}function lt(){if(ot){for(let R of ot.passes)R.dispose?.(),R instanceof ym&&(R.gtaoMaterial.dispose(),R.blendMaterial.dispose(),R.depthTexture?.dispose());ot.composer.dispose(),ot=null}}function Ut(){if(lt(),L.invalidate(),tt==="low")return;let R=["high","presentation"].includes(tt)&&dr!=="translucent"&&Tt.get()===0,q=F.extensions.has("EXT_color_buffer_float");if(R&&!q)throw Error("Floating-point render targets are unavailable.");let he=new Pi(1,1,{type:q?yn:gn,depthBuffer:!0,stencilBuffer:!1}),Fe=new q2(F,he),ze=[];ot={composer:Fe,passes:ze,occlusion:R};let Ve=new K2(ce,O);if(ze.push(Ve),R){let Bt=new ym(ce,O,1,1,void 0,rI(ne,tt));oI(Bt.normalMaterial),Bt.blendIntensity=.65,Bt.updatePdMaterial({radius:4,rings:2,samples:tt==="presentation"?24:12});let qt=Bt.overrideVisibility.bind(Bt);Bt.overrideVisibility=()=>{qt(),ce.traverse(ct=>{(Array.isArray(ct.material)?ct.material:[ct.material]).some(pr=>pr&&(pr.transparent||pr.depthTest===!1))&&(ct.visible=!1)})},ze.push(Bt)}let vt=new tP,At=new rP(1,1);for(let Bt of[At.areaTexture,At.searchTexture])Bt.image?.addEventListener?.("load",()=>{L.invalidate(),Ie()},{once:!0});ze.push(vt,At);for(let Bt of ze)Fe.addPass(Bt)}function xt(R){lt(),tt="balanced",I.value=tt,h.dataset.quality=tt,Ht=!1,F.setRenderTarget(null),Bn.apply(!1),fe(),mt(R),Ha()}function Dt(R,q=!0){if(tt=Im(R),I.value=tt,h.dataset.quality=tt,M.hidden=!0,Ht=!1,fe(),q)try{localStorage.setItem(X,tt==="presentation"?"high":tt==="photoreal-fast"?"balanced":tt)}catch{}Bn.apply(["presentation","photoreal-fast"].includes(tt)&&dr!=="translucent",{fast:tt==="photoreal-fast"}),F.shadowMap.enabled=tt!=="low"&&dr!=="translucent"&&Tt.get()===0,F.shadowMap.needsUpdate=!0;try{Ut()}catch{xt("Enhanced quality is unavailable on this graphics device. Balanced rendering is active.")}return Jo(),Ha(),Ie(),tt}I.onchange=()=>Dt(I.value),F.debug.onShaderError=()=>{Ht=!0},F.outputColorSpace=Pr,F.toneMapping=lu,F.toneMappingExposure=1,F.shadowMap.enabled=!0,F.shadowMap.type=nt,F.shadowMap.autoUpdate=!1,F.shadowMap.needsUpdate=!0;function gt(){if(!F.extensions.has("EXT_color_buffer_float"))return null;let R,q;try{return R=new G2,q=new td(F),q.fromScene(R,.04,.1,100)}catch{return mt("Studio reflections are unavailable on this graphics device. Direct lighting remains active."),null}finally{R?.dispose(),q?.dispose()}}let Vt=gt();ce.environment=Vt?.texture||null,ce.environmentIntensity=.65,m.append(F.domElement);let $e=new UI(O,F.domElement),Tr=!1,ni=!1,$r=null,qn=null,Yo=()=>{Tr=!0,ni=!0,$r!==null&&clearTimeout($r),$r=null},Va=()=>{$r!==null&&clearTimeout($r),$r=setTimeout(()=>{$r=null,ni=!1,Ie()},100)};$e.addEventListener("start",Yo),$e.addEventListener("end",Va),$e.addEventListener("change",Ie),$e.enableDamping=!1,$e.dampingFactor=.1,$e.screenSpacePanning=!0,$e.minDistance=.1,$e.maxDistance=He*8,ce.add(new kf(16777215,.35));for(let R of sI){let q=new Xh(R.color,R.intensity);Math.abs(R.z)===1&&(q.castShadow=!0,q.shadow.mapSize.set(1024,1024),q.shadow.camera.left=q.shadow.camera.bottom=-He,q.shadow.camera.right=q.shadow.camera.top=He,q.shadow.camera.near=.1,q.shadow.camera.far=He*5,q.shadow.normalBias=.02,q.shadow.bias=-1e-4),q.position.set(He*R.x,He*R.y,He*R.z),ce.add(q)}let Bn=eI(Le,{scene:ce,renderer:F,extent:He,bottom:oe,constrained:re.constrained}),Ei=new jr;ce.add(Ei);let Sn=new Map,ai=[],Bi=Hm(),Fs=[],ba=(R,q,he)=>(Fs.push({mesh:R,type:q,layer:he}),R.visible=Bi.visible(q,he),R),Od=new Set(a.filter(R=>Array.isArray(R)&&R[0]==="arc").map(R=>{let q=R.find(he=>Array.isArray(he)&&["uuid","tstamp"].includes(he[0]))?.[1];return typeof q=="object"?q?.quoted:q}).filter(Boolean)),Wm=R=>Od.has(R.id)||Od.has(R.id?.replace(/:\d+$/,""))||/^track-\d+:\d+$/.test(R.id||""),te=WP(o,ne).map(R=>R.name),Te=bP({...o,layers:te},a,ne),ke=Te.layers.map(R=>{let q=!["F.Cu","B.Cu"].includes(R.name);return{...R,internal:q,basis:q?Te.savedDepths?"saved-stackup":"illustrative":"outer-surface"}}),Ge=new Set,Se=new Map(ke.map(R=>[R.name,!0])),pt=o.vias.filter(R=>Te.viaSpans.get(R.id)?.through);pt.length<Te.viaSpans.size&&u.push("Blind and buried via walls follow saved endpoint layers. Partial-depth dielectric cavities are not cut.");let Wt=DP(o.tracks,a),jt;try{jt=LP(ne,Te.byLayer)}catch{jt={bottom:oe,depth:ne},u.push("Outer copper depths do not enclose a valid substrate. The nominal board envelope is shown.")}u.push(...Te.warnings,...Wt.warnings);function tr(R){let q=Te.byLayer.get(R);return R==="F.Cu"||R==="B.Cu"?IP(R,ne,q.thickness,q.z):{center:q.z,base:q.z-q.thickness/2,thickness:q.thickness}}let $t=null;function ur(R){return $t?R.name===$t:Se.get(R.name)&&(!R.internal||dr==="translucent"||Tt.get()>0)}let Tt=PI(Le,{layers:ke},{maxGap:Math.max(.8,Math.min(8,He*.45/Math.max(1,ke.length-1))),componentLift:Math.max(6,Math.min(40,He*.15))}),Cr=[],Fr=II(),zr=HP(),Ir=[],dr="realistic",ir=!1,Mi=!1,zn=!1,ji=!1,Kn=document.createElement("label");Kn.append(document.createTextNode("Appearance"));let yi=document.createElement("select");yi.setAttribute("aria-label","3D board appearance");for(let[R,q]of[["realistic","Realistic"],["layers","Layer colors"],["translucent","Translucent"]]){let he=document.createElement("option");he.value=R,he.textContent=q,yi.append(he)}Kn.append(yi);let _a=document.createElement("p");_a.className="quality-help",_a.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.",B.append(Kn,G,_a);function Dr(R=dr){let q=zx(R),he=dr;ir&&Jn.restore(),zr.setEnabled(!1),dr=q,yi.value=q,h.dataset.appearance=q,($t||q==="translucent"||Tt.get()>0)&&Fd();let Fe=!$t&&q==="realistic"&&Tt.get()===0;for(let{mesh:ze,role:Ve,layer:vt,pads:At}of Ir){let Bt=Array.isArray(ze.material)?ze.material:[ze.material];if(Ve==="pads"){for(let ct of Bt)ct.color.setHex(16777215);let qt=new yt;At.forEach((ct,pr)=>ze.setColorAt(pr,qt.setHex(Fe?iI(ct,vt)?wc.exposedCopper:wc.coatedCopper:Ld(vt)))),ze.instanceColor&&(ze.instanceColor.needsUpdate=!0)}else for(let qt of Bt)qt.color.setHex(Fe?wc.coatedCopper:Ld(vt));for(let qt of Bt)qt.metalness=Fe&&Ve!=="pads"?.08:Yn.copper.metalness,qt.roughness=Fe&&Ve!=="pads"?.52:Yn.copper.roughness}for(let ze of ke){let Ve=Sn.get(ze.name);Ve&&(Ve.visible=ur(ze))}if(zr.setEnabled(q==="translucent"),Bn.apply(["presentation","photoreal-fast"].includes(tt)&&q!=="translucent",{fast:tt==="photoreal-fast"}),F.shadowMap.enabled=tt!=="low"&&q!=="translucent"&&Tt.get()===0,F.shadowMap.needsUpdate=!0,he==="translucent"!=(q==="translucent"))try{Ut()}catch{xt("Enhanced quality is unavailable. Balanced rendering is active.")}return Rc(),ir&&An(Ii),r.onAppearanceChange?.(q),Ie(),q}yi.onchange=()=>Dr(yi.value);let Si=R=>{if(!Sn.has(R)){let q=new jr;q.name=R,Ei.add(q),Sn.set(R,q)}return Sn.get(R)},zi=BI(o,ie),vi=new Set,Qi=0,qo=0,Tn=0,GI=(R,q)=>{let he=!1;for(let Fe=0,ze=q.length-1;Fe<q.length;ze=Fe++){let[Ve,vt]=[q[Fe],q[ze]];Ve[1]>R[1]!=vt[1]>R[1]&&R[0]<(vt[0]-Ve[0])*(R[1]-Ve[1])/(vt[1]-Ve[1])+Ve[0]&&(he=!he)}return he},ab=o.outlineLoops?.[0],sb=o.outlineLoops?.slice(1)||[];for(let R of[...c,...pt.map(q=>({...q,shape:"circle",width:q.size,height:q.size,drillShape:"circle",rotation:0}))]){if(!(R.drill>0))continue;let q=Tm(R);if(!q){Tn++;continue}let he=(R.rotation||0)*Math.PI/180,Fe=Math.cos(he),ze=Math.sin(he),[Ve,vt]=ie(R.at);if(sb.some(qt=>GI(R.at,qt)))continue;let At=q.map(([qt,ct])=>[Ve+qt*Fe+ct*ze,vt+qt*ze-ct*Fe]),Bt=JSON.stringify(At.map(qt=>qt.map(ct=>Math.round(ct*1e4)/1e4)));if(!vi.has(Bt)){if(Qi>=1024||qo+At.length>1e5||!ab||!_I(At.map(([qt,ct])=>[qt+V,K-ct]),ab,sb)){Tn++;continue}vi.add(Bt),Qi++,qo+=At.length,zi.holes.push(Ac(At,qt=>qt))}}Tn&&u.push(`${Tn} drill loops could not be cut within the saved-geometry/triangulation budget.`);let Ci=new hr(new Wh(zi,{depth:jt.depth,bevelEnabled:!1,curveSegments:8}),[new on(Yn.solderMask),new Ki(Yn.substrateEdge)]);Ci.position.z=jt.bottom,Ci.receiveShadow=!0,Bn.addCaster(Ci),Ci.userData.record={type:"Board",name:"Substrate",layer:"Edge.Cuts",id:"board"},Ci.userData.identity=Wo("substrate","Edge.Cuts","board"),Ei.add(Ci),ai.push(Ci),zr.add(Ci,"substrate");let Dd=new Fi(new Ql(Ci.geometry,20),new ri({color:10205100,transparent:!0,opacity:.42}));Dd.position.z=jt.bottom,Ei.add(Dd);let Ko=new jr;Ei.add(Ko);function Rc(){let R=Math.min(1-Tt.phases().layers*.98,$t?.08:1),q=(dr==="translucent"?.12:1)*R,he=ir&&Ws.mode==="isolate"&&Cd(Ii)&&!Mi;for(let Fe of Array.isArray(Ci.material)?Ci.material:[Ci.material]){let ze=he?0:Math.min(q,Fe.userData.selectionOpacityCap??1),Ve=ze<1;Fe.transparent!==Ve&&(Fe.transparent=Ve,Fe.needsUpdate=!0),Fe.opacity=ze,Fe.depthWrite=!Ve}Dd.material.opacity=Math.min(.42*R,Dd.material.userData.selectionOpacityCap??1),Ci.castShadow=!$t&&Tt.get()===0&&Bn.enabled}let kd=kI(Le,{camera:O,document,bounds:o.bounds,centerX:V,centerY:K,graphics:re,resources:A,invalidate:Ie,arcThrough:globalThis.KiCadOwnedCanvas?.arcThrough,onError:R=>mt("Silkscreen detail could not be refreshed: "+R.message)});if(globalThis.KiCadPCBRenderer&&globalThis.KiCadOwnedCanvas?.arcThrough)try{let R=globalThis.KiCadPCBRenderer.build(OI(a),r.boardPath||"").primitives.filter(ze=>!ze.frame&&!ze.hidden&&["F.SilkS","B.SilkS"].includes(ze.layer)),q=DI(me,we,re.maxDimension,re.constrained),he=zi.extractPoints(8),Fe=[he.shape,...he.holes].map(ze=>ze.map(Ve=>[Ve.x+V,K-Ve.y]));for(let ze of["F.SilkS","B.SilkS"]){let Ve=R.filter(ct=>ct.layer===ze);if(!Ve.length||!q)continue;let vt=document.createElement("canvas");vt.width=q.width,vt.height=q.height;let At=vt.getContext("2d");if(!At)continue;ib(At,Ve,o.bounds,q,Fe,globalThis.KiCadOwnedCanvas.arcThrough);let Bt=A.track(new Lh(vt));Bt.colorSpace=Pr,Bt.anisotropy=Math.min(16,F.capabilities.getMaxAnisotropy());let qt=new hr(new Io(me,we),new Ki({map:Bt,color:16777215,roughness:.85,metalness:0,side:ze==="F.SilkS"?it:_t,transparent:!0,alphaTest:.05,depthWrite:!1}));qt.position.z=ze==="F.SilkS"?_e+.055:oe-.055,qt.renderOrder=1,Ko.add(qt),zr.add(qt,"silkscreen"),ba(qt,"silkscreen",ze),kd.add(qt,Ve,Fe,ze==="F.SilkS")}}catch(R){u.push("Saved silkscreen could not be prepared: "+R.message)}let Bs=new Map,Ud=0;for(let R of o.vias){let q=Te.viaSpans.get(R.id),he=kx({shape:"circle",width:R.size,height:R.size,drill:R.drill,drillShape:"circle"});if(!he||!q){Ud++;continue}let Fe=JSON.stringify([R.size,R.drill,q.zMin,q.zMax]);if(!Bs.has(Fe)){if(Bs.size>=128){Ud++;continue}Bs.set(Fe,{outline:he,span:q,vias:[]})}Bs.get(Fe).vias.push(R)}Ud&&u.push(`${Ud} via bodies with unsupported annuli or unknown saved spans omitted.`);let jm=new jr;Ei.add(jm);for(let[R,q]of Bs){let he=PP(Le,Tm({drill:q.vias[0].drill,drillShape:"circle"}),q.span.zMax-q.span.zMin),Fe=new Ki({color:wc.exposedCopper,...Yn.copper,side:Rt,...Tc("via","wall")}),ze=Cc(jm,he,Fe,q.vias,(Ve,vt)=>{let[At,Bt]=ie(vt.at);Ve.position.set(At,Bt,q.span.zMin)},Wo("via-barrel",q.span.through?"through":q.span.from+"-"+q.span.to,R));ze&&(ba(ze,"vias",q.span.through?"through":q.span.from+"-"+q.span.to),ai.push(ze),Cr.push({mesh:ze,span:q.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 VI=Bs.size?tb(Le,"via",{color:wc.exposedCopper,...Yn.copper}):null;function ob(R){if(Ge.has(R))return;Ge.add(R);let q=Ld(R),he=tr(R),Fe=he.center;for(let ct of["tracks","arcs"]){let pr=Wt.tracks.filter(Rr=>Rr.layer===R&&(Wm(Rr)?"arcs":"tracks")===ct),Yt=AP(Le,pr,{world:ie,z:Fe,thickness:he.thickness});Yt.invalid&&u.push(`${R}: invalid saved track widths or positions omitted.`),Yt.plan?.limited&&u.push(`${R}: large track caps exceed the ${Yt.plan.tolerance} mm tessellation tolerance at the 128-segment display limit.`);let nr=zm(new Ki({color:q,...Yn.copper,...Tc("track")}),"track");for(let Rr of Yt.batches){let wr=Cc(Si(R),Rr.geometry,nr,Rr.records,Rr.place,Wo("copper-track",R,ct+"-"+Rr.part));wr&&(ba(wr,ct,R),ai.push(wr),Ir.push({mesh:wr,role:"tracks",layer:R}))}Yt.batches.length||nr.dispose()}let ze=c.filter(ct=>!MP(ct)&&(ct.layer===R||ct.layers?.includes(R)||ct.layers?.includes("*.Cu"))),Ve=new Map,vt=0;for(let ct of ze){let pr=JSON.stringify([ct.shape,ct.width,ct.height,ct.roundrectRatio,ct.drill,ct.drillShape,ct.drillWidth,ct.drillHeight,ct.drillOffset,ct.customAnchor,ct.customPrimitives]);if(!Ve.has(pr)){let Yt=kx(ct);if(!Yt||Ve.size>=256){vt++;continue}Yt.tessellation.limited&&u.push(`${R}: a pad contour retains validated geometry because the 0.0025 mm tolerance could not be met within hole-containment/display limits.`),Ve.set(pr,{outline:Yt,pads:[]})}Ve.get(pr).pads.push(ct)}vt&&u.push(`${R}: ${vt} unsupported/ambiguous pad shapes omitted; no rectangular stand-ins were substituted.`);let At=Ve.size?tb(Le,"pad",{color:16777215,...Yn.copper}):null;for(let[ct,pr]of Ve){let Yt=de(pr.outline,he.thickness),nr=Cc(Si(R),Yt,At,pr.pads,(Rr,wr)=>{let[Gr,Lr]=ie(wr.at);Rr.position.set(Gr,Lr,he.base),Rr.rotation.z=(wr.rotation||0)*Math.PI/180},Wo("copper-pad",R,ct));nr&&(ba(nr,"pads",R),ai.push(nr),Ir.push({mesh:nr,role:"pads",layer:R,pads:pr.pads}))}let Bt=zm(new Ki({color:q,...Yn.copper,side:Rt,...Tc("zone")}),"zone"),qt=!1;for(let ct of s.forLayer(R)){let pr;try{let nr=_R(Le,ct,{world:ie,triangulate:iR.triangulate,maxBytes:se-pe.retainedBytes});pr=nr.geometry,pe.retainedBytes+=nr.bytes,pe.renderedContours++,pe.vertices+=nr.vertices}catch(nr){pe.rejected++,u.push(`${R}: saved zone ${ct.id} contour ${ct.contour}: ${nr.message}`);continue}if(!ct.filled){let nr=new Ch(pr,new ri({color:q,transparent:!0,opacity:.6}));nr.position.z=Fe,Si(R).add(nr),ba(nr,"polygons",R);continue}qt=!0;let Yt=new hr(pr,Bt);Yt.position.z=["F.Cu","B.Cu"].includes(R)?NP(R,he):Fe,Yt.userData.record={id:ct.id,net:ct.net,layer:R,filled:!0,contour:ct.contour,type:"Zone"},Si(R).add(Yt),ba(Yt,"fills",R),ai.push(Yt),Ir.push({mesh:Yt,role:"zone",layer:R}),zr.add(Yt,"zone")}qt||Bt.dispose();for(let[ct,pr]of Bs){if(pr.span.from!==R&&pr.span.to!==R)continue;let Yt=de(pr.outline,he.thickness),nr=Cc(Si(R),Yt,VI,pr.vias,(Rr,wr)=>{let[Gr,Lr]=ie(wr.at);Rr.position.set(Gr,Lr,he.base)},Wo("via-barrel",R,"annulus-"+ct));nr&&(ba(nr,"vias",R),ai.push(nr))}}for(let R of ke.filter(q=>!q.internal))ob(R.name);function Fd(){let R=ke.filter(he=>he.internal&&!Ge.has(he.name));if(!R.length)return;let q=u.length;for(let he of R)ob(he.name),A.retain(Sn.get(he.name));un.push(...u.slice(q)),R.some(he=>he.basis==="illustrative")&&un.push("Internal copper has saved XY coordinates and layer order; elevations are illustrative because a complete saved stackup is unavailable."),Lc()}let Zo=new jr;Ei.add(Zo);let HI=UP(o),qr=Cc(Zo,new V2(1,1,1,2,.06),new Ki(Yn.proxy),o.components,(R,q)=>{let he=HI.get(q),[Fe,ze]=ie(he?.at||q.at),Ve=q.layer?.startsWith("B.");R.position.set(Fe,ze,Ve?oe-1.1:_e+1.1),R.rotation.set(0,0,he?.rotation||0),R.scale.set(he?.width||0,he?.height||0,he?2.1:0)},Wo("component","F.Fab","proxies"));qr&&(ai.push(qr),zr.add(qr,"component")),qr&&(qr.castShadow=!0,qr.receiveShadow=!0);let lb=Fx(o.components),Bd=o.components.map((R,q)=>{let he=new Jt;return qr?.getMatrixAt(q,he),he}),WI=new Jt().makeScale(0,0,0),wa=new Map,Pc=new Set,Ic=null,Qo=o.components.map(()=>!0);function zd(){let R=new Jt;o.components.forEach((q,he)=>{R.copy(Bd[he]),R.elements[14]+=Tt.componentOffset(q.layer?.startsWith("B.")?"B.Cu":"F.Cu"),qr?.setMatrixAt(he,Qo[he]&&Bi.visible("bodies",q.layer)&&!Pc.has(he)?R:WI)}),qr&&(qr.instanceMatrix.needsUpdate=!0,qr.computeBoundingSphere());for(let[q,he]of wa)he.visible=Qo[q]&&Bi.visible("bodies",o.components[q].layer),Tt.component(he,o.components[q].layer?.startsWith("B.")?"B.Cu":"F.Cu");F.shadowMap.needsUpdate=!0,Ie()}let un=Array.isArray(r.assetWarnings)?r.assetWarnings.filter(R=>typeof R=="string").slice(0,48).map(R=>R.slice(0,500)):[];s.stats().unfilled&&un.push(`${s.stats().unfilled} zones have no saved copper fill; only their boundaries are shown.`),(s.stats().omitted||s.stats().invalid)&&un.push("Saved zone index: "+s.stats().omitted+" contours exceed the descriptor budget; "+s.stats().invalid+" invalid contours were rejected."),un.push(...u),Lc();let cb=0,Nc=jP(()=>{if(!st)return;L.invalidate();let R=performance.now();try{zd(),Km(),An(Ii),Lc()}finally{cb+=performance.now()-R}},Ie);function Lc(){let R=Pc.size,q=un.length;_.replaceChildren(document.createTextNode(`Material preview \xB7 linked models ${R}/${o.components.length}`));let he=document.createElement("details"),Fe=document.createElement("summary"),ze=document.createElement("ul");Fe.textContent=q?`${q} rendering notes`:"Rendering details";let Ve=["Mask openings follow saved pad layer flags; this is not a reconstructed solder-mask solid.",o.components.length-R+" footprints have no linked model; bounded stand-ins are used only where usable saved footprint bounds exist.",...un];for(let vt of Ve){let At=document.createElement("li");At.textContent=vt,ze.append(At)}he.append(Fe,ze),_.append(he),r.onDiagnostics?.(["Linked component models: "+R+"/"+o.components.length,...Ve]),_.title=un.join(`
`)}function Xm(R,q){try{return Ce.checkTemplate(R,2+(wa.has(q)?0:1)),A.retain(R,ue,Pe)}catch(he){throw A.discard(R),he}}async function jI(R,q,he,Fe){let ze=q?.base64,Ve=R.embeddedAsset?await globalThis.KiCadEmbeddedModels.decode(q,iP.default.decompress):globalThis.KiCadEmbeddedModels.decodeBase64(ze);if(Ve.byteLength>8388608)throw new Error("model asset exceeds 8 MiB");if(he(Ve.byteLength),["step","stp"].includes(R.format)){Ic||=new globalThis.KiCadStepDecoder.Client(new URL("step-worker.js",location.href).href);let At=await Ic.decode(Ve),Bt=new jr;for(let qt of At){let ct=new ar;ct.setAttribute("position",new Mr(qt.positions,3)),ct.setIndex(new Mr(qt.index,1)),qt.normals?ct.setAttribute("normal",new Mr(qt.normals,3)):ct.computeVertexNormals();let pr=qt.groups.map((nr,Rr)=>(ct.addGroup(nr.start,nr.count,Rr),new Ki({color:new yt(...nr.color),roughness:.65,metalness:.1}))),Yt=pr.length===1?pr[0]:pr;Bt.add(new hr(ct,Yt))}return Xm(Bt,Fe)}if(R.format==="glb"){try{Be(Ve,Ce.limit,{maxAccessorBytes:ue,maxTextureBytes:Pe,maxTextureDimension:re.maxDimension})}catch(At){throw["MODEL_GRAPH_BUDGET","MODEL_ALLOCATION_BUDGET"].includes(At.code)&&Ce.rejectPreflight(),At}return Xm((await new UR().parseAsync(Ve.buffer,"")).scene,Fe)}let vt=new TextDecoder("utf-8",{fatal:!0}).decode(Ve);if(/\b(?:Inline|ImageTexture|MovieTexture|AudioClip)\b|\burl\s*(?:\[|\")/i.test(vt))throw new Error("VRML has an external resource reference");return Xm(new k2().parse(vt),Fe)}async function XI(R){if(!r.boardPath)return;let q;try{q=globalThis.KiCadRepoModels.collectParsed(R,r.boardPath,r.assetPaths),R=null}catch(At){un.push(`Cannot read model references: ${At.message}`),Lc();return}un.push(...q.diagnostics),Lc();let he=Xt(q.models),Fe=new Map(o.components.map((At,Bt)=>[At.id,Bt])),ze=0,Ve=0;async function vt(At){let Bt=Fe.get(At.footprintId);if(Bt===void 0){un.push(`${At.reference}: footprint identity not found`),he.release(At);return}try{let qt=await he.get(At,async()=>{let ct=At.embeddedAsset||await r.loadAsset?.(At.path);if(!st)throw Error("3D viewer closed before model decoding.");return jI(At,ct,pr=>{if(ze+=pr,ze>25165824)throw new Error("Decoded 3D model assets exceed 24 MiB in this viewer")},Bt)});if(!st)return;Ce.admit(qt,2+(wa.has(Bt)?0:1),()=>{let ct=he.isLastUse(At)?qt:qt.clone(!0);A.retainClone(ct,ue,Pe);let pr=0;if(ct.traverse(wr=>{wr.isMesh&&wr.geometry?.attributes?.position?.count&&(pr++,wr.castShadow=!0,wr.receiveShadow=!0,wr.userData.record={...o.components[Bt],type:"Component",modelPath:At.path},zr.add(wr,"component"),ai.push(wr))}),!pr)throw new Error("asset has no drawable mesh");let Yt=globalThis.KiCadRepoModels.modelPose(At,V,K,ne),nr=new jr;nr.position.set(...Yt.position),nr.rotation.z=Yt.footprintAngle;let Rr=new jr;if(Rr.rotation.set(...Yt.modelRotation,"ZYX"),Rr.scale.set(...Yt.scale),Rr.add(ct),nr.add(Rr),!wa.has(Bt)){let wr=new jr;wa.set(Bt,wr),Zo.add(wr)}wa.get(Bt).add(nr),Pc.add(Bt),At.format==="glb"&&un.push(`${At.reference}: GLB geometry is interpreted in millimetres.`)})}catch(qt){un.push(`${At.reference}: ${At.path}: ${qt?.message||String(qt)}`)}finally{he.release(At)}Nc.request()}await Promise.all(Array.from({length:Math.min(je,q.models.length)},async()=>{for(;Ve<q.models.length&&st;)await vt(q.models[Ve++])})),he.clear(),Ic?.dispose(),Ic=null,st&&(Nc.flush(),!Tr&&Pc.size&&zs())}let Ym=Math.hypot(me,we,ne+5)/2,qm=new ee,YI=new ee,Oc=new Yr().setFromObject(Ei);function Jo(){let R=nI(O.position.toArray(),O.getWorldDirection(YI).toArray(),Oc.min.toArray(),Oc.max.toArray()),q=aI(O.position.distanceTo($e.target),Ym+$e.target.distanceTo(qm),R);O.near=q.near,O.far=Bn.enabled?Math.max(q.far,He*10):q.far,O.updateProjectionMatrix()}function Km(){Oc.setFromObject(Ei);let R=Oc.getBoundingSphere(new si);Number.isFinite(R.radius)&&R.radius>0&&(Ym=R.radius,qm.copy(R.center)),Jo()}$e.addEventListener("change",Jo);function ub(R){if(!qn)return;let{width:q,height:he,ratio:Fe}=qn,ze=R?Math.min(Fe,Math.sqrt(6e5/q/he),Fe*.78):Fe;(F.domElement.width!==Math.floor(q*ze)||F.domElement.height!==Math.floor(he*ze)||F.getPixelRatio()!==ze)&&F.setDrawingBufferSize(q,he,ze)}function Ha(){let R=qe();if(Ue.setState({hasSize:R}),!R){Ie();return}let q=Math.max(1,m.clientWidth),he=Math.max(1,m.clientHeight),Fe=Wx(q,he,globalThis.devicePixelRatio,re.maxDimension,ja.running()?"low":tt,re),ze=Fe.ratio;(F.domElement.width!==Math.floor(q*ze)||F.domElement.height!==Math.floor(he*ze))&&L.invalidate(),qn={width:q,height:he,ratio:ze},ub(ni),O.aspect=q/he,ot&&(ot.composer.setPixelRatio(ze),ot.composer.setSize(q,he)),O.updateProjectionMatrix(),Ie()}function zs(R="iso"){Ha(),Ei.updateWorldMatrix(!0,!0);let q=new Yr().setFromObject(Ei),he=q.getBoundingSphere(new si),Fe=Number.isFinite(he.radius)&&he.radius>0?he.radius:Math.hypot(me,we,ne+5)/2,ze=he.radius>0?he.center:new ee,Ve=TI(R),vt=new ee(...Ve.direction).normalize(),At=Px(q.getSize(new ee).toArray(),vt.toArray(),O.fov,O.aspect,.85,Ve.up)||Rx(Fe,O.fov,O.aspect)||He*3;Ym=Fe,qm.copy(ze),Oc.copy(q),$e.maxDistance=Math.max(He*8,At*4),O.position.copy(ze).addScaledVector(vt,At),O.up.fromArray(Ve.up),$e.target.copy(ze),$e.update(),Jo()}E("Fit",()=>{Tr=!0,zs()},"M8 3H3v5M16 3h5v5M21 16v5h-5M8 21H3v-5M8 8h8v8H8Z","Fit board to viewport").classList.add("fit-action");let Zn=document.createElement("select");Zn.className="view-select",Zn.title="Choose a board viewing side",Zn.setAttribute("aria-label","3D camera view");let Gd=document.createElement("option");Gd.value="",Gd.disabled=!0,Gd.textContent="View",Zn.append(Gd);for(let{id:R,label:q}of Id){let he=document.createElement("option");he.value=R,he.textContent=q,Zn.append(he)}Zn.value="",Zn.onchange=()=>{Tr=!0,zs(Zn.value),Zn.value=""},g.append(Zn);let Zm=document.createElement("span");Zm.className="divider",Zm.setAttribute("aria-hidden","true"),g.append(Zm);let Wa=!1;function hb(R){return Wa=!!R,kR($e,Le,Wa),Qm.setAttribute("aria-pressed",String(Wa)),F.domElement.style.cursor=Wa?"grab":"",Wa}let Qm=E("Pan",()=>{Hs(!1),hb(!Wa)},"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");Qm.setAttribute("aria-pressed","false");let Vd=E("Measure",()=>Hs(!Wr),"M3 17 17 3l4 4L7 21ZM7 13l3 3M10 10l2 2M13 7l3 3","Measure distance between 3D surfaces");Vd.setAttribute("aria-pressed","false");let $o=E("Display",()=>H(P.hidden),"M3 6h18M3 12h18M3 18h18M7 3v6M17 9v6M10 15v6","3D display settings");$o.setAttribute("aria-expanded","false"),$o.setAttribute("aria-controls",P.id);let Dc=document.createElement("label");Dc.className="explode-control",Dc.style.cssText="display:inline-flex;align-items:center;gap:5px;font-size:11px",Dc.title="Expand mode: components lift first, then copper layers separate, the substrate fades and vias stretch. Saved identities remain linked.";let db=document.createElement("span");db.textContent="Expand mode";let hn=document.createElement("input");hn.type="range",hn.min="0",hn.max="100",hn.step="1",hn.value="0",hn.style.cssText="width:80px;min-width:50px",hn.setAttribute("aria-label","Expand assembly");let Jm=document.createElement("output");Jm.textContent="0%",Dc.append(db,hn,Jm);let Gs=document.createElement("details");Gs.className="tools-more";let kc=document.createElement("summary");kc.textContent="3D tools",kc.title="More 3D tools",kc.setAttribute("aria-label","More 3D tools");let $m=document.createElement("div");$m.className="tools-panel",$m.append(Qm,Vd,$o,Dc),Gs.append(kc,$m),g.append(Gs);let Vs=document.createElement("p");Vs.className="quality-help",Vs.setAttribute("role","status"),Vs.hidden=!0,Vs.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",p.append(Vs);function pb(){Fr.sync(Sa.overlay,Tt.get())}function fb(R=Sa.getAnalysisOverlayState()){return Tt.get()>0&&R.placed?{...R,displaySuspended:!0,diagnostics:[...R.diagnostics,"Registered result and probes are hidden while Expand mode is active; restore Expand mode to 0% to view them."]}:R}let mb=0,gb=0,eg=0;function qI(R){let q=performance.now();if(!st)return Tt.get();let he=Tt.get(),Fe=Tt.set(R);if(he===0!=(Fe===0)&&(Fe>0&<(),Dr(dr)),F.shadowMap.enabled=!1,Fe>0){let Ve=Ge.size;Fd(),Ge.size!==Ve&&Dr(dr)}Fe!==he&&(Tr=!0,$n(),Wr&&Hs(!1));for(let Ve of ke){let vt=Sn.get(Ve.name);vt&&(Tt.layer(vt,Ve.name),vt.visible=ur(Ve))}for(let Ve of Ko.children){let vt=Fs.find(At=>At.mesh===Ve)?.layer;Tt.layer(Ve,vt==="B.SilkS"?"B.Cu":"F.Cu")}for(let{mesh:Ve,span:vt}of Cr)Tt.barrels(Ve,vt);zd(),ji?al.syncTransforms():Cd(Ii)&&An(Ii),Ji?.object&&!zn&&(Bb(Ji.object,Ji.instanceId),qs.getCenter(Ji.point)),Rc(),pb(),Km(),wb(),Jm.textContent=Math.round(Fe)+"%",hn.setAttribute("aria-valuetext",Math.round(Fe)+" percent expanded"),Vs.hidden=Fe===0,Vs.textContent="Display-only expansion: components lift first, then copper separates and substrate fades. "+(ke.some(Ve=>Ve.basis==="illustrative")?"Internal elevations are illustrative. ":"")+"Registered results and measurements resume at 0%.",mb++;let ze=performance.now()-q;return gb+=ze,eg=Math.max(eg,ze),r.onExplodeChange?.(Fe),Ie(),Fe}let ja=RI({request:R=>requestAnimationFrame(R),cancel:R=>cancelAnimationFrame(R),update:qI,canRun:()=>st&&!Pt&&!Ue.stats().paused,reducedMotion:()=>globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches===!0,settle:R=>{if(F.shadowMap.enabled=R===0&&tt!=="low"&&dr!=="translucent",F.shadowMap.needsUpdate=!0,R===0)try{Ut()}catch{xt("Enhanced quality is unavailable. Balanced rendering is active.")}Ha(),Ie()}});function Hd(R,q=!1){if(!st)return Tt.get();if(!Number.isFinite(R)||R<0||R>100)throw new TypeError("Expand amount must be between 0 and 100.");R>0&&Fd(),hn.value=String(R);let he=ja.set(R,{immediate:q});return Ha(),he}hn.oninput=()=>Hd(Number(hn.value));let yb=new Map,tg=()=>ke.filter(R=>Se.get(R.name)).map(R=>R.name);function vb(R){if(!Array.isArray(R)||R.some(ze=>typeof ze!="string"||!Se.has(ze))||new Set(R).size!==R.length)throw new TypeError("Choose saved physical copper layer names.");let q=new Set(R),he=!1;for(let ze of ke){let Ve=q.has(ze.name);Se.get(ze.name)!==Ve&&(he=!0),Se.set(ze.name,Ve);let vt=yb.get(ze.name);vt&&(vt.checked=Ve);let At=Sn.get(ze.name);At&&(At.visible=ur(ze))}An(Ii),Ie();let Fe=tg();return he&&r.onLayersChange?.([...Fe]),Fe}for(let R of ke)yb.set(R.name,U(R.name==="F.Cu"?"Front copper":R.name==="B.Cu"?"Back copper":R.name+" copper",!0,q=>{let he=new Set(tg());q?he.add(R.name):he.delete(R.name),vb([...he])}));let xb=document.createElement("label"),Uc=document.createElement("select");xb.append(document.createTextNode("Inspect copper layer"),Uc),Uc.setAttribute("aria-label","Inspect copper layer");for(let[R,q]of[["","Assembled board"],...ke.map(he=>[he.name,he.name])]){let he=document.createElement("option");he.value=R,he.textContent=q,Uc.append(he)}Q.append(xb);let KI=U("Parts",!0,R=>{Zo.visible=!$t&&R,Cd(Ii)&&An(Ii),F.shadowMap.needsUpdate=!0}),ZI=U("Silkscreen",!0,R=>{Ko.visible=!$t&&R});Uc.onchange=()=>{$t=Uc.value||null,Zo.visible=!$t&&KI.checked,Ko.visible=!$t&&ZI.checked,jm.visible=!$t,Dr(dr)};let bb=!1,Fc=new jr,Qn=new Map;ce.add(Fc);let _b=new Io(1,1),QI=c.filter(R=>R.name&&R.net&&R.name.length<=40&&R.net.length<=48).slice(0,1e4).map(R=>{let[q,he]=ie(R.at);return{pad:R,x:q,y:he}}),el=[],Wd=new Set;function JI(R){let q=JSON.stringify([R.name,R.net]);if(Qn.has(q)){let Ve=Qn.get(q);return Qn.delete(q),Qn.set(q,Ve),Wd.add(Ve),Ve}if(Qn.size>=150){let Ve=[...Qn].find(([,vt])=>!Wd.has(vt));if(!Ve)return null;Qn.delete(Ve[0]),Ve[1].dispose()}let he=document.createElement("canvas");he.width=512,he.height=48;let Fe=he.getContext("2d");Fe.font="600 14px monospace",Fe.textAlign="center",Fe.textBaseline="middle",Fe.lineJoin="round",Fe.lineWidth=5,Fe.strokeStyle="#101820",Fe.fillStyle="#f3f8fa";for(let[Ve,vt]of[[R.name,13],[R.net,34]])Fe.strokeText(Ve,256,vt),Fe.fillText(Ve,256,vt);let ze=new Lh(he);return ze.colorSpace=Pr,Qn.set(q,ze),Wd.add(ze),ze}let Bc=new ee,$I=new ee;function wb(){let R=0;if(Wd.clear(),Fc.visible=bb&&!Wr,!Fc.visible)return;if(!Bi.visible("pads"))return void el.forEach(Ve=>Ve.visible=!1);let q=Math.max(1,m.clientHeight),he=Math.max(1,m.clientWidth),Fe=[],ze=O.position.z>=$e.target.z?"F.Cu":"B.Cu";if(!Si(ze).visible||!Bi.visible("pads",ze))return void el.forEach(Ve=>Ve.visible=!1);for(let{pad:Ve,x:vt,y:At}of QI){if(R>=150)break;if(!(Ve.layers?.includes(ze)||Ve.layers?.includes("*.Cu")||Ve.layer===ze))continue;let Bt=(ze==="F.Cu"?_e+.055:oe-.055)+Tt.offset(ze),qt=O.position.distanceTo($I.set(vt,At,Bt)),ct=q/(2*Math.tan(O.fov*Math.PI/360)*qt),pr=Math.min(Ve.width,Ve.height)*ct;if(!Number.isFinite(pr)||pr<32||(Bc.set(vt,At,Bt).project(O),Bc.z<-1||Bc.z>1))continue;let Yt=Math.min(16,Math.max(10,pr*.22)),nr=(Math.max(Ve.name.length,Ve.net.length)*.63+1)*Yt,Rr=Yt*2.8,wr=(Bc.x+1)*he/2,Gr=(1-Bc.y)*q/2,Lr={x:wr-nr/2,y:Gr-Rr/2,w:nr,h:Rr};if(Lr.x<0||Lr.y<0||Lr.x+nr>he||Lr.y+Rr>q||Fe.some(cl=>Lr.x<cl.x+cl.w&&Lr.x+nr>cl.x&&Lr.y<cl.y+cl.h&&Lr.y+Rr>cl.y))continue;let Gi=JI(Ve);if(!Gi)continue;let Cn=el[R];Cn||(Cn=new hr(_b,new ti({transparent:!0,depthTest:!0,depthWrite:!1,side:Rt})),Cn.renderOrder=5,Fc.add(Cn),el.push(Cn)),Cn.material.map!==Gi&&(Cn.material.map=Gi,Cn.material.needsUpdate=!0),Cn.position.set(vt,At,Bt),Cn.quaternion.copy(O.quaternion),Cn.scale.set(36.57142857142857*Yt/ct,3.4285714285714284*Yt/ct,1),Cn.visible=!0,Fe.push(Lr),R++}for(let Ve=R;Ve<el.length;Ve++)el[Ve].visible=!1}U("Pad and net names (close zoom)",!1,R=>{bb=R}),zs();let Xa=new ic,Ya=new Xe,dn=new MI,Wr=!1,qa="mm",tl=document.createElement("section");tl.className="measurement-panel",tl.hidden=!0,tl.setAttribute("aria-label","3D surface measurement");let rg=document.createElement("div");rg.className="measurement-heading";let Eb=document.createElement("strong");Eb.textContent="Surface distance";let zc=document.createElement("select");zc.setAttribute("aria-label","3D measurement units");for(let R of["mm","mil"]){let q=document.createElement("option");q.value=R,q.textContent=R,zc.append(q)}let Gc=document.createElement("button");Gc.type="button",Gc.textContent="Done",Gc.title="Exit measurement mode",Gc.onclick=()=>Hs(!1),rg.append(Eb,zc,Gc);let Vc=document.createElement("select"),Hc=document.createElement("select"),ig=document.createElement("div");ig.className="measurement-tools",Vc.setAttribute("aria-label","3D measurement snap"),Hc.setAttribute("aria-label","3D measurement selection filter");for(let[R,q]of[["surface","Surface"],["edges","Snap to edges"],["corners","Snap to corners"]]){let he=document.createElement("option");he.value=R,he.textContent=q,Vc.append(he)}for(let[R,q]of[["all","All geometry"],["board","Board outline/body"],["models","Component models"],["pads","Pads"],["tracks","Tracks"],["vias","Vias"]]){let he=document.createElement("option");he.value=R,he.textContent=q,Hc.append(he)}ig.append(Vc,Hc);let Mb=new WeakMap,Ea=null,Wc=null,Ka=new Set,pn=document.createElement("canvas");pn.width=pn.height=240,pn.className="measurement-label",pn.hidden=!0,pn.setAttribute("aria-label","3D measurement magnifier"),pn.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",p.append(pn);function eN(){if(!Wr||!Ea){pn.hidden=!0;return}let R=F.domElement.getBoundingClientRect(),q=Ea.x-R.left,he=Ea.y-R.top;pn.hidden=!1;let Fe=pn.getContext("2d");if(!Fe)return;let ze=F.domElement.width/R.width,Ve=F.domElement.height/R.height;Fe.clearRect(0,0,240,240),Fe.drawImage(F.domElement,(q-20)*ze,(he-20)*Ve,40*ze,40*Ve,0,0,240,240),Fe.strokeStyle="#ffcf66",Fe.lineWidth=2,Fe.beginPath(),Fe.moveTo(110,120),Fe.lineTo(130,120),Fe.moveTo(120,110),Fe.lineTo(120,130),Fe.stroke()}let ng=document.createElement("output");ng.setAttribute("aria-live","polite");let ag=document.createElement("p");ag.setAttribute("role","status");let Sb=document.createElement("small"),Tb=document.createElement("small");Tb.textContent="Model surfaces \xB7 footprint stand-ins are approximate.";let sg=document.createElement("div");sg.className="measurement-tools";let Ma=document.createElement("select");Ma.setAttribute("aria-label","Recent 3D measurements");let jc=document.createElement("button");jc.type="button",jc.textContent="Clear",jc.title="Clear all 3D measurements",jc.onclick=Ib,sg.append(Ma,jc),tl.append(rg,ig,ng,ag,Sb,sg,Tb),p.append(tl);let Gn=document.createElement("div");Gn.className="measurement-label",Gn.hidden=!0,Gn.setAttribute("aria-hidden","true"),p.append(Gn);let rl=new jr;rl.visible=!1,ce.add(rl);let og=new ar;og.setAttribute("position",new Mr(new Float32Array(6),3));let tN=new ri({color:16765818,transparent:!0,opacity:.95,depthTest:!1,depthWrite:!1,toneMapped:!1}),jd=new jn(og,tN);jd.frustumCulled=!1,jd.renderOrder=201,rl.add(jd);let Ab=new Ua(1,12,8),Cb=new ti({color:16765818,transparent:!0,opacity:.95,depthTest:!1,depthWrite:!1,toneMapped:!1}),Xc=[new hr(Ab,Cb),new hr(Ab,Cb)];for(let R of Xc)R.renderOrder=202,rl.add(R);let Rb=R=>new ee(R.x-V,K-R.y,R.z);function il(R){let q=dn.selected,he=dn.pending;ng.textContent=q?(q.approximate?"\u2248 ":"")+Bm(q.distance,qa):"\u2014",ag.textContent=R||(he?"Choose the second surface point.":q?"Choose a point to start another measurement.":"Choose the first surface point.");let Fe=Ve=>(qa==="mil"?Ve/.0254:Ve).toFixed(qa==="mil"?2:3);Sb.textContent=q?`\u0394X ${Fe(q.delta.x)} \xB7 \u0394Y ${Fe(q.delta.y)} \xB7 \u0394Z ${Fe(q.delta.z)} ${qa}`:"",Ma.replaceChildren();let ze=document.createElement("option");ze.value="",ze.textContent=dn.records.length?"Recent measurements":"No measurements yet",Ma.append(ze);for(let Ve of dn.records){let vt=document.createElement("option");vt.value=String(Ve.id),vt.textContent=`#${Ve.id} \xB7 ${Ve.approximate?"\u2248 ":""}${Bm(Ve.distance,qa)}`,Ma.append(vt)}Ma.value=q?String(q.id):"",Ma.disabled=!dn.records.length,Gn.textContent=q?(q.approximate?"\u2248 ":"")+Bm(q.distance,qa):"",Pb(),Ie()}function Pb(){let R=dn.selected,q=dn.pending;if(rl.visible=Wr&&!!(R||q),Gn.hidden=!Wr||!R,!rl.visible)return;let he=Rb(R?.from||q),Fe=R?Rb(R.to):null;if(Xc[0].position.copy(he),Xc[1].visible=!!Fe,jd.visible=!!Fe,Fe){Xc[1].position.copy(Fe);let ze=og.getAttribute("position");ze.setXYZ(0,he.x,he.y,he.z),ze.setXYZ(1,Fe.x,Fe.y,Fe.z),ze.needsUpdate=!0;let Ve=he.clone().add(Fe).multiplyScalar(.5).project(O);Gn.hidden=Ve.z<-1||Ve.z>1,Gn.style.left=Math.max(8,Math.min(m.clientWidth-Gn.offsetWidth-8,(Ve.x+1)*m.clientWidth/2+8))+"px",Gn.style.top=Math.max(8,Math.min(m.clientHeight-Gn.offsetHeight-8,(1-Ve.y)*m.clientHeight/2-24))+"px"}for(let ze of Xc){let Ve=Math.max(.005,O.position.distanceTo(ze.position)*2*Math.tan(O.fov*Math.PI/360)/Math.max(1,m.clientHeight)*3.5);ze.scale.setScalar(Ve)}}function Hs(R){return st?R&&Tt.get()>0?(mt("Restore Expand mode to 0% before measuring saved geometry."),!1):(Wr=!!R,Wr&&hb(!1),h.dataset.measuring=String(Wr),Vd.setAttribute("aria-pressed",String(Wr)),tl.hidden=!Wr,Wr||(dn.pending=null,Ea=null,Wc=null,Ka.clear(),$e.enabled=!0,pn.hidden=!0),il(),r.onMeasurementMode?.(Wr),Wr):!1}function Ib(){dn.clear(),il(),r.onMeasurement?.(null)}zc.onchange=()=>{qa=zc.value==="mil"?"mil":"mm",il()},Ma.onchange=()=>{let R=dn.replay(Ma.value);R&&(il(),r.onMeasurement?.(R))};let Nb=R=>{R.key==="Escape"&&Wr&&(R.preventDefault(),R.stopPropagation(),Hs(!1),Vd.focus())};d.addEventListener("keydown",Nb);function rN(){let R=Gr=>Rm(Gr,Ci,$t||Tt.get()>0?"translucent":dr),q=Xa.intersectObjects(ai.filter(R),!1).find(Gr=>Jn.isVisible(Gr.object,Gr.instanceId));if(!q)return null;let he=q.object===Ci?"board":Fs.find(Gr=>Gr.mesh===q.object)?.type||"models",Fe=he==="arcs"?"tracks":he;if(Hc.value!=="all"&&Hc.value!==Fe)return null;if(Vc.value==="surface")return{point:q.point,approximate:q.object===qr,kind:"surface"};let ze=q.object.geometry,Ve=ze?.getAttribute("position");if(!Ve||Ve.count>2e5)return null;let vt=Mb.get(ze);if(!vt){let Gr=new Ql(ze,25),Lr=Gr.getAttribute("position");vt=[];for(let Gi=0;Gi+1<Lr.count&&vt.length<1e4;Gi+=2)vt.push([[Lr.getX(Gi),Lr.getY(Gi),Lr.getZ(Gi)],[Lr.getX(Gi+1),Lr.getY(Gi+1),Lr.getZ(Gi+1)]]);Gr.dispose(),Mb.set(ze,vt)}let At=q.object.matrixWorld.clone();if(Number.isInteger(q.instanceId)){let Gr=new Jt;q.object.getMatrixAt(q.instanceId,Gr),At.multiply(Gr)}let Bt=vt.map(Gr=>Gr.map(Lr=>{let Gi=new ee(...Lr).applyMatrix4(At);return{x:Gi.x,y:Gi.y,z:Gi.z}})),qt=F.domElement.getBoundingClientRect(),ct=Gr=>{let Lr=new Nr(Gr.x,Gr.y,Gr.z,1).applyMatrix4(O.matrixWorldInverse).applyMatrix4(O.projectionMatrix);return Lr.w<=0?null:{x:(Lr.x/Lr.w+1)*qt.width/2,y:(1-Lr.y/Lr.w)*qt.height/2,z:Lr.z/Lr.w,w:Lr.w}},pr=SI({x:(Ya.x+1)*qt.width/2,y:(1-Ya.y)*qt.height/2},Bt,ct,{mode:Vc.value,tolerance:Ea?18:12});if(!pr)return null;let Yt=new ee(pr.point.x,pr.point.y,pr.point.z),nr=Yt.clone().project(O),Rr=new ic;Rr.setFromCamera(new Xe(nr.x,nr.y),O);let wr=Rr.intersectObjects(ai.filter(R),!1).find(Gr=>Jn.isVisible(Gr.object,Gr.instanceId));return!wr||wr.object!==q.object||wr.instanceId!==q.instanceId||wr.point.distanceTo(Yt)>Math.max(.002,O.position.distanceTo(Yt)*5e-5)?null:{point:Yt,approximate:q.object===qr,kind:pr.kind}}function iN(){let R=rN();if(!R){il("No visible feature within snap range. Adjust snap/filter or zoom in.");return}let q=dn.add({x:R.point.x+V,y:K-R.point.y,z:R.point.z,approximate:R.approximate});il(R.kind+" selected. "+(dn.pending?"Choose the second point.":"Measurement complete.")),q?.distance!==void 0&&r.onMeasurement?.(q)}let Ji=null,Yc=CI({onPick:R=>{Wa||hg(R)},onContextMenu:jb,isHeld:()=>ll.isHeld()}),nl=!0,Ws=Cm(),Jn=GP(Le,()=>{let R=[];return Ei.traverse(q=>{q.material&&R.push(q)}),R});ir=!0;let js=2e3,Lb=new Ql(new da(1,1,1)),Za=Lb.getAttribute("position"),Xs=new ar,Xd=new Mr(new Float32Array(js*Za.count*3),3);Xd.setUsage(n0),Xs.setAttribute("position",Xd),Xs.setDrawRange(0,0);let Ob=()=>new ri({color:n?16768893:10179840,depthTest:!0,depthWrite:!1,toneMapped:!1}),Ys=new Fi(Xs,Ob());Ys.frustumCulled=!1,Ys.renderOrder=101,ce.add(Ys);let Ii={},al=NI(Le,{scene:ce,objects:()=>ai,colorForLayer:Ld,visible:(R,q)=>{if($t?q!==$t:Se.has(q)&&!Se.get(q))return!1;for(let he=R;he;he=he.parent)if(!he.visible&&he!==Sn.get(q))return!1;return!0}});function Db(R){al.update(R,Ws),al.stats().limited&&($i.hidden=!1,$i.style.display="",$i.textContent="Net shine-through reached its display budget; native selection is retained.")}let sl={netOnlyUpdates:0,netRecordsScanned:0,netBoundsAvoided:0,boundsEvaluations:0,outlineVerticesWritten:0},$i=document.createElement("div");$i.className="hint",$i.style.bottom="42px",$i.hidden=!0,p.append($i);function An(R={}){if(L.invalidate(),Ie(),Ii=R||{},ji=!1,Mi=!1,zn=!1,!Cd(Ii))return al.clear(),Xs.setDrawRange(0,0),$i.hidden=!0,$i.style.display="none",en.visible=!1,Ys.visible=!1,Jn.restore(),Rc(),{highlighted:0,matched:0,limited:!1};let q=YP(Ii,o);q.size&&Fd();let he=QP(Ii,o);if(Mi=he(Ci.userData.record),zn=q.size>0,qP(Ii,q)){ji=!0;let Yt=ZP(ai,he);return sl.netOnlyUpdates++,sl.netRecordsScanned+=Yt.visitedRecords,sl.netBoundsAvoided+=Yt.matchedRecords,Xs.setDrawRange(0,0),$i.hidden=!0,$i.style.display="none",en.visible=!1,Ys.visible=!1,Jn.update(he,Yt.matched>0&&nl,nr=>q.has(nr?.net),{...Ws,expanded:Tt.get()>0,netContext:q.size>0}),Rc(),Db(q),{highlighted:Math.min(Yt.matched,js),matched:Yt.matched,limited:Yt.matched>js}}let Fe=new Jt,ze=new Jt,Ve=new Yr,vt=new ee,At=new ee,Bt=0,qt=0,ct=new Map,pr=(Yt,nr,Rr)=>{if(Number.isInteger(nr)&&(Yt.getMatrixAt(nr,ze),ze.determinant()===0)||(sl.boundsEvaluations++,Yt.updateWorldMatrix(!0,!1),Number.isInteger(nr)?(Yt.geometry.boundingBox||Yt.geometry.computeBoundingBox(),Ve.copy(Yt.geometry.boundingBox),Fe.multiplyMatrices(Yt.matrixWorld,ze),Ve.applyMatrix4(Fe)):Ve.setFromObject(Yt),Ve.isEmpty()))return;let wr=Rr?.ref?"part:"+Rr.ref:Rr?.uuid||Rr?.id||Yt.uuid+":"+nr;ct.has(wr)?ct.get(wr).union(Ve):ct.size<js?ct.set(wr,Ve.clone()):qt++};for(let Yt of ai){let nr=!0;for(let wr=Yt;wr;wr=wr.parent)wr.visible||(nr=!1);if(!nr)continue;let Rr=Yt.userData.records;Rr?Rr.forEach((wr,Gr)=>{he(wr)&&pr(Yt,Gr,wr)}):he(Yt.userData.record)&&pr(Yt,void 0,Yt.userData.record)}for(let Yt of ct.values()){Yt.expandByScalar(.035),Yt.getCenter(vt),Yt.getSize(At);for(let nr=0;nr<Za.count;nr++)Xd.setXYZ(Bt*Za.count+nr,vt.x+Za.getX(nr)*At.x,vt.y+Za.getY(nr)*At.y,vt.z+Za.getZ(nr)*At.z);Bt++}return qt+=ct.size,Xs.setDrawRange(0,Bt*Za.count),Xd.needsUpdate=!0,sl.outlineVerticesWritten+=Bt*Za.count,$i.hidden=qt<=js,$i.textContent=`Showing ${Bt} of ${qt} selected 3D objects`,$i.style.display=qt>js?"block":"none",en.visible=!1,Ys.visible=!q.size,Jn.update(he,qt>0&&nl,q.size?Yt=>q.has(Yt?.net):null,{...Ws,expanded:Tt.get()>0,netContext:q.size>0}),Rc(),Db(q),{highlighted:Bt,matched:qt,limited:qt>js}}let en=new Fi(Lb,Ob());en.matrixAutoUpdate=!1,en.renderOrder=100,en.visible=!1,ce.add(en);let kb=new Jt,qs=new Yr,Ub=new ee,Fb=new ee;function Bb(R,q){if(Ie(),R.updateWorldMatrix(!0,!1),Number.isInteger(q)?(R.getMatrixAt(q,kb),R.geometry.boundingBox||R.geometry.computeBoundingBox(),qs.copy(R.geometry.boundingBox).applyMatrix4(kb).applyMatrix4(R.matrixWorld)):qs.setFromObject(R),qs.isEmpty()){en.visible=!1;return}qs.expandByScalar(.035),qs.getCenter(Ub),qs.getSize(Fb),en.matrix.compose(Ub,new di,Fb),en.matrixWorldNeedsUpdate=!0,en.visible=!0}function lg(){Ji=null,x.hidden=!0,b.hidden=!0,en.visible=!1,An({}),r.onSelect?.(null)}function cg(R,q,he,Fe){let ze=r.getSelectionMode?.()||dg;An(ze==="net"&&R.net?{netNames:[R.net]}:R.type==="Component"||typeof R.library=="string"?{references:[R.ref]}:{uuids:[R.uuid||R.id]}),Ji={record:R,point:q.clone(),object:he,instanceId:Fe},Xs.setDrawRange(0,0),ze!=="net"||!R.net?Bb(he,Fe):en.visible=!1,r.onSelect?.(R),x.replaceChildren();let Ve=document.createElement("h2");Ve.textContent=R.ref||R.name||R.type||"Board object";let vt=document.createElement("dl");for(let[At,Bt]of Object.entries({Type:R.type||(R.ref?"Component":"Copper"),Reference:R.ref,Value:R.value,Layer:R.layer||R.layers?.join(", "),Net:R.net,Model:R.modelPath||R.modelPaths?.join(", ")})){if(Bt==null||Bt==="")continue;let qt=document.createElement("dt"),ct=document.createElement("dd");qt.textContent=At,ct.textContent=String(Bt),vt.append(qt,ct)}x.append(Ve,vt),x.hidden=!!r.externalInspector}let tn=gP(Le,{scene:ce,objects:()=>ai,document,invalidate:Ie}),Ks=document.createElement("div");Ks.hidden=!0,Ks.setAttribute("role","status"),Ks.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",p.append(Ks);let ug=document.createElement("span"),ol=document.createElement("button");ol.type="button",ol.textContent="Cancel",ol.setAttribute("aria-label","Cancel demo face selection"),ol.style.cssText="pointer-events:auto;margin-left:10px",ol.onclick=()=>Qs(new DOMException("Face selection was cancelled.","AbortError")),Ks.append(ug,ol);let Zs=null,Vn=null,nN=R=>Rm(R,Ci,$t||Tt.get()>0?"translucent":dr);function Yd(R,q=!0){tn.sync();let he=F.domElement.getBoundingClientRect();return!he.width||!he.height?null:(Ya.set((R.clientX-he.left)/he.width*2-1,-((R.clientY-he.top)/he.height)*2+1),Xa.setFromCamera(Ya,O),Xa.intersectObjects((q?[...ai,...tn.objects()]:ai).filter(nN),!1).find(Fe=>Jn.isVisible(Fe.object,Fe.instanceId))||null)}function Qs(R,q){let he=Zs;he&&(Zs=null,he.signal?.removeEventListener("abort",he.abort),Ks.hidden=!0,F.domElement.style.cursor="",R?he.reject(R):he.resolve(q))}function aN({signal:R}={}){return st?R?.aborted?Promise.reject(new DOMException("Face selection was aborted.","AbortError")):(Qs(new DOMException("Face selection was replaced.","AbortError")),$n(),Hs(!1),new Promise((q,he)=>{let Fe=()=>Qs(new DOMException("Face selection was aborted.","AbortError"));Zs={resolve:q,reject:he,signal:R,abort:Fe},R?.addEventListener("abort",Fe,{once:!0}),ug.textContent="Choose a flat component face for the demo display. Drag to orbit; press Escape to cancel.",Ks.hidden=!1,F.domElement.style.cursor="crosshair",F.domElement.tabIndex=0,F.domElement.focus({preventScroll:!0})})):Promise.reject(new Error("The 3D view is closed."))}function $n(R){if(Vn===null)return;let q=Vn;Vn=null,tn.pointer(null,"cancel",{pointerId:q,clientY:R?.clientY||0,cancelled:!0}),$e.enabled=!0;try{F.domElement.releasePointerCapture(q)}catch{}}function zb(R){if(Vn!==null){R.preventDefault(),R.stopImmediatePropagation();return}if(Wr||Wa||Zs||R.button!==0)return;let q=Yd(R);if(tn.isHit(q)&&tn.pointer(q,"press",R)&&(R.preventDefault(),R.stopImmediatePropagation(),!(!st||!tn.isHit(q)))){Vn=R.pointerId,$e.enabled=!1,F.domElement.tabIndex=0,F.domElement.focus({preventScroll:!0});try{F.domElement.setPointerCapture(R.pointerId)}catch{}}}function Gb(R){Vn===R.pointerId&&(tn.pointer(Yd(R),"move",R),R.preventDefault(),R.stopImmediatePropagation())}function Vb(R){if(Vn!==R.pointerId)return;let q=Vn;Vn=null,tn.pointer(Yd(R),"release",R),$e.enabled=!0;try{F.domElement.releasePointerCapture(q)}catch{}R.preventDefault(),R.stopImmediatePropagation()}function qd(R){Vn===R.pointerId&&($n(R),R.preventDefault(),R.stopImmediatePropagation())}let Hb=R=>{R.key==="Escape"&&Zs&&(Qs(new DOMException("Face selection was cancelled.","AbortError")),R.preventDefault(),R.stopImmediatePropagation())};for(let[R,q]of[["pointerdown",zb],["pointermove",Gb],["pointerup",Vb],["pointercancel",qd],["lostpointercapture",qd]])F.domElement.addEventListener(R,q,!0);d.addEventListener("keydown",Hb,!0),document.defaultView?.addEventListener("blur",$n);function hg(R){if(Zs){try{let ct=Yd(R,!1);Qs(null,tn.selectFace(ct))}catch(ct){ug.textContent=ct.message+" Choose another flat component face, or press Escape."}return}let q=F.domElement.getBoundingClientRect();if(Ya.set((R.clientX-q.left)/q.width*2-1,-((R.clientY-q.top)/q.height)*2+1),Xa.setFromCamera(Ya,O),Wr){iN();return}let he=null,Fe=Sa.overlay;if(Fe?.group?.visible!==!1&&Fe?.mesh.visible){let ct=Fe.sample(Xa.intersectObject(Fe.mesh,!1)[0]);ct&&(he=ct)}let ze=ct=>Rm(ct,Ci,$t||Tt.get()>0?"translucent":dr),Ve=Xa.intersectObjects(ai.filter(ze),!1).filter(ct=>Jn.isVisible(ct.object,ct.instanceId)),vt=r.getSelectionMode?.()||dg,At=ct=>$P(ct.object.userData.records?.[ct.instanceId]||ct.object.userData.record,vt),Bt=dr==="translucent"&&Ve.find(ct=>At(ct)&&(ct.object.userData.records?.[ct.instanceId]||ct.object.userData.record)?.type!=="Zone")||Ve.find(At);if(!Bt){he?r.onAnalysisProbe?.(he):lg();return}let qt=Bt.object.userData.records?.[Bt.instanceId]||Bt.object.userData.record;qt&&cg(qt,Bt.point,Bt.object,Bt.instanceId),he&&r.onAnalysisProbe?.(he)}let dg="all",ll=JP(R=>jb(R)),Wb=R=>{Wr&&R.pointerType==="touch"&&Ka.size&&($e.enabled=!0)};F.domElement.addEventListener("pointerdown",Wb,!0),F.domElement.addEventListener("pointerdown",R=>{Yc.down(R),ll.down(R),b.hidden=!0,Wr&&R.pointerType==="touch"&&(Ka.add(R.pointerId),Wc=Ka.size===1?R.pointerId:null,$e.enabled=Ka.size!==1,Ea={x:R.clientX,y:R.clientY},Ie())}),F.domElement.addEventListener("pointermove",R=>{Yc.move(R),ll.move(R),Wr&&R.pointerType==="touch"&&(Ea={x:R.clientX,y:R.clientY},Ie());let q=Sa.overlay;if(q&&r.onAnalysisHover){let he=F.domElement.getBoundingClientRect();Ya.set((R.clientX-he.left)/he.width*2-1,-((R.clientY-he.top)/he.height)*2+1),Xa.setFromCamera(Ya,O),r.onAnalysisHover(q.group.visible&&q.mesh.visible?q.sample(Xa.intersectObject(q.mesh,!1)[0]):null)}}),F.domElement.addEventListener("pointercancel",R=>{Yc.cancel(R),ll.up(R),Ka.delete(R.pointerId),Wc=null,$e.enabled=!0,Ea=null,pn.hidden=!0}),F.domElement.addEventListener("pointerup",R=>{ll.up(R),Yc.up(R,{select:!(Wr&&R.pointerType==="touch")}),Wr&&R.pointerType==="touch"&&(Wc===R.pointerId&&Ka.size===1&&hg(R),Ka.delete(R.pointerId),Wc=null,$e.enabled=!0),Ea=null,pn.hidden=!0});function jb(R){if(R.preventDefault?.(),Wr||Zs||(hg(R),!Ji))return;b.replaceChildren();let q=[["Focus object",()=>{$e.target.copy(Ji.point),$e.update()}],["Copy reference",()=>navigator.clipboard.writeText(Ji.record.ref||Ji.record.name||"")]];typeof r.onInspect=="function"&&q.unshift(["Properties",()=>r.onInspect(Ji.record)]),typeof r.onComment=="function"&&q.push(["Comment on object",()=>r.onComment(Ji.record)]);for(let[ze,Ve]of q){let vt=document.createElement("button");vt.textContent=ze,vt.type="button",vt.addEventListener("click",()=>{Ve(),b.hidden=!0}),b.append(vt)}let he=p.getBoundingClientRect();b.hidden=!1,b.style.maxWidth="calc(100% - 16px)",b.style.maxHeight="calc(100% - 16px)",b.style.overflowY="auto";let Fe=b.getBoundingClientRect();b.style.left=`${Math.max(8,Math.min(R.clientX-he.left,he.width-Fe.width-8))}px`,b.style.top=`${Math.max(8,Math.min(R.clientY-he.top,he.height-Fe.height-8))}px`}F.domElement.addEventListener("contextmenu",R=>{Yc.context(R)});let Kd=Ha,Xb=new ResizeObserver(()=>{Kd(),k()});Xb.observe(m);let Yb=Vx(Ue,m);Kd(),k();let Sa=xI({bounds:o.bounds,thickness:ne,layers:o.layers||[]},{scene:ce,invalidate:Ie,isActive:()=>st}),sN=requestAnimationFrame(()=>{st&&(Kd(),Tr||zs())}),qb=zP(Le,{objects:()=>ai,camera:O,rect:()=>F.domElement.getBoundingClientRect(),positionToWorld:(R,q)=>{let[he,Fe]=ie([R.x,R.y]);return new ee(he,Fe,q==="back"?oe+Tt.offset("B.Cu"):_e+Tt.offset("F.Cu"))}}),qc=null,pg="",Kb="";function Zb(){if(!qc)return;let R=qb(qc),q=JSON.stringify(R);q!==pg&&(pg=q,r.onAnchor?.({anchor:qc,point:R}))}function oN(){let R=F.domElement.getBoundingClientRect(),q=JSON.stringify([O.matrixWorld.elements,O.projectionMatrix.elements,R.left,R.top,R.width,R.height]);q!==Kb&&(Kb=q,r.onViewChange?.()),Zb()}function lN(){if(ja.resume(),!st||Pt||document.hidden)return;let R=ni&&!Wr;R||Nc.flush(),$e.update(),ub(R),kd.sync({moving:ni||ja.running()}),tn.sync(),Vn!==null&&!tn.hasActivePointer&&$n(),Pb(),R?Fc.visible=!1:wb();let q=!1;Ht=!1;try{if(ot&&!R){if(ot.composer.render(),Ht||!L.check())throw Error("Enhanced rendering failed.")}else if(F.render(ce,O),Ht)throw Error("Board rendering shader failed.");ut++,q=!0}catch{Ht&&Sa.useColorFallback()?(Ht=!1,Ie()):ot&&!R?(xt("Enhanced rendering could not complete. Balanced rendering is active."),Ie()):mt("The graphics device could not draw this view. Try Low quality or reopen 3D.")}q&&(eN(),oN())}let Qb=R=>{$n(),Qs(new DOMException("The graphics context was interrupted.","AbortError")),R.preventDefault(),Pt=!0,Ue.setState({contextAvailable:!1}),I.disabled=!0,mt("The graphics context was interrupted. The board and selection are retained while the browser recovers.",!0)},Jb=()=>{st&&(Pt=!1,Ue.setState({contextAvailable:!0}),I.disabled=!1,lt(),Vt?.dispose(),Vt=gt(),ce.environment=Vt?.texture||null,F.shadowMap.needsUpdate=!0,tt="balanced",Bn.apply(!1),fe(),I.value=tt,h.dataset.quality=tt,mt("Graphics restored. Balanced rendering is active; High quality can be selected again."),Ha(),Ie())};F.domElement.addEventListener("webglcontextlost",Qb),F.domElement.addEventListener("webglcontextrestored",Jb);let $b=()=>{document.hidden&&$n(),Ue.setState({documentVisible:!document.hidden}),document.hidden||(ja.resume(),Ie())};document.addEventListener("visibilitychange",$b);let e1=R=>{let q=R.composedPath();!q.includes($o)&&!q.includes(P)&&H(!1)},t1=R=>{R.key==="Escape"&&!P.hidden?(H(!1,!0),R.preventDefault(),R.stopImmediatePropagation()):R.key==="Escape"&&Gs.open&&(Gs.open=!1,kc.focus(),R.preventDefault(),R.stopImmediatePropagation())};return document.addEventListener("pointerdown",e1),d.addEventListener("keydown",t1,!0),A.retain(ce),Dr(i),Dt(W,!1),XI(r.boardPath?globalThis.KiCadRepoModels.modelSource(a):null),{host:h,board:o,pickDemoFace:aN,createDemoSurface(R,q){if(L.invalidate(),!st)throw new Error("The 3D view is closed.");return tn.createSurface(R,q)},setDemoInputHandler(R){R===null&&$n(),tn.setInputHandler(R)},objectVisibilityCapabilities(){return{supportedTypes:[...Bi.supportedTypes],unsupportedTypes:["graphics","texts","regions","dimensions","rooms","footprints"]}},setObjectVisibility(R={}){let q=Hm(R||{});(q.side!==Bi.side||JSON.stringify(q.hiddenTypes)!==JSON.stringify(Bi.hiddenTypes))&&(Tr=!0),Bi=q;for(let{mesh:he,type:Fe,layer:ze}of Fs)he.visible=Bi.visible(Fe,ze);return zd(),An(Ii),{hiddenTypes:[...Bi.hiddenTypes],side:Bi.side,supportedTypes:[...Bi.supportedTypes],unsupportedTypes:[...Bi.unsupportedTypes]}},setMeasurementMode:Hs,clearMeasurements:Ib,measurementState(){return{mode:Wr,unit:qa,...dn.snapshot()}},setQuality(R){return st?Dt(R):tt},setAppearance(R){return st?Dr(R):dr},getAppearance(){return dr},getCopperLayers(){return ke.map(R=>R.name)},getVisibleCopperLayers(){return tg()},setVisibleCopperLayers:vb,getRenderStats(){return{...Wx(m.clientWidth,m.clientHeight,globalThis.devicePixelRatio,re.maxDimension,tt,re),...A.stats(),zones:{...s.stats(),...pe},modelGraph:{...Ce.stats(),decodeConcurrency:je,imagePreflight:"png-jpeg"},padGeometryCache:ae.stats(),selectionMaterials:Jn.stats(),appearance:dr,netGlow:al.stats(),effectiveLayerColors:!!$t||Tt.get()>0||dr!=="realistic",renderedPixels:F.domElement.width*F.domElement.height,expansion:{amount:Tt.get(),target:ja.target(),running:ja.running(),...Tt.phases(),frames:mb,cpuMilliseconds:gb,maxFrameMilliseconds:eg,frontComponentOffset:Tt.componentOffset("F.Cu"),backComponentOffset:Tt.componentOffset("B.Cu"),layerOffsets:ke.map(R=>({name:R.name,offset:Tt.offset(R.name)}))},renderActivity:{...Ue.stats(),observesIntersection:!!Yb},selectionWorkload:{...sl},modelUpdates:{...Nc.stats(),cpuMilliseconds:cb},copperLayers:[...Ge],translucency:zr.stats(),graphicsTier:re.tier,defaultQuality:re.defaultQuality,maxDimension:re.maxDimension,antialias:Y.getContextAttributes()?.antialias===!0,logarithmicDepth:F.capabilities.logarithmicDepthBuffer,floatTargets:re.premium||F.extensions.has("EXT_color_buffer_float"),presentationStage:Bn.enabled,environmentLighting:!!ce.environment,ambientOcclusion:!!ot?.occlusion,graphicsHealth:L.stats(),silkscreenDetail:kd.stats(),antialiasMethod:ot?"smaa":"none",renderCount:ut,contextLost:Pt,gpuTextures:F.info.memory.textures,drawCalls:F.info.render.calls,loadedModelCount:Pc.size,componentCount:o.components.length}},restoreExpand:R=>Hd(R,!0),setExplode:Hd,getExplode:()=>Tt.get(),setExpand:Hd,getExpand:()=>Tt.get(),setAnalysisOverlay(R,q){L.invalidate();let he=Sa.setAnalysisOverlay(R,q);return pb(),fb(he)},getAnalysisOverlayState:()=>fb(),setAnalysisProbes:Sa.setAnalysisProbes,setAnalysisOpacity:Sa.setAnalysisOpacity,setSelection:An,focusPart(R){if(!st||typeof R!="string")return!1;let q=o.components.flatMap((At,Bt)=>At.id===R?[Bt]:[]);if(q.length!==1)return!1;let he=q[0];if(!Qo[he]||!qr||!Bd[he])return!1;Ei.updateWorldMatrix(!0,!0);let Fe=wa.get(he),ze=new Yr;if(Fe?.children.length)ze.setFromObject(Fe);else{let At=new Jt;if(qr.getMatrixAt(he,At),At.determinant()===0)return!1;qr.geometry.boundingBox||qr.geometry.computeBoundingBox(),ze.copy(qr.geometry.boundingBox).applyMatrix4(new Jt().multiplyMatrices(qr.matrixWorld,At))}if(ze.isEmpty())return!1;Ha();let Ve=vP(ze.min.toArray(),ze.max.toArray(),o.components[he].layer,O.fov,O.aspect);if(!Ve)return!1;O.position.fromArray(Ve.position),$e.target.fromArray(Ve.target),O.up.fromArray(Ve.up);let vt=O.position.distanceTo($e.target);return $e.minDistance=Math.min($e.minDistance,vt),$e.maxDistance=Math.max($e.maxDistance,vt),Tr=!0,$e.update(),Km(),Ie(),!0},clearSelection:lg,projectAnchor:qb,setAnchor(R){qc=R&&typeof R=="object"?R:null,pg="",qc?Zb():r.onAnchor?.({anchor:null,point:null})},setSelectionDim(R){return nl=!!R,An(Ii),nl},setSelectionStyle(R){let q=Cm(R);return nl&&q.mode===Ws.mode&&q.color===Ws.color?{...q}:(nl=!0,Ws=q,An(Ii),{...q})},selectionAppearanceCapabilities(){return{dim:!0,bright:!0,isolate:!0,sourceColors:!0,instanceColors:!0,desaturatesTextures:!0}},setSelectionMode(R){dg=["all","part","net","pin"].includes(R)?R:"all"},fit(R=!1){st&&zs(R)},getCameraState(){return{position:O.position.toArray(),target:$e.target.toArray(),up:O.up.toArray()}},setCameraState(R){if(!st)return!1;let q=yP(R),he=$e.enableDamping;Yo(),Va(),$e.enableDamping=!1,$e.update(),O.position.fromArray(q.position),$e.target.fromArray(q.target),O.up.fromArray(q.up);let Fe=O.position.distanceTo($e.target);return $e.minDistance=Math.min($e.minDistance,Fe),$e.maxDistance=Math.max($e.maxDistance,Fe),$e.update(),$e.enableDamping=he,Tr=!0,Jo(),Ie(),!0},setView(R){return!st||!Id.some(q=>q.id===R)?!1:(Tr=!0,zs(R),!0)},zoom(R){if(!st||!Number.isFinite(R)||R<=0)return;let q=O.position.clone().sub($e.target),he=Math.max($e.minDistance,Math.min($e.maxDistance,q.length()/R));q.length()>0&&O.position.copy($e.target).add(q.setLength(he)),$e.update()},setTheme(R){st&&(h.dataset.theme=R?"dark":"light",fe(),en.material.color.setHex(R?16768893:10179840),Ys.material.color.setHex(R?16768893:10179840),Kd(),Ie())},selectReference(R){let q=lb.get(R);if(q==null||!qr||!Bd[q]||!st||!Qo[q])return!1;let he=wa.get(q);if(he?.children.length){let Bt=o.components[q],[qt,ct]=ie(Bt.at);return cg(Bt,new ee(qt,ct,(Bt.layer?.startsWith("B.")?oe:_e)+Tt.componentOffset(Bt.layer?.startsWith("B.")?"B.Cu":"F.Cu")),he),!0}let Fe=new Jt;if(qr.getMatrixAt(q,Fe),Fe.determinant()===0)return!1;let ze=o.components[q],[Ve,vt]=ie(ze.at),At=new ee(Ve,vt,(ze.layer?.startsWith("B.")?oe-1.1:_e+1.1)+Tt.componentOffset(ze.layer?.startsWith("B.")?"B.Cu":"F.Cu"));return qr.localToWorld(At),cg(ze,At,qr,q),!0},setPopulation(R){if(!(!qr||!st)&&(Qo=kP(o.components,R),zd(),An(Ii),Ji?.record?.ref)){let q=lb.get(Ji.record.ref);q!=null&&!Qo[q]&&lg()}},dispose(){kd.dispose(),$n(),Qs(new DOMException("The 3D view was closed.","AbortError")),tn.dispose();for(let[R,q]of[["pointerdown",zb],["pointermove",Gb],["pointerup",Vb],["pointercancel",qd],["lostpointercapture",qd]])F.domElement.removeEventListener(R,q,!0);d.removeEventListener("keydown",Hb,!0),document.defaultView?.removeEventListener("blur",$n),Wr&&r.onMeasurementMode?.(!1),st=!1,ja.dispose(),hn.oninput=null,Nc.dispose(),Sa.dispose(),Ic?.dispose(),Ue.dispose(),cancelAnimationFrame(sN),Xb.disconnect(),Yb?.disconnect(),$e.removeEventListener("change",Ie),$e.removeEventListener("change",Jo),$e.removeEventListener("start",Yo),$e.removeEventListener("end",Va),$r!==null&&clearTimeout($r),$r=null,$e.dispose(),lt(),Vt?.dispose(),F.domElement.removeEventListener("webglcontextlost",Qb),F.domElement.removeEventListener("webglcontextrestored",Jb),document.removeEventListener("pointerdown",e1),d.removeEventListener("keydown",t1,!0),d.removeEventListener("keydown",Nb),F.domElement.removeEventListener("pointerdown",Wb,!0),document.removeEventListener("visibilitychange",$b),al.dispose(),Jn.dispose(),zr.dispose(),ce.traverse(R=>R.shadow?.dispose?.()),A.retain(ce),Qn.forEach(R=>A.track(R)),A.track(_b),A.dispose(),ce.clear(),Ei.clear(),Zo.clear(),Ko.clear(),Sn.clear(),ai.length=0,Fs.length=0,Ir.length=0,Bd.length=0,wa.clear(),Qn.clear(),ae.clear(),ll.dispose(),F.dispose(),F.domElement.width=1,F.domElement.height=1,h.remove()}}}return fr(Ot)})()});var qN=mg(gg(),1),KN=mg(i1(),1),yg=globalThis.KiCadAnalysisData,vg=globalThis.KiCadAnalysisSpatial,n1=64*1024*1024,s1=64,o1=4e6,yN=ye=>typeof ye=="string"&&/^[a-f0-9]{64}$/i.test(ye);function vN(ye){let Z=0,xe=0,Re=/(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/y,Ne=()=>{throw new TypeError("Invalid, duplicate-key or over-limit JSON result.")},Ae=()=>{for(;Z<ye.length&&/[\x20\t\r\n]/.test(ye[Z]);)Z++},Ee=()=>{let er=Z++;for(;Z<ye.length;){let Qt=ye[Z++];if(Qt==='"')try{return JSON.parse(ye.slice(er,Z))}catch{return Ne()}if(Qt==="\\"){if(Z>=ye.length)return Ne();let fr=ye[Z++];if(fr==="u"){if(!/^[0-9a-fA-F]{4}$/.test(ye.slice(Z,Z+4)))return Ne();Z+=4}else if(!'"\\/bfnrt'.includes(fr))return Ne()}else if(Qt.charCodeAt(0)<32)return Ne()}return Ne()};function Kt(er){if(er>s1||++xe>o1)return Ne();Ae();let Qt=ye[Z];if(Qt==='"'){Ee();return}if(Qt==="{"){Z++,Ae();let rr=new Set;if(ye[Z]==="}"){Z++;return}for(;;){if(Ae(),ye[Z]!=='"')return Ne();let Ye=Ee();if(rr.has(Ye)||(rr.add(Ye),Ae(),ye[Z++]!==":"))return Ne();Kt(er+1),Ae();let Ct=ye[Z++];if(Ct==="}")return;if(Ct!==",")return Ne()}}if(Qt==="["){if(Z++,Ae(),ye[Z]==="]"){Z++;return}for(;;){Kt(er+1),Ae();let rr=ye[Z++];if(rr==="]")return;if(rr!==",")return Ne()}}Re.lastIndex=Z;let fr=Re.exec(ye)?.[0];if(!fr||fr!=="true"&&fr!=="false"&&fr!=="null"&&!Number.isFinite(Number(fr)))return Ne();Z+=fr.length}return Kt(0),Ae(),Z!==ye.length?Ne():JSON.parse(ye)}function xN(ye){if(typeof ye=="string"){if(new TextEncoder().encode(ye).length>n1)throw new RangeError("Result exceeds 64 MiB.");return vN(ye.replace(/^\uFEFF/,""))}let Z=new WeakSet,xe=0;function Re(Ae,Ee){if(Ee>s1||++xe>o1)throw new RangeError("Result exceeds depth or work limit.");if(Ae===null||typeof Ae=="string"||typeof Ae=="boolean"||typeof Ae=="number"&&Number.isFinite(Ae))return;if(!Ae||typeof Ae!="object"||Z.has(Ae))throw new TypeError("Result must be acyclic JSON data.");if(!Array.isArray(Ae)&&Object.getPrototypeOf(Ae)!==Object.prototype&&Object.getPrototypeOf(Ae)!==null)throw new TypeError("Result must use plain JSON objects.");Z.add(Ae);let Kt=Object.getOwnPropertyDescriptors(Ae);for(let[er,Qt]of Object.entries(Kt))if(!(Array.isArray(Ae)&&er==="length")){if(!Qt.enumerable||!("value"in Qt))throw new TypeError("Result must contain only JSON data properties.");Re(Qt.value,Ee+1)}if(Object.getOwnPropertySymbols(Ae).length)throw new TypeError("Result must not contain symbol keys.");if(Array.isArray(Ae)&&Object.keys(Ae).length!==Ae.length)throw new TypeError("Sparse arrays are not JSON results.");Z.delete(Ae)}Re(ye,0);let Ne=JSON.stringify(ye);if(new TextEncoder().encode(Ne).length>n1)throw new RangeError("Result exceeds 64 MiB.");return JSON.parse(Ne)}function l1(ye,Z=new WeakSet){if(!ye||typeof ye!="object"||Z.has(ye))return ye;Z.add(ye);for(let xe of Object.values(ye))l1(xe,Z);return Object.freeze(ye)}function bN(ye){if(!ye||typeof ye!="object"||Array.isArray(ye)||typeof ye.schema=="string"&&/setup/i.test(ye.schema))return!1;let Z=ye.pocket_kivi_export,xe=ye.wayricad_saved_result;if(Z&&Z.schema!=="wayricad.pocket-kivi-export/v1")throw new TypeError("Unsupported portable result metadata.");if(xe&&(xe.schema!=="wayricad.project-result/v1"||!["quick-pi","quick-si","quick-therm","quick-emerge"].includes(xe.plugin)))throw new TypeError("Unsupported project result metadata.");return!!(ye.mesh&&ye.result||ye.schema==="wayricad.quick-si/v1"&&(ye.path||ye.eye)||ye.quick_therm&&(ye.board_thermal_view||ye.thermal_network)||xe&&ye.result)}function xg(ye,{path:Z="wayricad-results.json"}={}){if(typeof Z!="string"||Z.length>4096||!Z.toLowerCase().endsWith(".json"))throw new TypeError("Choose a JSON result path.");let xe=xN(ye);if(!bN(xe))throw new TypeError("Unsupported WayriCAD result or setup file.");let Re=yg.parseJSONValue(xe,Z),Ne=vg.sourceBindings(xe),Ae={portable:xe.pocket_kivi_export??null,library:xe.wayricad_saved_result??null,libraryIntegrity:"unverified"};return l1({raw:xe,report:Re,sourceBindings:Ne,path:Z,metadata:Ae})}function bg(ye,Z){if(!yN(Z)||!ye?.sourceBindings?.length||ye.metadata?.library||ye.metadata?.portable&&ye.metadata.portable.source_state!=="saved")return"unverified";let xe=new Set(ye.sourceBindings.map(Re=>Re.sha256));return xe.size!==1?"unverified":xe.has(Z.toLowerCase())?"matching":"stale"}var _g=(ye,Z)=>yg.frameValues(ye,Z),Kc=(ye,Z,xe,Re)=>yg.probe(ye,Z,xe,Re),wg=(ye,Z,xe)=>vg.pointHistory(ye,Z,xe),a1=ye=>Array.isArray(ye)&&ye.length>=2&&ye.every((Z,xe)=>typeof Z=="number"&&Number.isFinite(Z)&&(!xe||(ye[1]>ye[0]?Z>ye[xe-1]:Z<ye[xe-1]))),$d=ye=>ye?.type==="heatmap"&&(!a1(ye.x)||!a1(ye.y))?null:vg.toSurface(ye);var u1=Object.freeze([[26,64,115],[20,136,156],[107,196,151],[255,225,112]].map(ye=>Object.freeze(ye))),c1=Object.freeze({wayricad:u1,viridis:Object.freeze([[68,1,84],[49,104,142],[53,183,121],[253,231,37]].map(ye=>Object.freeze(ye))),inferno:Object.freeze([[0,0,4],[120,28,109],[237,105,37],[252,255,164]].map(ye=>Object.freeze(ye))),grayscale:Object.freeze([[0,0,0],[85,85,85],[170,170,170],[255,255,255]].map(ye=>Object.freeze(ye)))});function ul(ye="wayricad"){if(typeof ye!="string"||!Object.hasOwn(c1,ye))throw new TypeError("Choose wayricad, viridis, inferno or grayscale palette.");return c1[ye]}function hl(ye){let Z=1/0,xe=-1/0;for(let Re of ye)Number.isFinite(Re)&&(Z=Math.min(Z,Re),xe=Math.max(xe,Re));if(!Number.isFinite(Z))return null;if(Z===xe){let Re=.5*Math.max(1,Math.abs(Z));return[Math.max(-Number.MAX_VALUE,Z-Re),Math.min(Number.MAX_VALUE,xe+Re)]}return[Z,xe]}function Eg(ye,Z){let xe=Z[1]-Z[0],Re=Number.isFinite(xe)?(ye-Z[0])/xe:(ye/2-Z[0]/2)/(Z[1]/2-Z[0]/2);return Math.max(0,Math.min(1,Re))}function Mg(ye,Z,xe=u1){let Re=Eg(ye,Z)*3,Ne=Math.min(2,Math.floor(Re)),Ae=Re-Ne;return xe[Ne].map((Ee,Kt)=>Math.round(Ee+(xe[Ne+1][Kt]-Ee)*Ae))}var _N=ye=>hl(ye.values);function wN(ye){let Z=1/0,xe=1/0,Re=-1/0,Ne=-1/0;for(let Ae of ye.points)Z=Math.min(Z,Ae[0]),Re=Math.max(Re,Ae[0]),xe=Math.min(xe,Ae[1]),Ne=Math.max(Ne,Ae[1]);return![Z,xe,Re,Ne].every(Number.isFinite)||Re<=Z||Ne<=xe?null:{x0:Z,y0:xe,x1:Re,y1:Ne}}function h1(ye,{maxSize:Z=768,maxPixelTests:xe=16e6,range:Re,palette:Ne="wayricad"}={}){if(!Number.isSafeInteger(Z)||Z<2||Z>1024||!Number.isSafeInteger(xe)||xe<1||xe>32e6)throw new RangeError("Invalid field preview budget.");if(Re&&(!Array.isArray(Re)||Re.length!==2||!Re.every(Number.isFinite)||Re[1]<=Re[0]))throw new RangeError("Invalid fixed field range.");let Ae=ul(Ne),Ee=wN(ye),Kt=Re||_N(ye);if(!Ee||!Kt)return null;let er=Ee.x1-Ee.x0,Qt=Ee.y1-Ee.y0;if(!Number.isFinite(er+Qt))throw new RangeError("Field extent exceeds the preview range.");let fr=Math.max(2,Math.round(Z*er/Math.max(er,Qt))),rr=Math.max(2,Math.round(Z*Qt/Math.max(er,Qt))),Ye=new Uint8ClampedArray(fr*rr*4),Ct=Array.from({length:256},(zt,Ot)=>Mg(Ot,[0,255],Ae)),It=0,wt=0,at=0;for(let zt=0;zt<ye.triangles.length;zt++){let Ot=ye.triangles[zt],Nt=Ot.map(We=>ye.points[We]),Xt=ye.nodal?Ot.map(We=>ye.values[We]):[ye.values[zt]];if(Xt.some(We=>!Number.isFinite(We))){at++;continue}let sr=Nt.map(We=>[(We[0]-Ee.x0)/er*fr,(We[1]-Ee.y0)/Qt*rr]),[Et,Lt,ge]=sr,ve=(Lt[1]-ge[1])*(Et[0]-ge[0])+(ge[0]-Lt[0])*(Et[1]-ge[1]);if(!Number.isFinite(ve)||Math.abs(ve)<1e-14){at++;continue}let Je=Math.max(0,Math.floor(Math.min(Et[0],Lt[0],ge[0]))),Ze=Math.min(fr-1,Math.ceil(Math.max(Et[0],Lt[0],ge[0]))),Ke=Math.max(0,Math.floor(Math.min(Et[1],Lt[1],ge[1]))),De=Math.min(rr-1,Math.ceil(Math.max(Et[1],Lt[1],ge[1])));if(It+=(Ze-Je+1)*(De-Ke+1),It>xe)throw new RangeError("Field exceeds the bounded 2D raster preview budget. Use a smaller result or 3D; full data is retained.");for(let We=Ke;We<=De;We++)for(let rt=Je;rt<=Ze;rt++){let Be=rt+.5,Le=We+.5,Qe=((Lt[1]-ge[1])*(Be-ge[0])+(ge[0]-Lt[0])*(Le-ge[1]))/ve,ht=((ge[1]-Et[1])*(Be-ge[0])+(Et[0]-ge[0])*(Le-ge[1]))/ve,bt=1-Qe-ht;if(Qe<-1e-10||ht<-1e-10||bt<-1e-10)continue;let et=ye.nodal?Qe*Xt[0]+ht*Xt[1]+bt*Xt[2]:Xt[0],dt=Ct[Math.max(0,Math.min(255,Math.round(Eg(et,Kt)*255)))],St=(We*fr+rt)*4;Ye[St]=dt[0],Ye[St+1]=dt[1],Ye[St+2]=dt[2],Ye[St+3]=255}wt++}return{bounds:Ee,range:Kt,palette:Ne,width:fr,height:rr,pixels:Ye,drawn:wt,omitted:at,pixelTests:It}}function d1(ye,Z,{maxPoints:xe=1e5}={}){let Re=[],Ne=0,Ae=0,Ee=1/0,Kt=-1/0,er=1/0,Qt=-1/0;for(let[rr,Ye]of(ye.series||[]).entries()){if(!Z.has(rr))continue;Ae+=Ye.points.length;let Ct=Math.min(Ye.points.length,Math.max(0,xe-Ne)),It=Ye.points.slice(0,Ct);Ne+=Ct;for(let wt of It)Number.isFinite(wt.x)&&(Ee=Math.min(Ee,wt.x),Kt=Math.max(Kt,wt.x)),Number.isFinite(wt.y)&&(er=Math.min(er,wt.y),Qt=Math.max(Qt,wt.y));Re.push({index:rr,name:Ye.name,points:It})}let fr=(rr,Ye)=>rr===Ye?[rr-.5*Math.max(1,Math.abs(rr)),Ye+.5*Math.max(1,Math.abs(Ye))]:[rr,Ye];return{series:Re,shown:Ne,total:Ae,limited:Ne<Ae,bounds:[Ee,Kt,er,Qt].every(Number.isFinite)?{x:fr(Ee,Kt),y:fr(er,Qt)}:null}}function p1(ye,{raster:Z,surface:xe,range:Re,allowed:Ne,layer:Ae,probe:Ee=()=>null,onProbe:Kt=()=>{},onState:er=()=>{},opacity:Qt=()=>.65,palette:fr=()=>"wayricad"}){let rr=ye.host.ownerDocument.createElement("canvas");rr.setAttribute("aria-hidden","true"),rr.style.cssText="position:absolute;inset:0;width:100%;height:100%;pointer-events:none;z-index:2";let Ye=Symbol("WayriCAD saved field"),Ct,It=null,wt=!1,at=null,zt=null,Ot=null,Nt={placed:!1,reason:"No registered field."},Xt=null,sr=De=>{Nt=De,er({...Nt})},Et=De=>{De?.setAnalysisOverlay?.(null,{owner:Ye}),at=zt=Ot=null},Lt=()=>{let De=Ee(),We=xe();if(!De||!We||!Number.isFinite(De.x)||!Number.isFinite(De.y))return[];let rt=Number.isFinite(De.z)?De.z:We.points?.[0]?.[2];return Number.isFinite(rt)?[{x:De.x,y:De.y,z:rt,label:""}]:[]};function ge(){if(It=null,wt)return;let De=ye.renderer;Ct!==De&&(Ct?.removeEventListener?.("kicad:viewframe",ve),Et(Ct),Ct=De,Ct?.addEventListener?.("kicad:viewframe",ve));let We=xe(),rt=Ae(),Be=ye.getLayers?.(),Le=Ne()&&We&&(!rt||!Be||Be.includes(rt))&&(!rt||(ye.view==="3d"?ye.getLayerState?.().visible?.includes(rt)!==!1:ye.renderer?.visibleLayers?.has(rt)!==!1));if(rr.hidden=!0,ye.view==="3d"){if(!Le||!Ct?.setAnalysisOverlay){Et(Ct),sr({placed:!1,reason:Le?"This renderer cannot register saved fields.":"Field disabled, hidden layer or unmatched source."});return}try{let nt=Re(),ft=fr();if(at!==We||zt!==nt||Ot!==ft){let it=Ct.setAnalysisOverlay(We,{owner:Ye,range:nt,palette:ft,throughBoard:!0,layer:rt});if(!it.placed){Et(Ct),sr(it);return}at=We,zt=nt,Ot=ft,sr({...it,layer:rt,view:"3d",throughBoard:!0})}Ct.setAnalysisOpacity?.(Qt(),{owner:Ye}),Ct.setAnalysisProbes?.(Lt(),{owner:Ye})}catch(nt){Et(Ct),sr({placed:!1,reason:nt.message})}return}Et(Ct);let Qe=ye.view==="pcb"&&Ct?.viewport?.camera;if(!Le||!Qe){sr({placed:!1,reason:"Field disabled, hidden layer or unmatched source."});return}let ht=Z();if(!ht){sr({placed:!1,reason:"No finite saved field coverage."});return}rr.hidden=!1;let bt=Math.min(2,globalThis.devicePixelRatio||1),et=Math.max(1,Math.round(Qe.width*bt)),dt=Math.max(1,Math.round(Qe.height*bt));(rr.width!==et||rr.height!==dt)&&(rr.width=et,rr.height=dt);let St=rr.getContext("2d");St.setTransform(1,0,0,1,0,0),St.clearRect(0,0,et,dt);let be=Qe.world_to_screen({x:ht.bounds.x0,y:ht.bounds.y0}),Oe=Qe.world_to_screen({x:ht.bounds.x1,y:ht.bounds.y1});St.setTransform(bt,0,0,bt,0,0),St.save(),St.globalAlpha=Qt(),St.translate(be.x,be.y),St.scale((Oe.x-be.x)/ht.width,(Oe.y-be.y)/ht.height),St.drawImage(ht.canvas,0,0),St.restore();let Me=Ee();if(Me&&Number.isFinite(Me.x)&&Number.isFinite(Me.y)){let nt=Qe.world_to_screen(Me);St.beginPath(),St.arc(nt.x,nt.y,7,0,2*Math.PI),St.strokeStyle="#fff",St.lineWidth=3,St.stroke(),St.strokeStyle="#073e49",St.lineWidth=1,St.stroke()}sr({placed:!0,layer:rt,view:"pcb",throughBoard:!1})}function ve(){wt||(rr.parentNode!==ye.stage&&ye.stage.append(rr),It===null&&(It=requestAnimationFrame(ge)))}function Je(De){Xt=De.button===0?{x:De.clientX,y:De.clientY,id:De.pointerId}:null}function Ze(De){let We=Xt;if(Xt=null,!We||We.id!==De.pointerId||De.button!==0||Math.hypot(We.x-De.clientX,We.y-De.clientY)>5||ye.view!=="pcb"||!Ne())return;let rt=ye.renderer?.viewport?.camera;if(!rt)return;let Be=ye.stage.getBoundingClientRect(),Le=rt.world_to_screen({x:0,y:0}),Qe=rt.world_to_screen({x:1,y:1});Qe.x===Le.x||Qe.y===Le.y||Kt((De.clientX-Be.left-Le.x)/(Qe.x-Le.x),(De.clientY-Be.top-Le.y)/(Qe.y-Le.y))}let Ke=["ready","viewchange","camerachange","layerschange"];for(let De of Ke)ye.addEventListener(De,ve);return ye.stage.addEventListener("pointerdown",Je),ye.stage.addEventListener("pointerup",Ze),ve(),{sync:ve,ownsProbe(De){return!wt&&Ne()&&ye.view==="3d"&&Ct===ye.renderer&&at===xe()&&De?.overlayOwner===Ye},getState(){return{...Nt}},dispose(){if(!wt){wt=!0,It!==null&&cancelAnimationFrame(It),Et(Ct),Ct?.removeEventListener?.("kicad:viewframe",ve);for(let De of Ke)ye.removeEventListener(De,ve);ye.stage.removeEventListener("pointerdown",Je),ye.stage.removeEventListener("pointerup",Ze),rr.remove(),rr.width=rr.height=1}}}}async function f1(ye){if(typeof ye!="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(ye)))].map(Z=>Z.toString(16).padStart(2,"0")).join("")}var m1=Object.freeze({bytes:16777216,commands:2e5,operations:2e5,segments:5e5,apertures:1024,repeats:1e4});var nL=Math.PI*2;var lL=Object.freeze({parts:16384,points:131072,pathBytes:8*1024*1024,macroCommands:32768,expressionTokens:524288});var AL=mg(b1(),1),Sg=globalThis.KiCadDesignDiff,_1=Sg.MAX_FILE_BYTES,CL=Sg.MAX_PROJECT_BYTES,RL=Sg.MAX_RENDER_PRIMITIVES;var Tg=_1,BL=8*1024*1024,zL=8*1024*1024;function IN(ye,Z){if(!(ye instanceof URL)&&(typeof ye!="string"||!ye||ye.length>8192))throw new TypeError("Supply a non-empty design URL.");let xe=new URL(ye,Z);if(!["http:","https:"].includes(xe.protocol)||xe.username||xe.password)throw new TypeError("Use an HTTP(S) design URL without embedded credentials.");return xe}function NN(ye){if(!["omit","same-origin"].includes(ye))throw new TypeError("Credentials must be omit or same-origin.");return ye}async function Ag(ye){try{await ye.body?.cancel()}catch{}}async function LN(ye,{signal:Z,credentials:xe="omit",limit:Re=Tg}={},Ne=!1){if(NN(xe),!Number.isSafeInteger(Re)||Re<=0||Re>Tg)throw new TypeError("Invalid download limit.");Z?.throwIfAborted();let Ae=await fetch(IN(ye),{signal:Z,credentials:xe,referrerPolicy:"no-referrer"});if(Z?.aborted&&(await Ag(Ae),Z.throwIfAborted()),!Ae.ok)throw await Ag(Ae),new Error(`Design request failed (${Ae.status}).`);let Ee=()=>new Error(`Design exceeds the ${Re===Tg?"256 MiB":Re+" byte"} download limit.`);if(Number(Ae.headers.get("content-length"))>Re)throw await Ag(Ae),Ee();if(!Ae.body?.getReader)throw new Error("Streaming downloads are unavailable; use loadSource.");let Kt=Ae.body.getReader(),er=new TextDecoder,Qt=0,fr="",rr=Ne?[]:null;try{for(;;){Z?.throwIfAborted();let{done:Ct,value:It}=await Kt.read();if(Z?.throwIfAborted(),Ct)break;if(Qt+=It.byteLength,Qt>Re)throw Ee();Ne?rr.push(It.slice()):fr+=er.decode(It,{stream:!0})}Ne||(fr+=er.decode())}finally{try{await Kt.cancel()}catch{}}let Ye;if(Ne){Ye=new Uint8Array(Qt);let Ct=0;for(let It of rr)Ye.set(It,Ct),Ct+=It.byteLength}return{source:fr,bytes:Ye,size:Qt,type:Ae.headers.get("content-type")||"",url:Ae.url||String(ye)}}async function w1(ye,Z={}){return(await LN(ye,Z)).source}function Cg(ye){let Z=ye?.raw,xe=Z?.schema==="wayricad.quick-si/v1"?Z.path:null,Re=xe?.net_name||(Z?.mesh&&Z?.result?Z.request?.net_name:null),Ne=typeof Re=="string"&&Re.length>0&&Re.length<=1e3?Re:null,Ae=[...new Set((Array.isArray(xe?.segments)?xe.segments:[]).map(Ee=>Ee?.item_uuid).filter(Ee=>typeof Ee=="string"&&Ee.length>0&&Ee.length<=240))];return Object.freeze({netName:Ne,objectIds:Object.freeze(Ae)})}var Zc=new WeakMap;var Rn=ye=>Number.isFinite(ye)?Number(ye.toPrecision(6)).toString():"missing",ml=(ye,Z=500)=>typeof ye=="string"?ye.slice(0,Z)+(ye.length>Z?" \u2026 [full text retained]":""):ye===null||typeof ye=="number"||typeof ye=="boolean"?ye:"[structured data retained]";function kN(ye){let Z=ye.metadata.portable,xe=Z?Object.fromEntries(["schema","tool","version","source_state","coordinate_frame","zBasis"].map(Re=>[Re,ml(Z[Re])])):null;if(xe&&Z.units&&typeof Z.units=="object"){xe.units={};let Re=0;for(let Ne in Z.units){if(++Re>32)break;Object.defineProperty(xe.units,Ne.slice(0,80),{enumerable:!0,value:ml(Z.units[Ne],80)})}}return{producer:xe,projectRecord:ye.metadata.library?{schema:ml(ye.metadata.library.schema),plugin:ml(ye.metadata.library.plugin),identity:"unverified; original record retained"}:null,sourceBindings:ye.sourceBindings.slice(0,32).map(Re=>({path:ml(Re.path,200),sha256:Re.sha256})),notes:ye.report.warnings.slice(0,24).map(Re=>ml(Re)),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 ip=["#58d8de","#f2c66d","#b59af5","#ff8f9b","#87cc8f","#9cbeff"],UN=".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}}",Pg=class extends EventTarget{constructor(Z,{theme:xe="dark",boardViewer:Re=null,palette:Ne="wayricad"}={}){if(super(),ul(Ne),!["light","dark"].includes(xe))throw new TypeError("Choose light or dark theme.");let Ae=typeof Z=="string"?globalThis.document?.querySelector(Z):Z;if(!Ae?.ownerDocument)throw new TypeError("Choose a results mount element.");if(Zc.has(Ae))throw new Error("This container already has a viewer.");this.host=Ae,this.doc=Ae.ownerDocument,this.theme=xe,this.ticket=0,this.plotTicket=0,this.model=null,this.mode="2d",this.palette=Ne,this.opacity=.65,this.overlayWanted=!1,this.sourceState="unverified",this.sourceSnapshot=null,this.selected=new Set,this.stops=[],this.make=(wt,at)=>{let zt=this.doc.createElement(wt);return at!==void 0&&(zt.textContent=String(at)),zt};let Ee=this.make;this.root=Ee("section"),this.root.className="kw-results",this.root.dataset.theme=xe,this.root.setAttribute("aria-label","WayriCAD saved results");let Kt=Ee("style",UN),er=Ee("strong","WayriCAD \xB7 saved results"),Qt=Ee("div");Qt.className="kw-result-tools",this.plotSelect=Ee("select"),this.plotSelect.setAttribute("aria-label","Saved result plot"),this.viewSelect=Ee("select"),this.viewSelect.setAttribute("aria-label","Result view");for(let[wt,at]of[["2d","2D field / graph"],["3d","3D saved field"]]){let zt=Ee("option",at);zt.value=wt,this.viewSelect.append(zt)}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=Ee("select"),this.layerSelect.setAttribute("aria-label","Saved result layer"),this.layerSelect.disabled=!0,this.paletteSelect=Ee("select"),this.paletteSelect.setAttribute("aria-label","Saved field palette");for(let[wt,at]of[["wayricad","WayriCAD"],["viridis","Viridis (4 stops)"],["inferno","Inferno (4 stops)"],["grayscale","Grayscale"]]){let zt=Ee("option",at);zt.value=wt,this.paletteSelect.append(zt)}this.paletteSelect.value=Ne,this.paletteSelect.disabled=!0,this.paletteSelect.onchange=()=>{try{this.setPalette(this.paletteSelect.value)}catch(wt){this.paletteSelect.value=this.palette,this.fail(wt)}},Qt.append(this.plotSelect,this.layerSelect,this.viewSelect,this.paletteSelect,this.fitButton,this.sourceButton,this.routeButton,this.downloadButton),this.status=Ee("p","Open a saved WayriCAD result JSON."),this.status.className="kw-result-status",this.status.setAttribute("role","status"),this.sourceNote=Ee("p","No PCB registration. Independent result plots do not establish engineering validity."),this.sourceNote.className="kw-result-small",this.viewport=Ee("div"),this.viewport.className="kw-result-viewport",this.canvas=Ee("canvas"),this.canvas.setAttribute("role","img"),this.canvas.setAttribute("aria-label","Saved numerical result plot; use the probe readout for values"),this.threeHost=Ee("div"),this.threeHost.className="kw-result-three",this.threeHost.hidden=!0,this.viewport.append(this.canvas,this.threeHost),this.legend=Ee("p"),this.legend.className="kw-result-small",this.colorBar=Ee("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=Ee("p"),this.boardStatus.className="kw-result-small",this.boardStatus.setAttribute("role","status"),this.probe=Ee("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=Ee("label","Saved frame"),this.frameRow.className="kw-result-controls",this.frame=Ee("input"),this.frame.type="range",this.frame.min="0",this.frame.step="1",this.frame.setAttribute("aria-label","Saved thermal frame"),this.frameTime=Ee("span"),this.frameRow.append(this.frame,this.frameTime),this.frameRow.hidden=!0,this.series=Ee("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 fr=Ee("div");fr.className="kw-result-controls",this.overlayInput=Ee("input"),this.overlayInput.type="checkbox",this.overlayInput.setAttribute("aria-label","Show result on matching PCB");let rr=Ee("label");rr.append(this.overlayInput,Ee("span","Show on matching PCB")),this.alpha=Ee("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"),fr.append(rr,this.alpha);let Ye=Ee("details"),Ct=Ee("summary","Producer, assumptions & display limits");this.metadata=Ee("pre"),Ye.append(Ct,this.metadata);let It=Ee("details");It.append(Ee("summary","Complete numerical data")),this.dataPath=Ee("p"),this.dataPath.className="kw-result-data-path",this.dataList=Ee("div"),this.dataList.className="kw-result-data",It.append(this.dataPath,this.dataList),this.root.append(Kt,er,Qt,this.status,this.sourceNote,this.viewport,this.colorBar,this.legend,this.probe,this.historyButton,this.frameRow,this.series,this.seriesMore,fr,Ye,It),Ae.append(this.root),Zc.set(Ae,this),this.plotSelect.onchange=()=>this.setPlot(Number(this.plotSelect.value)),this.viewSelect.onchange=()=>{this.setView(this.viewSelect.value).catch(wt=>this.fail(wt))},this.frame.oninput=()=>{try{this.setFrame(Number(this.frame.value))}catch(wt){this.frame.value=String(this.plot?.frameIndex||0),this.fail(wt)}},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=wt=>this.probeAt(wt),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(wt=>{this.visible=wt.some(at=>at.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(Re)}button(Z,xe){let Re=this.make("button",Z);return Re.type="button",Re.onclick=()=>{try{xe()}catch(Ne){this.fail(Ne)}},Re}assertActive(){if(this.disposed)throw new Error("Results viewer is disposed.")}emit(Z,xe){this.dispatchEvent(new CustomEvent(Z,{detail:xe}))}fail(Z){this.disposed||(this.status.textContent=Z.message,this.emit("error",{message:Z.message}))}beginLoad(Z){this.assertActive(),Z?.throwIfAborted(),this.downloadController?.abort();let xe=this.downloadController=new AbortController,Re=++this.ticket,Ne=()=>xe.abort(Z.reason);return Z?.addEventListener("abort",Ne,{once:!0}),{ticket:Re,controller:xe,current:()=>!this.disposed&&this.ticket===Re,check:()=>{Z?.throwIfAborted(),xe.signal.throwIfAborted()},cleanup:()=>Z?.removeEventListener("abort",Ne)}}async commitResult(Z,xe,Re){Re.check();let Ne=xg(Z,{path:xe}),Ae=await this.assessSource(Ne);return Re.current()?(Re.check(),this.scene?.dispose(),this.scene=null,this.boardLayer?.dispose(),this.boardLayer=null,this.model=Ne,this.downloadButton.disabled=!1,this.mode="2d",this.plotSelect.replaceChildren(),this.sourceLinks=Cg(Ne),Ne.report.plots.forEach((Ee,Kt)=>{let er=this.make("option",Ee.title);er.value=String(Kt),this.plotSelect.append(er)}),this.metadata.textContent=JSON.stringify(kN(Ne),null,2),this.rawPath=[],this.rawPage=0,this.showRaw(),this.setPlot(0),this.applyAssessment(Ae),this.emit("ready",{path:xe,plots:Ne.report.plots.length,sourceState:this.sourceState}),!0):!1}async load(Z,{path:xe="wayricad-results.json",signal:Re}={}){let Ne=this.beginLoad(Re);try{return await this.commitResult(Z,xe,Ne)}catch(Ae){if(!Ne.current()&&!Re?.aborted)return!1;throw Ae}finally{Ne.cleanup()}}async loadURL(Z,{signal:xe,credentials:Re="omit",path:Ne}={}){let Ae=this.beginLoad(xe);try{let Ee=new URL(Z,this.doc.baseURI),Kt=await w1(Ee.href,{signal:Ae.controller.signal,credentials:Re,limit:64*1024*1024});return Ae.current()?await this.commitResult(Kt,Ne||Ee.pathname.split("/").at(-1)||"wayricad-results.json",Ae):!1}catch(Ee){if(!Ae.current()&&!xe?.aborted)return!1;throw Ee}finally{Ae.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(Z){if(this.assertActive(),ul(Z),this.palette===Z)return Z;if(this.scene){if(typeof this.scene.setPalette!="function")throw new Error("Use a matching library distribution to change 3D palettes.");this.scene.setPalette(Z),this.scene.setProbes?.(this.probePins())}return this.palette=Z,this.paletteSelect.value=Z,this.cache=null,this.updateColorBar(),this.boardLayer?.sync(),this.invalidate(),this.emit("palettechange",{palette:Z}),Z}updateColorBar(){let Z=this.colorRange;this.colorBar.hidden=!this.surface||!Z,Z&&(this.colorBar.style.background="linear-gradient(to right,"+ul(this.palette).map(xe=>"rgb("+xe.join(",")+")").join(",")+")",this.colorBar.setAttribute("aria-label",this.palette+" palette, "+Rn(Z[0])+" to "+Rn(Z[1])+" "+(this.plot?.unit||"")+". Missing values are transparent."))}getResultLayers(){return this.assertActive(),[...new Set((this.model?.report.plots||[]).map(Z=>Z.layerName).filter(Boolean))]}setLayer(Z){this.assertActive();let xe=this.model?.report.plots||[],Re=this.plot?.title?.replace(/ · [^·]+$/,""),Ne=xe.map((Ee,Kt)=>({p:Ee,i:Kt})).filter(({p:Ee})=>Ee.layerName===Z),Ae=Ne.find(({p:Ee})=>Ee.type===this.plot?.type&&Ee.title.replace(/ · [^·]+$/,"")===Re)||Ne[0];if(!Ae)throw new RangeError("Choose a saved result layer.");return this.setPlot(Ae.i)}setBoardOverlay(Z){if(this.assertActive(),typeof Z!="boolean")throw new TypeError("Choose true or false for the board overlay.");return this.overlayWanted=Z&&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(Z){if(this.assertActive(),!this.model)return!1;let xe=this.model.report.plots[Z];if(!xe){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=Z,this.plot=xe,this.plotSelect.value=String(Z),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(xe),this.selected=new Set((xe.series||[]).slice(0,/eye/i.test(xe.title)?32:4).map((Re,Ne)=>Ne)),this.updatePlot(),this.updateSeries(),this.status.textContent=xe.title,this.emit("plotchange",{index:Z,title:xe.title}),!0}updatePlot(Z){let xe=this.getResultLayers();this.layerSelect.replaceChildren(...xe.map(Re=>{let Ne=this.make("option",Re);return Ne.value=Re,Ne})),this.layerSelect.disabled=!xe.length,this.layerSelect.value=this.plot?.layerName||"",this.fitButton.disabled=this.mode!=="3d",this.viewSelect.value=this.mode,this.surface=Z===void 0?$d(this.plot):Z,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?Rn(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(Z){if(Z?.frames&&Z.cells&&Number.isSafeInteger(Z.layerIndex)){let xe=Z.cells.length,Re=Z.layerIndex*xe;function*Ne(){for(let Ae of Z.frames)for(let Ee=0;Ee<xe;Ee++)yield Ae.temperatures_c?.[Re+Ee]}return hl(Ne())}if(Z?.type==="mesh-field")return hl(Z.values);if(Z?.type==="heatmap"){function*xe(){for(let Re of Z.values)yield*Re}return hl(xe())}return null}setFrame(Z){if(this.assertActive(),!this.plot?.frames||!Number.isSafeInteger(Z)||Z<0||Z>=this.plot.frames.length)throw new RangeError("Choose a saved thermal frame.");let xe={...this.plot,frameIndex:Z,values:_g(this.plot,Z)},Re=$d(xe);if(this.scene)try{this.scene.setSurface(Re)}catch(Ne){if(!["NO_SAVED_FIELD_VALUES","SAVED_Z_REQUIRED"].includes(Ne.code))throw Ne;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=xe,this.cache=null,this.updatePlot(Re),this.lastProbe&&this.showProbe(Kc(this.plot,this.lastProbe.x,this.lastProbe.y)),this.emit("framechange",{index:Z,time:this.plot.frames[Z].time_s})}async setView(Z){if(this.assertActive(),!["2d","3d"].includes(Z))throw new TypeError("Choose 2d or 3d results.");let xe=++this.plotTicket;if(Z==="2d")return this.scene?.dispose(),this.scene=null,this.mode=Z,this.viewSelect.value=Z,this.updatePlot(),Z;if(!this.surface?.zKnown)throw new Error("This field has no explicit saved elevation. Use its 2D plot.");let Re=this.surface,Ne=await Promise.resolve().then(()=>(i_(),r_)),Ae=await Ne.loadThree();if(this.disposed||xe!==this.plotTicket||Re!==this.surface)return!1;if(typeof Ae.mountSavedResult3D!="function")throw new Error("This renderer does not support saved-result 3D. Use the matching library distribution.");let Ee=Ae.mountSavedResult3D(this.threeHost,Re,{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:Kt=>this.showProbe(Kt),onDiagnostics:Kt=>{this.disposed||(this.legend.textContent=Kt.join(" "))}});if(this.disposed||xe!==this.plotTicket)return Ee.dispose(),!1;if(Ee.unavailable)throw Ee.dispose(),new Error(Ee.diagnostic?.message||Ee.diagnostic||"Saved field 3D is unavailable.");return this.scene?.dispose(),this.scene=Ee,Ee.setOpacity(this.opacity),Ee.setProbes?.(this.probePins()),this.mode="3d",this.viewSelect.value="3d",this.updatePlot(),Z}setTheme(Z){if(this.assertActive(),!["light","dark"].includes(Z))throw new TypeError("Choose light or dark theme.");this.theme=Z,this.root.dataset.theme=Z,this.scene?.setTheme(Z==="dark"),this.invalidate()}setOpacity(Z){if(this.assertActive(),!Number.isFinite(Z)||Z<0||Z>1)throw new RangeError("Opacity must be 0\u20131.");return this.opacity=Z,this.alpha.value=String(Math.round(Z*100)),this.scene?.setOpacity(Z),this.boardLayer?.sync(),this.invalidate(),Z}attachBoard(Z){if(this.assertActive(),this.boardLayer?.dispose(),this.boardLayer=null,this.stopBoard?.(),this.boardViewer=Z,this.sourceHashCache=null,this.sourceSnapshot=null,this.sourceState="unverified",Z){let xe=()=>{this.checkSource().catch(Ae=>this.fail(Ae))};Z.addEventListener("ready",xe);let Re=Ae=>this.receiveSourceSelection(Ae.detail),Ne=Ae=>{let Ee=Ae.detail?.probe;if(this.sourceReady()&&this.overlayInput.checked&&this.boardLayer?.ownsProbe(Ee)&&[Ee.x,Ee.y,Ee.z,Ee.value].every(Number.isFinite)){let{overlayOwner:Kt,...er}=Ee;this.showProbe(er)}};Z.addEventListener("select",Re),Z.addEventListener("analysisprobe",Ne),this.stopBoard=()=>{Z.removeEventListener("ready",xe),Z.removeEventListener("select",Re),Z.removeEventListener("analysisprobe",Ne)}}else this.stopBoard=null;this.model&&this.checkSource().catch(xe=>this.fail(xe))}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 Z=this.boardViewer.getNets().filter(xe=>xe.name===this.sourceLinks.netName);return Z.length===1?this.boardViewer.selectNet(Z[0].id,{locate:!0}):!1}locateSource(){if(this.assertActive(),!this.sourceReady())return!1;for(let Z of this.sourceLinks?.objectIds||[])if(this.boardViewer.selectObject(Z,{locate:!0}))return!0;return!1}probeSourcePoint(Z,xe){!this.sourceReady()||!this.surface||this.showProbe(Kc(this.plot,Z,xe))}receiveSourceSelection(Z){if(!this.sourceReady()||!this.model)return;let xe=this.boardViewer?.getSelectionPosition?.();xe&&(!this.overlayInput.checked&&xe.layer&&xe.layer!==this.plot?.layerName&&this.getResultLayers().includes(xe.layer)&&this.setLayer(xe.layer),this.probeSourcePoint(xe.x,xe.y));let Re=Z?.item||{},Ne=!!(this.sourceLinks?.objectIds.includes(Re.uuid||Re.id)||this.sourceLinks?.netName&&Re.netName===this.sourceLinks.netName);this.viewport.style.outline=Ne?"2px solid var(--accent)":"",Ne&&(this.status.textContent=(this.plot?.title||"Saved result")+" \xB7 source selection matched",this.emit("sourceselection",{matched:!0,netName:Re.netName||null,objectId:Re.uuid||Re.id||null}))}async assessSource(Z){let xe=this.boardViewer,Re=xe?.source;if(!Z||xe?.kind!=="pcb"||typeof Re!="string")return{state:"unverified",source:null,viewer:xe};if(!globalThis.crypto?.subtle)return{state:"unverified",source:Re,viewer:xe,reason:"PCB registration requires HTTPS or localhost; independent saved results remain available."};(this.sourceHashCache?.viewer!==xe||this.sourceHashCache?.source!==Re)&&(this.sourceHashCache={viewer:xe,source:Re,promise:f1(Re)});let Ne=await this.sourceHashCache.promise;return{state:xe.source===Re?bg(Z,Ne):"unverified",source:Re,viewer:xe}}applyAssessment(Z){this.boardLayer?.dispose(),this.boardLayer=null,this.overlayInput.checked=this.overlayWanted,this.sourceState=Z.viewer===this.boardViewer&&Z.viewer?.source===Z.source?Z.state:"unverified",this.sourceSnapshot=this.sourceState==="matching"?Z.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.":Z.reason||"Unverified PCB association \xB7 board overlay is disabled.",this.sourceState==="matching"&&(this.boardLayer=p1(this.boardViewer,{surface:()=>this.surface,range:()=>this.colorRange,palette:()=>this.palette,probe:()=>this.lastProbe,onProbe:(xe,Re)=>this.probeSourcePoint(xe,Re),onState:xe=>{this.boardStatus.textContent=xe.placed?xe.view==="3d"?"Registered on 3D PCB \xB7 "+(xe.layer||"saved elevation")+" \xB7 visible through board and components":"Registered on PCB \xB7 "+(xe.layer||"saved XY field"):xe.reason},raster:()=>{try{return this.getRaster()}catch(xe){return this.fail(xe),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 Z=this.model,xe=this.ticket,Re=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 Ne=await this.assessSource(Z);return this.disposed||this.model!==Z||this.ticket!==xe||this.sourceTicket!==Re?"unverified":(this.applyAssessment(Ne),this.sourceState)}updatePlotIfLoaded(){this.plot&&this.updatePlot(this.surface)}getRaster(){if(!this.surface)return null;if(this.cache)return this.cache;let Z=h1(this.surface,{range:this.colorRange||void 0,palette:this.palette});if(!Z)return null;let xe=this.make("canvas");xe.width=Z.width,xe.height=Z.height;let Re=xe.getContext("2d"),Ne=Re.createImageData(Z.width,Z.height);return Ne.data.set(Z.pixels),Re.putImageData(Ne,0,0),this.cache={...Z,canvas:xe},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(Z){this.fail(Z)}}))}draw(){if(this.mode==="3d")return;let Z=this.viewport.getBoundingClientRect(),xe=Math.max(1,Z.width),Re=Math.max(1,Z.height),Ne=Math.min(2,globalThis.devicePixelRatio||1);this.canvas.width=Math.max(1,Math.round(xe*Ne)),this.canvas.height=Math.max(1,Math.round(Re*Ne));let Ae=this.canvas.getContext("2d");if(Ae.setTransform(Ne,0,0,Ne,0,0),Ae.fillStyle=this.theme==="dark"?"#1b2d3b":"#eef4f8",Ae.fillRect(0,0,xe,Re),this.mapping=null,!this.plot)return;if(this.surface){let wt=this.getRaster();if(!wt){this.legend.textContent="No finite saved field coverage.";return}let at=wt.bounds,zt=Math.min((xe-44)/(at.x1-at.x0),(Re-44)/(at.y1-at.y0)),Ot=(at.x1-at.x0)*zt,Nt=(at.y1-at.y0)*zt,Xt=(xe-Ot)/2,sr=(Re-Nt)/2;if(Ae.globalAlpha=this.opacity,Ae.drawImage(wt.canvas,Xt,sr,Ot,Nt),Ae.globalAlpha=1,this.lastProbe&&Number.isFinite(this.lastProbe.x)&&Number.isFinite(this.lastProbe.y)){let Et=Xt+(this.lastProbe.x-at.x0)*zt,Lt=sr+(this.lastProbe.y-at.y0)*zt;Ae.beginPath(),Ae.arc(Et,Lt,6,0,Math.PI*2),Ae.strokeStyle="#fff",Ae.lineWidth=3,Ae.stroke(),Ae.strokeStyle="#073e49",Ae.lineWidth=1,Ae.stroke()}this.mapping={x:Xt,y:sr,width:Ot,height:Nt,bounds:at,field:!0},this.legend.textContent=Rn(wt.range[0])+" \u2013 "+Rn(wt.range[1])+" "+(this.plot.unit||"")+" \xB7 "+wt.drawn+" supplied triangles \xB7 "+wt.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 Ee=d1(this.plot,this.selected);if(this.chartData=Ee,!Ee.bounds){this.legend.textContent="No finite selected samples.";return}let{x:[Kt,er],y:[Qt,fr]}=Ee.bounds,rr=60,Ye=18,Ct=Math.max(1,xe-78),It=Math.max(1,Re-62);Ae.strokeStyle=this.theme==="dark"?"#7891a3":"#5a7083",Ae.beginPath(),Ae.moveTo(rr,Ye),Ae.lineTo(rr,Ye+It),Ae.lineTo(rr+Ct,Ye+It),Ae.stroke();for(let wt of Ee.series){Ae.strokeStyle=ip[wt.index%ip.length],Ae.lineWidth=1.4,Ae.beginPath();let at=!1;for(let zt of wt.points){if(!Number.isFinite(zt.x)||!Number.isFinite(zt.y)){at=!1;continue}let Ot=rr+(zt.x-Kt)/(er-Kt)*Ct,Nt=Ye+It-(zt.y-Qt)/(fr-Qt)*It;at?Ae.lineTo(Ot,Nt):(Ae.moveTo(Ot,Nt),at=!0)}if(Ae.stroke(),wt.points.length===1&&Number.isFinite(wt.points[0].y)){let zt=wt.points[0];Ae.fillStyle=Ae.strokeStyle,Ae.fillRect(rr+(zt.x-Kt)/(er-Kt)*Ct-2,Ye+It-(zt.y-Qt)/(fr-Qt)*It-2,4,4)}}Ae.fillStyle=this.theme==="dark"?"#edf4f8":"#152534",Ae.font="11px system-ui",Ae.fillText(Rn(fr),4,Ye+10),Ae.fillText(Rn(Qt),4,Ye+It),Ae.fillText(Rn(Kt),rr,Ye+It+17),Ae.textAlign="right",Ae.fillText(Rn(er),rr+Ct,Ye+It+17),Ae.textAlign="center",Ae.fillText(this.plot.xLabel||"Saved axis",rr+Ct/2,Re-7),Ae.textAlign="left",this.mapping={x:rr,y:Ye,width:Ct,height:It,bounds:{x0:Kt,x1:er,y0:Qt,y1:fr},field:!1},this.legend.textContent=Ee.series.length+" of "+this.plot.series.length+" saved series selected \xB7 "+Ee.shown+" of "+Ee.total+" selected saved samples shown"+(Ee.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 Z=this.plot?.series||[],xe=(this.seriesPage||0)*20;for(let Re=xe;Re<Math.min(Z.length,xe+20);Re++){let Ne=this.make("label"),Ae=this.make("input");Ae.type="checkbox",Ae.checked=this.selected.has(Re),Ae.onchange=()=>{Ae.checked?this.selected.add(Re):this.selected.delete(Re),this.invalidate()},Ne.append(Ae,this.make("span",Z[Re].name)),Ne.style.borderBottom="2px solid "+ip[Re%ip.length],this.series.append(Ne)}if(xe>0){let Re=this.button("Previous series",()=>{this.seriesPage--,this.updateSeries()});this.series.append(Re)}this.seriesMore.hidden=xe+20>=Z.length}probeAt(Z){if(!this.mapping||!this.plot)return;let xe=this.canvas.getBoundingClientRect(),Re=this.mapping,Ne=Z.clientX-xe.left,Ae=Z.clientY-xe.top;if(Ne<Re.x||Ne>Re.x+Re.width||Ae<Re.y||Ae>Re.y+Re.height)return;let Ee=Re.bounds.x0+(Ne-Re.x)/Re.width*(Re.bounds.x1-Re.bounds.x0),Kt=Re.field?Re.bounds.y0+(Ae-Re.y)/Re.height*(Re.bounds.y1-Re.bounds.y0):Re.bounds.y1-(Ae-Re.y)/Re.height*(Re.bounds.y1-Re.bounds.y0),er=[...this.selected][0];if(this.showProbe(Kc(this.plot,Ee,Kt,this.plot.series?.[er]?.name)),this.sourceReady()&&this.sourceLinks?.netName){let Qt=this.boardViewer.getNets().filter(fr=>fr.name===this.sourceLinks.netName);Qt.length===1&&this.boardViewer.selectNet(Qt[0].id,{locate:!1})}}probePins(){let Z=this.lastProbe;if(!Z||!this.surface||!Number.isFinite(Z.x)||!Number.isFinite(Z.y))return[];let xe=Number.isFinite(Z.z)?Z.z:this.surface.points[0]?.[2];return Number.isFinite(xe)?[{x:Z.x,y:Z.y,z:xe}]:[]}showProbe(Z){this.lastProbe=Z,this.scene?.setProbes?.(this.probePins()),this.boardLayer?.sync(),this.invalidate(),this.probe.textContent=Z?(Z.name||this.plot?.title||"Saved field")+" \xB7 "+Rn(Z.value)+" "+(Z.unit||"")+" \xB7 x "+Rn(Z.x)+(Z.y!==void 0?", y "+Rn(Z.y):"")+" \xB7 "+(Z.method||"Saved field"):"No saved value at this position.",this.historyButton.hidden=!Z||!this.plot?.frames||!Number.isFinite(Z.y),this.emit("probe",{...Z})}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 Z=wg(this.plot,this.lastProbe.x,this.lastProbe.y);Z&&(this.scene?.dispose(),this.scene=null,this.historySource=this.plot,this.mode="2d",this.viewSelect.value="2d",this.plot=Z,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=Z.title)}showRaw(){if(this.dataList.replaceChildren(),!this.model)return;let Z=this.model.raw;for(let Ee of this.rawPath)Z=Z?.[Ee];if(this.dataPath.textContent="root"+this.rawPath.map(Ee=>"["+JSON.stringify(String(Ee).slice(0,120))+"]").join(""),this.rawPath.length&&this.dataList.append(this.button("Up one level",()=>{this.rawPath.pop(),this.rawPage=0,this.showRaw()})),Z===null||typeof Z!="object"){if(typeof Z=="string"){let Ee=(this.rawPage||0)*4096;this.dataList.append(this.make("pre",Z.slice(Ee,Ee+4096))),Ee&&this.dataList.append(this.button("Previous text block",()=>{this.rawPage--,this.showRaw()})),Ee+4096<Z.length&&this.dataList.append(this.button("Next text block",()=>{this.rawPage++,this.showRaw()})),this.dataList.append(this.make("small",Math.min(Ee+4096,Z.length)+" of "+Z.length+" characters"))}else this.dataList.append(this.make("pre",JSON.stringify(Z)));return}let xe=Array.isArray(Z),Re=xe?null:Object.keys(Z),Ne=xe?Z.length:Re.length,Ae=(this.rawPage||0)*100;for(let Ee=Ae;Ee<Math.min(Ne,Ae+100);Ee++){let Kt=xe?String(Ee):Re[Ee],er=Z[Kt],Qt=String(Kt).slice(0,120)+": "+(er&&typeof er=="object"?Array.isArray(er)?"["+er.length+" saved entries]":"{structured fields}":typeof er=="string"?JSON.stringify(er.slice(0,180))+(er.length>180?" \u2026":""):JSON.stringify(er));this.dataList.append(this.button(Qt,()=>{this.rawPath.push(Kt),this.rawPage=0,this.showRaw()}))}Ae&&this.dataList.append(this.button("Previous entries",()=>{this.rawPage--,this.showRaw()})),Ae+100<Ne&&this.dataList.append(this.button("Next entries",()=>{this.rawPage++,this.showRaw()})),this.dataList.append(this.make("small",Math.min(Ae+100,Ne)+" of "+Ne+" entries \xB7 full arrays retained."))}download(){if(this.assertActive(),!this.model)return;let Z=URL.createObjectURL(new Blob([JSON.stringify(this.model.raw)+`
`],{type:"application/json"})),xe=this.make("a");xe.href=Z,xe.download="wayricad-results.json",xe.click(),setTimeout(()=>URL.revokeObjectURL(Z),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(),Zc.get(this.host)===this&&Zc.delete(this.host),this.boardViewer=null)}};export{Pg as WayriCADResultsViewer,bg as classifyWayriCADSource,$d as createWayriCADSurface,_g as getWayriCADFrame,wg as getWayriCADPointHistory,Cg as getWayriCADSourceLinks,xg as parseWayriCADResults,Kc as probeWayriCADPlot};
/*! 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. */