@codrihub/memora 1.3.1 → 1.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/assets/app.js CHANGED
@@ -3375,7 +3375,7 @@ button.ov-name:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
3375
3375
  `,vo={folder:'<svg class="cc-i" viewBox="0 0 24 24" aria-hidden="true"><path d="M3.5 7.5a2 2 0 0 1 2-2h4l2 2.5h7a2 2 0 0 1 2 2v7.5a2 2 0 0 1-2 2h-13a2 2 0 0 1-2-2z"/></svg>',link:'<svg class="cc-i" viewBox="0 0 24 24" aria-hidden="true"><path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1"/><path d="M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"/></svg>',agent:'<svg class="cc-i" viewBox="0 0 24 24" aria-hidden="true"><rect x="5" y="8" width="14" height="11" rx="3"/><path d="M12 4v4M9.5 13h0M14.5 13h0M3 13v2M21 13v2"/></svg>',pulse:'<svg class="cc-i" viewBox="0 0 24 24" aria-hidden="true"><path d="M3 12h4l2.5-6 5 12 2.5-6h4"/></svg>',clock:'<svg class="cc-i" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="8"/><path d="M12 8v4l2.5 2"/></svg>'},ZC=5,JC=/^(create|save|patch|move|rename|delete|soft_delete|merge|duplicate|batch_create|bulk_|restore|add_tags|remove_tags|set_tags|template_create|import)/,og=8,QC=24*3600;function fw(n,e){return n<og?`<div class="ov-rest">${b(e)}</div>`:""}const rg=5,lg=5;let xo=[],mw=new Set,bo=[],cg="",Fp=0,dg=!1,vc=!1,gw=0;async function vw(){_a(),Wd(),it("ov-home-css",jC);const n=document.getElementById("view-home");if(n){if(!n.querySelector("#ovVault")){const e=D.me&&(D.me.user||D.me.username)||"",t=(a,s,o,r)=>`<button type="button" class="ov-kpi" id="${a}" data-go="${s}"><span class="ov-kpi-k"><span class="ic">${o}</span>${r}</span>
3376
3376
  <span class="ov-kpi-m"><span class="ov-kpi-v" data-v>0</span><span class="ov-kpi-viz" data-viz></span></span>
3377
3377
  <span class="ov-kpi-h" data-h>&nbsp;</span></button>`;n.innerHTML=`<div class="cc ov">
3378
- <header class="ov-head"><div class="t"><h1>${b(eR())}${e?", "+b(e):""}</h1><p id="ovSub">&nbsp;</p></div>
3378
+ <header class="ov-head"><div class="t"><h1>${b(e4())}${e?", "+b(e):""}</h1><p id="ovSub">&nbsp;</p></div>
3379
3379
  <div class="ov-acts"><button type="button" class="ov-ibtn" id="ovReload" aria-label="Refresh" title="Refresh">${pe.refresh}</button>
3380
3380
  <button type="button" class="btn" id="ovNew">${pe.plus}New node</button>
3381
3381
  <button type="button" class="btn primary" id="ovBrain">Open the brain ${pe.arrow}</button></div></header>
@@ -3397,7 +3397,7 @@ button.ov-name:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
3397
3397
  <section class="ov-card ov-health" aria-labelledby="ovHealthT"><div class="ov-card-h"><h2 id="ovHealthT">System status</h2><span class="grow"></span>
3398
3398
  <span id="ovHealthPill"></span></div><div class="ov-sys" id="ovHealth"></div></section>
3399
3399
  </div>
3400
- </div>`,U("#ovBrain").onclick=()=>he.go("brain"),U("#ovNew").onclick=()=>he.openNewNote(),U("#ovNodes").onclick=()=>he.go("vault"),U("#ovRecentAll").onclick=()=>he.go("vault"),U("#ovKeys").onclick=()=>he.go("keys"),U("#ovAll").onclick=()=>he.go("logs"),n.querySelectorAll(".ov-kpi[data-go]").forEach(a=>a.onclick=()=>he.go(a.dataset.go));const i=U("#ovReload");i.onclick=()=>{if(i.classList.contains("busy"))return;i.classList.add("busy"),i.setAttribute("aria-busy","true"),i.title="Refreshing…";const a=new Promise(s=>setTimeout(s,500));Promise.all([he.loadCore().then(()=>xw()),a]).finally(()=>{i.classList.remove("busy"),i.removeAttribute("aria-busy"),i.title="Refresh"})},ar(U("#ovAct"),a=>bo.find(s=>s.id===a))}Dl(n,()=>{cg=Bl.state,Fp=Bl.clients;const e=[zf(i=>{Fd(bo,i,500),tR()}),jn("connection",i=>{cg=i,Hp()}),jn("presence",i=>{Fp=i,Hp()})],t=window.setInterval(()=>{fg(),gg()},2e3);return()=>{e.forEach(i=>i()),clearInterval(t)}}),Sw(),mg(),Hp(),await xw()}}function eR(){const n=new Date().getHours();return n<5?"Good night":n<12?"Good morning":n<18?"Good afternoon":"Good evening"}function tR(){dg||(dg=!0,setTimeout(()=>{dg=!1,fg(),gg(),mg()},150))}async function xw(){const n=++gw,[e,t,i]=await Promise.all([tt("/api/keys").catch(()=>null),Ud("1d",500).catch(()=>[]),tt("/api/oauth/clients").catch(()=>null)]);n===gw&&(e&&(xo=Array.isArray(e)?e:e.keys||[]),Ku(xo),mw=new Set((i?.connections||[]).map(a=>a.key_id)),bo=t,vc=!0,Sw(),fg(),mg(),gg(),Hp())}const nR=/(<time data-ts="[^"]*">)[^<]*(<\/time>)/g;function wr(n,e){const t=e.replace(nR,"$1$2");if(n.dataset.html===t){const i=Array.from(e.matchAll(/<time data-ts="[^"]*">([^<]*)<\/time>/g),a=>a[1]);return n.querySelectorAll("time[data-ts]").forEach((a,s)=>{const o=i[s];o!==void 0&&a.innerHTML!==o&&(a.innerHTML=o)}),!1}return n.dataset.html=t,n.innerHTML=e,!0}function pg(n){return`<time data-ts="${n}">${b(iR(n))}</time>`}function iR(n){const e=Fn(n);return e==="now"?"just now":e==="-"?e:e+" ago"}function aR(n){const e=n.replace(/[\\/]+$/,"").search(/[^\\/]+$/),t=e>0?n.slice(0,e):"",i=e>0?n.slice(e):n;return`<span class="ov-path" title="${O(n)}"><span class="h">${b(t)}</span><span class="e">${b(i)}</span></span>`}function hg(n,e,t,i=""){return`<div class="ov-empty"><span class="ov-tile">${n}</span><b>${e}</b><p>${t}</p>${i}</div>`}function bw(){const n=new Map;for(const e of Mn()){const t=(e.folder||"Root").split("/")[0]||"Root";n.set(t,(n.get(t)||0)+1)}return[...n.entries()].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0]))}function yw(n){return An(n==="Root"?"":n)}function Bp(n,e,t,i){const a=document.getElementById(n);a&&(a.querySelector("[data-v]").textContent=e.toLocaleString(),wr(a.querySelector("[data-viz]"),t),wr(a.querySelector("[data-h]"),i))}function ug(n,e,t){const i=Date.now()/1e3,a=new Array(e).fill(0);for(const s of n){const o=Math.floor((i-s)/t);o>=0&&o<e&&a[e-1-o]++}return a}function ww(n,e){const t=Math.max(...n);return t?`<span class="ov-mini" title="${O(e)}">${n.map(i=>`<i${i?' class="on"':""} style="height:${i?Math.max(12,Math.round(i/t*100)):0}%"></i>`).join("")}</span>`:""}function kw(){const n=document.getElementById("ovSub");n&&(n.textContent=!D.health.vault&&D.health.vault_configured===!1?"No vault folder is configured yet.":"Your vault, your agents and what they are doing, at a glance.")}function sR(){const n=Mn(),e=D.stats,t=e.notes||n.length,i=new Date;i.setHours(0,0,0,0);const a=n.filter(c=>(c.mtime||0)>=i.getTime()/1e3).length,s=n.reduce((c,p)=>Math.max(c,p.mtime||0),0);Bp("ovKNodes",t,ww(ug(n.map(c=>c.mtime||0),14,86400),"Nodes changed per day, last 14 days"),a?`<b>${a}</b> changed today`:s?`Last change ${b(si(s))}`:"Empty vault");const o=t?(e.links||0)/t:0;Bp("ovKLinks",e.links||0,"",t?`<b>${o.toFixed(1)}</b> per node`:"No links yet");const r=bw(),l=r.reduce((c,p)=>c+p[1],0)||1;Bp("ovKFolders",e.folders||0,r.length?`<span class="ov-kpi-bar" title="${O(r.map(([c,p])=>`${c} ${p}`).join(", "))}">${r.slice(0,8).map(([c,p])=>`<i style="flex:${p/l};background:${O(yw(c))}"></i>`).join("")}</span>`:"",r.length?`<b>${r.length}</b> top-level ${r.length===1?"region":"regions"}`:"No folders yet"),_w()}function _w(){const n=Mw(),e=xo.filter(s=>s.enabled!==!1).length,t=n.filter(s=>s.active).length,i=bo.filter(s=>s.source==="agent").map(s=>s.ts),a=i.length;Bp("ovKAgents",e,ww(ug(i,24,3600),"Agent calls per hour, last 24 hours"),vc?t?`<span class="cc-dot ok"></span><b>${t}</b> active now`:a?`<b>${a.toLocaleString()}</b> ${a===1?"call":"calls"} in 24h`:e?"No calls in 24h":"None connected yet":"&nbsp;")}function oR(){const n=document.getElementById("ovWelcome");if(!n)return;const e=!D.stats.notes&&!Mn().length;if(n.hidden=!e,!e||n.childElementCount)return;const t=(i,a,s,o,r,l=!1)=>`<li><span class="ov-wl-n">${i}</span><div><b>${a}</b><span>${s}</span></div>
3400
+ </div>`,U("#ovBrain").onclick=()=>he.go("brain"),U("#ovNew").onclick=()=>he.openNewNote(),U("#ovNodes").onclick=()=>he.go("vault"),U("#ovRecentAll").onclick=()=>he.go("vault"),U("#ovKeys").onclick=()=>he.go("keys"),U("#ovAll").onclick=()=>he.go("logs"),n.querySelectorAll(".ov-kpi[data-go]").forEach(a=>a.onclick=()=>he.go(a.dataset.go));const i=U("#ovReload");i.onclick=()=>{if(i.classList.contains("busy"))return;i.classList.add("busy"),i.setAttribute("aria-busy","true"),i.title="Refreshing…";const a=new Promise(s=>setTimeout(s,500));Promise.all([he.loadCore().then(()=>xw()),a]).finally(()=>{i.classList.remove("busy"),i.removeAttribute("aria-busy"),i.title="Refresh"})},ar(U("#ovAct"),a=>bo.find(s=>s.id===a))}Dl(n,()=>{cg=Bl.state,Fp=Bl.clients;const e=[zf(i=>{Fd(bo,i,500),t4()}),jn("connection",i=>{cg=i,Hp()}),jn("presence",i=>{Fp=i,Hp()})],t=window.setInterval(()=>{fg(),gg()},2e3);return()=>{e.forEach(i=>i()),clearInterval(t)}}),Sw(),mg(),Hp(),await xw()}}function e4(){const n=new Date().getHours();return n<5?"Good night":n<12?"Good morning":n<18?"Good afternoon":"Good evening"}function t4(){dg||(dg=!0,setTimeout(()=>{dg=!1,fg(),gg(),mg()},150))}async function xw(){const n=++gw,[e,t,i]=await Promise.all([tt("/api/keys").catch(()=>null),Ud("1d",500).catch(()=>[]),tt("/api/oauth/clients").catch(()=>null)]);n===gw&&(e&&(xo=Array.isArray(e)?e:e.keys||[]),Ku(xo),mw=new Set((i?.connections||[]).map(a=>a.key_id)),bo=t,vc=!0,Sw(),fg(),mg(),gg(),Hp())}const n4=/(<time data-ts="[^"]*">)[^<]*(<\/time>)/g;function wr(n,e){const t=e.replace(n4,"$1$2");if(n.dataset.html===t){const i=Array.from(e.matchAll(/<time data-ts="[^"]*">([^<]*)<\/time>/g),a=>a[1]);return n.querySelectorAll("time[data-ts]").forEach((a,s)=>{const o=i[s];o!==void 0&&a.innerHTML!==o&&(a.innerHTML=o)}),!1}return n.dataset.html=t,n.innerHTML=e,!0}function pg(n){return`<time data-ts="${n}">${b(i4(n))}</time>`}function i4(n){const e=Fn(n);return e==="now"?"just now":e==="-"?e:e+" ago"}function a4(n){const e=n.replace(/[\\/]+$/,"").search(/[^\\/]+$/),t=e>0?n.slice(0,e):"",i=e>0?n.slice(e):n;return`<span class="ov-path" title="${O(n)}"><span class="h">${b(t)}</span><span class="e">${b(i)}</span></span>`}function hg(n,e,t,i=""){return`<div class="ov-empty"><span class="ov-tile">${n}</span><b>${e}</b><p>${t}</p>${i}</div>`}function bw(){const n=new Map;for(const e of Mn()){const t=(e.folder||"Root").split("/")[0]||"Root";n.set(t,(n.get(t)||0)+1)}return[...n.entries()].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0]))}function yw(n){return An(n==="Root"?"":n)}function Bp(n,e,t,i){const a=document.getElementById(n);a&&(a.querySelector("[data-v]").textContent=e.toLocaleString(),wr(a.querySelector("[data-viz]"),t),wr(a.querySelector("[data-h]"),i))}function ug(n,e,t){const i=Date.now()/1e3,a=new Array(e).fill(0);for(const s of n){const o=Math.floor((i-s)/t);o>=0&&o<e&&a[e-1-o]++}return a}function ww(n,e){const t=Math.max(...n);return t?`<span class="ov-mini" title="${O(e)}">${n.map(i=>`<i${i?' class="on"':""} style="height:${i?Math.max(12,Math.round(i/t*100)):0}%"></i>`).join("")}</span>`:""}function kw(){const n=document.getElementById("ovSub");n&&(n.textContent=!D.health.vault&&D.health.vault_configured===!1?"No vault folder is configured yet.":"Your vault, your agents and what they are doing, at a glance.")}function s4(){const n=Mn(),e=D.stats,t=e.notes||n.length,i=new Date;i.setHours(0,0,0,0);const a=n.filter(c=>(c.mtime||0)>=i.getTime()/1e3).length,s=n.reduce((c,p)=>Math.max(c,p.mtime||0),0);Bp("ovKNodes",t,ww(ug(n.map(c=>c.mtime||0),14,86400),"Nodes changed per day, last 14 days"),a?`<b>${a}</b> changed today`:s?`Last change ${b(si(s))}`:"Empty vault");const o=t?(e.links||0)/t:0;Bp("ovKLinks",e.links||0,"",t?`<b>${o.toFixed(1)}</b> per node`:"No links yet");const r=bw(),l=r.reduce((c,p)=>c+p[1],0)||1;Bp("ovKFolders",e.folders||0,r.length?`<span class="ov-kpi-bar" title="${O(r.map(([c,p])=>`${c} ${p}`).join(", "))}">${r.slice(0,8).map(([c,p])=>`<i style="flex:${p/l};background:${O(yw(c))}"></i>`).join("")}</span>`:"",r.length?`<b>${r.length}</b> top-level ${r.length===1?"region":"regions"}`:"No folders yet"),_w()}function _w(){const n=Mw(),e=xo.filter(s=>s.enabled!==!1).length,t=n.filter(s=>s.active).length,i=bo.filter(s=>s.source==="agent").map(s=>s.ts),a=i.length;Bp("ovKAgents",e,ww(ug(i,24,3600),"Agent calls per hour, last 24 hours"),vc?t?`<span class="cc-dot ok"></span><b>${t}</b> active now`:a?`<b>${a.toLocaleString()}</b> ${a===1?"call":"calls"} in 24h`:e?"No calls in 24h":"None connected yet":"&nbsp;")}function o4(){const n=document.getElementById("ovWelcome");if(!n)return;const e=!D.stats.notes&&!Mn().length;if(n.hidden=!e,!e||n.childElementCount)return;const t=(i,a,s,o,r,l=!1)=>`<li><span class="ov-wl-n">${i}</span><div><b>${a}</b><span>${s}</span></div>
3401
3401
  <button type="button" class="btn${l?" primary":""} sm" id="${r}">${o}</button></li>`;n.innerHTML=`<div class="ov-card-b"><div class="ov-wl-top">${or("ov-wl-mark")}
3402
3402
  <div><div class="ov-wl-motto">${Jf}</div><h2 id="ovWelcomeT">Welcome to Memora</h2></div></div>
3403
3403
  <p class="ov-wl-desc">${Qf} ${Ny} <button type="button" class="ov-lnk" id="ovWlTour">Read the full welcome</button></p>
@@ -3406,13 +3406,13 @@ button.ov-name:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
3406
3406
  ${t(2,"Connect an agent","Give Claude, Cursor or any MCP app its own key so it can read and write here.","Agents & keys","ovWlKeys")}
3407
3407
  ${t(3,"Watch it grow","Every node becomes a point in the brain; agent calls pulse through it live.","Open the brain","ovWlBrain")}
3408
3408
  </ol>
3409
- <p class="ov-wl-name">${em}</p></div>`,U("#ovWlNew").onclick=()=>he.openNewNote(),U("#ovWlKeys").onclick=()=>he.go("keys"),U("#ovWlBrain").onclick=()=>he.go("brain"),U("#ovWlTour").onclick=()=>rr()}function Sw(){oR(),kw(),sR();const n=document.getElementById("ovVault");if(!n)return;const e=D.health.vault||"",t=Mn(),i=bw(),a=i[0]?.[1]||1,s=t.reduce((d,u)=>(u.mtime||0)>(d?.mtime||0)?u:d,null),o=s?Aw(s.path):void 0,r=`<div><div class="ov-cap">Location</div><div class="ov-row"><span class="ov-tile">${vo.folder}</span>
3410
- <span class="t">${e?aR(e):'<span class="ov-name">Not configured</span>'}<span class="ov-sub">${e?b(bn(t.length,"Markdown file")):"Set MEMORA_VAULT to a folder of Markdown files"}</span></span>${e?`<button type="button" class="cc-ibtn ov-copy" id="ovCopyPath" aria-label="Copy the vault path" title="Copy path">${pe.copy}</button>`:""}</div></div>`,l=o&&typeof o.raw.actor_id=="string"?o.raw.actor_id:null,p=`<div><div class="ov-cap">Last change</div><div class="ov-row">${o?`<span title="${O("by "+o.actor)}" style="display:flex">${qt(o.actor,32,"",l)}</span>`:`<span class="ov-tile">${vo.clock}</span>`}<span class="t">${s?`<button type="button" class="ov-name" data-path="${O(s.path)}" title="${O(s.path)}">${b(s.name||bt(s.path))}</button><span class="ov-sub" title="${O(ai(s.mtime))}">${b(si(s.mtime))} · ${b(s.folder||"Root")}</span>`:'<span class="ov-name">Nothing yet</span><span class="ov-sub">Changes to nodes show up here</span>'}</span></div></div>`,h=`<div><div class="ov-cap">Largest folders</div>${i.length?`<div class="ov-bars">${i.slice(0,lg).map(([d,u])=>{const f=O(yw(d));return`<button type="button" class="ov-bar" data-folder="${O(d)}" aria-label="${O(`${d}: ${bn(u,"node")}`)}">
3409
+ <p class="ov-wl-name">${em}</p></div>`,U("#ovWlNew").onclick=()=>he.openNewNote(),U("#ovWlKeys").onclick=()=>he.go("keys"),U("#ovWlBrain").onclick=()=>he.go("brain"),U("#ovWlTour").onclick=()=>rr()}function Sw(){o4(),kw(),s4();const n=document.getElementById("ovVault");if(!n)return;const e=D.health.vault||"",t=Mn(),i=bw(),a=i[0]?.[1]||1,s=t.reduce((d,u)=>(u.mtime||0)>(d?.mtime||0)?u:d,null),o=s?Aw(s.path):void 0,r=`<div><div class="ov-cap">Location</div><div class="ov-row"><span class="ov-tile">${vo.folder}</span>
3410
+ <span class="t">${e?a4(e):'<span class="ov-name">Not configured</span>'}<span class="ov-sub">${e?b(bn(t.length,"Markdown file")):"Set MEMORA_VAULT to a folder of Markdown files"}</span></span>${e?`<button type="button" class="cc-ibtn ov-copy" id="ovCopyPath" aria-label="Copy the vault path" title="Copy path">${pe.copy}</button>`:""}</div></div>`,l=o&&typeof o.raw.actor_id=="string"?o.raw.actor_id:null,p=`<div><div class="ov-cap">Last change</div><div class="ov-row">${o?`<span title="${O("by "+o.actor)}" style="display:flex">${qt(o.actor,32,"",l)}</span>`:`<span class="ov-tile">${vo.clock}</span>`}<span class="t">${s?`<button type="button" class="ov-name" data-path="${O(s.path)}" title="${O(s.path)}">${b(s.name||bt(s.path))}</button><span class="ov-sub" title="${O(ai(s.mtime))}">${b(si(s.mtime))} · ${b(s.folder||"Root")}</span>`:'<span class="ov-name">Nothing yet</span><span class="ov-sub">Changes to nodes show up here</span>'}</span></div></div>`,h=`<div><div class="ov-cap">Largest folders</div>${i.length?`<div class="ov-bars">${i.slice(0,lg).map(([d,u])=>{const f=O(yw(d));return`<button type="button" class="ov-bar" data-folder="${O(d)}" aria-label="${O(`${d}: ${bn(u,"node")}`)}">
3411
3411
  <span class="l"><span class="d" style="background:${f}"></span><span>${b(d)}</span></span>
3412
- <span class="tr"><i style="width:${Math.max(4,Math.round(u/a*100))}%;background:${f}"></i></span><span class="c">${u}</span></button>`}).join("")}</div>${i.length>lg?`<div class="ov-more">+${bn(i.length-lg,"more folder")}</div>`:""}`:'<div class="ov-sub">The vault is empty.</div>'}</div>`;n.innerHTML=`<div class="ov-facts"><div class="ov-pair">${r}${p}</div>${h}</div>`,n.querySelector("#ovCopyPath")?.addEventListener("click",()=>{Sa(e,"Vault path copied")}),n.querySelectorAll("[data-path]").forEach(d=>d.onclick=()=>he.openNote(d.dataset.path)),n.querySelectorAll("[data-folder]").forEach(d=>{d.onclick=()=>mt.selectFolder(d.dataset.folder==="Root"?"":d.dataset.folder)})}function rR(n){const e=n.name||n.id;return bo.filter(t=>{if(t.source!=="agent")return!1;const i=typeof t.raw.actor_id=="string"?t.raw.actor_id:"";return i?i===n.id:t.actor===e})}function Mw(){const n=Date.now()/1e3;return xo.map(t=>{const i=rR(t),a=i[0],s=a?n-a.ts:1/0;return{k:t,items:i,last:a,active:t.enabled!==!1&&s<ZC,since:s}}).sort((t,i)=>Number(i.active)-Number(t.active)||t.since-i.since||(t.k.name||"").localeCompare(i.k.name||""))}function fg(){const n=document.getElementById("ovAgents");if(!n)return;_w(),kw(),Ew();const e=Mw();U("#ovAgN").textContent=e.length?String(e.length):"";let t;vc?e.length?t=e.slice(0,rg).map(i=>{const a=i.k.name||i.k.id,o=i.k.enabled===!1?'<span class="ov-st off">Disabled</span>':i.active?'<span class="ov-st on"><span class="cc-dot ok" style="box-shadow:none;width:7px;height:7px"></span>Active now</span>':i.last?`<span class="ov-st">Seen ${pg(i.last.ts)}</span>`:`<span class="ov-st">${mw.has(i.k.id)?"Connected over OAuth":"No calls in 24h"}</span>`,r=i.last?`<span class="sep">·</span><span>${b(cn(i.last.action))}${i.last.paths.length?" "+b(bt(i.last.paths[0])):""}</span>`:"",l=ug(i.items.map(h=>h.ts),30,60),c=l.reduce((h,d)=>h+d,0),p=c?`<span class="sp" title="${bn(c,"call")} in the last 30 minutes">${Bd(l,56,24)}</span>`:"";return`<button type="button" class="ov-li" data-agent="${O(a)}" style="--ag:${O(xn(a,i.k.id))}">${qt(a,32,i.active?"live":"",i.k.id)}<span class="t"><span class="n"><span>${b(a)}</span></span><span class="s">${o}${r}</span></span>${p}
3412
+ <span class="tr"><i style="width:${Math.max(4,Math.round(u/a*100))}%;background:${f}"></i></span><span class="c">${u}</span></button>`}).join("")}</div>${i.length>lg?`<div class="ov-more">+${bn(i.length-lg,"more folder")}</div>`:""}`:'<div class="ov-sub">The vault is empty.</div>'}</div>`;n.innerHTML=`<div class="ov-facts"><div class="ov-pair">${r}${p}</div>${h}</div>`,n.querySelector("#ovCopyPath")?.addEventListener("click",()=>{Sa(e,"Vault path copied")}),n.querySelectorAll("[data-path]").forEach(d=>d.onclick=()=>he.openNote(d.dataset.path)),n.querySelectorAll("[data-folder]").forEach(d=>{d.onclick=()=>mt.selectFolder(d.dataset.folder==="Root"?"":d.dataset.folder)})}function r4(n){const e=n.name||n.id;return bo.filter(t=>{if(t.source!=="agent")return!1;const i=typeof t.raw.actor_id=="string"?t.raw.actor_id:"";return i?i===n.id:t.actor===e})}function Mw(){const n=Date.now()/1e3;return xo.map(t=>{const i=r4(t),a=i[0],s=a?n-a.ts:1/0;return{k:t,items:i,last:a,active:t.enabled!==!1&&s<ZC,since:s}}).sort((t,i)=>Number(i.active)-Number(t.active)||t.since-i.since||(t.k.name||"").localeCompare(i.k.name||""))}function fg(){const n=document.getElementById("ovAgents");if(!n)return;_w(),kw(),Ew();const e=Mw();U("#ovAgN").textContent=e.length?String(e.length):"";let t;vc?e.length?t=e.slice(0,rg).map(i=>{const a=i.k.name||i.k.id,o=i.k.enabled===!1?'<span class="ov-st off">Disabled</span>':i.active?'<span class="ov-st on"><span class="cc-dot ok" style="box-shadow:none;width:7px;height:7px"></span>Active now</span>':i.last?`<span class="ov-st">Seen ${pg(i.last.ts)}</span>`:`<span class="ov-st">${mw.has(i.k.id)?"Connected over OAuth":"No calls in 24h"}</span>`,r=i.last?`<span class="sep">·</span><span>${b(cn(i.last.action))}${i.last.paths.length?" "+b(bt(i.last.paths[0])):""}</span>`:"",l=ug(i.items.map(h=>h.ts),30,60),c=l.reduce((h,d)=>h+d,0),p=c?`<span class="sp" title="${bn(c,"call")} in the last 30 minutes">${Bd(l,56,24)}</span>`:"";return`<button type="button" class="ov-li" data-agent="${O(a)}" style="--ag:${O(xn(a,i.k.id))}">${qt(a,32,i.active?"live":"",i.k.id)}<span class="t"><span class="n"><span>${b(a)}</span></span><span class="s">${o}${r}</span></span>${p}
3413
3413
  <span class="m"><b>${i.items.length.toLocaleString()}</b>${i.items.length===1?"call":"calls"}</span></button>`}).join("")+(e.length>rg?`<div class="ov-foot"><button type="button" class="ov-lnk" data-more>+${bn(e.length-rg,"more agent")}</button></div>`:""):t=hg(vo.agent,"No agents yet","Give each AI app its own key, or connect Claude or ChatGPT over OAuth.",`<button type="button" class="btn primary sm" id="ovNewKey">${pe.plus}New agent</button>`):t=jo(3),wr(n,t)&&(n.querySelector("#ovNewKey")?.addEventListener("click",Tw),n.querySelector("[data-more]")?.addEventListener("click",()=>he.go("keys")),n.querySelectorAll("[data-agent]").forEach(i=>{i.onclick=()=>{try{sessionStorage.setItem("memora.activity.agent",i.dataset.agent)}catch{}he.go("logs")}}))}function Aw(n){return bo.find(e=>(e.source==="vault"||e.source==="agent"&&JC.test(e.action))&&e.paths.includes(n))}function mg(){const n=document.getElementById("ovRecent");if(!n)return;const e=Mn().filter(i=>i.mtime).sort((i,a)=>(a.mtime||0)-(i.mtime||0)).slice(0,og),t=e.length?e.map(i=>{const a=Aw(i.path),s=a&&typeof a.raw.actor_id=="string"?a.raw.actor_id:null,o=a?`<span class="sep">·</span><span class="who">${qt(a.actor,14,"",s)}${b(a.actor)}</span>`:"";return`<button type="button" class="ov-li" data-path="${O(i.path)}" title="${O(i.path)}"><span class="ov-tile fc" style="--fc:${O(An(i.folder||""))}">${pe.note}</span><span class="t"><span class="n"><span>${b(i.name||bt(i.path))}</span></span><span class="s"><span>${b(i.folder||"Root")}</span>${o}</span></span><span class="m" title="${O(ai(i.mtime))}">${pg(i.mtime||0)}</span></button>`}).join("")+fw(e.length,"That is every node in the vault."):hg(pe.note,"No changes yet","Nodes you or your agents write show up here, newest first.");wr(n,t)&&n.querySelectorAll("[data-path]").forEach(i=>i.onclick=()=>he.openNote(i.dataset.path))}function gg(){const n=document.getElementById("ovAct");if(!n)return;const e=new Set(xo.map(o=>o.id)),t=new Set(xo.map(o=>o.name||o.id)),i=Date.now()/1e3,a=bo.filter(o=>o.source!=="auth"&&i-o.ts<QC).slice(0,og),s=vc?a.length?a.map(o=>{const r=typeof o.raw.actor_id=="string"?o.raw.actor_id:"",l=o.source==="agent"&&(r?!e.has(r):!t.has(o.actor)),c=!!o.live&&i-o.ts<2,p=o.paths[0],h=o.label&&!o.paths.includes(o.label)?o.label:"",d=p?`<button type="button" class="nt" data-note="${O(p)}" title="${O(p)}">${b(bt(p))}</button>${o.paths.length>1?`<span class="sep">+${o.paths.length-1}</span>`:""}`:`<span>${b(h||(o.source==="agent"?"over MCP":"vault"))}</span>`,u=o.running?'<span class="ov-st"><span class="cc-dot run"></span>running</span>':o.ok===!1?'<span class="ov-st off">failed</span>':`<span>${o.source==="agent"?"mcp":o.source}</span>`;return`<div class="ov-li${l?" gone":""}${c?" new":""}" role="button" tabindex="0" data-act="${O(o.id)}" style="--ag:${O(xn(o.actor,r||null))}" aria-label="${O(`${o.actor} ${cn(o.action)} ${p?bt(p):h}`)}">${qt(o.actor,32,o.running?"live":"",r||null)}
3414
3414
  <span class="t"><span class="n"><span class="ag-who">${b(o.actor)}</span><span class="vb">${b(cn(o.action))}</span>${l?'<span class="ov-tag">removed key</span>':""}</span><span class="s">${d}</span></span>
3415
- <span class="m"><span title="${O(ai(o.ts))}">${pg(o.ts)}</span>${u}</span></div>`}).join("")+fw(a.length,"Nothing else in the last 24 hours."):hg(vo.pulse,"Quiet for now","Nothing in the last 24 hours. Agent calls and node changes stream in here live."):jo(8);wr(n,s)}function Hp(){const n=document.getElementById("ovHealth");if(!n)return;const e=D.health,t=e.ok!==!1&&!!e.server,i=cg||"connecting",a=(l,c,p)=>`<div><span class="cc-dot ${l}"></span><span class="t"><small>${b(c)}</small><b title="${O(p.replace(/<[^>]+>/g,""))}">${p}</b></span></div>`,s=e.vault_configured!==!1;n.innerHTML=a(t?"ok":"err","Server",t?b(e.version?"Online · v"+e.version:"Online"):"Unreachable")+a(i==="on"?"ok":i==="off"?"err":"run","Realtime",i==="on"?"Live"+(Fp?` · ${bn(Fp,"browser")}`:""):i==="off"?"Offline":"Connecting")+a(s?"ok":"err","Vault",s?"Ready":"Not configured")+a(e.locked?"err":e.armed?"run":"ok","Gateway",e.locked?"Locked":e.armed?"Sign-in window open":"Normal"),Ew();const o=!t||i==="off"||!s||e.locked,r=document.getElementById("ovHealthPill");r&&(r.innerHTML=o?'<span class="ov-pill err"><span class="cc-dot err"></span>Needs attention</span>':i!=="on"||e.armed?`<span class="ov-pill warn"><span class="cc-dot run"></span>${e.armed?"Sign-in window open":"Connecting"}</span>`:'<span class="ov-pill"><span class="cc-dot ok"></span>All systems normal</span>')}function Tw(){uw(),he.go("keys")}function Ew(){const n=document.getElementById("ovConnect");if(!n)return;const e=D.health.base_url,t=e?e.replace(/\/+$/,"")+"/mcp":"",i=`<span class="ov-tile">${pe.plug}</span><span class="t"><small>MCP endpoint</small>${t?`<span class="ov-path" title="${O(t)}"><span class="h">${b(t.replace(/^https?:\/\//,""))}</span></span>`:'<span class="ov-sub">Not known yet</span>'}</span>${t?`<button type="button" class="cc-ibtn ov-copy" data-copy-mcp aria-label="Copy the MCP endpoint" title="Copy endpoint">${pe.copy}</button>`:""}${vc&&xo.length?`<button type="button" class="btn sm" data-new-agent aria-label="New agent" title="New agent">${pe.plus}<span class="lbl">New agent</span></button>`:""}`;wr(n,i)&&(n.querySelector("[data-copy-mcp]")?.addEventListener("click",()=>{Sa(t,"MCP endpoint copied")}),n.querySelector("[data-new-agent]")?.addEventListener("click",Tw))}const lR=n=>n<.5?4*n*n*n:1-Math.pow(-2*n+2,3)/2;let cR=class{constructor(){this.x=0,this.y=0,this.k=1,this.w=1,this.h=1,this.minK=.04,this.maxK=6,this.vx=0,this.vy=0,this.anim=null}toWorld(e,t){return{x:(e-this.w/2)/this.k+this.x,y:(t-this.h/2)/this.k+this.y}}toScreen(e,t){return{x:(e-this.x)*this.k+this.w/2,y:(t-this.y)*this.k+this.h/2}}view(e=0){const t=e/this.k;return{x0:this.x-this.w/2/this.k-t,y0:this.y-this.h/2/this.k-t,x1:this.x+this.w/2/this.k+t,y1:this.y+this.h/2/this.k+t}}zoomAt(e,t,i){this.anim=null;const a=this.toWorld(e,t);this.k=Math.max(this.minK,Math.min(this.maxK,this.k*i));const s=this.toWorld(e,t);this.x+=a.x-s.x,this.y+=a.y-s.y}panBy(e,t){this.anim=null,this.x-=e/this.k,this.y-=t/this.k}stop(){this.anim=null,this.vx=this.vy=0}animateTo(e,t,i,a=650){this.vx=this.vy=0,i=Math.max(this.minK,Math.min(this.maxK,i)),this.anim={x0:this.x,y0:this.y,k0:this.k,x1:e,y1:t,k1:i,t0:performance.now(),ms:a}}fit(e,t=60,i=650,a=1.6,s=0,o=0){const r=Math.max(1,e.x1-e.x0),l=Math.max(1,e.y1-e.y0),c=Math.min((this.w-t*2)/r,(this.h-t*2-s-o)/l,a),p=(e.x0+e.x1)/2,h=(e.y0+e.y1)/2-(s-o)/2/c;i<=0?(this.x=p,this.y=h,this.k=Math.max(this.minK,c),this.anim=null):this.animateTo(p,h,c,i)}step(e){if(this.anim){const t=this.anim,i=Math.min(1,(e-t.t0)/t.ms),a=lR(i);return this.k=t.k0*Math.pow(t.k1/t.k0,a),this.x=t.x0+(t.x1-t.x0)*a,this.y=t.y0+(t.y1-t.y0)*a,i>=1&&(this.anim=null),!0}return Math.abs(this.vx)>.05||Math.abs(this.vy)>.05?(this.x-=this.vx/this.k,this.y-=this.vy/this.k,this.vx*=.93,this.vy*=.93,!0):(this.vx=this.vy=0,!1)}};const xc="\0dir:";function Gp(n){const e=n.lastIndexOf("/");return e<0?"":n.slice(0,e)}const dR=["#2dd4bf","#60a5fa","#c084fc","#fbbf24","#f472b6","#4ade80","#fb923c","#a3e635","#f87171","#818cf8","#22d3ee","#e879f9"],pR=["#0d9488","#2563eb","#9333ea","#d97706","#db2777","#16a34a","#ea580c","#65a30d","#dc2626","#4f46e5","#0891b2","#c026d3"];function Cw(n,e,t){const i=n.replace("#","");if(i.length!==6)return n;const a=parseInt(i,16),s=c=>Math.round(c+(e-c)*t),o=s(a>>16&255),r=s(a>>8&255),l=s(a&255);return"#"+(1<<24|o<<16|r<<8|l).toString(16).slice(1)}function hR(n){return 3.6+Math.sqrt(n)*1.9}class uR{constructor(){this.all=new Map,this.refs=[],this.outgoing=new Map,this.incoming=new Map,this.byPath=new Map,this.tagsByPath=new Map,this.byName=new Map}make(e,t,i,a,s,o,r){return{id:e,kind:t,label:i,path:a,group:s,dir:o,tags:[],color:r,degree:0,r:4,x:NaN,y:NaN,vx:0,vy:0,fx:null,fy:null,pinned:!1,tx:0,ty:0,born:0,dying:0,fade:1,i:0}}ingest(e,t,i){const a=e.nodes||[],s=new Set,o=[];this.byPath.clear();const r=new Set;this.byName.clear();for(const d of a){const u=d.path||d.id+".md",f=Gp(u),v=d.folder||(f?f.split("/")[0]:"Root"),g=u;this.byName.has(d.id)||this.byName.set(d.id,g);let m=this.all.get(g);(!m||m.kind!=="note")&&(m=this.make(g,"note",d.id,u,v,f,""),this.all.set(g,m),o.push(m),i&&(m.born=t)),m.path=u,m.dir=f,m.group=v,m.dying=0,Array.isArray(d.tags)&&this.tagsByPath.set(u,d.tags),m.tags=this.tagsByPath.get(u)||m.tags,s.add(g),this.byPath.set(u,m);for(let x=f;x;x=Gp(x))r.add(x)}for(const d of r){const u=xc+d;let f=this.all.get(u);const v=d.split("/")[0];f||(f=this.make(u,"folder",d.split("/").pop()||d,d,v,Gp(d),""),this.all.set(u,f),o.push(f),i&&(f.born=t)),f.dying=0,s.add(u)}const l=[];this.all.forEach((d,u)=>{s.has(u)||(i?d.dying||(d.dying=t,l.push(d)):this.all.delete(u))}),this.outgoing.clear(),this.incoming.clear();const c=new Set;this.refs=[];for(const d of e.links||[]){const u={source:this.byName.get(d.source)||d.source,target:this.byName.get(d.target)||d.target};if(u.source===u.target||!this.all.has(u.source)||!this.all.has(u.target))continue;this.outgoing.has(u.source)||this.outgoing.set(u.source,new Set),this.incoming.has(u.target)||this.incoming.set(u.target,new Set),this.outgoing.get(u.source).add(u.target),this.incoming.get(u.target).add(u.source);const f=u.source<u.target?u.source+""+u.target:u.target+""+u.source;c.has(f)||(c.add(f),this.refs.push([u.source,u.target]))}const p=new Map;for(const[d,u]of this.refs)p.set(d,(p.get(d)||0)+1),p.set(u,(p.get(u)||0)+1);const h=new Map;this.all.forEach(d=>{d.dying||d.dir&&h.set(d.dir,(h.get(d.dir)||0)+1)}),this.all.forEach(d=>{d.kind==="note"?(d.degree=p.get(d.id)||0,d.r=hR(d.degree)):(d.degree=h.get(d.path)||0,d.r=9+Math.sqrt(d.degree)*1.6)});for(const d of o){if(!Number.isNaN(d.x))continue;const u=this.anchorFor(d);if(u&&!Number.isNaN(u.x)){const f=Math.random()*Math.PI*2;d.x=u.x+Math.cos(f)*(u.r+14),d.y=u.y+Math.sin(f)*(u.r+14)}}return{added:o,removed:l}}recolor(e){const t=e?pR:dR,i=new Map;this.all.forEach(c=>i.set(c.group,(i.get(c.group)||0)+1));const a=Array.from(i.keys()).sort((c,p)=>(i.get(p)||0)-(i.get(c)||0)||c.localeCompare(p)),s=new Map;a.forEach((c,p)=>{const h=D.folderMeta[c];s.set(c,h&&h.color||t[p%t.length])});const o=new Map,r=Array.from(new Set(Array.from(this.all.values()).map(c=>c.kind==="folder"?c.path:c.dir))).sort(),l=new Map;for(const c of r){const p=c.split("/")[0];if(!c.includes("/"))continue;const h=l.get(p)||0;l.set(p,h+1),o.set(c,h+1)}this.all.forEach(c=>{const p=s.get(c.group)||t[0],h=c.kind==="folder"?c.path:c.dir,d=o.get(h)||0;if(!d){c.color=p;return}const u=Math.ceil(d/2)*.13;c.color=d%2?Cw(p,e?0:255,Math.min(.4,u)):Cw(p,e?255:0,Math.min(.35,u))})}groupColor(e){for(const t of this.all.values())if(t.group===e&&t.kind==="note"&&!t.dir.includes("/"))return t.color;for(const t of this.all.values())if(t.group===e)return t.color;return"#888"}anchorFor(e){const t=this.outgoing.get(e.id)||this.incoming.get(e.id);if(t)for(const i of t){const a=this.all.get(i);if(a&&!Number.isNaN(a.x))return a}return this.all.get(xc+e.dir)||this.all.get(xc+e.path.split("/")[0])}reap(e,t){let i=!1;return this.all.forEach((a,s)=>{a.dying&&e-a.dying>t&&(this.all.delete(s),i=!0)}),i}visible(e){const t=r=>e.tags.size?(this.tagsByPath.get(r.path)||r.tags).some(c=>e.tags.has(c)):!0,i=new Set;if(this.all.forEach(r=>{r.kind!=="note"||e.hiddenGroups.has(r.group)||!t(r)||!e.orphans&&!r.degree&&!r.dying||i.add(r)}),e.folders){const r=new Set;i.forEach(l=>{for(let c=l.dir;c;c=Gp(c))r.add(c)}),r.forEach(l=>{const c=this.all.get(xc+l);c&&i.add(c)})}const a=[],s=(r,l,c)=>({s:r,t:l,kind:c,k:0,len:0,bias:.5});e.folders&&i.forEach(r=>{if(!r.dir)return;const l=this.all.get(xc+r.dir);l&&i.has(l)&&a.push(s(l,r,"tree"))});for(const[r,l]of this.refs){const c=this.all.get(r),p=this.all.get(l);c&&p&&i.has(c)&&i.has(p)&&a.push(s(c,p,"ref"))}return{nodes:Array.from(i).sort((r,l)=>r.kind!==l.kind?r.kind==="folder"?1:-1:r.degree-l.degree),links:a}}groups(){const e=new Map;return this.all.forEach(t=>{t.kind==="note"&&!t.dying&&e.set(t.group,(e.get(t.group)||0)+1)}),Array.from(e.entries()).sort((t,i)=>i[1]-t[1]).map(([t,i])=>[t,i,this.groupColor(t)])}}function fR(n){const e={path:"",depth:0,folder:null,notes:[],kids:[],weight:0},t=new Map([["",e]]),i=s=>{let o=t.get(s);if(o)return o;const r=s.lastIndexOf("/"),l=i(r<0?"":s.slice(0,r));return o={path:s,depth:l.depth+1,folder:null,notes:[],kids:[],weight:0},l.kids.push(o),t.set(s,o),o};for(const s of n)s.kind==="folder"?i(s.path).folder=s:i(s.dir).notes.push(s);const a=s=>(s.kids.sort((o,r)=>o.path.localeCompare(r.path)),s.notes.sort((o,r)=>r.degree-o.degree||o.label.localeCompare(r.label)),s.weight=s.notes.length+s.kids.reduce((o,r)=>o+a(r),0)+(s.folder?1:0),Math.max(1,s.weight));return a(e),e}const bc=150;function mR(n){const e=fR(n),t=new Set,i=(a,s,o)=>{const r=o-s,l=(s+o)/2;if(a.folder){const v=a.depth*bc;a.folder.tx=Math.cos(l)*v,a.folder.ty=Math.sin(l)*v,t.add(v)}const c=Math.max(1,a.weight-(a.folder?1:0)),p=r*a.notes.length/c,h=r-p;let d=s;const u=Math.ceil(a.kids.length/2),f=v=>{const g=h*Math.max(1,v.weight)/Math.max(1,c-a.notes.length);i(v,d,d+g),d+=g};if(a.kids.slice(0,u).forEach(f),a.notes.length){const v=(a.depth+1)*bc-bc*.35,g=d,m=d+p,x=15,_=Math.max(.001,(m-g)*v),w=Math.max(1,Math.ceil(a.notes.length*x/_)),S=Math.ceil(a.notes.length/w);a.notes.forEach((A,C)=>{const y=C%w,M=Math.floor(C/w),T=S>1?(M+.5)/S:.5,L=g+(m-g)*(w>1?(M+.5+y%2*.5)/(S+.5):T),P=v+y*13;A.tx=Math.cos(L)*P,A.ty=Math.sin(L)*P}),t.add((a.depth+1)*bc-bc*.35),d=m}a.kids.slice(u).forEach(f)};return i(e,-Math.PI/2,Math.PI*1.5),{rings:Array.from(t).sort((a,s)=>a-s)}}function gR(n){const e=new Map,t=new Map;for(const r of n){if(r.kind==="folder"){t.set(r.path,r);continue}const l=e.get(r.dir)||[];l.push(r),e.set(r.dir,l)}const i=Array.from(e.entries()).sort((r,l)=>r[0].split("/")[0].localeCompare(l[0].split("/")[0])||l[1].length-r[1].length),a=[],s=new Map;for(const[r,l]of i){l.sort((u,f)=>f.degree-u.degree);let c=0;for(const u of l)c+=(u.r+5)*(u.r+5)*4.2;const p=Math.sqrt(c/Math.PI)+22;let h=0,d=0;for(let u=0;;u+=.12){const f=9*u;if(h=Math.cos(u)*f,d=Math.sin(u)*f,a.every(v=>Math.hypot(v.x-h,v.y-d)>v.r+p+36)||u>4e3)break}a.push({x:h,y:d,r:p}),s.set(r,{x:h,y:d}),l.forEach((u,f)=>{const v=Math.sqrt(f+.5)*Math.sqrt(c/Math.PI/Math.max(1,l.length)),g=f*2.399963;u.tx=h+Math.cos(g)*v,u.ty=d+Math.sin(g)*v})}const o=Array.from(t.keys()).sort((r,l)=>l.split("/").length-r.split("/").length);for(const r of o){const l=t.get(r),c=s.get(r);if(c){const u=a.find(f=>f.x===c.x&&f.y===c.y);l.tx=c.x,l.ty=c.y-(u?u.r+10:30);continue}let p=0,h=0,d=0;s.forEach((u,f)=>{f.startsWith(r+"/")&&(p+=u.x,h+=u.y,d++)}),l.tx=d?p/d:0,l.ty=d?h/d:0,s.set(r,{x:l.tx,y:l.ty})}}function Rw(n){const e=new Map;for(const s of n)e.has(s.group)||e.set(s.group,e.size);const t=Math.max(1,e.size),i=120+Math.sqrt(n.length)*14;let a=0;for(const s of n){if(!Number.isNaN(s.x))continue;const r=(e.get(s.group)||0)/t*Math.PI*2,l=Math.sqrt(a++)*9,c=a*2.399963;s.x=Math.cos(r)*i+Math.cos(c)*l*.4,s.y=Math.sin(r)*i+Math.sin(c)*l*.4}}const Lw="memora.layout.graph",vg="memora.graph.prefs";function Pw(n){try{const e=localStorage.getItem(n);return e?JSON.parse(e):null}catch{return null}}function Iw(n,e){try{localStorage.setItem(n,JSON.stringify(e))}catch{}}function $w(n){const e={v:1,pins:{}},t=n&&typeof n=="object"?n.pins:null;if(t&&typeof t=="object")for(const[i,a]of Object.entries(t))Array.isArray(a)&&a.length===2&&a.every(s=>typeof s=="number"&&Number.isFinite(s))&&(e.pins[i]=[a[0],a[1]]);return e}async function vR(){try{const n=await Dn("/api/ui/layout/graph");if(n&&n.data)return $w(n.data)}catch{}return $w(Pw(Lw))}let Nw=0;function Dw(n){Iw(Lw,n),clearTimeout(Nw),Nw=window.setTimeout(()=>{Dn("/api/ui/layout/graph",{method:"PUT",body:{data:n}}).catch(()=>{})},700)}function xR(){return Ow(Pw(vg)||{})}function zw(){return Ow({})}function Ow(n){return{mode:n.mode==="radial"||n.mode==="clusters"?n.mode:"force",labels:typeof n.labels=="number"?n.labels:.45,spacing:typeof n.spacing=="number"?n.spacing:1,spacingBy:{force:xg(n.spacingBy?.force,typeof n.spacing=="number"?n.spacing:1),radial:xg(n.spacingBy?.radial,1),clusters:xg(n.spacingBy?.clusters,1)},noteLabels:n.noteLabels!==!1,folderLabels:n.folderLabels!==!1,folders:n.folders!==!1,hulls:n.hulls!==!1,orphans:n.orphans!==!1,minimap:n.minimap!==!1}}function xg(n,e){return typeof n=="number"&&isFinite(n)?n:e}function bR(){try{localStorage.removeItem(vg)}catch{}return zw()}function yc(n){Iw(vg,n)}const yR=650,Uw=520,Qi=Math.PI*2,wR=n=>1+2.70158*Math.pow(n-1,3)+1.70158*Math.pow(n-1,2);function qp(n,e){if(n.dying)return Math.max(0,1-(e-n.dying)/Uw);if(n.born){const t=(e-n.born)/yR;return t>=1?(n.born=0,1):Math.max(0,wR(Math.max(0,t)))}return 1}function ks(n,e){let t=n.trim();if(t.startsWith("rgb"))return t;t[0]==="#"&&(t=t.slice(1)),t.length===3&&(t=t.split("").map(a=>a+a).join(""));const i=parseInt(t.slice(0,6),16);return Number.isNaN(i)?`rgba(125,211,252,${e})`:`rgba(${i>>16&255},${i>>8&255},${i&255},${e})`}function kR(n){if(n.length<3)return n;n.sort((a,s)=>a[0]-s[0]||a[1]-s[1]);const e=(a,s,o)=>(s[0]-a[0])*(o[1]-a[1])-(s[1]-a[1])*(o[0]-a[0]),t=[];for(const a of n){for(;t.length>=2&&e(t[t.length-2],t[t.length-1],a)<=0;)t.pop();t.push(a)}const i=[];for(let a=n.length-1;a>=0;a--){const s=n[a];for(;i.length>=2&&e(i[i.length-2],i[i.length-1],s)<=0;)i.pop();i.push(s)}return i.pop(),t.pop(),t.concat(i)}class _R{constructor(e){this.ctx=e,this.hullCv=document.createElement("canvas"),this.widths=new Map,this.occ=new Uint8Array(0),this.hullCache=[],this.hullsDirty=!0}measure(e,t){const i=t+"|"+e;let a=this.widths.get(i);return a==null&&(this.ctx.font=t,a=this.ctx.measureText(e).width,this.widths.size>2e4&&this.widths.clear(),this.widths.set(i,a)),a}draw(e,t,i,a){const s=this.ctx,o=e.w,r=e.h;s.setTransform(a,0,0,a,0,0),s.globalAlpha=1,s.fillStyle=i.bg,s.fillRect(0,0,o,r),this.grid(e,i);const l=e.k,c=e.view(80);for(const p of t.nodes){const h=!t.focus||t.focus.has(p)?1:i.light?.13:.1;p.fade+=(h-p.fade)*.18,Math.abs(h-p.fade)<.004&&(p.fade=h)}if(t.mode==="radial"){s.save(),s.strokeStyle=ks(i.muted,i.light?.22:.16),s.setLineDash([3,6]),s.lineWidth=1;const p=e.toScreen(0,0);for(const h of t.rings)s.beginPath(),s.arc(p.x,p.y,h*l,0,Qi),s.stroke();s.restore()}t.hulls&&t.mode!=="radial"&&this.drawHulls(e,t,i,a),this.drawLinks(e,t,i,c),this.drawNodes(e,t,i,c),this.drawPulses(e,t,i),this.drawLabels(e,t,i),s.globalAlpha=1}grid(e,t){const i=this.ctx;let a=24;for(;a*e.k<18;)a*=2;for(;a*e.k>40;)a/=2;const s=a*e.k,o=e.toScreen(0,0),r=(o.x%s+s)%s,l=(o.y%s+s)%s,c=s>28?1.25:1.05;i.fillStyle=t.light?"rgba(15,23,42,.26)":"rgba(148,163,184,.28)",i.beginPath();for(let p=r;p<e.w;p+=s)for(let h=l;h<e.h;h+=s)i.moveTo(p+c,h),i.arc(p,h,c,0,Math.PI*2);i.fill()}drawHulls(e,t,i,a){if(this.hullsDirty){const d=new Map;for(const u of t.nodes){if(u.dying)continue;let f=d.get(u.group);f||d.set(u.group,f={color:u.color,pts:[]}),u.kind==="folder"&&!u.dir&&(f.color=u.color),f.pts.push([u.x,u.y])}this.hullCache=[],d.forEach((u,f)=>{if(u.pts.length<2)return;const v=kR(u.pts);let g=v[0],m=0;for(const x of v)m+=x[0],x[1]<g[1]&&(g=x);g=[m/v.length,g[1]],this.hullCache.push({group:f,color:u.color,pts:v,top:g})}),this.hullsDirty=!1}const s=this.hullCv,o=Math.floor(e.w*a),r=Math.floor(e.h*a);(s.width!==o||s.height!==r)&&(s.width=o,s.height=r);const l=s.getContext("2d");if(!l)return;l.setTransform(1,0,0,1,0,0),l.clearRect(0,0,o,r),l.setTransform(a,0,0,a,0,0),l.lineJoin="round",l.lineCap="round";const c=Math.max(16,26*e.k),p=t.focus?new Set(Array.from(t.focus).map(d=>d.group)):null;for(const d of this.hullCache)l.globalAlpha=p&&!p.has(d.group)?.35:1,l.fillStyle=d.color,l.strokeStyle=d.color,l.lineWidth=c*2,l.beginPath(),d.pts.forEach((u,f)=>{const v=e.toScreen(u[0],u[1]);f?l.lineTo(v.x,v.y):l.moveTo(v.x,v.y)}),l.closePath(),l.fill(),l.stroke();const h=this.ctx;h.save(),h.setTransform(1,0,0,1,0,0),h.globalAlpha=i.light?.085:.07,h.drawImage(s,0,0),h.restore()}drawLinks(e,t,i,a){const s=this.ctx,o=e.k,r=e.w/2-e.x*o,l=e.h/2-e.y*o,c=t.links.length<6e3&&o>.12,p=t.hover||t.selected,h=new Map,d=new Path2D;let u=0;const f=[];for(const m of t.links){const x=m.s,_=m.t;if(x.x<a.x0&&_.x<a.x0||x.x>a.x1&&_.x>a.x1||x.y<a.y0&&_.y<a.y0||x.y>a.y1&&_.y>a.y1)continue;const w=x.x*o+r,S=x.y*o+l,A=_.x*o+r,C=_.y*o+l,y=!!p&&(x===p||_===p);let M;if(y)M=d,u++,f.length<80&&f.push(m);else{const T=Math.min(x.fade,_.fade)*Math.min(qp(x,t.now),qp(_,t.now)),L=T>.75?2:T>.3?1:0,P=(m.kind==="tree"?x.color:"")+"|"+L;let z=h.get(P);z||h.set(P,z=new Path2D),M=z}if(M.moveTo(w,S),c){const T=(w+A)/2,L=(S+C)/2,P=m.kind==="tree"?.06:.12;M.quadraticCurveTo(T-(C-S)*P,L+(A-w)*P,A,C)}else M.lineTo(A,C)}const v=i.light?.3:.24,g=Math.max(.6,Math.min(1.6,.5+o*.7));if(s.lineCap="round",h.forEach((m,x)=>{const[_,w]=x.split("|"),S=Number(w),A=S===2?1:S===1?.45:.12;_?(s.strokeStyle=ks(_,(i.light?.5:.42)*A),s.lineWidth=g*1.25):(s.strokeStyle=ks(i.muted,v*A*1.4),s.lineWidth=g),s.stroke(m)}),u){s.strokeStyle=ks(i.accent,.95),s.lineWidth=Math.max(1.4,g*1.7),s.stroke(d);const m=t.now%1600/1600;s.fillStyle=i.accent;for(const x of f){const _=x.s.x*o+r,w=x.s.y*o+l,S=x.t.x*o+r,A=x.t.y*o+l,C=(_+S)/2-(A-w)*(x.kind==="tree"?.06:.12),y=(w+A)/2+(S-_)*(x.kind==="tree"?.06:.12),M=1-m,T=c?M*M*_+2*M*m*C+m*m*S:_+(S-_)*m,L=c?M*M*w+2*M*m*y+m*m*A:w+(A-w)*m;s.beginPath(),s.arc(T,L,2.2,0,Qi),s.fill()}}}drawNodes(e,t,i,a){const s=this.ctx,o=e.k,r=e.w/2-e.x*o,l=e.h/2-e.y*o;for(const c of t.nodes){if(c.x+c.r<a.x0||c.x-c.r>a.x1||c.y+c.r<a.y0||c.y-c.r>a.y1)continue;const p=qp(c,t.now);if(p<=.01)continue;const h=c.x*o+r,d=c.y*o+l,u=Math.max(1.3,c.r*o)*p,f=c.fade*(c.dying?p:1);if(s.globalAlpha=f,c.kind==="folder"?(s.beginPath(),s.arc(h,d,u,0,Qi),s.fillStyle=ks(c.color,i.light?.22:.2),s.fill(),s.lineWidth=Math.max(1.5,u*.26),s.strokeStyle=c.color,s.stroke(),s.beginPath(),s.arc(h,d,Math.max(1,u*.3),0,Qi),s.fillStyle=c.color,s.fill()):(c.degree>=8&&u>3&&(s.beginPath(),s.arc(h,d,u*1.85,0,Qi),s.fillStyle=ks(c.color,.13),s.fill()),s.beginPath(),s.arc(h,d,u,0,Qi),s.fillStyle=c.color,s.fill(),u>4&&(s.lineWidth=1,s.strokeStyle=i.light?"rgba(255,255,255,.75)":"rgba(0,0,0,.35)",s.stroke())),(c===t.selected||c===t.hover||c===t.dragging)&&(s.globalAlpha=1,s.beginPath(),s.arc(h,d,u+3.5,0,Qi),s.lineWidth=c===t.selected?2.2:1.5,s.strokeStyle=c===t.selected?i.accent:i.ink,s.stroke()),c.pinned){s.globalAlpha=f;const v=h+u*.75,g=d-u*.75;s.beginPath(),s.arc(v,g,Math.max(2.4,u*.32),0,Qi),s.fillStyle=i.ink,s.fill(),s.lineWidth=1.2,s.strokeStyle=i.bg,s.stroke()}}s.globalAlpha=1}drawPulses(e,t,i){if(!t.pulses.size)return;const a=this.ctx,s=new Map;for(const o of t.nodes)t.pulses.has(o.id)&&s.set(o.id,o);t.pulses.forEach((o,r)=>{const l=s.get(r);if(!l)return;const c=e.toScreen(l.x,l.y),p=Math.max(2,l.r*e.k);o.forEach((h,d)=>{const u=h.end?Math.min(1,Math.max(0,1-(t.now-h.end)/2600)):1;if(u<=0)return;const f=Math.max(0,t.now-h.start)%1300/1300;a.globalAlpha=(1-f)*.85*u,a.beginPath(),a.arc(c.x,c.y,p+3+f*26,0,Qi),a.lineWidth=2.4,a.strokeStyle=h.color,a.stroke(),a.globalAlpha=.5*u,a.beginPath(),a.arc(c.x,c.y,p+2,0,Qi),a.fillStyle=h.color,a.fill();const v=xl(h.actor);a.font="700 9.5px system-ui, -apple-system, Segoe UI, sans-serif";const m=a.measureText(v).width+9,x=c.x+p*.7+2+d*(m+2),_=c.y-p*.7-16;a.globalAlpha=u,a.beginPath(),SR(a,x,_,m,14,7),a.fillStyle=h.color,a.fill(),a.lineWidth=1.5,a.strokeStyle=i.bg,a.stroke(),a.fillStyle="#fff",a.textAlign="left",a.fillText(v,x+4.5,_+10.3)})}),a.globalAlpha=1}drawLabels(e,t,i){const a=this.ctx,s=e.w,o=e.h,r=8,l=Math.ceil(s/r)+1,c=Math.ceil(o/r)+1;this.occ.length<l*c&&(this.occ=new Uint8Array(l*c*2));const p=this.occ;p.fill(0,0,l*c);const h=e.k,d=12-t.labelDensity*10.5,u=Math.ceil(t.reserveTop/r);p.fill(1,0,Math.min(c,u)*l);const f=[],v=[];for(const x of[t.selected,t.hover,t.dragging])x&&!v.includes(x)&&v.push(x);t.focus&&t.focus.size<60&&t.focus.forEach(x=>!v.includes(x)&&v.push(x));for(let x=t.nodes.length-1;x>=0;x--){const _=t.nodes[x];if(_.fade<.5||_.dying||v.includes(_)||(_.kind==="folder"?!t.folderLabels:!t.noteLabels))continue;const w=_.r*h;(_.kind==="folder"?w*1.6>=d*.6:w>=d)&&f.push(_)}a.textBaseline="middle",a.textAlign="left",a.lineJoin="round";let g=0;const m=(x,_)=>{const w=e.toScreen(x.x,x.y),S=Math.max(1.3,x.r*h)*qp(x,t.now),A=x.kind==="folder"||_,C=x.kind==="folder"?12.5:Math.min(13,10.5+S*.12),y=`${A?600:450} ${C}px system-ui, -apple-system, Segoe UI, sans-serif`,M=x.label.length>34?x.label.slice(0,32)+"…":x.label,T=this.measure(M,y);let L,P;if(x.kind==="folder"?(L=w.x-T/2,P=w.y+S+10):(L=w.x+S+4,P=w.y),L>s||L+T<0||P<-10||P>o+10)return;const z=Math.max(0,Math.floor((L-2)/r)),R=Math.min(l-1,Math.floor((L+T+2)/r)),B=Math.max(0,Math.floor((P-C/2-1)/r)),K=Math.min(c-1,Math.floor((P+C/2+1)/r));if(!_){for(let N=B;N<=K;N++)for(let V=z;V<=R;V++)if(p[N*l+V])return}for(let N=B;N<=K;N++)for(let V=z;V<=R;V++)p[N*l+V]=1;a.font=y,a.globalAlpha=Math.min(1,x.fade*1.1),a.lineWidth=3.2,a.strokeStyle=i.bg,a.strokeText(M,L,P),a.fillStyle=x.kind==="folder"?x.color:_?i.ink:ks(i.ink,.86),a.fillText(M,L,P),g++};if(v.forEach((x,_)=>m(x,_<1||x===t.selected)),t.folderLabels&&t.hulls&&t.mode!=="radial"){const x=t.focus?new Set(Array.from(t.focus).map(S=>S.group)):null,_=Math.max(16,26*e.k),w="650 11.5px system-ui, -apple-system, Segoe UI, sans-serif";a.font=w;for(const S of this.hullCache){const A=S.group.toUpperCase(),C=this.measure(A,w)*1.08,y=e.toScreen(S.top[0],S.top[1]),M=y.x-C/2,T=y.y-_-2;if(M>s||M+C<0||T<0||T>o)continue;const L=Math.max(0,Math.floor(M/r)),P=Math.min(l-1,Math.floor((M+C)/r)),z=Math.max(0,Math.floor((T-7)/r)),R=Math.min(c-1,Math.floor((T+7)/r));let B=!0;for(let K=z;K<=R&&B;K++)for(let N=L;N<=P;N++)p[K*l+N]&&(B=!1);if(B){for(let K=z;K<=R;K++)for(let N=L;N<=P;N++)p[K*l+N]=1;a.globalAlpha=x&&!x.has(S.group)?.25:.8,a.font=w,a.letterSpacing="0.08em",a.fillStyle=S.color,a.fillText(A,M,T),a.letterSpacing="0px"}}}for(const x of f){if(g>420)break;m(x,!1)}a.globalAlpha=1,a.textBaseline="alphabetic"}}function SR(n,e,t,i,a,s){n.moveTo(e+s,t),n.arcTo(e+i,t,e+i,t+a,s),n.arcTo(e+i,t+a,e,t+a,s),n.arcTo(e,t+a,e,t,s),n.arcTo(e,t,e+i,t,s),n.closePath()}function MR(n,e,t,i,a,s,o){n.setTransform(i,0,0,i,0,0),n.clearRect(0,0,e,t);let r=1/0,l=1/0,c=-1/0,p=-1/0;for(const S of a)S.x<r&&(r=S.x),S.y<l&&(l=S.y),S.x>c&&(c=S.x),S.y>p&&(p=S.y);const h=s.view();r=Math.min(r,h.x0),l=Math.min(l,h.y0),c=Math.max(c,h.x1),p=Math.max(p,h.y1);const d=6,u=Math.min((e-d*2)/Math.max(1,c-r),(t-d*2)/Math.max(1,p-l)),f=d+(e-d*2-(c-r)*u)/2-r*u,v=d+(t-d*2-(p-l)*u)/2-l*u;let g="";for(const S of a){S.color!==g&&(n.fillStyle=S.color,g=S.color),n.globalAlpha=.35+.65*S.fade;const A=S.kind==="folder"?2:1.1;n.fillRect(S.x*u+f-A/2,S.y*u+v-A/2,A,A)}n.globalAlpha=1,n.strokeStyle=o.accent,n.lineWidth=1.2,n.fillStyle=ks(o.accent,.08);const m=h.x0*u+f,x=h.y0*u+v,_=(h.x1-h.x0)*u,w=(h.y1-h.y0)*u;return n.fillRect(m,x,_,w),n.strokeRect(m,x,_,w),{x0:f,y0:v,s:u}}const AR=.81,Vp=1;class TR{constructor(){this.cap=0,this.count=0,this.x0=new Float64Array(0),this.y0=new Float64Array(0),this.size=new Float64Array(0),this.child=new Int32Array(0),this.body=new Int32Array(0),this.mass=new Float64Array(0),this.cx=new Float64Array(0),this.cy=new Float64Array(0),this.next=new Int32Array(0),this.stack=new Int32Array(0)}grow(e){if(e<=this.cap)return;const t=Math.max(64,e*2),i=o=>{const r=new Float64Array(t);return r.set(o),r};this.x0=i(this.x0),this.y0=i(this.y0),this.size=i(this.size),this.mass=i(this.mass),this.cx=i(this.cx),this.cy=i(this.cy);const a=new Int32Array(t*4);a.set(this.child),this.child=a;const s=new Int32Array(t);s.set(this.body),this.body=s,this.cap=t}alloc(e,t,i){this.count>=this.cap&&this.grow(this.count+1);const a=this.count++;return this.x0[a]=e,this.y0[a]=t,this.size[a]=i,this.child[a*4]=-1,this.body[a]=-1,a}build(e,t){const i=e.length;this.next.length<i&&(this.next=new Int32Array(i*2)),this.stack.length<i*4+64&&(this.stack=new Int32Array(i*4+256)),this.grow(i*2+8),this.count=0;let a=1/0,s=1/0,o=-1/0,r=-1/0;for(const c of e)c.x<a&&(a=c.x),c.y<s&&(s=c.y),c.x>o&&(o=c.x),c.y>r&&(r=c.y);const l=Math.max(o-a,r-s,1)*1.0001+1;this.alloc(a,s,l);for(let c=0;c<i;c++)this.next[c]=-1,this.insert(c,e[c].x,e[c].y,e);for(let c=this.count-1;c>=0;c--){let p=0,h=0,d=0,u=0;if(this.child[c*4]<0)for(let f=this.body[c];f>=0;f=this.next[f]){const v=t[f],g=Math.abs(v);p+=v,h+=g,d+=e[f].x*g,u+=e[f].y*g}else for(let f=0;f<4;f++){const v=this.child[c*4+f],g=Math.abs(this.mass[v]);g&&(p+=this.mass[v],h+=g,d+=this.cx[v]*g,u+=this.cy[v]*g)}this.mass[c]=p,this.cx[c]=h?d/h:0,this.cy[c]=h?u/h:0}}insert(e,t,i,a){let s=0;for(let o=0;;o++){if(this.child[s*4]>=0){s=this.child[s*4+this.quadrant(s,t,i)];continue}const r=this.body[s];if(r<0){this.body[s]=e;return}const l=a[r];if(o>40||Math.abs(l.x-t)<1e-6&&Math.abs(l.y-i)<1e-6){this.next[e]=this.next[r],this.next[r]=e;return}const c=this.size[s]/2,p=this.x0[s],h=this.y0[s],d=this.alloc(p,h,c),u=this.alloc(p+c,h,c),f=this.alloc(p,h+c,c),v=this.alloc(p+c,h+c,c);this.child[s*4]=d,this.child[s*4+1]=u,this.child[s*4+2]=f,this.child[s*4+3]=v,this.body[s]=-1;const g=this.child[s*4+this.quadrant(s,l.x,l.y)];this.body[g]=r}}quadrant(e,t,i){const a=this.size[e]/2;return(t>=this.x0[e]+a?1:0)+(i>=this.y0[e]+a?2:0)}apply(e,t,i,a,s,o){const r=this.stack;let l=0;r[l++]=0;let c=0,p=0;for(;l;){const h=r[--l],d=this.mass[h];if(!d)continue;let u=this.cx[h]-t.x,f=this.cy[h]-t.y,v=u*u+f*f;const g=this.size[h],m=this.child[h*4]<0;if(!m&&g*g/AR<v){v<o&&(v<Vp&&(v=Math.sqrt(Vp*v)),c+=u*d/v,p+=f*d/v);continue}if(!m){r[l++]=this.child[h*4],r[l++]=this.child[h*4+1],r[l++]=this.child[h*4+2],r[l++]=this.child[h*4+3];continue}for(let x=this.body[h];x>=0;x=this.next[x]){if(x===e)continue;const _=i[x];u=_.x-t.x,f=_.y-t.y,v=u*u+f*f,!(v>=o)&&(v===0&&(u=(Math.random()-.5)*.001,f=(Math.random()-.5)*.001,v=u*u+f*f),v<Vp&&(v=Math.sqrt(Vp*v)),c+=u*a[x]/v,p+=f*a[x]/v)}}t.vx+=c*s,t.vy+=p*s}}class ER{constructor(){this.nodes=[],this.links=[],this.alpha=1,this.alphaTarget=0,this.alphaMin=.002,this.alphaDecay=1-Math.pow(.002,1/320),this.velocityDecay=.42,this.mode="force",this.targetPull=0,this.spacing=1,this.tree=new TR,this.charge=new Float64Array(0),this.cellNext=new Int32Array(0),this.cellHead=new Int32Array(0)}setData(e,t){this.nodes=e,this.links=t,e.forEach((a,s)=>a.i=s);const i=new Map;for(const a of t)i.set(a.s,(i.get(a.s)||0)+1),i.set(a.t,(i.get(a.t)||0)+1);for(const a of t){const s=i.get(a.s)||1,o=i.get(a.t)||1;a.bias=s/(s+o);const r=1/Math.min(s,o);a.k=a.kind==="tree"?r*.9:r*.7,a.len=a.kind==="tree"?26+a.t.r*2+Math.sqrt(i.get(a.s)||1)*2.5:38+(a.s.r+a.t.r)*1.4}}get running(){return this.alpha>=this.alphaMin||this.alphaTarget>0}reheat(e=.6){this.alpha=Math.max(this.alpha,e)}tick(){const e=this.nodes,t=e.length;if(!t)return;this.alpha+=(this.alphaTarget-this.alpha)*this.alphaDecay;const i=this.alpha,a=this.mode!=="force",s=a?this.mode==="radial"?.015:.06:1;for(const h of this.links){const d=h.s,u=h.t;if(d.dying||u.dying)continue;let f=u.x+u.vx-d.x-d.vx||(Math.random()-.5)*.001,v=u.y+u.vy-d.y-d.vy||(Math.random()-.5)*.001,g=Math.sqrt(f*f+v*v);g=(g-h.len)/g*i*h.k*s,f*=g,v*=g,u.vx-=f*h.bias,u.vy-=v*h.bias,d.vx+=f*(1-h.bias),d.vy+=v*(1-h.bias)}this.charge.length<t&&(this.charge=new Float64Array(t*2));const o=(a?this.mode==="radial"?.04:.12:1)*this.spacing;for(let h=0;h<t;h++){const d=e[h];this.charge[h]=d.dying?0:-(d.kind==="folder"?220:34+d.r*5)*o}this.tree.build(e,this.charge);const r=a?14400:1600*1600;for(let h=0;h<t;h++)this.tree.apply(h,e[h],e,this.charge,i,r);const l=this.targetPull,c=a?0:.035;for(let h=0;h<t;h++){const d=e[h];l&&(d.vx+=(d.tx-d.x)*l,d.vy+=(d.ty-d.y)*l),c&&(d.vx-=d.x*c*i,d.vy-=d.y*c*i)}this.collide(a?.9:.6);const p=1-this.velocityDecay;for(let h=0;h<t;h++){const d=e[h];if(d.fx!=null&&d.fy!=null){d.x=d.fx,d.y=d.fy,d.vx=0,d.vy=0;continue}d.vx*=p,d.vy*=p;const u=d.vx*d.vx+d.vy*d.vy;if(u>3600){const f=60/Math.sqrt(u);d.vx*=f,d.vy*=f}d.x+=d.vx,d.y+=d.vy}}collide(e){const t=this.nodes,i=t.length;let a=1,s=1/0,o=1/0,r=-1/0,l=-1/0;for(const g of t)g.r>a&&(a=g.r),g.x<s&&(s=g.x),g.y<o&&(o=g.y),g.x>r&&(r=g.x),g.y>l&&(l=g.y);const c=3;let p=(a+c)*2,h=Math.ceil((r-s)/p)+1,d=Math.ceil((l-o)/p)+1;for(;h*d>65536;)p*=1.5,h=Math.ceil((r-s)/p)+1,d=Math.ceil((l-o)/p)+1;const u=h*d;this.cellHead.length<u&&(this.cellHead=new Int32Array(u*2)),this.cellNext.length<i&&(this.cellNext=new Int32Array(i*2));const f=this.cellHead,v=this.cellNext;f.fill(-1,0,u);for(let g=0;g<i;g++){const m=t[g],x=Math.floor((m.x-s)/p)+Math.floor((m.y-o)/p)*h;v[g]=f[x],f[x]=g}for(let g=0;g<i;g++){const m=t[g];if(m.dying)continue;const x=Math.floor((m.x-s)/p),_=Math.floor((m.y-o)/p);for(let w=_-1;w<=_+1;w++)if(!(w<0||w>=d)){for(let S=x-1;S<=x+1;S++)if(!(S<0||S>=h))for(let A=f[S+w*h];A>=0;A=v[A]){if(A<=g)continue;const C=t[A];if(C.dying)continue;let y=m.x+m.vx-C.x-C.vx,M=m.y+m.vy-C.y-C.vy;const T=m.r+C.r+c;let L=y*y+M*M;if(L>=T*T)continue;L===0&&(y=(Math.random()-.5)*.01,M=(Math.random()-.5)*.01,L=y*y+M*M);const P=Math.sqrt(L),z=(T-P)/P*e,R=C.r*C.r/(m.r*m.r+C.r*C.r);m.vx+=y*z*R,m.vy+=M*z*R,C.vx-=y*z*(1-R),C.vy-=M*z*(1-R)}}}}}const CR=`
3415
+ <span class="m"><span title="${O(ai(o.ts))}">${pg(o.ts)}</span>${u}</span></div>`}).join("")+fw(a.length,"Nothing else in the last 24 hours."):hg(vo.pulse,"Quiet for now","Nothing in the last 24 hours. Agent calls and node changes stream in here live."):jo(8);wr(n,s)}function Hp(){const n=document.getElementById("ovHealth");if(!n)return;const e=D.health,t=e.ok!==!1&&!!e.server,i=cg||"connecting",a=(l,c,p)=>`<div><span class="cc-dot ${l}"></span><span class="t"><small>${b(c)}</small><b title="${O(p.replace(/<[^>]+>/g,""))}">${p}</b></span></div>`,s=e.vault_configured!==!1;n.innerHTML=a(t?"ok":"err","Server",t?b(e.version?"Online · v"+e.version:"Online"):"Unreachable")+a(i==="on"?"ok":i==="off"?"err":"run","Realtime",i==="on"?"Live"+(Fp?` · ${bn(Fp,"browser")}`:""):i==="off"?"Offline":"Connecting")+a(s?"ok":"err","Vault",s?"Ready":"Not configured")+a(e.locked?"err":e.armed?"run":"ok","Gateway",e.locked?"Locked":e.armed?"Sign-in window open":"Normal"),Ew();const o=!t||i==="off"||!s||e.locked,r=document.getElementById("ovHealthPill");r&&(r.innerHTML=o?'<span class="ov-pill err"><span class="cc-dot err"></span>Needs attention</span>':i!=="on"||e.armed?`<span class="ov-pill warn"><span class="cc-dot run"></span>${e.armed?"Sign-in window open":"Connecting"}</span>`:'<span class="ov-pill"><span class="cc-dot ok"></span>All systems normal</span>')}function Tw(){uw(),he.go("keys")}function Ew(){const n=document.getElementById("ovConnect");if(!n)return;const e=D.health.base_url,t=e?e.replace(/\/+$/,"")+"/mcp":"",i=`<span class="ov-tile">${pe.plug}</span><span class="t"><small>MCP endpoint</small>${t?`<span class="ov-path" title="${O(t)}"><span class="h">${b(t.replace(/^https?:\/\//,""))}</span></span>`:'<span class="ov-sub">Not known yet</span>'}</span>${t?`<button type="button" class="cc-ibtn ov-copy" data-copy-mcp aria-label="Copy the MCP endpoint" title="Copy endpoint">${pe.copy}</button>`:""}${vc&&xo.length?`<button type="button" class="btn sm" data-new-agent aria-label="New agent" title="New agent">${pe.plus}<span class="lbl">New agent</span></button>`:""}`;wr(n,i)&&(n.querySelector("[data-copy-mcp]")?.addEventListener("click",()=>{Sa(t,"MCP endpoint copied")}),n.querySelector("[data-new-agent]")?.addEventListener("click",Tw))}const l4=n=>n<.5?4*n*n*n:1-Math.pow(-2*n+2,3)/2;let c4=class{constructor(){this.x=0,this.y=0,this.k=1,this.w=1,this.h=1,this.minK=.04,this.maxK=6,this.vx=0,this.vy=0,this.anim=null}toWorld(e,t){return{x:(e-this.w/2)/this.k+this.x,y:(t-this.h/2)/this.k+this.y}}toScreen(e,t){return{x:(e-this.x)*this.k+this.w/2,y:(t-this.y)*this.k+this.h/2}}view(e=0){const t=e/this.k;return{x0:this.x-this.w/2/this.k-t,y0:this.y-this.h/2/this.k-t,x1:this.x+this.w/2/this.k+t,y1:this.y+this.h/2/this.k+t}}zoomAt(e,t,i){this.anim=null;const a=this.toWorld(e,t);this.k=Math.max(this.minK,Math.min(this.maxK,this.k*i));const s=this.toWorld(e,t);this.x+=a.x-s.x,this.y+=a.y-s.y}panBy(e,t){this.anim=null,this.x-=e/this.k,this.y-=t/this.k}stop(){this.anim=null,this.vx=this.vy=0}animateTo(e,t,i,a=650){this.vx=this.vy=0,i=Math.max(this.minK,Math.min(this.maxK,i)),this.anim={x0:this.x,y0:this.y,k0:this.k,x1:e,y1:t,k1:i,t0:performance.now(),ms:a}}fit(e,t=60,i=650,a=1.6,s=0,o=0){const r=Math.max(1,e.x1-e.x0),l=Math.max(1,e.y1-e.y0),c=Math.min((this.w-t*2)/r,(this.h-t*2-s-o)/l,a),p=(e.x0+e.x1)/2,h=(e.y0+e.y1)/2-(s-o)/2/c;i<=0?(this.x=p,this.y=h,this.k=Math.max(this.minK,c),this.anim=null):this.animateTo(p,h,c,i)}step(e){if(this.anim){const t=this.anim,i=Math.min(1,(e-t.t0)/t.ms),a=l4(i);return this.k=t.k0*Math.pow(t.k1/t.k0,a),this.x=t.x0+(t.x1-t.x0)*a,this.y=t.y0+(t.y1-t.y0)*a,i>=1&&(this.anim=null),!0}return Math.abs(this.vx)>.05||Math.abs(this.vy)>.05?(this.x-=this.vx/this.k,this.y-=this.vy/this.k,this.vx*=.93,this.vy*=.93,!0):(this.vx=this.vy=0,!1)}};const xc="\0dir:";function Gp(n){const e=n.lastIndexOf("/");return e<0?"":n.slice(0,e)}const d4=["#2dd4bf","#60a5fa","#c084fc","#fbbf24","#f472b6","#4ade80","#fb923c","#a3e635","#f87171","#818cf8","#22d3ee","#e879f9"],p4=["#0d9488","#2563eb","#9333ea","#d97706","#db2777","#16a34a","#ea580c","#65a30d","#dc2626","#4f46e5","#0891b2","#c026d3"];function Cw(n,e,t){const i=n.replace("#","");if(i.length!==6)return n;const a=parseInt(i,16),s=c=>Math.round(c+(e-c)*t),o=s(a>>16&255),r=s(a>>8&255),l=s(a&255);return"#"+(1<<24|o<<16|r<<8|l).toString(16).slice(1)}function h4(n){return 3.6+Math.sqrt(n)*1.9}class u4{constructor(){this.all=new Map,this.refs=[],this.outgoing=new Map,this.incoming=new Map,this.byPath=new Map,this.tagsByPath=new Map,this.byName=new Map}make(e,t,i,a,s,o,r){return{id:e,kind:t,label:i,path:a,group:s,dir:o,tags:[],color:r,degree:0,r:4,x:NaN,y:NaN,vx:0,vy:0,fx:null,fy:null,pinned:!1,tx:0,ty:0,born:0,dying:0,fade:1,i:0}}ingest(e,t,i){const a=e.nodes||[],s=new Set,o=[];this.byPath.clear();const r=new Set;this.byName.clear();for(const d of a){const u=d.path||d.id+".md",f=Gp(u),v=d.folder||(f?f.split("/")[0]:"Root"),g=u;this.byName.has(d.id)||this.byName.set(d.id,g);let m=this.all.get(g);(!m||m.kind!=="note")&&(m=this.make(g,"note",d.id,u,v,f,""),this.all.set(g,m),o.push(m),i&&(m.born=t)),m.path=u,m.dir=f,m.group=v,m.dying=0,Array.isArray(d.tags)&&this.tagsByPath.set(u,d.tags),m.tags=this.tagsByPath.get(u)||m.tags,s.add(g),this.byPath.set(u,m);for(let x=f;x;x=Gp(x))r.add(x)}for(const d of r){const u=xc+d;let f=this.all.get(u);const v=d.split("/")[0];f||(f=this.make(u,"folder",d.split("/").pop()||d,d,v,Gp(d),""),this.all.set(u,f),o.push(f),i&&(f.born=t)),f.dying=0,s.add(u)}const l=[];this.all.forEach((d,u)=>{s.has(u)||(i?d.dying||(d.dying=t,l.push(d)):this.all.delete(u))}),this.outgoing.clear(),this.incoming.clear();const c=new Set;this.refs=[];for(const d of e.links||[]){const u={source:this.byName.get(d.source)||d.source,target:this.byName.get(d.target)||d.target};if(u.source===u.target||!this.all.has(u.source)||!this.all.has(u.target))continue;this.outgoing.has(u.source)||this.outgoing.set(u.source,new Set),this.incoming.has(u.target)||this.incoming.set(u.target,new Set),this.outgoing.get(u.source).add(u.target),this.incoming.get(u.target).add(u.source);const f=u.source<u.target?u.source+""+u.target:u.target+""+u.source;c.has(f)||(c.add(f),this.refs.push([u.source,u.target]))}const p=new Map;for(const[d,u]of this.refs)p.set(d,(p.get(d)||0)+1),p.set(u,(p.get(u)||0)+1);const h=new Map;this.all.forEach(d=>{d.dying||d.dir&&h.set(d.dir,(h.get(d.dir)||0)+1)}),this.all.forEach(d=>{d.kind==="note"?(d.degree=p.get(d.id)||0,d.r=h4(d.degree)):(d.degree=h.get(d.path)||0,d.r=9+Math.sqrt(d.degree)*1.6)});for(const d of o){if(!Number.isNaN(d.x))continue;const u=this.anchorFor(d);if(u&&!Number.isNaN(u.x)){const f=Math.random()*Math.PI*2;d.x=u.x+Math.cos(f)*(u.r+14),d.y=u.y+Math.sin(f)*(u.r+14)}}return{added:o,removed:l}}recolor(e){const t=e?p4:d4,i=new Map;this.all.forEach(c=>i.set(c.group,(i.get(c.group)||0)+1));const a=Array.from(i.keys()).sort((c,p)=>(i.get(p)||0)-(i.get(c)||0)||c.localeCompare(p)),s=new Map;a.forEach((c,p)=>{const h=D.folderMeta[c];s.set(c,h&&h.color||t[p%t.length])});const o=new Map,r=Array.from(new Set(Array.from(this.all.values()).map(c=>c.kind==="folder"?c.path:c.dir))).sort(),l=new Map;for(const c of r){const p=c.split("/")[0];if(!c.includes("/"))continue;const h=l.get(p)||0;l.set(p,h+1),o.set(c,h+1)}this.all.forEach(c=>{const p=s.get(c.group)||t[0],h=c.kind==="folder"?c.path:c.dir,d=o.get(h)||0;if(!d){c.color=p;return}const u=Math.ceil(d/2)*.13;c.color=d%2?Cw(p,e?0:255,Math.min(.4,u)):Cw(p,e?255:0,Math.min(.35,u))})}groupColor(e){for(const t of this.all.values())if(t.group===e&&t.kind==="note"&&!t.dir.includes("/"))return t.color;for(const t of this.all.values())if(t.group===e)return t.color;return"#888"}anchorFor(e){const t=this.outgoing.get(e.id)||this.incoming.get(e.id);if(t)for(const i of t){const a=this.all.get(i);if(a&&!Number.isNaN(a.x))return a}return this.all.get(xc+e.dir)||this.all.get(xc+e.path.split("/")[0])}reap(e,t){let i=!1;return this.all.forEach((a,s)=>{a.dying&&e-a.dying>t&&(this.all.delete(s),i=!0)}),i}visible(e){const t=r=>e.tags.size?(this.tagsByPath.get(r.path)||r.tags).some(c=>e.tags.has(c)):!0,i=new Set;if(this.all.forEach(r=>{r.kind!=="note"||e.hiddenGroups.has(r.group)||!t(r)||!e.orphans&&!r.degree&&!r.dying||i.add(r)}),e.folders){const r=new Set;i.forEach(l=>{for(let c=l.dir;c;c=Gp(c))r.add(c)}),r.forEach(l=>{const c=this.all.get(xc+l);c&&i.add(c)})}const a=[],s=(r,l,c)=>({s:r,t:l,kind:c,k:0,len:0,bias:.5});e.folders&&i.forEach(r=>{if(!r.dir)return;const l=this.all.get(xc+r.dir);l&&i.has(l)&&a.push(s(l,r,"tree"))});for(const[r,l]of this.refs){const c=this.all.get(r),p=this.all.get(l);c&&p&&i.has(c)&&i.has(p)&&a.push(s(c,p,"ref"))}return{nodes:Array.from(i).sort((r,l)=>r.kind!==l.kind?r.kind==="folder"?1:-1:r.degree-l.degree),links:a}}groups(){const e=new Map;return this.all.forEach(t=>{t.kind==="note"&&!t.dying&&e.set(t.group,(e.get(t.group)||0)+1)}),Array.from(e.entries()).sort((t,i)=>i[1]-t[1]).map(([t,i])=>[t,i,this.groupColor(t)])}}function f4(n){const e={path:"",depth:0,folder:null,notes:[],kids:[],weight:0},t=new Map([["",e]]),i=s=>{let o=t.get(s);if(o)return o;const r=s.lastIndexOf("/"),l=i(r<0?"":s.slice(0,r));return o={path:s,depth:l.depth+1,folder:null,notes:[],kids:[],weight:0},l.kids.push(o),t.set(s,o),o};for(const s of n)s.kind==="folder"?i(s.path).folder=s:i(s.dir).notes.push(s);const a=s=>(s.kids.sort((o,r)=>o.path.localeCompare(r.path)),s.notes.sort((o,r)=>r.degree-o.degree||o.label.localeCompare(r.label)),s.weight=s.notes.length+s.kids.reduce((o,r)=>o+a(r),0)+(s.folder?1:0),Math.max(1,s.weight));return a(e),e}const bc=150;function m4(n){const e=f4(n),t=new Set,i=(a,s,o)=>{const r=o-s,l=(s+o)/2;if(a.folder){const v=a.depth*bc;a.folder.tx=Math.cos(l)*v,a.folder.ty=Math.sin(l)*v,t.add(v)}const c=Math.max(1,a.weight-(a.folder?1:0)),p=r*a.notes.length/c,h=r-p;let d=s;const u=Math.ceil(a.kids.length/2),f=v=>{const g=h*Math.max(1,v.weight)/Math.max(1,c-a.notes.length);i(v,d,d+g),d+=g};if(a.kids.slice(0,u).forEach(f),a.notes.length){const v=(a.depth+1)*bc-bc*.35,g=d,m=d+p,x=15,_=Math.max(.001,(m-g)*v),w=Math.max(1,Math.ceil(a.notes.length*x/_)),S=Math.ceil(a.notes.length/w);a.notes.forEach((A,C)=>{const y=C%w,M=Math.floor(C/w),T=S>1?(M+.5)/S:.5,L=g+(m-g)*(w>1?(M+.5+y%2*.5)/(S+.5):T),P=v+y*13;A.tx=Math.cos(L)*P,A.ty=Math.sin(L)*P}),t.add((a.depth+1)*bc-bc*.35),d=m}a.kids.slice(u).forEach(f)};return i(e,-Math.PI/2,Math.PI*1.5),{rings:Array.from(t).sort((a,s)=>a-s)}}function g4(n){const e=new Map,t=new Map;for(const r of n){if(r.kind==="folder"){t.set(r.path,r);continue}const l=e.get(r.dir)||[];l.push(r),e.set(r.dir,l)}const i=Array.from(e.entries()).sort((r,l)=>r[0].split("/")[0].localeCompare(l[0].split("/")[0])||l[1].length-r[1].length),a=[],s=new Map;for(const[r,l]of i){l.sort((u,f)=>f.degree-u.degree);let c=0;for(const u of l)c+=(u.r+5)*(u.r+5)*4.2;const p=Math.sqrt(c/Math.PI)+22;let h=0,d=0;for(let u=0;;u+=.12){const f=9*u;if(h=Math.cos(u)*f,d=Math.sin(u)*f,a.every(v=>Math.hypot(v.x-h,v.y-d)>v.r+p+36)||u>4e3)break}a.push({x:h,y:d,r:p}),s.set(r,{x:h,y:d}),l.forEach((u,f)=>{const v=Math.sqrt(f+.5)*Math.sqrt(c/Math.PI/Math.max(1,l.length)),g=f*2.399963;u.tx=h+Math.cos(g)*v,u.ty=d+Math.sin(g)*v})}const o=Array.from(t.keys()).sort((r,l)=>l.split("/").length-r.split("/").length);for(const r of o){const l=t.get(r),c=s.get(r);if(c){const u=a.find(f=>f.x===c.x&&f.y===c.y);l.tx=c.x,l.ty=c.y-(u?u.r+10:30);continue}let p=0,h=0,d=0;s.forEach((u,f)=>{f.startsWith(r+"/")&&(p+=u.x,h+=u.y,d++)}),l.tx=d?p/d:0,l.ty=d?h/d:0,s.set(r,{x:l.tx,y:l.ty})}}function Rw(n){const e=new Map;for(const s of n)e.has(s.group)||e.set(s.group,e.size);const t=Math.max(1,e.size),i=120+Math.sqrt(n.length)*14;let a=0;for(const s of n){if(!Number.isNaN(s.x))continue;const r=(e.get(s.group)||0)/t*Math.PI*2,l=Math.sqrt(a++)*9,c=a*2.399963;s.x=Math.cos(r)*i+Math.cos(c)*l*.4,s.y=Math.sin(r)*i+Math.sin(c)*l*.4}}const Lw="memora.layout.graph",vg="memora.graph.prefs";function Pw(n){try{const e=localStorage.getItem(n);return e?JSON.parse(e):null}catch{return null}}function Iw(n,e){try{localStorage.setItem(n,JSON.stringify(e))}catch{}}function $w(n){const e={v:1,pins:{}},t=n&&typeof n=="object"?n.pins:null;if(t&&typeof t=="object")for(const[i,a]of Object.entries(t))Array.isArray(a)&&a.length===2&&a.every(s=>typeof s=="number"&&Number.isFinite(s))&&(e.pins[i]=[a[0],a[1]]);return e}async function v4(){try{const n=await Dn("/api/ui/layout/graph");if(n&&n.data)return $w(n.data)}catch{}return $w(Pw(Lw))}let Nw=0;function Dw(n){Iw(Lw,n),clearTimeout(Nw),Nw=window.setTimeout(()=>{Dn("/api/ui/layout/graph",{method:"PUT",body:{data:n}}).catch(()=>{})},700)}function x4(){return Ow(Pw(vg)||{})}function zw(){return Ow({})}function Ow(n){return{mode:n.mode==="radial"||n.mode==="clusters"?n.mode:"force",labels:typeof n.labels=="number"?n.labels:.45,spacing:typeof n.spacing=="number"?n.spacing:1,spacingBy:{force:xg(n.spacingBy?.force,typeof n.spacing=="number"?n.spacing:1),radial:xg(n.spacingBy?.radial,1),clusters:xg(n.spacingBy?.clusters,1)},noteLabels:n.noteLabels!==!1,folderLabels:n.folderLabels!==!1,folders:n.folders!==!1,hulls:n.hulls!==!1,orphans:n.orphans!==!1,minimap:n.minimap!==!1}}function xg(n,e){return typeof n=="number"&&isFinite(n)?n:e}function b4(){try{localStorage.removeItem(vg)}catch{}return zw()}function yc(n){Iw(vg,n)}const y4=650,Uw=520,Qi=Math.PI*2,w4=n=>1+2.70158*Math.pow(n-1,3)+1.70158*Math.pow(n-1,2);function qp(n,e){if(n.dying)return Math.max(0,1-(e-n.dying)/Uw);if(n.born){const t=(e-n.born)/y4;return t>=1?(n.born=0,1):Math.max(0,w4(Math.max(0,t)))}return 1}function ks(n,e){let t=n.trim();if(t.startsWith("rgb"))return t;t[0]==="#"&&(t=t.slice(1)),t.length===3&&(t=t.split("").map(a=>a+a).join(""));const i=parseInt(t.slice(0,6),16);return Number.isNaN(i)?`rgba(125,211,252,${e})`:`rgba(${i>>16&255},${i>>8&255},${i&255},${e})`}function k4(n){if(n.length<3)return n;n.sort((a,s)=>a[0]-s[0]||a[1]-s[1]);const e=(a,s,o)=>(s[0]-a[0])*(o[1]-a[1])-(s[1]-a[1])*(o[0]-a[0]),t=[];for(const a of n){for(;t.length>=2&&e(t[t.length-2],t[t.length-1],a)<=0;)t.pop();t.push(a)}const i=[];for(let a=n.length-1;a>=0;a--){const s=n[a];for(;i.length>=2&&e(i[i.length-2],i[i.length-1],s)<=0;)i.pop();i.push(s)}return i.pop(),t.pop(),t.concat(i)}class _4{constructor(e){this.ctx=e,this.hullCv=document.createElement("canvas"),this.widths=new Map,this.occ=new Uint8Array(0),this.hullCache=[],this.hullsDirty=!0}measure(e,t){const i=t+"|"+e;let a=this.widths.get(i);return a==null&&(this.ctx.font=t,a=this.ctx.measureText(e).width,this.widths.size>2e4&&this.widths.clear(),this.widths.set(i,a)),a}draw(e,t,i,a){const s=this.ctx,o=e.w,r=e.h;s.setTransform(a,0,0,a,0,0),s.globalAlpha=1,s.fillStyle=i.bg,s.fillRect(0,0,o,r),this.grid(e,i);const l=e.k,c=e.view(80);for(const p of t.nodes){const h=!t.focus||t.focus.has(p)?1:i.light?.13:.1;p.fade+=(h-p.fade)*.18,Math.abs(h-p.fade)<.004&&(p.fade=h)}if(t.mode==="radial"){s.save(),s.strokeStyle=ks(i.muted,i.light?.22:.16),s.setLineDash([3,6]),s.lineWidth=1;const p=e.toScreen(0,0);for(const h of t.rings)s.beginPath(),s.arc(p.x,p.y,h*l,0,Qi),s.stroke();s.restore()}t.hulls&&t.mode!=="radial"&&this.drawHulls(e,t,i,a),this.drawLinks(e,t,i,c),this.drawNodes(e,t,i,c),this.drawPulses(e,t,i),this.drawLabels(e,t,i),s.globalAlpha=1}grid(e,t){const i=this.ctx;let a=24;for(;a*e.k<18;)a*=2;for(;a*e.k>40;)a/=2;const s=a*e.k,o=e.toScreen(0,0),r=(o.x%s+s)%s,l=(o.y%s+s)%s,c=s>28?1.25:1.05;i.fillStyle=t.light?"rgba(15,23,42,.26)":"rgba(148,163,184,.28)",i.beginPath();for(let p=r;p<e.w;p+=s)for(let h=l;h<e.h;h+=s)i.moveTo(p+c,h),i.arc(p,h,c,0,Math.PI*2);i.fill()}drawHulls(e,t,i,a){if(this.hullsDirty){const d=new Map;for(const u of t.nodes){if(u.dying)continue;let f=d.get(u.group);f||d.set(u.group,f={color:u.color,pts:[]}),u.kind==="folder"&&!u.dir&&(f.color=u.color),f.pts.push([u.x,u.y])}this.hullCache=[],d.forEach((u,f)=>{if(u.pts.length<2)return;const v=k4(u.pts);let g=v[0],m=0;for(const x of v)m+=x[0],x[1]<g[1]&&(g=x);g=[m/v.length,g[1]],this.hullCache.push({group:f,color:u.color,pts:v,top:g})}),this.hullsDirty=!1}const s=this.hullCv,o=Math.floor(e.w*a),r=Math.floor(e.h*a);(s.width!==o||s.height!==r)&&(s.width=o,s.height=r);const l=s.getContext("2d");if(!l)return;l.setTransform(1,0,0,1,0,0),l.clearRect(0,0,o,r),l.setTransform(a,0,0,a,0,0),l.lineJoin="round",l.lineCap="round";const c=Math.max(16,26*e.k),p=t.focus?new Set(Array.from(t.focus).map(d=>d.group)):null;for(const d of this.hullCache)l.globalAlpha=p&&!p.has(d.group)?.35:1,l.fillStyle=d.color,l.strokeStyle=d.color,l.lineWidth=c*2,l.beginPath(),d.pts.forEach((u,f)=>{const v=e.toScreen(u[0],u[1]);f?l.lineTo(v.x,v.y):l.moveTo(v.x,v.y)}),l.closePath(),l.fill(),l.stroke();const h=this.ctx;h.save(),h.setTransform(1,0,0,1,0,0),h.globalAlpha=i.light?.085:.07,h.drawImage(s,0,0),h.restore()}drawLinks(e,t,i,a){const s=this.ctx,o=e.k,r=e.w/2-e.x*o,l=e.h/2-e.y*o,c=t.links.length<6e3&&o>.12,p=t.hover||t.selected,h=new Map,d=new Path2D;let u=0;const f=[];for(const m of t.links){const x=m.s,_=m.t;if(x.x<a.x0&&_.x<a.x0||x.x>a.x1&&_.x>a.x1||x.y<a.y0&&_.y<a.y0||x.y>a.y1&&_.y>a.y1)continue;const w=x.x*o+r,S=x.y*o+l,A=_.x*o+r,C=_.y*o+l,y=!!p&&(x===p||_===p);let M;if(y)M=d,u++,f.length<80&&f.push(m);else{const T=Math.min(x.fade,_.fade)*Math.min(qp(x,t.now),qp(_,t.now)),L=T>.75?2:T>.3?1:0,P=(m.kind==="tree"?x.color:"")+"|"+L;let z=h.get(P);z||h.set(P,z=new Path2D),M=z}if(M.moveTo(w,S),c){const T=(w+A)/2,L=(S+C)/2,P=m.kind==="tree"?.06:.12;M.quadraticCurveTo(T-(C-S)*P,L+(A-w)*P,A,C)}else M.lineTo(A,C)}const v=i.light?.3:.24,g=Math.max(.6,Math.min(1.6,.5+o*.7));if(s.lineCap="round",h.forEach((m,x)=>{const[_,w]=x.split("|"),S=Number(w),A=S===2?1:S===1?.45:.12;_?(s.strokeStyle=ks(_,(i.light?.5:.42)*A),s.lineWidth=g*1.25):(s.strokeStyle=ks(i.muted,v*A*1.4),s.lineWidth=g),s.stroke(m)}),u){s.strokeStyle=ks(i.accent,.95),s.lineWidth=Math.max(1.4,g*1.7),s.stroke(d);const m=t.now%1600/1600;s.fillStyle=i.accent;for(const x of f){const _=x.s.x*o+r,w=x.s.y*o+l,S=x.t.x*o+r,A=x.t.y*o+l,C=(_+S)/2-(A-w)*(x.kind==="tree"?.06:.12),y=(w+A)/2+(S-_)*(x.kind==="tree"?.06:.12),M=1-m,T=c?M*M*_+2*M*m*C+m*m*S:_+(S-_)*m,L=c?M*M*w+2*M*m*y+m*m*A:w+(A-w)*m;s.beginPath(),s.arc(T,L,2.2,0,Qi),s.fill()}}}drawNodes(e,t,i,a){const s=this.ctx,o=e.k,r=e.w/2-e.x*o,l=e.h/2-e.y*o;for(const c of t.nodes){if(c.x+c.r<a.x0||c.x-c.r>a.x1||c.y+c.r<a.y0||c.y-c.r>a.y1)continue;const p=qp(c,t.now);if(p<=.01)continue;const h=c.x*o+r,d=c.y*o+l,u=Math.max(1.3,c.r*o)*p,f=c.fade*(c.dying?p:1);if(s.globalAlpha=f,c.kind==="folder"?(s.beginPath(),s.arc(h,d,u,0,Qi),s.fillStyle=ks(c.color,i.light?.22:.2),s.fill(),s.lineWidth=Math.max(1.5,u*.26),s.strokeStyle=c.color,s.stroke(),s.beginPath(),s.arc(h,d,Math.max(1,u*.3),0,Qi),s.fillStyle=c.color,s.fill()):(c.degree>=8&&u>3&&(s.beginPath(),s.arc(h,d,u*1.85,0,Qi),s.fillStyle=ks(c.color,.13),s.fill()),s.beginPath(),s.arc(h,d,u,0,Qi),s.fillStyle=c.color,s.fill(),u>4&&(s.lineWidth=1,s.strokeStyle=i.light?"rgba(255,255,255,.75)":"rgba(0,0,0,.35)",s.stroke())),(c===t.selected||c===t.hover||c===t.dragging)&&(s.globalAlpha=1,s.beginPath(),s.arc(h,d,u+3.5,0,Qi),s.lineWidth=c===t.selected?2.2:1.5,s.strokeStyle=c===t.selected?i.accent:i.ink,s.stroke()),c.pinned){s.globalAlpha=f;const v=h+u*.75,g=d-u*.75;s.beginPath(),s.arc(v,g,Math.max(2.4,u*.32),0,Qi),s.fillStyle=i.ink,s.fill(),s.lineWidth=1.2,s.strokeStyle=i.bg,s.stroke()}}s.globalAlpha=1}drawPulses(e,t,i){if(!t.pulses.size)return;const a=this.ctx,s=new Map;for(const o of t.nodes)t.pulses.has(o.id)&&s.set(o.id,o);t.pulses.forEach((o,r)=>{const l=s.get(r);if(!l)return;const c=e.toScreen(l.x,l.y),p=Math.max(2,l.r*e.k);o.forEach((h,d)=>{const u=h.end?Math.min(1,Math.max(0,1-(t.now-h.end)/2600)):1;if(u<=0)return;const f=Math.max(0,t.now-h.start)%1300/1300;a.globalAlpha=(1-f)*.85*u,a.beginPath(),a.arc(c.x,c.y,p+3+f*26,0,Qi),a.lineWidth=2.4,a.strokeStyle=h.color,a.stroke(),a.globalAlpha=.5*u,a.beginPath(),a.arc(c.x,c.y,p+2,0,Qi),a.fillStyle=h.color,a.fill();const v=xl(h.actor);a.font="700 9.5px system-ui, -apple-system, Segoe UI, sans-serif";const m=a.measureText(v).width+9,x=c.x+p*.7+2+d*(m+2),_=c.y-p*.7-16;a.globalAlpha=u,a.beginPath(),S4(a,x,_,m,14,7),a.fillStyle=h.color,a.fill(),a.lineWidth=1.5,a.strokeStyle=i.bg,a.stroke(),a.fillStyle="#fff",a.textAlign="left",a.fillText(v,x+4.5,_+10.3)})}),a.globalAlpha=1}drawLabels(e,t,i){const a=this.ctx,s=e.w,o=e.h,r=8,l=Math.ceil(s/r)+1,c=Math.ceil(o/r)+1;this.occ.length<l*c&&(this.occ=new Uint8Array(l*c*2));const p=this.occ;p.fill(0,0,l*c);const h=e.k,d=12-t.labelDensity*10.5,u=Math.ceil(t.reserveTop/r);p.fill(1,0,Math.min(c,u)*l);const f=[],v=[];for(const x of[t.selected,t.hover,t.dragging])x&&!v.includes(x)&&v.push(x);t.focus&&t.focus.size<60&&t.focus.forEach(x=>!v.includes(x)&&v.push(x));for(let x=t.nodes.length-1;x>=0;x--){const _=t.nodes[x];if(_.fade<.5||_.dying||v.includes(_)||(_.kind==="folder"?!t.folderLabels:!t.noteLabels))continue;const w=_.r*h;(_.kind==="folder"?w*1.6>=d*.6:w>=d)&&f.push(_)}a.textBaseline="middle",a.textAlign="left",a.lineJoin="round";let g=0;const m=(x,_)=>{const w=e.toScreen(x.x,x.y),S=Math.max(1.3,x.r*h)*qp(x,t.now),A=x.kind==="folder"||_,C=x.kind==="folder"?12.5:Math.min(13,10.5+S*.12),y=`${A?600:450} ${C}px system-ui, -apple-system, Segoe UI, sans-serif`,M=x.label.length>34?x.label.slice(0,32)+"…":x.label,T=this.measure(M,y);let L,P;if(x.kind==="folder"?(L=w.x-T/2,P=w.y+S+10):(L=w.x+S+4,P=w.y),L>s||L+T<0||P<-10||P>o+10)return;const z=Math.max(0,Math.floor((L-2)/r)),R=Math.min(l-1,Math.floor((L+T+2)/r)),B=Math.max(0,Math.floor((P-C/2-1)/r)),K=Math.min(c-1,Math.floor((P+C/2+1)/r));if(!_){for(let N=B;N<=K;N++)for(let V=z;V<=R;V++)if(p[N*l+V])return}for(let N=B;N<=K;N++)for(let V=z;V<=R;V++)p[N*l+V]=1;a.font=y,a.globalAlpha=Math.min(1,x.fade*1.1),a.lineWidth=3.2,a.strokeStyle=i.bg,a.strokeText(M,L,P),a.fillStyle=x.kind==="folder"?x.color:_?i.ink:ks(i.ink,.86),a.fillText(M,L,P),g++};if(v.forEach((x,_)=>m(x,_<1||x===t.selected)),t.folderLabels&&t.hulls&&t.mode!=="radial"){const x=t.focus?new Set(Array.from(t.focus).map(S=>S.group)):null,_=Math.max(16,26*e.k),w="650 11.5px system-ui, -apple-system, Segoe UI, sans-serif";a.font=w;for(const S of this.hullCache){const A=S.group.toUpperCase(),C=this.measure(A,w)*1.08,y=e.toScreen(S.top[0],S.top[1]),M=y.x-C/2,T=y.y-_-2;if(M>s||M+C<0||T<0||T>o)continue;const L=Math.max(0,Math.floor(M/r)),P=Math.min(l-1,Math.floor((M+C)/r)),z=Math.max(0,Math.floor((T-7)/r)),R=Math.min(c-1,Math.floor((T+7)/r));let B=!0;for(let K=z;K<=R&&B;K++)for(let N=L;N<=P;N++)p[K*l+N]&&(B=!1);if(B){for(let K=z;K<=R;K++)for(let N=L;N<=P;N++)p[K*l+N]=1;a.globalAlpha=x&&!x.has(S.group)?.25:.8,a.font=w,a.letterSpacing="0.08em",a.fillStyle=S.color,a.fillText(A,M,T),a.letterSpacing="0px"}}}for(const x of f){if(g>420)break;m(x,!1)}a.globalAlpha=1,a.textBaseline="alphabetic"}}function S4(n,e,t,i,a,s){n.moveTo(e+s,t),n.arcTo(e+i,t,e+i,t+a,s),n.arcTo(e+i,t+a,e,t+a,s),n.arcTo(e,t+a,e,t,s),n.arcTo(e,t,e+i,t,s),n.closePath()}function M4(n,e,t,i,a,s,o){n.setTransform(i,0,0,i,0,0),n.clearRect(0,0,e,t);let r=1/0,l=1/0,c=-1/0,p=-1/0;for(const S of a)S.x<r&&(r=S.x),S.y<l&&(l=S.y),S.x>c&&(c=S.x),S.y>p&&(p=S.y);const h=s.view();r=Math.min(r,h.x0),l=Math.min(l,h.y0),c=Math.max(c,h.x1),p=Math.max(p,h.y1);const d=6,u=Math.min((e-d*2)/Math.max(1,c-r),(t-d*2)/Math.max(1,p-l)),f=d+(e-d*2-(c-r)*u)/2-r*u,v=d+(t-d*2-(p-l)*u)/2-l*u;let g="";for(const S of a){S.color!==g&&(n.fillStyle=S.color,g=S.color),n.globalAlpha=.35+.65*S.fade;const A=S.kind==="folder"?2:1.1;n.fillRect(S.x*u+f-A/2,S.y*u+v-A/2,A,A)}n.globalAlpha=1,n.strokeStyle=o.accent,n.lineWidth=1.2,n.fillStyle=ks(o.accent,.08);const m=h.x0*u+f,x=h.y0*u+v,_=(h.x1-h.x0)*u,w=(h.y1-h.y0)*u;return n.fillRect(m,x,_,w),n.strokeRect(m,x,_,w),{x0:f,y0:v,s:u}}const A4=.81,Vp=1;class T4{constructor(){this.cap=0,this.count=0,this.x0=new Float64Array(0),this.y0=new Float64Array(0),this.size=new Float64Array(0),this.child=new Int32Array(0),this.body=new Int32Array(0),this.mass=new Float64Array(0),this.cx=new Float64Array(0),this.cy=new Float64Array(0),this.next=new Int32Array(0),this.stack=new Int32Array(0)}grow(e){if(e<=this.cap)return;const t=Math.max(64,e*2),i=o=>{const r=new Float64Array(t);return r.set(o),r};this.x0=i(this.x0),this.y0=i(this.y0),this.size=i(this.size),this.mass=i(this.mass),this.cx=i(this.cx),this.cy=i(this.cy);const a=new Int32Array(t*4);a.set(this.child),this.child=a;const s=new Int32Array(t);s.set(this.body),this.body=s,this.cap=t}alloc(e,t,i){this.count>=this.cap&&this.grow(this.count+1);const a=this.count++;return this.x0[a]=e,this.y0[a]=t,this.size[a]=i,this.child[a*4]=-1,this.body[a]=-1,a}build(e,t){const i=e.length;this.next.length<i&&(this.next=new Int32Array(i*2)),this.stack.length<i*4+64&&(this.stack=new Int32Array(i*4+256)),this.grow(i*2+8),this.count=0;let a=1/0,s=1/0,o=-1/0,r=-1/0;for(const c of e)c.x<a&&(a=c.x),c.y<s&&(s=c.y),c.x>o&&(o=c.x),c.y>r&&(r=c.y);const l=Math.max(o-a,r-s,1)*1.0001+1;this.alloc(a,s,l);for(let c=0;c<i;c++)this.next[c]=-1,this.insert(c,e[c].x,e[c].y,e);for(let c=this.count-1;c>=0;c--){let p=0,h=0,d=0,u=0;if(this.child[c*4]<0)for(let f=this.body[c];f>=0;f=this.next[f]){const v=t[f],g=Math.abs(v);p+=v,h+=g,d+=e[f].x*g,u+=e[f].y*g}else for(let f=0;f<4;f++){const v=this.child[c*4+f],g=Math.abs(this.mass[v]);g&&(p+=this.mass[v],h+=g,d+=this.cx[v]*g,u+=this.cy[v]*g)}this.mass[c]=p,this.cx[c]=h?d/h:0,this.cy[c]=h?u/h:0}}insert(e,t,i,a){let s=0;for(let o=0;;o++){if(this.child[s*4]>=0){s=this.child[s*4+this.quadrant(s,t,i)];continue}const r=this.body[s];if(r<0){this.body[s]=e;return}const l=a[r];if(o>40||Math.abs(l.x-t)<1e-6&&Math.abs(l.y-i)<1e-6){this.next[e]=this.next[r],this.next[r]=e;return}const c=this.size[s]/2,p=this.x0[s],h=this.y0[s],d=this.alloc(p,h,c),u=this.alloc(p+c,h,c),f=this.alloc(p,h+c,c),v=this.alloc(p+c,h+c,c);this.child[s*4]=d,this.child[s*4+1]=u,this.child[s*4+2]=f,this.child[s*4+3]=v,this.body[s]=-1;const g=this.child[s*4+this.quadrant(s,l.x,l.y)];this.body[g]=r}}quadrant(e,t,i){const a=this.size[e]/2;return(t>=this.x0[e]+a?1:0)+(i>=this.y0[e]+a?2:0)}apply(e,t,i,a,s,o){const r=this.stack;let l=0;r[l++]=0;let c=0,p=0;for(;l;){const h=r[--l],d=this.mass[h];if(!d)continue;let u=this.cx[h]-t.x,f=this.cy[h]-t.y,v=u*u+f*f;const g=this.size[h],m=this.child[h*4]<0;if(!m&&g*g/A4<v){v<o&&(v<Vp&&(v=Math.sqrt(Vp*v)),c+=u*d/v,p+=f*d/v);continue}if(!m){r[l++]=this.child[h*4],r[l++]=this.child[h*4+1],r[l++]=this.child[h*4+2],r[l++]=this.child[h*4+3];continue}for(let x=this.body[h];x>=0;x=this.next[x]){if(x===e)continue;const _=i[x];u=_.x-t.x,f=_.y-t.y,v=u*u+f*f,!(v>=o)&&(v===0&&(u=(Math.random()-.5)*.001,f=(Math.random()-.5)*.001,v=u*u+f*f),v<Vp&&(v=Math.sqrt(Vp*v)),c+=u*a[x]/v,p+=f*a[x]/v)}}t.vx+=c*s,t.vy+=p*s}}class E4{constructor(){this.nodes=[],this.links=[],this.alpha=1,this.alphaTarget=0,this.alphaMin=.002,this.alphaDecay=1-Math.pow(.002,1/320),this.velocityDecay=.42,this.mode="force",this.targetPull=0,this.spacing=1,this.tree=new T4,this.charge=new Float64Array(0),this.cellNext=new Int32Array(0),this.cellHead=new Int32Array(0)}setData(e,t){this.nodes=e,this.links=t,e.forEach((a,s)=>a.i=s);const i=new Map;for(const a of t)i.set(a.s,(i.get(a.s)||0)+1),i.set(a.t,(i.get(a.t)||0)+1);for(const a of t){const s=i.get(a.s)||1,o=i.get(a.t)||1;a.bias=s/(s+o);const r=1/Math.min(s,o);a.k=a.kind==="tree"?r*.9:r*.7,a.len=a.kind==="tree"?26+a.t.r*2+Math.sqrt(i.get(a.s)||1)*2.5:38+(a.s.r+a.t.r)*1.4}}get running(){return this.alpha>=this.alphaMin||this.alphaTarget>0}reheat(e=.6){this.alpha=Math.max(this.alpha,e)}tick(){const e=this.nodes,t=e.length;if(!t)return;this.alpha+=(this.alphaTarget-this.alpha)*this.alphaDecay;const i=this.alpha,a=this.mode!=="force",s=a?this.mode==="radial"?.015:.06:1;for(const h of this.links){const d=h.s,u=h.t;if(d.dying||u.dying)continue;let f=u.x+u.vx-d.x-d.vx||(Math.random()-.5)*.001,v=u.y+u.vy-d.y-d.vy||(Math.random()-.5)*.001,g=Math.sqrt(f*f+v*v);g=(g-h.len)/g*i*h.k*s,f*=g,v*=g,u.vx-=f*h.bias,u.vy-=v*h.bias,d.vx+=f*(1-h.bias),d.vy+=v*(1-h.bias)}this.charge.length<t&&(this.charge=new Float64Array(t*2));const o=(a?this.mode==="radial"?.04:.12:1)*this.spacing;for(let h=0;h<t;h++){const d=e[h];this.charge[h]=d.dying?0:-(d.kind==="folder"?220:34+d.r*5)*o}this.tree.build(e,this.charge);const r=a?14400:1600*1600;for(let h=0;h<t;h++)this.tree.apply(h,e[h],e,this.charge,i,r);const l=this.targetPull,c=a?0:.035;for(let h=0;h<t;h++){const d=e[h];l&&(d.vx+=(d.tx-d.x)*l,d.vy+=(d.ty-d.y)*l),c&&(d.vx-=d.x*c*i,d.vy-=d.y*c*i)}this.collide(a?.9:.6);const p=1-this.velocityDecay;for(let h=0;h<t;h++){const d=e[h];if(d.fx!=null&&d.fy!=null){d.x=d.fx,d.y=d.fy,d.vx=0,d.vy=0;continue}d.vx*=p,d.vy*=p;const u=d.vx*d.vx+d.vy*d.vy;if(u>3600){const f=60/Math.sqrt(u);d.vx*=f,d.vy*=f}d.x+=d.vx,d.y+=d.vy}}collide(e){const t=this.nodes,i=t.length;let a=1,s=1/0,o=1/0,r=-1/0,l=-1/0;for(const g of t)g.r>a&&(a=g.r),g.x<s&&(s=g.x),g.y<o&&(o=g.y),g.x>r&&(r=g.x),g.y>l&&(l=g.y);const c=3;let p=(a+c)*2,h=Math.ceil((r-s)/p)+1,d=Math.ceil((l-o)/p)+1;for(;h*d>65536;)p*=1.5,h=Math.ceil((r-s)/p)+1,d=Math.ceil((l-o)/p)+1;const u=h*d;this.cellHead.length<u&&(this.cellHead=new Int32Array(u*2)),this.cellNext.length<i&&(this.cellNext=new Int32Array(i*2));const f=this.cellHead,v=this.cellNext;f.fill(-1,0,u);for(let g=0;g<i;g++){const m=t[g],x=Math.floor((m.x-s)/p)+Math.floor((m.y-o)/p)*h;v[g]=f[x],f[x]=g}for(let g=0;g<i;g++){const m=t[g];if(m.dying)continue;const x=Math.floor((m.x-s)/p),_=Math.floor((m.y-o)/p);for(let w=_-1;w<=_+1;w++)if(!(w<0||w>=d)){for(let S=x-1;S<=x+1;S++)if(!(S<0||S>=h))for(let A=f[S+w*h];A>=0;A=v[A]){if(A<=g)continue;const C=t[A];if(C.dying)continue;let y=m.x+m.vx-C.x-C.vx,M=m.y+m.vy-C.y-C.vy;const T=m.r+C.r+c;let L=y*y+M*M;if(L>=T*T)continue;L===0&&(y=(Math.random()-.5)*.01,M=(Math.random()-.5)*.01,L=y*y+M*M);const P=Math.sqrt(L),z=(T-P)/P*e,R=C.r*C.r/(m.r*m.r+C.r*C.r);m.vx+=y*z*R,m.vy+=M*z*R,C.vx-=y*z*(1-R),C.vy-=M*z*(1-R)}}}}}const C4=`
3416
3416
  #view-graph{padding:0 !important;overflow:hidden !important}
3417
3417
  .gx{position:absolute;inset:0;overflow:hidden;background:var(--bg,#0b0e14);color:var(--fg,#e6e9ef);
3418
3418
  --gx-glass:var(--panel,#12161f);
@@ -3429,7 +3429,7 @@ button.ov-name:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
3429
3429
  .gx-empty{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;flex-direction:column;gap:6px;color:var(--gx-mut);z-index:3;pointer-events:none;text-align:center;padding:24px}
3430
3430
  .gx-empty b{color:var(--fg,#e6e9ef);font-size:15px}
3431
3431
  .gx-hide{display:none !important}
3432
- `;function RR(){it("gx-styles",CR)}function Fw(n){const e={raw:n,text:"",words:[],tags:[],folders:[],partial:null},t=n.trim().split(/\s+/).filter(Boolean),i=[],a=!/\s$/.test(n);return t.forEach((s,o)=>{const r=s.toLowerCase(),l=o===t.length-1&&a;if(r.startsWith("#")){const c=r.slice(1);c&&e.tags.push(c),l&&(e.partial={kind:"tag",value:c})}else if(/^(in|folder):/.test(r)){const c=r.replace(/^(in|folder):/,"");c&&e.folders.push(c),l&&(e.partial={kind:"folder",value:c})}else i.push(r)}),e.words=i,e.text=i.join(" "),e}const Bw=/[\s\-_./()[\]]/,LR=n=>!n||n==="Root"?"the vault root":n;function PR(n,e){const t=e.text;if(!t)return{score:1,badge:"",text:"",field:"none",ranges:[]};const i=n.name.toLowerCase(),a=kf(n.name,t);if(a){const r=ns(n.name,t);return i===t?{score:100,badge:"Exact",text:`The name is exactly “${e.text}”`,field:"name",ranges:[a]}:a[0]===0?{score:90+r/100,badge:"Starts with",text:`The name starts with “${e.text}”`,field:"name",ranges:[a]}:Bw.test(i[a[0]-1])?{score:80+r/100,badge:"Word",text:`A word in the name starts with “${e.text}”`,field:"name",ranges:[a]}:{score:70+r/100,badge:"Contains",text:`The name contains “${e.text}”`,field:"name",ranges:[a]}}let s=null;for(const r of n.tags){const l=kf(r,t);if(!l)continue;const c=r.toLowerCase()===t,p={score:c?66:l[0]===0?62:56,badge:"Tag",text:c?`Tagged #${r}`:`Has the tag #${r}`,field:"tag",ranges:[l],tag:r};(!s||p.score>s.score)&&(s=p)}if(s)return s;const o=kf(n.folder,t);return o?{score:o[0]===0||Bw.test(n.folder[o[0]-1])?48:44,badge:"Folder",text:`In the folder ${n.folder}`,field:"folder",ranges:[o]}:null}function IR(n,e,t){const i=[];let a=0;for(const s of n){if(e.tags.length&&!e.tags.every(r=>s.tags.some(l=>l.toLowerCase().startsWith(r)))||e.folders.length&&!e.folders.every(r=>s.folder.toLowerCase().includes(r)))continue;const o=PR(s,e);if(o){if(t?.(s.region)){a++;continue}i.push({item:s,why:o})}}return i.sort((s,o)=>o.why.score-s.why.score||o.item.degree-s.item.degree||s.item.name.length-o.item.name.length),{hits:i,held:a}}function $R(n,e){const t=[];for(const i of n){const a=wf(i.name,e);if(!a)continue;const s=i.name.indexOf(a.word);t.push({item:i,why:{score:a.s,badge:"Near",text:a.why,field:"name",ranges:s>=0?[[s,s+a.word.length]]:[]}})}return t.sort((i,a)=>a.why.score-i.why.score||a.item.degree-i.item.degree).slice(0,4)}const Hw="memora.find.recent",wc=30;function Gw(){try{const n=JSON.parse(localStorage.getItem(Hw)||"[]");return Array.isArray(n)?n.filter(e=>typeof e=="string").slice(0,6):[]}catch{return[]}}function NR(n){try{localStorage.setItem(Hw,JSON.stringify([n,...Gw().filter(e=>e!==n)].slice(0,6)))}catch{}}function kc(n,e){if(!e.length)return b(n);let t="",i=0;for(const[a,s]of e)a<i||(t+=b(n.slice(i,a))+"<mark>"+b(n.slice(a,s))+"</mark>",i=s);return t+b(n.slice(i))}const Wp=(n,e)=>`${n} ${e}${n===1?"":"s"}`,DR=`
3432
+ `;function R4(){it("gx-styles",C4)}function Fw(n){const e={raw:n,text:"",words:[],tags:[],folders:[],partial:null},t=n.trim().split(/\s+/).filter(Boolean),i=[],a=!/\s$/.test(n);return t.forEach((s,o)=>{const r=s.toLowerCase(),l=o===t.length-1&&a;if(r.startsWith("#")){const c=r.slice(1);c&&e.tags.push(c),l&&(e.partial={kind:"tag",value:c})}else if(/^(in|folder):/.test(r)){const c=r.replace(/^(in|folder):/,"");c&&e.folders.push(c),l&&(e.partial={kind:"folder",value:c})}else i.push(r)}),e.words=i,e.text=i.join(" "),e}const Bw=/[\s\-_./()[\]]/,L4=n=>!n||n==="Root"?"the vault root":n;function P4(n,e){const t=e.text;if(!t)return{score:1,badge:"",text:"",field:"none",ranges:[]};const i=n.name.toLowerCase(),a=kf(n.name,t);if(a){const r=ns(n.name,t);return i===t?{score:100,badge:"Exact",text:`The name is exactly “${e.text}”`,field:"name",ranges:[a]}:a[0]===0?{score:90+r/100,badge:"Starts with",text:`The name starts with “${e.text}”`,field:"name",ranges:[a]}:Bw.test(i[a[0]-1])?{score:80+r/100,badge:"Word",text:`A word in the name starts with “${e.text}”`,field:"name",ranges:[a]}:{score:70+r/100,badge:"Contains",text:`The name contains “${e.text}”`,field:"name",ranges:[a]}}let s=null;for(const r of n.tags){const l=kf(r,t);if(!l)continue;const c=r.toLowerCase()===t,p={score:c?66:l[0]===0?62:56,badge:"Tag",text:c?`Tagged #${r}`:`Has the tag #${r}`,field:"tag",ranges:[l],tag:r};(!s||p.score>s.score)&&(s=p)}if(s)return s;const o=kf(n.folder,t);return o?{score:o[0]===0||Bw.test(n.folder[o[0]-1])?48:44,badge:"Folder",text:`In the folder ${n.folder}`,field:"folder",ranges:[o]}:null}function I4(n,e,t){const i=[];let a=0;for(const s of n){if(e.tags.length&&!e.tags.every(r=>s.tags.some(l=>l.toLowerCase().startsWith(r)))||e.folders.length&&!e.folders.every(r=>s.folder.toLowerCase().includes(r)))continue;const o=P4(s,e);if(o){if(t?.(s.region)){a++;continue}i.push({item:s,why:o})}}return i.sort((s,o)=>o.why.score-s.why.score||o.item.degree-s.item.degree||s.item.name.length-o.item.name.length),{hits:i,held:a}}function $4(n,e){const t=[];for(const i of n){const a=wf(i.name,e);if(!a)continue;const s=i.name.indexOf(a.word);t.push({item:i,why:{score:a.s,badge:"Near",text:a.why,field:"name",ranges:s>=0?[[s,s+a.word.length]]:[]}})}return t.sort((i,a)=>a.why.score-i.why.score||a.item.degree-i.item.degree).slice(0,4)}const Hw="memora.find.recent",wc=30;function Gw(){try{const n=JSON.parse(localStorage.getItem(Hw)||"[]");return Array.isArray(n)?n.filter(e=>typeof e=="string").slice(0,6):[]}catch{return[]}}function N4(n){try{localStorage.setItem(Hw,JSON.stringify([n,...Gw().filter(e=>e!==n)].slice(0,6)))}catch{}}function kc(n,e){if(!e.length)return b(n);let t="",i=0;for(const[a,s]of e)a<i||(t+=b(n.slice(i,a))+"<mark>"+b(n.slice(a,s))+"</mark>",i=s);return t+b(n.slice(i))}const Wp=(n,e)=>`${n} ${e}${n===1?"":"s"}`,D4=`
3433
3433
  .mf{position:absolute;z-index:9;display:flex;flex-direction:column;max-height:min(520px,calc(100% - 80px));overflow:hidden;
3434
3434
  border-radius:14px;background:var(--panel,#12161f);border:1px solid var(--vc-ctl-line,var(--line));color:var(--fg,#e6e9ef);
3435
3435
  box-shadow:0 18px 50px -12px rgba(0,0,0,.6),0 0 0 1px rgba(0,0,0,.25);animation:mf-in .16s ease}
@@ -3476,9 +3476,9 @@ button.ov-name:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
3476
3476
  .mf-foot{display:none}
3477
3477
  .mf-row{padding:9px 10px}}
3478
3478
  @media (prefers-reduced-motion:reduce){.mf{animation:none}}
3479
- `;class zR{constructor(e,t){this.host=e,this.src=t,this.acts=[],this.active=0,this.query=Fw(""),this.timer=0,it("map-find-css",DR),this.box=document.createElement("div"),this.box.className="mf",this.box.hidden=!0,this.box.innerHTML=`<div class="mf-head"></div><div class="mf-list" role="listbox" aria-label="Search results"></div>
3480
- <div class="mf-foot"><span><kbd>↑</kbd><kbd>↓</kbd>move</span><span><kbd>Enter</kbd>open</span><span><kbd>Tab</kbd>use tag or folder</span><span><kbd>Esc</kbd>close</span></div>`,e.root.appendChild(this.box),this.head=this.box.querySelector(".mf-head"),this.list=this.box.querySelector(".mf-list"),this.box.addEventListener("pointerdown",i=>{i.target.closest("input")||i.preventDefault()}),this.list.addEventListener("click",i=>{const a=i.target.closest("[data-k]");a&&this.run(Number(a.dataset.k),!1)}),this.list.addEventListener("pointermove",i=>{const a=i.target.closest("[data-k]");a&&Number(a.dataset.k)!==this.active&&(this.active=Number(a.dataset.k),this.paintActive(!1))}),this.head.addEventListener("click",i=>{const a=i.target.closest("[data-drop]");a&&this.dropToken(a.dataset.drop);const s=i.target.closest("[data-try]");s&&this.setInput(s.dataset.try||"")}),e.input.setAttribute("role","combobox"),e.input.setAttribute("aria-autocomplete","list"),e.input.setAttribute("aria-expanded","false")}get el(){return this.box}get isOpen(){return!this.box.hidden}input(){clearTimeout(this.timer),this.timer=window.setTimeout(()=>{this.refresh(),this.show()},60)}show(){this.place(),this.box.hidden&&(this.box.hidden=!1,this.host.input.setAttribute("aria-expanded","true"),this.refresh())}hide(){this.box.hidden=!0,this.host.input.setAttribute("aria-expanded","false")}update(){this.query.raw&&this.refresh()}clear(){this.host.input.value="",this.refresh()}destroy(){clearTimeout(this.timer),this.box.remove()}key(e){const t=this.acts.length;if(e.key==="ArrowDown"||e.key==="ArrowUp")return this.isOpen?t&&(this.active=(this.active+(e.key==="ArrowDown"?1:t-1))%t,this.paintActive(!0)):this.show(),!0;if(e.key==="Enter")return t&&this.run(this.active,!1),!0;if(e.key==="Tab"&&!e.shiftKey&&this.isOpen){const i=this.acts[this.active];return i&&(i.kind==="tag"||i.kind==="folder"||i.kind==="query")?(this.run(this.active,!0),!0):!1}return e.key==="Escape"?(this.host.input.value?this.clear():this.hide(),!0):!1}place(){const e=this.host.anchor();if(!e)return;const t=e.getBoundingClientRect(),i=this.host.root.getBoundingClientRect();this.host.compact()?(this.box.style.left="12px",this.box.style.right="12px",this.box.style.width="auto"):(this.box.style.left=t.left-i.left+"px",this.box.style.right="",this.box.style.width=Math.max(t.width,Math.min(440,i.width-(t.left-i.left)-16))+"px"),this.box.style.top=t.bottom-i.top+8+"px"}setInput(e){this.host.input.value=e,this.host.input.focus({preventScroll:!0});const t=e.length;this.host.input.setSelectionRange(t,t),this.refresh(),this.show()}complete(e){const t=this.host.input.value,i=t.split(/(\s+)/);!/\s$/.test(t)&&i.length?i[i.length-1]=e:i.push(e),this.setInput(i.join("").trimStart()+" ")}dropToken(e){const t=this.host.input.value.split(/\s+/).filter(i=>i&&i.toLowerCase()!==e.toLowerCase()).join(" ");this.setInput(t?t+" ":"")}run(e,t){const i=this.acts[e];i&&(i.kind==="node"?(NR(i.item.id),this.hide(),this.host.input.blur(),this.src.pick(i.item)):i.kind==="tag"?this.complete("#"+i.tag):i.kind==="folder"?(this.complete("in:"+i.folder),t||this.src.folder?.(i.region)):this.setInput(i.q))}refresh(){const e=this.host.input.value;this.query=Fw(e);const t=this.query,i=this.src.items(),a=this.src.noun||"node";this.acts=[],this.active=0;const s=[],o=(g,m)=>{s.push(m.replace("data-k",`data-k="${this.acts.length}"`)),this.acts.push(g)},r=(g,m)=>{const x=g?.why,_=x?.field==="name"?kc(m.name,x.ranges):b(m.name),w=x?.field==="folder"?kc(m.folder,x.ranges):b(LR(m.folder)),S=m.tags.slice(0,3);x?.tag&&!S.includes(x.tag)&&S.unshift(x.tag);const A=S.slice(0,3).map(y=>`<span class="t">#${x?.tag===y?kc(y,x.ranges):b(y)}</span>`).join(""),C=x?.badge?`<span class="mf-why${x.score>=84?" top":""}" title="${O(x.text)}">${b(x.badge)}</span>`:`<span class="mf-n">${Wp(m.degree,"link")}</span>`;return`<div class="mf-row" role="option" data-k style="--c:${O(m.color)}"><i></i>
3481
- <div class="mf-main"><span class="mf-name">${_}</span><div class="mf-sub"><span>${w}</span>${A}</div></div>${C}</div>`},l=new Map,c=new Map;for(const g of i){for(const _ of g.tags)l.set(_,(l.get(_)||0)+1);const m=g.folder||"Root",x=c.get(m);x?x.n++:c.set(m,{n:1,region:g.region,color:g.color})}if(!e.trim()){this.src.highlight(null),this.host.setCount("");const g=new Map(i.map(C=>[C.id,C])),m=Gw().map(C=>g.get(C)).filter(C=>!!C&&!this.src.hidden?.(C.region));if(m.length){s.push('<div class="mf-sec">Recent</div>');for(const C of m.slice(0,4))o({kind:"node",item:C},r(null,C))}const x=i.filter(C=>!this.src.hidden?.(C.region)&&!m.includes(C)).sort((C,y)=>y.degree-C.degree).slice(0,m.length?4:5);if(x.length){s.push('<div class="mf-sec">Most connected</div>');for(const C of x)o({kind:"node",item:C},r(null,C))}const _=[...l.entries()].sort((C,y)=>y[1]-C[1])[0]?.[0],w=[...c.entries()].filter(([C])=>C!=="Root").sort((C,y)=>y[1].n-C[1].n)[0]?.[0],S=w?w.split("/").pop():"",A=(C,y,M)=>`<button type="button" class="mf-try" data-try="${O(y)}" title="${O(M)}">${b(C)}</button>`;this.head.innerHTML="<span>Try</span>"+A("#"+(_||"tag"),_?`#${_} `:"#","Nodes with a tag; the start of the tag is enough")+A("in:"+(S||"folder"),S?`in:${S} `:"in:","Nodes inside a folder")+A("name words","","Plain words match names first, then tags and folders")+'<span class="grow"></span><span>Matches light up on the map</span>',this.paint(s);return}const{hits:p,held:h}=IR(i,t,this.src.hidden?.bind(this.src));this.src.highlight(new Set(p.map(g=>g.item.id))),this.host.setCount(p.length?String(p.length):"none");const d=[...t.tags.map(g=>["#"+g,`#${g}`]),...t.folders.map(g=>["in:"+g,`in: ${g}`])].map(([g,m])=>`<span class="mf-chip">${b(m)}<button type="button" data-drop="${O(g)}" aria-label="Remove ${O(m)}">×</button></span>`).join(""),u=t.text?` for “<b>${b(t.text)}</b>”`:"";this.head.innerHTML=d+`<span>${p.length?`<b>${Wp(p.length,a)}</b>${u} lit on the map`:`No ${a}s${u}`}${h?` · ${h} more in hidden regions`:""}</span>`;const f=t.partial;if(f?.kind==="tag"||!f&&t.text&&!t.tags.length){const g=f?.kind==="tag"?f.value:t.text,m=[...l.entries()].filter(([x])=>x.toLowerCase().includes(g)).sort((x,_)=>Number(_[0].toLowerCase().startsWith(g))-Number(x[0].toLowerCase().startsWith(g))||_[1]-x[1]).slice(0,f?6:3);if(m.length){s.push(`<div class="mf-sec">Tags <span>${f?"Tab or click to filter by it":""}</span></div>`);for(const[x,_]of m){const w=x.toLowerCase().indexOf(g);o({kind:"tag",tag:x},`<div class="mf-row" role="option" data-k><i class="tg">#</i><div class="mf-main"><span class="mf-name">${kc(x,g&&w>=0?[[w,w+g.length]]:[])}</span></div><span class="mf-n">${Wp(_,a)}</span></div>`)}}}if(f?.kind==="folder"||!f&&t.text&&!t.folders.length){const g=f?.kind==="folder"?f.value:t.text,m=[...c.entries()].filter(([x])=>x!=="Root"&&x.toLowerCase().includes(g)).sort((x,_)=>_[1].n-x[1].n).slice(0,f?6:3);if(m.length){s.push(`<div class="mf-sec">Folders <span>${f?"Tab to filter · click to go there":""}</span></div>`);for(const[x,_]of m){const w=x.toLowerCase().indexOf(g);o({kind:"folder",folder:x.split("/").pop()||x,region:_.region},`<div class="mf-row" role="option" data-k style="--c:${O(_.color)}"><i class="sq"></i><div class="mf-main"><span class="mf-name">${kc(x,g&&w>=0?[[w,w+g.length]]:[])}</span></div><span class="mf-n">${Wp(_.n,a)}</span></div>`)}}}if(p.length){const g=new Map;p.forEach(m=>g.set(m.why.badge,(g.get(m.why.badge)||0)+1)),s.push(`<div class="mf-sec">${a[0].toUpperCase()+a.slice(1)}s <span>${p.length>wc?`top ${wc} of ${p.length}`:""}</span></div>`);for(const m of p.slice(0,wc))o({kind:"node",item:m.item},r(m,m.item));p.length>wc&&s.push(`<div class="mf-more">${p.length-wc} more are lit on the map. Add a word, a #tag or in:folder to narrow.</div>`)}else if(!s.length||!this.acts.length){const g=$R(i,t.text);if(s.push(`<div class="mf-empty">Nothing matches${t.text?` “<b>${b(t.text)}</b>”`:""}${t.tags.length||t.folders.length?" with these filters":""}.${h?` ${h} ${a}s match in hidden regions: show them in Regions.`:""}</div>`),g.length){s.push('<div class="mf-sec">Did you mean</div>');for(const m of g)o({kind:"node",item:m.item},r(m,m.item))}(t.tags.length||t.folders.length)&&(s.push('<div class="mf-sec">Try</div>'),o({kind:"query",q:t.text},`<div class="mf-tip" role="option" data-k><code>no filters</code><span>search “${b(t.text||"…")}” without #tag and in:</span></div>`))}const v=this.acts.findIndex(g=>g.kind==="node");v>0&&!f&&(this.active=v),this.paint(s)}paint(e){this.list.innerHTML=e.join(""),this.paintActive(!1)}paintActive(e){const t=this.list.querySelectorAll("[data-k]");let i=null;t.forEach(a=>{const s=Number(a.dataset.k)===this.active;a.setAttribute("aria-selected",String(s)),s?i=a:a.removeAttribute("id")}),i?(i.id="mfActive",this.host.input.setAttribute("aria-activedescendant","mfActive"),e&&i.scrollIntoView({block:"nearest"})):this.host.input.removeAttribute("aria-activedescendant")}}function _c(){const n=window.innerWidth;return n<=760?"phone":n<=1100?"tablet":"desktop"}const bg=()=>"memora.viewChrome.v3."+_c(),Pa=()=>_c()!=="desktop";function yg(){const n=_c();return{minimap:n==="desktop",controls:n!=="phone"}}function qw(){const n=yg();try{const e=JSON.parse(localStorage.getItem(bg())||"{}");return{minimap:e.minimap??n.minimap,controls:e.controls??n.controls}}catch{return n}}function Vw(n){try{localStorage.setItem(bg(),JSON.stringify(n))}catch{}}const OR=[["brain","3D",'<svg class="i" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3 4 7.5v9L12 21l8-4.5v-9z"/><path d="m4 7.5 8 4.5 8-4.5M12 12v9"/></svg>'],["graph","Graph",je("graph")],["canvas","Canvas",je("canvas")]];let Ww=0;const on={search:'<svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="7"/><path d="m20.5 20.5-4.3-4.3"/></svg>',filter:'<svg viewBox="0 0 24 24"><path d="M4 6h16M7 12h10M10 18h4"/></svg>',plus:'<svg viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></svg>',minus:'<svg viewBox="0 0 24 24"><path d="M5 12h14"/></svg>',fit:'<svg viewBox="0 0 24 24"><rect x="8" y="8" width="8" height="8" rx="1.6"/><path d="M3.5 3.5 6.5 6.5M20.5 3.5l-3 3M3.5 20.5l3-3M20.5 20.5l-3-3"/></svg>',full:'<svg viewBox="0 0 24 24"><path d="M14 4h6v6M10 20H4v-6M20 4l-6.5 6.5M4 20l6.5-6.5"/></svg>',exitFull:'<svg viewBox="0 0 24 24"><path d="M4 14h6v6M20 10h-6V4M14 10l6.5-6.5M10 14l-6.5 6.5"/></svg>',target:'<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="7"/><circle cx="12" cy="12" r="2"/></svg>',up:'<svg viewBox="0 0 24 24"><path d="m6 14 6-6 6 6"/></svg>',home:'<svg viewBox="0 0 24 24"><path d="M4 11.5 12 5l8 6.5M6.5 10v9h11v-9"/></svg>',reset:'<svg viewBox="0 0 24 24"><path d="M4 12a8 8 0 1 0 2.4-5.7L4 8.5"/><path d="M4 4v4.5h4.5"/></svg>',close:'<svg viewBox="0 0 24 24"><path d="M6 6l12 12M18 6 6 18"/></svg>',layers:'<svg class="tic" viewBox="0 0 24 24"><path d="m12 4 8 4.5-8 4.5-8-4.5z"/><path d="m4 12.5 8 4.5 8-4.5"/><path d="m4 16.5 8 4.5 8-4.5"/></svg>',pulse:'<svg class="tic" viewBox="0 0 24 24"><path d="M3 12h4l3-7 4 14 3-7h4"/></svg>',pad:'<svg viewBox="0 0 24 24"><path d="M7 9h10a4 4 0 0 1 3.9 4.9l-.6 2.6a2.3 2.3 0 0 1-4 1L14.6 16H9.4l-1.7 1.5a2.3 2.3 0 0 1-4-1l-.6-2.6A4 4 0 0 1 7 9z"/><path d="M8 11.5v3M6.5 13h3"/><circle cx="15.5" cy="12" r=".6"/><circle cx="17" cy="13.8" r=".6"/></svg>'},UR=`
3479
+ `;class z4{constructor(e,t){this.host=e,this.src=t,this.acts=[],this.active=0,this.query=Fw(""),this.timer=0,it("map-find-css",D4),this.box=document.createElement("div"),this.box.className="mf",this.box.hidden=!0,this.box.innerHTML=`<div class="mf-head"></div><div class="mf-list" role="listbox" aria-label="Search results"></div>
3480
+ <div class="mf-foot"><span><kbd>↑</kbd><kbd>↓</kbd>move</span><span><kbd>Enter</kbd>open</span><span><kbd>Tab</kbd>use tag or folder</span><span><kbd>Esc</kbd>close</span></div>`,e.root.appendChild(this.box),this.head=this.box.querySelector(".mf-head"),this.list=this.box.querySelector(".mf-list"),this.box.addEventListener("pointerdown",i=>{i.target.closest("input")||i.preventDefault()}),this.list.addEventListener("click",i=>{const a=i.target.closest("[data-k]");a&&this.run(Number(a.dataset.k),!1)}),this.list.addEventListener("pointermove",i=>{const a=i.target.closest("[data-k]");a&&Number(a.dataset.k)!==this.active&&(this.active=Number(a.dataset.k),this.paintActive(!1))}),this.head.addEventListener("click",i=>{const a=i.target.closest("[data-drop]");a&&this.dropToken(a.dataset.drop);const s=i.target.closest("[data-try]");s&&this.setInput(s.dataset.try||"")}),e.input.setAttribute("role","combobox"),e.input.setAttribute("aria-autocomplete","list"),e.input.setAttribute("aria-expanded","false")}get el(){return this.box}get isOpen(){return!this.box.hidden}input(){clearTimeout(this.timer),this.timer=window.setTimeout(()=>{this.refresh(),this.show()},60)}show(){this.place(),this.box.hidden&&(this.box.hidden=!1,this.host.input.setAttribute("aria-expanded","true"),this.refresh())}hide(){this.box.hidden=!0,this.host.input.setAttribute("aria-expanded","false")}update(){this.query.raw&&this.refresh()}clear(){this.host.input.value="",this.refresh()}destroy(){clearTimeout(this.timer),this.box.remove()}key(e){const t=this.acts.length;if(e.key==="ArrowDown"||e.key==="ArrowUp")return this.isOpen?t&&(this.active=(this.active+(e.key==="ArrowDown"?1:t-1))%t,this.paintActive(!0)):this.show(),!0;if(e.key==="Enter")return t&&this.run(this.active,!1),!0;if(e.key==="Tab"&&!e.shiftKey&&this.isOpen){const i=this.acts[this.active];return i&&(i.kind==="tag"||i.kind==="folder"||i.kind==="query")?(this.run(this.active,!0),!0):!1}return e.key==="Escape"?(this.host.input.value?this.clear():this.hide(),!0):!1}place(){const e=this.host.anchor();if(!e)return;const t=e.getBoundingClientRect(),i=this.host.root.getBoundingClientRect();this.host.compact()?(this.box.style.left="12px",this.box.style.right="12px",this.box.style.width="auto"):(this.box.style.left=t.left-i.left+"px",this.box.style.right="",this.box.style.width=Math.max(t.width,Math.min(440,i.width-(t.left-i.left)-16))+"px"),this.box.style.top=t.bottom-i.top+8+"px"}setInput(e){this.host.input.value=e,this.host.input.focus({preventScroll:!0});const t=e.length;this.host.input.setSelectionRange(t,t),this.refresh(),this.show()}complete(e){const t=this.host.input.value,i=t.split(/(\s+)/);!/\s$/.test(t)&&i.length?i[i.length-1]=e:i.push(e),this.setInput(i.join("").trimStart()+" ")}dropToken(e){const t=this.host.input.value.split(/\s+/).filter(i=>i&&i.toLowerCase()!==e.toLowerCase()).join(" ");this.setInput(t?t+" ":"")}run(e,t){const i=this.acts[e];i&&(i.kind==="node"?(N4(i.item.id),this.hide(),this.host.input.blur(),this.src.pick(i.item)):i.kind==="tag"?this.complete("#"+i.tag):i.kind==="folder"?(this.complete("in:"+i.folder),t||this.src.folder?.(i.region)):this.setInput(i.q))}refresh(){const e=this.host.input.value;this.query=Fw(e);const t=this.query,i=this.src.items(),a=this.src.noun||"node";this.acts=[],this.active=0;const s=[],o=(g,m)=>{s.push(m.replace("data-k",`data-k="${this.acts.length}"`)),this.acts.push(g)},r=(g,m)=>{const x=g?.why,_=x?.field==="name"?kc(m.name,x.ranges):b(m.name),w=x?.field==="folder"?kc(m.folder,x.ranges):b(L4(m.folder)),S=m.tags.slice(0,3);x?.tag&&!S.includes(x.tag)&&S.unshift(x.tag);const A=S.slice(0,3).map(y=>`<span class="t">#${x?.tag===y?kc(y,x.ranges):b(y)}</span>`).join(""),C=x?.badge?`<span class="mf-why${x.score>=84?" top":""}" title="${O(x.text)}">${b(x.badge)}</span>`:`<span class="mf-n">${Wp(m.degree,"link")}</span>`;return`<div class="mf-row" role="option" data-k style="--c:${O(m.color)}"><i></i>
3481
+ <div class="mf-main"><span class="mf-name">${_}</span><div class="mf-sub"><span>${w}</span>${A}</div></div>${C}</div>`},l=new Map,c=new Map;for(const g of i){for(const _ of g.tags)l.set(_,(l.get(_)||0)+1);const m=g.folder||"Root",x=c.get(m);x?x.n++:c.set(m,{n:1,region:g.region,color:g.color})}if(!e.trim()){this.src.highlight(null),this.host.setCount("");const g=new Map(i.map(C=>[C.id,C])),m=Gw().map(C=>g.get(C)).filter(C=>!!C&&!this.src.hidden?.(C.region));if(m.length){s.push('<div class="mf-sec">Recent</div>');for(const C of m.slice(0,4))o({kind:"node",item:C},r(null,C))}const x=i.filter(C=>!this.src.hidden?.(C.region)&&!m.includes(C)).sort((C,y)=>y.degree-C.degree).slice(0,m.length?4:5);if(x.length){s.push('<div class="mf-sec">Most connected</div>');for(const C of x)o({kind:"node",item:C},r(null,C))}const _=[...l.entries()].sort((C,y)=>y[1]-C[1])[0]?.[0],w=[...c.entries()].filter(([C])=>C!=="Root").sort((C,y)=>y[1].n-C[1].n)[0]?.[0],S=w?w.split("/").pop():"",A=(C,y,M)=>`<button type="button" class="mf-try" data-try="${O(y)}" title="${O(M)}">${b(C)}</button>`;this.head.innerHTML="<span>Try</span>"+A("#"+(_||"tag"),_?`#${_} `:"#","Nodes with a tag; the start of the tag is enough")+A("in:"+(S||"folder"),S?`in:${S} `:"in:","Nodes inside a folder")+A("name words","","Plain words match names first, then tags and folders")+'<span class="grow"></span><span>Matches light up on the map</span>',this.paint(s);return}const{hits:p,held:h}=I4(i,t,this.src.hidden?.bind(this.src));this.src.highlight(new Set(p.map(g=>g.item.id))),this.host.setCount(p.length?String(p.length):"none");const d=[...t.tags.map(g=>["#"+g,`#${g}`]),...t.folders.map(g=>["in:"+g,`in: ${g}`])].map(([g,m])=>`<span class="mf-chip">${b(m)}<button type="button" data-drop="${O(g)}" aria-label="Remove ${O(m)}">×</button></span>`).join(""),u=t.text?` for “<b>${b(t.text)}</b>”`:"";this.head.innerHTML=d+`<span>${p.length?`<b>${Wp(p.length,a)}</b>${u} lit on the map`:`No ${a}s${u}`}${h?` · ${h} more in hidden regions`:""}</span>`;const f=t.partial;if(f?.kind==="tag"||!f&&t.text&&!t.tags.length){const g=f?.kind==="tag"?f.value:t.text,m=[...l.entries()].filter(([x])=>x.toLowerCase().includes(g)).sort((x,_)=>Number(_[0].toLowerCase().startsWith(g))-Number(x[0].toLowerCase().startsWith(g))||_[1]-x[1]).slice(0,f?6:3);if(m.length){s.push(`<div class="mf-sec">Tags <span>${f?"Tab or click to filter by it":""}</span></div>`);for(const[x,_]of m){const w=x.toLowerCase().indexOf(g);o({kind:"tag",tag:x},`<div class="mf-row" role="option" data-k><i class="tg">#</i><div class="mf-main"><span class="mf-name">${kc(x,g&&w>=0?[[w,w+g.length]]:[])}</span></div><span class="mf-n">${Wp(_,a)}</span></div>`)}}}if(f?.kind==="folder"||!f&&t.text&&!t.folders.length){const g=f?.kind==="folder"?f.value:t.text,m=[...c.entries()].filter(([x])=>x!=="Root"&&x.toLowerCase().includes(g)).sort((x,_)=>_[1].n-x[1].n).slice(0,f?6:3);if(m.length){s.push(`<div class="mf-sec">Folders <span>${f?"Tab to filter · click to go there":""}</span></div>`);for(const[x,_]of m){const w=x.toLowerCase().indexOf(g);o({kind:"folder",folder:x.split("/").pop()||x,region:_.region},`<div class="mf-row" role="option" data-k style="--c:${O(_.color)}"><i class="sq"></i><div class="mf-main"><span class="mf-name">${kc(x,g&&w>=0?[[w,w+g.length]]:[])}</span></div><span class="mf-n">${Wp(_.n,a)}</span></div>`)}}}if(p.length){const g=new Map;p.forEach(m=>g.set(m.why.badge,(g.get(m.why.badge)||0)+1)),s.push(`<div class="mf-sec">${a[0].toUpperCase()+a.slice(1)}s <span>${p.length>wc?`top ${wc} of ${p.length}`:""}</span></div>`);for(const m of p.slice(0,wc))o({kind:"node",item:m.item},r(m,m.item));p.length>wc&&s.push(`<div class="mf-more">${p.length-wc} more are lit on the map. Add a word, a #tag or in:folder to narrow.</div>`)}else if(!s.length||!this.acts.length){const g=$4(i,t.text);if(s.push(`<div class="mf-empty">Nothing matches${t.text?` “<b>${b(t.text)}</b>”`:""}${t.tags.length||t.folders.length?" with these filters":""}.${h?` ${h} ${a}s match in hidden regions: show them in Regions.`:""}</div>`),g.length){s.push('<div class="mf-sec">Did you mean</div>');for(const m of g)o({kind:"node",item:m.item},r(m,m.item))}(t.tags.length||t.folders.length)&&(s.push('<div class="mf-sec">Try</div>'),o({kind:"query",q:t.text},`<div class="mf-tip" role="option" data-k><code>no filters</code><span>search “${b(t.text||"…")}” without #tag and in:</span></div>`))}const v=this.acts.findIndex(g=>g.kind==="node");v>0&&!f&&(this.active=v),this.paint(s)}paint(e){this.list.innerHTML=e.join(""),this.paintActive(!1)}paintActive(e){const t=this.list.querySelectorAll("[data-k]");let i=null;t.forEach(a=>{const s=Number(a.dataset.k)===this.active;a.setAttribute("aria-selected",String(s)),s?i=a:a.removeAttribute("id")}),i?(i.id="mfActive",this.host.input.setAttribute("aria-activedescendant","mfActive"),e&&i.scrollIntoView({block:"nearest"})):this.host.input.removeAttribute("aria-activedescendant")}}function _c(){const n=window.innerWidth;return n<=760?"phone":n<=1100?"tablet":"desktop"}const bg=()=>"memora.viewChrome.v3."+_c(),Pa=()=>_c()!=="desktop";function yg(){const n=_c();return{minimap:n==="desktop",controls:n!=="phone"}}function qw(){const n=yg();try{const e=JSON.parse(localStorage.getItem(bg())||"{}");return{minimap:e.minimap??n.minimap,controls:e.controls??n.controls}}catch{return n}}function Vw(n){try{localStorage.setItem(bg(),JSON.stringify(n))}catch{}}const O4=[["brain","3D",'<svg class="i" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3 4 7.5v9L12 21l8-4.5v-9z"/><path d="m4 7.5 8 4.5 8-4.5M12 12v9"/></svg>'],["graph","Graph",je("graph")],["canvas","Canvas",je("canvas")]];let Ww=0;const on={search:'<svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="7"/><path d="m20.5 20.5-4.3-4.3"/></svg>',filter:'<svg viewBox="0 0 24 24"><path d="M4 6h16M7 12h10M10 18h4"/></svg>',plus:'<svg viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></svg>',minus:'<svg viewBox="0 0 24 24"><path d="M5 12h14"/></svg>',fit:'<svg viewBox="0 0 24 24"><rect x="8" y="8" width="8" height="8" rx="1.6"/><path d="M3.5 3.5 6.5 6.5M20.5 3.5l-3 3M3.5 20.5l3-3M20.5 20.5l-3-3"/></svg>',full:'<svg viewBox="0 0 24 24"><path d="M14 4h6v6M10 20H4v-6M20 4l-6.5 6.5M4 20l6.5-6.5"/></svg>',exitFull:'<svg viewBox="0 0 24 24"><path d="M4 14h6v6M20 10h-6V4M14 10l6.5-6.5M10 14l-6.5 6.5"/></svg>',target:'<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="7"/><circle cx="12" cy="12" r="2"/></svg>',up:'<svg viewBox="0 0 24 24"><path d="m6 14 6-6 6 6"/></svg>',home:'<svg viewBox="0 0 24 24"><path d="M4 11.5 12 5l8 6.5M6.5 10v9h11v-9"/></svg>',reset:'<svg viewBox="0 0 24 24"><path d="M4 12a8 8 0 1 0 2.4-5.7L4 8.5"/><path d="M4 4v4.5h4.5"/></svg>',close:'<svg viewBox="0 0 24 24"><path d="M6 6l12 12M18 6 6 18"/></svg>',layers:'<svg class="tic" viewBox="0 0 24 24"><path d="m12 4 8 4.5-8 4.5-8-4.5z"/><path d="m4 12.5 8 4.5 8-4.5"/><path d="m4 16.5 8 4.5 8-4.5"/></svg>',pulse:'<svg class="tic" viewBox="0 0 24 24"><path d="M3 12h4l3-7 4 14 3-7h4"/></svg>',pad:'<svg viewBox="0 0 24 24"><path d="M7 9h10a4 4 0 0 1 3.9 4.9l-.6 2.6a2.3 2.3 0 0 1-4 1L14.6 16H9.4l-1.7 1.5a2.3 2.3 0 0 1-4-1l-.6-2.6A4 4 0 0 1 7 9z"/><path d="M8 11.5v3M6.5 13h3"/><circle cx="15.5" cy="12" r=".6"/><circle cx="17" cy="13.8" r=".6"/></svg>'},U4=`
3482
3482
  .vc{--vc-glass:var(--panel,#12161f);--vc-line:color-mix(in srgb,var(--line,#232a38) 85%,transparent);
3483
3483
  /* the floating controls: a step lighter than the map, a clear edge and shadow */
3484
3484
  --vc-ctl:var(--surface-2,#131823);--vc-ctl-line:rgba(148,163,184,.30);--vc-ctl-icon:var(--text-2,#a3afc2)}
@@ -3742,7 +3742,7 @@ button.ov-name:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
3742
3742
  .vc-search{width:40px;height:40px}
3743
3743
  }
3744
3744
  @media (prefers-reduced-motion:reduce){.vc-drawer,.vc-sheet,.vc-modes button span{transition:none}.vc-tab.live,.vc-tab.live::before,.vc-tab.live .dot{animation:none}}
3745
- `;class wg{constructor(e){this.finder=null,this.prefs=qw(),this.q=i=>this.el.querySelector(i),this.orient={yaw:.6,pitch:.35},this.repeat=0,this.open=null,this.unsubAgents=null,this.agentTimer=0,this.dirtyTimer=0,this.phone=_c()==="phone",this.off=new AbortController,this.onFs=()=>this.paintFs(),this.onResize=()=>{!Pa()&&this.open==="search"&&this.close(),this.sizeSearch();const i=_c()==="phone";i!==this.phone&&(this.phone=i,this.prefs=qw(),this.place())},this.themeObs=new MutationObserver(()=>{this.drawGlobe(),this.redrawMini()}),this.onDocDown=i=>{const a=this.open;if(!a||a==="sheet")return;const s=i.target;(a==="filter"?[this.panel,this.q("[data-vc=filter]")]:a==="search"?[this.q(".vc-search"),...this.finder?[this.finder.el]:[]]:[this.q(`[data-d=${a}]`),this.q(`[data-open=${a}]`)]).some(r=>r.contains(s))||this.close()},it("view-chrome",UR),this.o=e;const t=document.createElement("div");t.className="vc",t.innerHTML=this.template(),e.root.appendChild(t),this.el=t,this.input=this.q(".vc-search input"),this.panel=this.q(".vc-panel"),this.miniCanvas=this.q(".vc-mini canvas"),this.globe=this.q(".vc-globe canvas"),this.wire(),this.place(),this.refreshRegions(),this.markActive(),this.drawGlobe(),this.themeObs.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),window.addEventListener("resize",this.onResize),this.unsubAgents=Fl(()=>this.paintAgents()),this.agentTimer=window.setInterval(()=>!document.hidden&&this.paintAgents(),1e3)}template(){const e=this.o,t=OR.map(([i,a,s])=>`<button type="button" data-page="${i}" aria-label="${a}" aria-pressed="${i===e.page}">${s}<span>${a}</span></button>`).join("");return`
3745
+ `;class wg{constructor(e){this.finder=null,this.prefs=qw(),this.q=i=>this.el.querySelector(i),this.orient={yaw:.6,pitch:.35},this.repeat=0,this.open=null,this.unsubAgents=null,this.agentTimer=0,this.dirtyTimer=0,this.phone=_c()==="phone",this.off=new AbortController,this.onFs=()=>this.paintFs(),this.onResize=()=>{!Pa()&&this.open==="search"&&this.close(),this.sizeSearch();const i=_c()==="phone";i!==this.phone&&(this.phone=i,this.prefs=qw(),this.place())},this.themeObs=new MutationObserver(()=>{this.drawGlobe(),this.redrawMini()}),this.onDocDown=i=>{const a=this.open;if(!a||a==="sheet")return;const s=i.target;(a==="filter"?[this.panel,this.q("[data-vc=filter]")]:a==="search"?[this.q(".vc-search"),...this.finder?[this.finder.el]:[]]:[this.q(`[data-d=${a}]`),this.q(`[data-open=${a}]`)]).some(r=>r.contains(s))||this.close()},it("view-chrome",U4),this.o=e;const t=document.createElement("div");t.className="vc",t.innerHTML=this.template(),e.root.appendChild(t),this.el=t,this.input=this.q(".vc-search input"),this.panel=this.q(".vc-panel"),this.miniCanvas=this.q(".vc-mini canvas"),this.globe=this.q(".vc-globe canvas"),this.wire(),this.place(),this.refreshRegions(),this.markActive(),this.drawGlobe(),this.themeObs.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),window.addEventListener("resize",this.onResize),this.unsubAgents=Fl(()=>this.paintAgents()),this.agentTimer=window.setInterval(()=>!document.hidden&&this.paintAgents(),1e3)}template(){const e=this.o,t=O4.map(([i,a,s])=>`<button type="button" data-page="${i}" aria-label="${a}" aria-pressed="${i===e.page}">${s}<span>${a}</span></button>`).join("");return`
3746
3746
  <div class="vc-tl">
3747
3747
  <label class="vc-p vc-search">${on.search}<input type="search" placeholder="${O(e.search.placeholder)}" aria-label="${O(e.search.placeholder)}" autocomplete="off" spellcheck="false"><em></em><kbd>/</kbd></label>
3748
3748
  <nav class="vc-p vc-col vc-modes" aria-label="View">${t}</nav>
@@ -3791,7 +3791,7 @@ button.ov-name:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
3791
3791
  <div class="vc-sh"><h4>Controller</h4><button type="button" class="vc-b" data-close title="Close" aria-label="Close">${on.close}</button></div>
3792
3792
  <div class="vc-sgrid"><div data-slot="globe"></div><div data-slot="mini"></div></div>
3793
3793
  <div data-slot="labels"></div>
3794
- </section>`}place(){const e=this.q(".vc-globe"),t=this.q(".vc-mini");this.phone?(this.q("[data-slot=globe]").appendChild(e),this.q("[data-slot=mini]").appendChild(t)):(this.q(".vc-dock").prepend(e),this.el.insertBefore(t,this.q(".vc-dock"))),this.applyPrefs()}shown(){this.markActive()}markActive(){const e=this.o.page;this.el.querySelectorAll(".vc-modes button").forEach(t=>{t.classList.toggle("on",t.dataset.page===e),t.setAttribute("aria-pressed",String(t.dataset.page===e))})}show(e){if(this.open!==e)if(this.close(),this.open=e,this.el.dataset.open=e,this.o.root.dataset.vcOpen=e,this.o.onOverlay?.(),e==="filter")this.panel.hidden=!1,this.q("[data-vc=filter]").classList.add("on"),this.q("[data-vc=filter]").setAttribute("aria-expanded","true"),this.renderPanel();else if(e==="regions"||e==="activity"){this.q(`[data-d=${e}]`).classList.add("open");const t=this.q(`[data-open=${e}]`);t.classList.add("on"),t.setAttribute("aria-expanded","true"),e==="activity"&&this.paintAgents()}else e==="sheet"?(this.q(".vc-sheet").classList.add("open"),this.q(".vc-scrim").classList.add("on"),this.o.root.classList.add("vc-sheet-open"),this.renderSheetLabels(),requestAnimationFrame(()=>this.redrawMini())):e==="search"&&(this.q(".vc-search").classList.add("open"),this.sizeSearch(),this.input.focus())}close(){const e=this.open;if(e){if(_s(),this.open=null,delete this.el.dataset.open,delete this.o.root.dataset.vcOpen,e==="filter")this.panel.hidden=!0,this.q("[data-vc=filter]").classList.remove("on"),this.q("[data-vc=filter]").setAttribute("aria-expanded","false");else if(e==="regions"||e==="activity"){this.q(`[data-d=${e}]`).classList.remove("open");const t=this.q(`[data-open=${e}]`);t.classList.remove("on"),t.setAttribute("aria-expanded","false")}else if(e==="sheet")this.q(".vc-sheet").classList.remove("open"),this.q(".vc-scrim").classList.remove("on"),this.o.root.classList.remove("vc-sheet-open");else if(e==="search"){const t=this.q(".vc-search");t.classList.remove("open"),t.style.width=""}}}sizeSearch(){const e=this.q(".vc-search");if(this.open!=="search"||!Pa())return;const t=e.getBoundingClientRect(),i=this.o.root.getBoundingClientRect(),a=t.left-i.left;e.style.width=Math.max(t.height,i.right-a-t.left)+"px"}openPanel(){this.show("filter")}closePanel(){this.open==="filter"&&this.close()}wire(){const e=this.o;this.el.querySelectorAll(".vc-modes button").forEach(c=>{c.onclick=()=>{const p=c.dataset.page;if(p===e.page)return;this.el.querySelectorAll(".vc-modes button").forEach(d=>d.classList.toggle("on",d===c));const h=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;clearTimeout(Ww),Ww=window.setTimeout(()=>{he.go(p),this.markActive()},h?0:140)}}),this.q(".vc-search").addEventListener("click",()=>{Pa()&&this.open!=="search"&&this.show("search")});const i=this.input,a=e.search.find?new zR({input:i,root:e.root,setCount:c=>this.setCount(c),anchor:()=>this.q(".vc-search"),compact:Pa},e.search.find):null;this.finder=a,i.oninput=()=>{a?.input(),e.search.onInput?.(i.value.trim())},i.onfocus=()=>{Pa()&&this.open!=="search"?this.show("search"):!Pa()&&this.open&&this.open!=="search"&&this.close(),a&&requestAnimationFrame(()=>a.show()),e.search.onFocus?.()},i.addEventListener("blur",()=>{window.setTimeout(()=>{document.activeElement!==i&&a?.hide()},120),Pa()&&!i.value&&window.setTimeout(()=>this.open==="search"&&this.close(),150)}),i.onkeydown=c=>{if(a){if(c.key==="Escape"&&!i.value){a.hide(),i.blur(),this.open==="search"&&this.close(),c.preventDefault();return}a.key(c)&&c.preventDefault();return}if(e.search.onKey?.(c,i.value.trim())){c.preventDefault();return}c.key==="Escape"&&(i.value="",e.search.onInput?.(""),i.blur(),this.open==="search"&&this.close())},this.q("[data-vc=filter]").onclick=()=>this.open==="filter"?this.close():this.show("filter"),document.addEventListener("pointerdown",this.onDocDown,!0);const s=this.q("[data-reset]"),o=()=>{const c=JSON.stringify(this.prefs)!==JSON.stringify(yg())||!!e.changed?.();if(s.classList.contains("dirty")===c)return;s.classList.toggle("dirty",c);const p=c?"Reset: this view differs from its defaults":"Reset this view to its defaults";s.title=p,s.setAttribute("aria-label",p)};this.dirtyTimer=window.setInterval(()=>{!document.hidden&&this.el.isConnected&&o()},400),s.onclick=()=>{s.classList.remove("spin"),s.offsetWidth,s.classList.add("spin"),this.close();try{localStorage.removeItem(bg())}catch{}this.prefs=yg(),e.reset(),this.applyPrefs(),this.refreshRegions()},this.el.querySelectorAll("[data-open]").forEach(c=>{c.onclick=()=>{const p=c.dataset.open;this.open===p?this.close():this.show(p)}}),this.el.querySelectorAll("[data-close]").forEach(c=>c.onclick=()=>this.close()),this.q(".vc-scrim").onclick=()=>this.close(),this.el.querySelectorAll("[data-all]").forEach(c=>{c.onclick=()=>{e.regions.setAll(c.dataset.all==="hide"),this.refreshRegions()}}),e.root.addEventListener("keydown",c=>{c.key==="Escape"&&this.open&&this.open!=="search"&&this.close()},{signal:this.off.signal}),this.el.querySelectorAll("[data-z]").forEach(c=>{c.onclick=()=>{const p=c.dataset.z;p==="in"?e.nav.zoom(1.4):p==="out"?e.nav.zoom(1/1.4):p==="fit"?e.nav.fit():this.toggleFullscreen()}}),document.addEventListener("fullscreenchange",this.onFs);const r={u:[0,-1],d:[0,1],l:[-1,0],r:[1,0]};this.el.querySelectorAll(".vc-globe [data-g]").forEach(c=>{const p=c.dataset.g||"";if(p==="h"){c.onclick=()=>e.nav.home();return}const h=()=>e.nav.nudge(r[p][0],r[p][1]);c.onpointerdown=u=>{u.preventDefault(),h(),clearTimeout(this.repeat);const f=()=>{h(),this.repeat=window.setTimeout(f,110)};this.repeat=window.setTimeout(f,380)};const d=()=>clearTimeout(this.repeat);c.onpointerup=d,c.onpointerleave=d,c.onpointercancel=d,c.onkeydown=u=>{(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),h())}});const l=this.q(".vc-mini");if(e.minimapNav){const c=h=>{const d=l.getBoundingClientRect();e.minimapNav(Math.max(0,Math.min(1,(h.clientX-d.left)/d.width)),Math.max(0,Math.min(1,(h.clientY-d.top)/d.height)))};let p=!1;l.onpointerdown=h=>{h.stopPropagation(),p=!0,l.setPointerCapture(h.pointerId),c(h)},l.onpointermove=h=>p&&c(h),l.onpointerup=()=>p=!1}for(const c of this.el.querySelectorAll(".vc-p,.vc-tab,.vc-drawer,.vc-sheet,.vc-scrim"))c.addEventListener("pointerdown",p=>p.stopPropagation()),c.addEventListener("wheel",p=>p.stopPropagation(),{passive:!0}),c.addEventListener("dblclick",p=>p.stopPropagation())}renderPanel(){if(this.open!=="filter")return;const e=this.panel,t=e.scrollTop,i=this.o.page==="brain"?"turn the brain":"move the map";e.innerHTML=(this.phone?"":"<h4>View</h4>"+Ia("vc-minimap","Minimap",this.prefs.minimap,"The small overview at the bottom left. Click or drag it to move the view.")+Ia("vc-controls","Orbit globe",this.prefs.controls,`The globe at the bottom right: its arrows ${i}, the middle button goes back to the default view.`))+"<h4>Labels</h4>"+this.labelsHTML()+"<div data-own></div>",e.querySelectorAll("[data-t^=vc-]").forEach(a=>a.onclick=()=>this.toggleShared(a.dataset.t||"")),this.o.filter(e.querySelector("[data-own]")),Kw(e),e.scrollTop=t}labelsHTML(){const e=this.o.labels.get();return Ia("vc-lab-nodes","Node labels",e.nodes,this.o.labels.help.nodes)+Ia("vc-lab-folders","Folder labels",e.folders,this.o.labels.help.folders)}toggleShared(e){if(e==="vc-lab-nodes"||e==="vc-lab-folders"){const t=e==="vc-lab-nodes"?"nodes":"folders";this.o.labels.set(t,!this.o.labels.get()[t])}else e==="vc-minimap"?this.prefs.minimap=!this.prefs.minimap:this.prefs.controls=!this.prefs.controls,Vw(this.prefs),this.applyPrefs();this.renderPanel(),this.renderSheetLabels()}renderSheetLabels(){if(this.open!=="sheet")return;const e=this.q("[data-slot=labels]");e.innerHTML="<h4>Labels</h4>"+this.labelsHTML(),e.querySelectorAll("[data-t]").forEach(t=>t.onclick=()=>this.toggleShared(t.dataset.t||"")),Kw(e)}toggleMinimap(){if(this.phone){this.open==="sheet"?this.close():this.show("sheet");return}this.prefs.minimap=!this.prefs.minimap,Vw(this.prefs),this.applyPrefs(),this.renderPanel()}setBadge(e){this.q(".vc-badge").textContent=e?String(e):""}setCount(e){this.q(".vc-search em").textContent=e}applyPrefs(){this.q(".vc-mini").classList.toggle("vc-hide",!this.phone&&!this.prefs.minimap),this.q(".vc-globe").classList.toggle("vc-hide",!this.phone&&!this.prefs.controls),this.o.onPrefs?.(this.prefs),this.redrawMini()}refreshRegions(){const e=this.o.regions.list(),t=this.q(".vc-rl"),i=e.filter(s=>!s.hidden).length;this.el.querySelectorAll("[data-rn]").forEach(s=>s.textContent=i===e.length?String(e.length):`${i}/${e.length}`),this.q(".vc-bulk").classList.toggle("vc-hide",e.length<2);const a=!!this.o.regions.focus;t.innerHTML=e.length?e.map(s=>`<div class="vc-rr${s.hidden?" off":""}" style="--c:${O(s.color)}"><button type="button" class="tg" data-r="${O(s.name)}" aria-pressed="${!s.hidden}" title="${s.hidden?"Show":"Hide"} ${O(s.name)}" aria-label="${s.hidden?"Show":"Hide"} ${O(s.name)}"><i></i></button><button type="button" class="t" data-f="${O(s.name)}" title="${a?"Go to":s.hidden?"Show":"Hide"} ${O(s.name)}"><span>${b(s.name)}</span><em>${s.count}</em>${a?on.target:""}</button></div>`).join(""):'<div class="vc-empty">No folders yet.</div>',t.querySelectorAll("[data-r]").forEach(s=>{s.onclick=()=>{this.o.regions.toggle(s.dataset.r||""),this.refreshRegions()}}),t.querySelectorAll("[data-f]").forEach(s=>{s.onclick=()=>{const o=s.dataset.f||"";if(!this.o.regions.focus){this.o.regions.toggle(o),this.refreshRegions();return}e.find(r=>r.name===o)?.hidden&&(this.o.regions.toggle(o),this.refreshRegions()),this.close(),this.o.regions.focus(o)}})}paintAgents(){const e=Date.now(),t=r=>r.open>0&&e-r.lastAt<12e4||e-r.lastAt<5e3,i=sr(),a=Qd(),s=this.q(".vc-tab-r");if(s.classList.toggle("live",a.length>0),this.q("[data-an]").textContent=String(a.length),s.title=a.length?`${a.length} agent${a.length===1?"":"s"} working now`:"Agent activity",this.open!=="activity")return;const o=this.q(".vc-al");o.innerHTML=i.length?i.slice(0,30).map(r=>{const l=t(r),c=r.lastLabel||r.lastAction||(r.kind==="user"?"in the app":"connected");return`<div class="vc-ag${l?" on":""}" style="--ag:var(--accent)">${qt(r.actor,30,l?"live":"",r.id)}<div class="m"><b>${b(r.actor)}</b><small>${b(c)}</small></div><time>${l?"now":b(Fn(Math.floor(r.lastAt/1e3)))}</time></div>`}).join(""):'<div class="vc-empty">No agent activity yet. Agents show up here the moment they read or write your memory.</div>'}redrawMini(){if(!this.phone&&!this.prefs.minimap||this.phone&&this.open!=="sheet")return;const e=this.miniCanvas.getBoundingClientRect();if(!e.width||!e.height)return;const t=Math.min(2,window.devicePixelRatio||1),i=Math.round(e.width),a=Math.round(e.height);(this.miniCanvas.width!==i*t||this.miniCanvas.height!==a*t)&&(this.miniCanvas.width=i*t,this.miniCanvas.height=a*t),this.o.minimap(this.miniCanvas,i,a,t)}setOrientation(e,t){Math.abs(e-this.orient.yaw)<.004&&Math.abs(t-this.orient.pitch)<.004||(this.orient={yaw:e,pitch:t},this.drawGlobe())}drawGlobe(){const e=this.globe,t=Math.min(2,window.devicePixelRatio||1),i=64;e.width!==i*t&&(e.width=i*t,e.height=i*t);const a=e.getContext("2d");if(!a)return;const s=document.documentElement.dataset.theme==="light",o=s?"15,23,42":"230,233,239",r=s?"13,148,136":"94,234,212";a.setTransform(t,0,0,t,0,0),a.clearRect(0,0,i,i);const l=i/2-2,c=i/2,p=a.createRadialGradient(c-l*.35,c-l*.4,l*.1,c,c,l);p.addColorStop(0,`rgba(${r},.28)`),p.addColorStop(1,`rgba(${r},.04)`),a.fillStyle=p,a.beginPath(),a.arc(c,c,l,0,Math.PI*2),a.fill(),a.strokeStyle=`rgba(${r},.55)`,a.lineWidth=1.2,a.stroke();const{yaw:h,pitch:d}=this.orient,u=Math.cos(h),f=Math.sin(h),v=Math.cos(d),g=Math.sin(d),m=(_,w)=>{const S=Math.cos(_)*Math.sin(w),A=Math.sin(_),C=Math.cos(_)*Math.cos(w),y=S*u-C*f,M=S*f+C*u,T=A*v-M*g,L=A*g+M*v;return[c+y*l,c-T*l,L]},x=(_,w)=>{for(let S=1;S<_.length;S++){const A=_[S-1],C=_[S],y=(A[2]+C[2])/2>0;a.strokeStyle=`rgba(${w?r:o},${y?w?.85:.38:.09})`,a.lineWidth=w&&y?1.4:1,a.beginPath(),a.moveTo(A[0],A[1]),a.lineTo(C[0],C[1]),a.stroke()}};for(let _=0;_<6;_++){const w=_/6*Math.PI,S=[];for(let A=0;A<=36;A++)S.push(m(-Math.PI/2+A/36*Math.PI*2,w));x(S,!1)}for(const _ of[-.9,-.45,0,.45,.9]){const w=[];for(let S=0;S<=48;S++)w.push(m(_,S/48*Math.PI*2));x(w,_===0)}}toggleFullscreen(){const e=this.o.root;document.fullscreenElement?document.exitFullscreen().catch(()=>{}):e.requestFullscreen?.().catch(()=>{})}paintFs(){const e=this.q("[data-z=full]"),t=document.fullscreenElement===this.o.root;e.innerHTML=t?on.exitFull:on.full,e.title=t?"Exit full screen":"Full screen",e.setAttribute("aria-label",e.title),window.setTimeout(()=>window.dispatchEvent(new Event("resize")),60)}focusSearch(){Pa()&&this.show("search"),this.input.focus(),this.input.select()}setQuery(e){Pa()&&this.show("search"),this.input.value=e,this.input.focus(),this.finder?.input()}destroy(){clearTimeout(this.repeat),clearInterval(this.agentTimer),clearInterval(this.dirtyTimer),this.unsubAgents?.(),document.removeEventListener("pointerdown",this.onDocDown,!0),document.removeEventListener("fullscreenchange",this.onFs),window.removeEventListener("resize",this.onResize),this.themeObs.disconnect(),this.off.abort(),_s(),this.finder?.destroy(),this.el.remove()}}function kg(n){return n?`<b class="vc-q" tabindex="0" role="img" aria-label="${O(n)}" data-help="${O(n)}">?</b>`:""}function Ia(n,e,t,i=""){return`<button type="button" class="vc-tg${t?" on":""}" data-t="${O(n)}" role="switch" aria-checked="${t}"><span>${kg(i)}${b(e)}</span><i></i></button>`}function FR(n,e,t,i,a,s,o=""){return`<label class="vc-sl"><span>${kg(o)}${b(e)}</span><input type="range" min="${t}" max="${i}" step="${a}" value="${s}" data-s="${O(n)}"></label>`}let Sc=null;const Xw=new WeakSet;function _s(){Sc?.remove(),Sc=null}function Kw(n){_s();const e=t=>{_s();const i=document.createElement("div");Sc=i,i.className="vc-tip",i.textContent=t.dataset.help||"",document.body.appendChild(i);const a=t.getBoundingClientRect(),s=i.offsetWidth,o=a.left-s-10>=8?a.left-s-10:Math.min(innerWidth-s-8,a.right+10);i.style.left=Math.max(8,o)+"px",i.style.top=Math.max(8,Math.min(innerHeight-i.offsetHeight-8,a.top-4))+"px"};n.querySelectorAll(".vc-q").forEach(t=>{t.onmouseenter=()=>e(t),t.onfocus=()=>e(t),t.onmouseleave=_s,t.onblur=_s,t.onclick=i=>{i.stopPropagation(),i.preventDefault(),e(t);const a=Sc;window.setTimeout(()=>a===Sc&&_s(),3500)}}),Xw.has(n)||(Xw.add(n),n.addEventListener("scroll",_s,{passive:!0}))}const hi={close:'<svg viewBox="0 0 24 24"><path d="M6 6l12 12M18 6 6 18"/></svg>',more:'<svg viewBox="0 0 24 24"><circle cx="5" cy="12" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="19" cy="12" r="1.6"/></svg>',open:'<svg viewBox="0 0 24 24"><path d="M14 4h6v6M20 4l-8 8"/><path d="M19 14v4a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h4"/></svg>',target:'<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="7"/><circle cx="12" cy="12" r="2.5"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3"/></svg>',folder:'<svg viewBox="0 0 24 24"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"/></svg>',only:'<svg viewBox="0 0 24 24"><path d="M4 5h16l-6 7.5V19l-4 1.5v-8z"/></svg>',plus:'<svg viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></svg>',up:'<svg viewBox="0 0 24 24"><path d="m6 15 6-6 6 6"/></svg>'},BR=`
3794
+ </section>`}place(){const e=this.q(".vc-globe"),t=this.q(".vc-mini");this.phone?(this.q("[data-slot=globe]").appendChild(e),this.q("[data-slot=mini]").appendChild(t)):(this.q(".vc-dock").prepend(e),this.el.insertBefore(t,this.q(".vc-dock"))),this.applyPrefs()}shown(){this.markActive()}markActive(){const e=this.o.page;this.el.querySelectorAll(".vc-modes button").forEach(t=>{t.classList.toggle("on",t.dataset.page===e),t.setAttribute("aria-pressed",String(t.dataset.page===e))})}show(e){if(this.open!==e)if(this.close(),this.open=e,this.el.dataset.open=e,this.o.root.dataset.vcOpen=e,this.o.onOverlay?.(),e==="filter")this.panel.hidden=!1,this.q("[data-vc=filter]").classList.add("on"),this.q("[data-vc=filter]").setAttribute("aria-expanded","true"),this.renderPanel();else if(e==="regions"||e==="activity"){this.q(`[data-d=${e}]`).classList.add("open");const t=this.q(`[data-open=${e}]`);t.classList.add("on"),t.setAttribute("aria-expanded","true"),e==="activity"&&this.paintAgents()}else e==="sheet"?(this.q(".vc-sheet").classList.add("open"),this.q(".vc-scrim").classList.add("on"),this.o.root.classList.add("vc-sheet-open"),this.renderSheetLabels(),requestAnimationFrame(()=>this.redrawMini())):e==="search"&&(this.q(".vc-search").classList.add("open"),this.sizeSearch(),this.input.focus())}close(){const e=this.open;if(e){if(_s(),this.open=null,delete this.el.dataset.open,delete this.o.root.dataset.vcOpen,e==="filter")this.panel.hidden=!0,this.q("[data-vc=filter]").classList.remove("on"),this.q("[data-vc=filter]").setAttribute("aria-expanded","false");else if(e==="regions"||e==="activity"){this.q(`[data-d=${e}]`).classList.remove("open");const t=this.q(`[data-open=${e}]`);t.classList.remove("on"),t.setAttribute("aria-expanded","false")}else if(e==="sheet")this.q(".vc-sheet").classList.remove("open"),this.q(".vc-scrim").classList.remove("on"),this.o.root.classList.remove("vc-sheet-open");else if(e==="search"){const t=this.q(".vc-search");t.classList.remove("open"),t.style.width=""}}}sizeSearch(){const e=this.q(".vc-search");if(this.open!=="search"||!Pa())return;const t=e.getBoundingClientRect(),i=this.o.root.getBoundingClientRect(),a=t.left-i.left;e.style.width=Math.max(t.height,i.right-a-t.left)+"px"}openPanel(){this.show("filter")}closePanel(){this.open==="filter"&&this.close()}wire(){const e=this.o;this.el.querySelectorAll(".vc-modes button").forEach(c=>{c.onclick=()=>{const p=c.dataset.page;if(p===e.page)return;this.el.querySelectorAll(".vc-modes button").forEach(d=>d.classList.toggle("on",d===c));const h=window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;clearTimeout(Ww),Ww=window.setTimeout(()=>{he.go(p),this.markActive()},h?0:140)}}),this.q(".vc-search").addEventListener("click",()=>{Pa()&&this.open!=="search"&&this.show("search")});const i=this.input,a=e.search.find?new z4({input:i,root:e.root,setCount:c=>this.setCount(c),anchor:()=>this.q(".vc-search"),compact:Pa},e.search.find):null;this.finder=a,i.oninput=()=>{a?.input(),e.search.onInput?.(i.value.trim())},i.onfocus=()=>{Pa()&&this.open!=="search"?this.show("search"):!Pa()&&this.open&&this.open!=="search"&&this.close(),a&&requestAnimationFrame(()=>a.show()),e.search.onFocus?.()},i.addEventListener("blur",()=>{window.setTimeout(()=>{document.activeElement!==i&&a?.hide()},120),Pa()&&!i.value&&window.setTimeout(()=>this.open==="search"&&this.close(),150)}),i.onkeydown=c=>{if(a){if(c.key==="Escape"&&!i.value){a.hide(),i.blur(),this.open==="search"&&this.close(),c.preventDefault();return}a.key(c)&&c.preventDefault();return}if(e.search.onKey?.(c,i.value.trim())){c.preventDefault();return}c.key==="Escape"&&(i.value="",e.search.onInput?.(""),i.blur(),this.open==="search"&&this.close())},this.q("[data-vc=filter]").onclick=()=>this.open==="filter"?this.close():this.show("filter"),document.addEventListener("pointerdown",this.onDocDown,!0);const s=this.q("[data-reset]"),o=()=>{const c=JSON.stringify(this.prefs)!==JSON.stringify(yg())||!!e.changed?.();if(s.classList.contains("dirty")===c)return;s.classList.toggle("dirty",c);const p=c?"Reset: this view differs from its defaults":"Reset this view to its defaults";s.title=p,s.setAttribute("aria-label",p)};this.dirtyTimer=window.setInterval(()=>{!document.hidden&&this.el.isConnected&&o()},400),s.onclick=()=>{s.classList.remove("spin"),s.offsetWidth,s.classList.add("spin"),this.close();try{localStorage.removeItem(bg())}catch{}this.prefs=yg(),e.reset(),this.applyPrefs(),this.refreshRegions()},this.el.querySelectorAll("[data-open]").forEach(c=>{c.onclick=()=>{const p=c.dataset.open;this.open===p?this.close():this.show(p)}}),this.el.querySelectorAll("[data-close]").forEach(c=>c.onclick=()=>this.close()),this.q(".vc-scrim").onclick=()=>this.close(),this.el.querySelectorAll("[data-all]").forEach(c=>{c.onclick=()=>{e.regions.setAll(c.dataset.all==="hide"),this.refreshRegions()}}),e.root.addEventListener("keydown",c=>{c.key==="Escape"&&this.open&&this.open!=="search"&&this.close()},{signal:this.off.signal}),this.el.querySelectorAll("[data-z]").forEach(c=>{c.onclick=()=>{const p=c.dataset.z;p==="in"?e.nav.zoom(1.4):p==="out"?e.nav.zoom(1/1.4):p==="fit"?e.nav.fit():this.toggleFullscreen()}}),document.addEventListener("fullscreenchange",this.onFs);const r={u:[0,-1],d:[0,1],l:[-1,0],r:[1,0]};this.el.querySelectorAll(".vc-globe [data-g]").forEach(c=>{const p=c.dataset.g||"";if(p==="h"){c.onclick=()=>e.nav.home();return}const h=()=>e.nav.nudge(r[p][0],r[p][1]);c.onpointerdown=u=>{u.preventDefault(),h(),clearTimeout(this.repeat);const f=()=>{h(),this.repeat=window.setTimeout(f,110)};this.repeat=window.setTimeout(f,380)};const d=()=>clearTimeout(this.repeat);c.onpointerup=d,c.onpointerleave=d,c.onpointercancel=d,c.onkeydown=u=>{(u.key==="Enter"||u.key===" ")&&(u.preventDefault(),h())}});const l=this.q(".vc-mini");if(e.minimapNav){const c=h=>{const d=l.getBoundingClientRect();e.minimapNav(Math.max(0,Math.min(1,(h.clientX-d.left)/d.width)),Math.max(0,Math.min(1,(h.clientY-d.top)/d.height)))};let p=!1;l.onpointerdown=h=>{h.stopPropagation(),p=!0,l.setPointerCapture(h.pointerId),c(h)},l.onpointermove=h=>p&&c(h),l.onpointerup=()=>p=!1}for(const c of this.el.querySelectorAll(".vc-p,.vc-tab,.vc-drawer,.vc-sheet,.vc-scrim"))c.addEventListener("pointerdown",p=>p.stopPropagation()),c.addEventListener("wheel",p=>p.stopPropagation(),{passive:!0}),c.addEventListener("dblclick",p=>p.stopPropagation())}renderPanel(){if(this.open!=="filter")return;const e=this.panel,t=e.scrollTop,i=this.o.page==="brain"?"turn the brain":"move the map";e.innerHTML=(this.phone?"":"<h4>View</h4>"+Ia("vc-minimap","Minimap",this.prefs.minimap,"The small overview at the bottom left. Click or drag it to move the view.")+Ia("vc-controls","Orbit globe",this.prefs.controls,`The globe at the bottom right: its arrows ${i}, the middle button goes back to the default view.`))+"<h4>Labels</h4>"+this.labelsHTML()+"<div data-own></div>",e.querySelectorAll("[data-t^=vc-]").forEach(a=>a.onclick=()=>this.toggleShared(a.dataset.t||"")),this.o.filter(e.querySelector("[data-own]")),Kw(e),e.scrollTop=t}labelsHTML(){const e=this.o.labels.get();return Ia("vc-lab-nodes","Node labels",e.nodes,this.o.labels.help.nodes)+Ia("vc-lab-folders","Folder labels",e.folders,this.o.labels.help.folders)}toggleShared(e){if(e==="vc-lab-nodes"||e==="vc-lab-folders"){const t=e==="vc-lab-nodes"?"nodes":"folders";this.o.labels.set(t,!this.o.labels.get()[t])}else e==="vc-minimap"?this.prefs.minimap=!this.prefs.minimap:this.prefs.controls=!this.prefs.controls,Vw(this.prefs),this.applyPrefs();this.renderPanel(),this.renderSheetLabels()}renderSheetLabels(){if(this.open!=="sheet")return;const e=this.q("[data-slot=labels]");e.innerHTML="<h4>Labels</h4>"+this.labelsHTML(),e.querySelectorAll("[data-t]").forEach(t=>t.onclick=()=>this.toggleShared(t.dataset.t||"")),Kw(e)}toggleMinimap(){if(this.phone){this.open==="sheet"?this.close():this.show("sheet");return}this.prefs.minimap=!this.prefs.minimap,Vw(this.prefs),this.applyPrefs(),this.renderPanel()}setBadge(e){this.q(".vc-badge").textContent=e?String(e):""}setCount(e){this.q(".vc-search em").textContent=e}applyPrefs(){this.q(".vc-mini").classList.toggle("vc-hide",!this.phone&&!this.prefs.minimap),this.q(".vc-globe").classList.toggle("vc-hide",!this.phone&&!this.prefs.controls),this.o.onPrefs?.(this.prefs),this.redrawMini()}refreshRegions(){const e=this.o.regions.list(),t=this.q(".vc-rl"),i=e.filter(s=>!s.hidden).length;this.el.querySelectorAll("[data-rn]").forEach(s=>s.textContent=i===e.length?String(e.length):`${i}/${e.length}`),this.q(".vc-bulk").classList.toggle("vc-hide",e.length<2);const a=!!this.o.regions.focus;t.innerHTML=e.length?e.map(s=>`<div class="vc-rr${s.hidden?" off":""}" style="--c:${O(s.color)}"><button type="button" class="tg" data-r="${O(s.name)}" aria-pressed="${!s.hidden}" title="${s.hidden?"Show":"Hide"} ${O(s.name)}" aria-label="${s.hidden?"Show":"Hide"} ${O(s.name)}"><i></i></button><button type="button" class="t" data-f="${O(s.name)}" title="${a?"Go to":s.hidden?"Show":"Hide"} ${O(s.name)}"><span>${b(s.name)}</span><em>${s.count}</em>${a?on.target:""}</button></div>`).join(""):'<div class="vc-empty">No folders yet.</div>',t.querySelectorAll("[data-r]").forEach(s=>{s.onclick=()=>{this.o.regions.toggle(s.dataset.r||""),this.refreshRegions()}}),t.querySelectorAll("[data-f]").forEach(s=>{s.onclick=()=>{const o=s.dataset.f||"";if(!this.o.regions.focus){this.o.regions.toggle(o),this.refreshRegions();return}e.find(r=>r.name===o)?.hidden&&(this.o.regions.toggle(o),this.refreshRegions()),this.close(),this.o.regions.focus(o)}})}paintAgents(){const e=Date.now(),t=r=>r.open>0&&e-r.lastAt<12e4||e-r.lastAt<5e3,i=sr(),a=Qd(),s=this.q(".vc-tab-r");if(s.classList.toggle("live",a.length>0),this.q("[data-an]").textContent=String(a.length),s.title=a.length?`${a.length} agent${a.length===1?"":"s"} working now`:"Agent activity",this.open!=="activity")return;const o=this.q(".vc-al");o.innerHTML=i.length?i.slice(0,30).map(r=>{const l=t(r),c=r.lastLabel||r.lastAction||(r.kind==="user"?"in the app":"connected");return`<div class="vc-ag${l?" on":""}" style="--ag:var(--accent)">${qt(r.actor,30,l?"live":"",r.id)}<div class="m"><b>${b(r.actor)}</b><small>${b(c)}</small></div><time>${l?"now":b(Fn(Math.floor(r.lastAt/1e3)))}</time></div>`}).join(""):'<div class="vc-empty">No agent activity yet. Agents show up here the moment they read or write your memory.</div>'}redrawMini(){if(!this.phone&&!this.prefs.minimap||this.phone&&this.open!=="sheet")return;const e=this.miniCanvas.getBoundingClientRect();if(!e.width||!e.height)return;const t=Math.min(2,window.devicePixelRatio||1),i=Math.round(e.width),a=Math.round(e.height);(this.miniCanvas.width!==i*t||this.miniCanvas.height!==a*t)&&(this.miniCanvas.width=i*t,this.miniCanvas.height=a*t),this.o.minimap(this.miniCanvas,i,a,t)}setOrientation(e,t){Math.abs(e-this.orient.yaw)<.004&&Math.abs(t-this.orient.pitch)<.004||(this.orient={yaw:e,pitch:t},this.drawGlobe())}drawGlobe(){const e=this.globe,t=Math.min(2,window.devicePixelRatio||1),i=64;e.width!==i*t&&(e.width=i*t,e.height=i*t);const a=e.getContext("2d");if(!a)return;const s=document.documentElement.dataset.theme==="light",o=s?"15,23,42":"230,233,239",r=s?"13,148,136":"94,234,212";a.setTransform(t,0,0,t,0,0),a.clearRect(0,0,i,i);const l=i/2-2,c=i/2,p=a.createRadialGradient(c-l*.35,c-l*.4,l*.1,c,c,l);p.addColorStop(0,`rgba(${r},.28)`),p.addColorStop(1,`rgba(${r},.04)`),a.fillStyle=p,a.beginPath(),a.arc(c,c,l,0,Math.PI*2),a.fill(),a.strokeStyle=`rgba(${r},.55)`,a.lineWidth=1.2,a.stroke();const{yaw:h,pitch:d}=this.orient,u=Math.cos(h),f=Math.sin(h),v=Math.cos(d),g=Math.sin(d),m=(_,w)=>{const S=Math.cos(_)*Math.sin(w),A=Math.sin(_),C=Math.cos(_)*Math.cos(w),y=S*u-C*f,M=S*f+C*u,T=A*v-M*g,L=A*g+M*v;return[c+y*l,c-T*l,L]},x=(_,w)=>{for(let S=1;S<_.length;S++){const A=_[S-1],C=_[S],y=(A[2]+C[2])/2>0;a.strokeStyle=`rgba(${w?r:o},${y?w?.85:.38:.09})`,a.lineWidth=w&&y?1.4:1,a.beginPath(),a.moveTo(A[0],A[1]),a.lineTo(C[0],C[1]),a.stroke()}};for(let _=0;_<6;_++){const w=_/6*Math.PI,S=[];for(let A=0;A<=36;A++)S.push(m(-Math.PI/2+A/36*Math.PI*2,w));x(S,!1)}for(const _ of[-.9,-.45,0,.45,.9]){const w=[];for(let S=0;S<=48;S++)w.push(m(_,S/48*Math.PI*2));x(w,_===0)}}toggleFullscreen(){const e=this.o.root;document.fullscreenElement?document.exitFullscreen().catch(()=>{}):e.requestFullscreen?.().catch(()=>{})}paintFs(){const e=this.q("[data-z=full]"),t=document.fullscreenElement===this.o.root;e.innerHTML=t?on.exitFull:on.full,e.title=t?"Exit full screen":"Full screen",e.setAttribute("aria-label",e.title),window.setTimeout(()=>window.dispatchEvent(new Event("resize")),60)}focusSearch(){Pa()&&this.show("search"),this.input.focus(),this.input.select()}setQuery(e){Pa()&&this.show("search"),this.input.value=e,this.input.focus(),this.finder?.input()}destroy(){clearTimeout(this.repeat),clearInterval(this.agentTimer),clearInterval(this.dirtyTimer),this.unsubAgents?.(),document.removeEventListener("pointerdown",this.onDocDown,!0),document.removeEventListener("fullscreenchange",this.onFs),window.removeEventListener("resize",this.onResize),this.themeObs.disconnect(),this.off.abort(),_s(),this.finder?.destroy(),this.el.remove()}}function kg(n){return n?`<b class="vc-q" tabindex="0" role="img" aria-label="${O(n)}" data-help="${O(n)}">?</b>`:""}function Ia(n,e,t,i=""){return`<button type="button" class="vc-tg${t?" on":""}" data-t="${O(n)}" role="switch" aria-checked="${t}"><span>${kg(i)}${b(e)}</span><i></i></button>`}function F4(n,e,t,i,a,s,o=""){return`<label class="vc-sl"><span>${kg(o)}${b(e)}</span><input type="range" min="${t}" max="${i}" step="${a}" value="${s}" data-s="${O(n)}"></label>`}let Sc=null;const Xw=new WeakSet;function _s(){Sc?.remove(),Sc=null}function Kw(n){_s();const e=t=>{_s();const i=document.createElement("div");Sc=i,i.className="vc-tip",i.textContent=t.dataset.help||"",document.body.appendChild(i);const a=t.getBoundingClientRect(),s=i.offsetWidth,o=a.left-s-10>=8?a.left-s-10:Math.min(innerWidth-s-8,a.right+10);i.style.left=Math.max(8,o)+"px",i.style.top=Math.max(8,Math.min(innerHeight-i.offsetHeight-8,a.top-4))+"px"};n.querySelectorAll(".vc-q").forEach(t=>{t.onmouseenter=()=>e(t),t.onfocus=()=>e(t),t.onmouseleave=_s,t.onblur=_s,t.onclick=i=>{i.stopPropagation(),i.preventDefault(),e(t);const a=Sc;window.setTimeout(()=>a===Sc&&_s(),3500)}}),Xw.has(n)||(Xw.add(n),n.addEventListener("scroll",_s,{passive:!0}))}const hi={close:'<svg viewBox="0 0 24 24"><path d="M6 6l12 12M18 6 6 18"/></svg>',more:'<svg viewBox="0 0 24 24"><circle cx="5" cy="12" r="1.6"/><circle cx="12" cy="12" r="1.6"/><circle cx="19" cy="12" r="1.6"/></svg>',open:'<svg viewBox="0 0 24 24"><path d="M14 4h6v6M20 4l-8 8"/><path d="M19 14v4a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h4"/></svg>',target:'<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="7"/><circle cx="12" cy="12" r="2.5"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3"/></svg>',folder:'<svg viewBox="0 0 24 24"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"/></svg>',only:'<svg viewBox="0 0 24 24"><path d="M4 5h16l-6 7.5V19l-4 1.5v-8z"/></svg>',plus:'<svg viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></svg>',up:'<svg viewBox="0 0 24 24"><path d="m6 15 6-6 6 6"/></svg>'},B4=`
3795
3795
  .nc{position:absolute;z-index:35;right:14px;top:12px;bottom:14px;width:min(380px,calc(100% - 28px));display:flex;flex-direction:column;
3796
3796
  background:var(--panel,#12161f);color:var(--fg,#e6e9ef);border:1px solid var(--vc-ctl-line,var(--line,#232a38));border-radius:16px;
3797
3797
  box-shadow:0 24px 60px -18px rgba(0,0,0,.7),0 0 0 1px rgba(0,0,0,.25);overflow:hidden;
@@ -3866,7 +3866,7 @@ button.ov-name:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
3866
3866
  .nc.peek .nc-head{cursor:pointer}
3867
3867
  }
3868
3868
  @media (prefers-reduced-motion:reduce){.nc,.nc.open,.nc-fold,.nc-fold-b svg{transition:none}}
3869
- `;class _g{constructor(e){this.host=e,this.path=null,this.seq=0,this.tab="preview",this.mapTap=-1e9,this.off=new AbortController,it("node-card-css",BR),this.el=document.createElement("section"),this.el.className="nc",this.el.setAttribute("role","dialog"),this.el.setAttribute("aria-label","Node details"),e.root.appendChild(this.el);for(const t of["pointerdown","wheel","dblclick","contextmenu"])this.el.addEventListener(t,i=>i.stopPropagation(),{passive:t==="wheel"});this.el.addEventListener("keydown",t=>{t.key==="Escape"&&(t.stopPropagation(),this.close(!0))}),this.wireSwipe(),e.root.addEventListener("pointerdown",t=>{const i=t.target;this.isOpen&&!i.closest(".nc,.vc,.mf,.cv-ui")&&(this.mapTap=performance.now(),Sg()&&this.collapse())},{capture:!0,signal:this.off.signal}),this.el.addEventListener("click",t=>{if(!this.el.classList.contains("peek"))return;const i=t.target;!i.closest(".nc-grab,.nc-head,.nc-title")||i.closest("[data-a=close],[data-a=menu],[data-a=fold],[data-x]")||this.expand()})}get isOpen(){return this.el.classList.contains("open")}close(e=!1){if(this.isOpen){if(!e&&Sg()&&performance.now()-this.mapTap<600){this.collapse();return}this.seq++,this.path=null,this.el.classList.remove("open","peek"),this.el.style.removeProperty("--nc-drag"),e&&(this.host.closed(),this.host.home?.())}}collapse(){this.isOpen&&Sg()&&this.el.classList.add("peek")}expand(){this.el.classList.remove("peek")}destroy(){this.seq++,this.off.abort(),this.el.remove()}showNote(e,t,i,a,s=[]){const o=++this.seq,r=this.path===e;this.path=e,r||(this.tab="preview");const{out:l,in:c}=this.host.links(e),p=this.host.extras?.(e)||[];r||this.expand(),this.el.setAttribute("aria-label",`Node ${t}`),this.el.innerHTML=`<div class="nc-grab" aria-hidden="true"></div>
3869
+ `;class _g{constructor(e){this.host=e,this.path=null,this.seq=0,this.tab="preview",this.mapTap=-1e9,this.off=new AbortController,it("node-card-css",B4),this.el=document.createElement("section"),this.el.className="nc",this.el.setAttribute("role","dialog"),this.el.setAttribute("aria-label","Node details"),e.root.appendChild(this.el);for(const t of["pointerdown","wheel","dblclick","contextmenu"])this.el.addEventListener(t,i=>i.stopPropagation(),{passive:t==="wheel"});this.el.addEventListener("keydown",t=>{t.key==="Escape"&&(t.stopPropagation(),this.close(!0))}),this.wireSwipe(),e.root.addEventListener("pointerdown",t=>{const i=t.target;this.isOpen&&!i.closest(".nc,.vc,.mf,.cv-ui")&&(this.mapTap=performance.now(),Sg()&&this.collapse())},{capture:!0,signal:this.off.signal}),this.el.addEventListener("click",t=>{if(!this.el.classList.contains("peek"))return;const i=t.target;!i.closest(".nc-grab,.nc-head,.nc-title")||i.closest("[data-a=close],[data-a=menu],[data-a=fold],[data-x]")||this.expand()})}get isOpen(){return this.el.classList.contains("open")}close(e=!1){if(this.isOpen){if(!e&&Sg()&&performance.now()-this.mapTap<600){this.collapse();return}this.seq++,this.path=null,this.el.classList.remove("open","peek"),this.el.style.removeProperty("--nc-drag"),e&&(this.host.closed(),this.host.home?.())}}collapse(){this.isOpen&&Sg()&&this.el.classList.add("peek")}expand(){this.el.classList.remove("peek")}destroy(){this.seq++,this.off.abort(),this.el.remove()}showNote(e,t,i,a,s=[]){const o=++this.seq,r=this.path===e;this.path=e,r||(this.tab="preview");const{out:l,in:c}=this.host.links(e),p=this.host.extras?.(e)||[];r||this.expand(),this.el.setAttribute("aria-label",`Node ${t}`),this.el.innerHTML=`<div class="nc-grab" aria-hidden="true"></div>
3870
3870
  <div class="nc-head"><div class="nc-crumb"><i style="--c:${O(a)}"></i><span title="${O(e)}">${b(this.crumb(i))}</span></div>
3871
3871
  ${p.map(f=>`<button type="button" class="nc-ib${f.on?" on":""}" data-x="${O(f.id)}" title="${O(f.label)}" aria-label="${O(f.label)}">${f.icon}</button>`).join("")}
3872
3872
  <button type="button" class="nc-ib" data-a="menu" title="More: rename, move, pin, delete" aria-label="More actions">${hi.more}</button>
@@ -3887,7 +3887,7 @@ button.ov-name:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
3887
3887
  <button type="button" role="tab" data-tab="in">Backlinks<span>${c.length}</span></button>
3888
3888
  </div>
3889
3889
  <div class="nc-body" role="tabpanel"></div>
3890
- </div></div>`;const h=this.el.querySelector(".nc-body");let d=AA();const u=()=>{this.el.querySelectorAll("[data-tab]").forEach(f=>f.setAttribute("aria-selected",String(f.dataset.tab===this.tab))),h.innerHTML=this.tab==="preview"?`<div class="nc-prev note-body">${d}</div>`:this.rows(this.tab==="out"?l:c,this.tab==="out"?"This node links to nothing yet.":"Nothing links here yet."),this.wireRows(h),h.querySelector("[data-a=more]")?.addEventListener("click",()=>he.openNote(e))};this.el.querySelectorAll("[data-tab]").forEach(f=>f.onclick=()=>{this.tab=f.dataset.tab,u()}),u(),this.wireCommon(p),this.on("open",()=>he.openNote(e)),this.on("node",()=>{this.host.focusNode(e),this.collapse()}),this.on("folder",()=>{this.host.focusFolder(i),this.collapse()}),this.on("menu",f=>ts([e],f)),this.el.classList.add("open"),tt("/api/note?path="+encodeURIComponent(e)).then(f=>{if(o!==this.seq)return;const v=this.el.querySelector("[data-meta]");if(v&&(v.textContent=[f.mtime?"edited "+si(f.mtime):"",f.size?`${Math.max(1,Math.round(f.size/1024))} KB`:""].filter(Boolean).join(" · ")),f.tags&&f.tags.length){const m=this.el.querySelector(".nc-tags");m.innerHTML=this.tagChips(f.tags),this.wireTags(m)}const g=f.html||(f.content?`<pre>${b(f.content)}</pre>`:"");d=g?GR(g):'<div class="nc-empty">This node is empty.</div>',this.tab==="preview"&&u()}).catch(f=>{o===this.seq&&(d=`<div class="nc-empty">Could not load the preview: ${b(f.message)}</div>`,this.tab==="preview"&&u())})}showFolder(e,t,i){++this.seq;const a=this.path===e+"/";this.path=e+"/",this.tab="items";const s=this.host.folderItems(e),o=i??s.length,r=!e||e==="Root",l=r?"Vault root":e.split("/").pop()||e,c=r?"":e.split("/").slice(0,-1).join("/");a||this.expand(),this.el.setAttribute("aria-label",`Folder ${l}`),this.el.innerHTML=`<div class="nc-grab" aria-hidden="true"></div>
3890
+ </div></div>`;const h=this.el.querySelector(".nc-body");let d=AA();const u=()=>{this.el.querySelectorAll("[data-tab]").forEach(f=>f.setAttribute("aria-selected",String(f.dataset.tab===this.tab))),h.innerHTML=this.tab==="preview"?`<div class="nc-prev note-body">${d}</div>`:this.rows(this.tab==="out"?l:c,this.tab==="out"?"This node links to nothing yet.":"Nothing links here yet."),this.wireRows(h),h.querySelector("[data-a=more]")?.addEventListener("click",()=>he.openNote(e))};this.el.querySelectorAll("[data-tab]").forEach(f=>f.onclick=()=>{this.tab=f.dataset.tab,u()}),u(),this.wireCommon(p),this.on("open",()=>he.openNote(e)),this.on("node",()=>{this.host.focusNode(e),this.collapse()}),this.on("folder",()=>{this.host.focusFolder(i),this.collapse()}),this.on("menu",f=>ts([e],f)),this.el.classList.add("open"),tt("/api/note?path="+encodeURIComponent(e)).then(f=>{if(o!==this.seq)return;const v=this.el.querySelector("[data-meta]");if(v&&(v.textContent=[f.mtime?"edited "+si(f.mtime):"",f.size?`${Math.max(1,Math.round(f.size/1024))} KB`:""].filter(Boolean).join(" · ")),f.tags&&f.tags.length){const m=this.el.querySelector(".nc-tags");m.innerHTML=this.tagChips(f.tags),this.wireTags(m)}const g=f.html||(f.content?`<pre>${b(f.content)}</pre>`:"");d=g?G4(g):'<div class="nc-empty">This node is empty.</div>',this.tab==="preview"&&u()}).catch(f=>{o===this.seq&&(d=`<div class="nc-empty">Could not load the preview: ${b(f.message)}</div>`,this.tab==="preview"&&u())})}showFolder(e,t,i){++this.seq;const a=this.path===e+"/";this.path=e+"/",this.tab="items";const s=this.host.folderItems(e),o=i??s.length,r=!e||e==="Root",l=r?"Vault root":e.split("/").pop()||e,c=r?"":e.split("/").slice(0,-1).join("/");a||this.expand(),this.el.setAttribute("aria-label",`Folder ${l}`),this.el.innerHTML=`<div class="nc-grab" aria-hidden="true"></div>
3891
3891
  <div class="nc-head"><div class="nc-crumb"><i class="sq" style="--c:${O(t)}"></i><span>${b(c?this.crumb(c):"Vault")}</span></div>
3892
3892
  ${r?"":`<button type="button" class="nc-ib" data-a="menu" title="More: rename, move, colour, delete" aria-label="More actions">${hi.more}</button>`}
3893
3893
  <button type="button" class="nc-ib nc-fold-b" data-a="fold" title="Fold or open the details" aria-label="Fold or open the details">${hi.up}</button>
@@ -3903,20 +3903,20 @@ button.ov-name:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
3903
3903
  </div>
3904
3904
  <div class="nc-tabs" role="tablist"><button type="button" role="tab" aria-selected="true">Nodes<span>${o}</span></button></div>
3905
3905
  <div class="nc-body" role="tabpanel">${this.rows(s,"No nodes directly in this folder.")}</div>
3906
- </div></div>`,this.wireRows(this.el.querySelector(".nc-body")),this.wireCommon([]),this.on("open",()=>{he.go("vault"),mt.selectFolder(r?"":e)}),this.on("folder",()=>{this.host.focusFolder(e),this.collapse()}),this.on("only",()=>{this.host.onlyFolder?.(e),this.collapse()}),this.on("new",()=>mt.newNote(r?"":e)),this.on("menu",p=>es(e,p)),this.el.classList.add("open")}crumb(e){return!e||e==="Root"?"Vault root":e.split("/").join(" / ")}tagChips(e){return e.map(t=>`<button type="button" class="nc-tag" data-tag="${O(t)}" title="Find #${O(t)} on the map">#${b(t)}</button>`).join("")}rows(e,t){return e.length?`<div class="nc-list">${e.slice(0,80).map(i=>`<button type="button" class="nc-row" data-path="${O(i.path)}" title="${O(i.path)}" style="--c:${O(i.color)}"><i></i><span>${b(i.name)}</span>${i.degree!==void 0?`<em>${i.degree}</em>`:""}</button>`).join("")}</div>${e.length>80?`<div class="nc-empty">and ${e.length-80} more</div>`:""}`:`<div class="nc-empty">${b(t)}</div>`}wireRows(e){e.querySelectorAll("[data-path]").forEach(t=>t.onclick=()=>this.host.pick(t.dataset.path||""))}wireTags(e){e.querySelectorAll("[data-tag]").forEach(t=>t.onclick=()=>this.host.tag(t.dataset.tag||""))}wireCommon(e){this.on("close",()=>this.close(!0)),this.on("fold",()=>this.el.classList.contains("peek")?this.expand():this.collapse()),this.wireTags(this.el);for(const t of e){const i=Array.from(this.el.querySelectorAll("[data-x]")).find(a=>a.dataset.x===t.id);i&&(i.onclick=()=>t.run())}}on(e,t){const i=this.el.querySelector(`[data-a="${e}"]`);i&&(i.onclick=()=>t(i))}wireSwipe(){let e=-1,t=0;this.el.addEventListener("pointerdown",a=>{const s=a.target;window.matchMedia("(max-width:760px)").matches&&(!s.closest(".nc-grab,.nc-head")||s.closest("button")||(e=a.clientY,t=0,this.el.classList.add("dragging"),this.el.setPointerCapture(a.pointerId)))}),this.el.addEventListener("pointermove",a=>{e<0||(t=a.clientY-e,this.el.style.setProperty("--nc-drag",Math.max(0,t)+"px"))});const i=()=>{if(e<0)return;e=-1,this.el.classList.remove("dragging"),this.el.style.removeProperty("--nc-drag");const a=this.el.classList.contains("peek");t>60?a?this.close(!0):this.collapse():t<-30&&a&&this.expand()};this.el.addEventListener("pointerup",i),this.el.addEventListener("pointercancel",i)}}function Sg(){return window.matchMedia("(max-width:760px)").matches}const HR=700;function GR(n){const e=document.createElement("div");e.innerHTML=n;const t=Array.from(e.children);let i=0,a=0;for(const s of t)if(i+=(s.textContent||"").length,a++,i>=HR||a>=6)break;return a>=t.length?n:(t.slice(a).forEach(s=>s.remove()),e.innerHTML+'<button type="button" class="nc-more" data-a="more">Read more</button>')}const qR={brain:'<path d="M9.5 4.5A2.5 2.5 0 0 0 7 7a2.6 2.6 0 0 0-2.5 3.2A3 3 0 0 0 5 15.6 2.8 2.8 0 0 0 9.5 19.5V4.5z"/><path d="M14.5 4.5A2.5 2.5 0 0 1 17 7a2.6 2.6 0 0 1 2.5 3.2 3 3 0 0 1-.5 5.4 2.8 2.8 0 0 1-4.5 3.9V4.5z"/>',graph:'<circle cx="6" cy="17" r="2.4"/><circle cx="17.5" cy="6.5" r="2.4"/><circle cx="17.5" cy="17.5" r="2.2"/><path d="M7.9 15.3 15.4 8.4M8.8 17.4h6.3"/>',canvas:'<rect x="3.5" y="3.5" width="17" height="17" rx="3"/><rect x="6.5" y="7" width="5" height="4" rx="1"/><rect x="12.5" y="12.5" width="5" height="4.5" rx="1"/>',force:'<circle cx="12" cy="12" r="2.5"/><circle cx="5" cy="6" r="1.6"/><circle cx="19" cy="7" r="1.6"/><circle cx="7" cy="19" r="1.6"/><path d="M10 10.5 6.3 7M14 11l3.6-3M10.4 14 8 17.6"/>',radial:'<circle cx="12" cy="12" r="2"/><circle cx="12" cy="12" r="5.5"/><circle cx="12" cy="12" r="9"/>',clusters:'<circle cx="7.5" cy="8" r="3.5"/><circle cx="16.5" cy="9" r="3"/><circle cx="11" cy="17" r="3.5"/>',search:'<circle cx="11" cy="11" r="7"/><path d="m20.5 20.5-4.3-4.3"/>',filter:'<path d="M4 5h16M7 12h10M10 19h4"/>',plus:'<path d="M12 5v14M5 12h14"/>',minus:'<path d="M5 12h14"/>',fit:'<path d="M4 9V5a1 1 0 0 1 1-1h4M15 4h4a1 1 0 0 1 1 1v4M20 15v4a1 1 0 0 1-1 1h-4M9 20H5a1 1 0 0 1-1-1v-4"/>',open:'<path d="M14 4h6v6M20 4l-8.5 8.5M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5"/>',pin:'<path d="M9 4h6l-1 5 3 3H7l3-3zM12 15v5"/>',target:'<circle cx="12" cy="12" r="7"/><circle cx="12" cy="12" r="2"/>',map:'<path d="m9 5-5 2v12l5-2 6 2 5-2V5l-5 2z"/><path d="M9 5v12M15 7v12"/>'},Yw=n=>`<svg viewBox="0 0 24 24">${qR[n]||""}</svg>`;class VR{constructor(e){this.cam=new cR,this.sim=new ER,this.model=new uR,this.prefs=xR(),this.layout={v:1,pins:{}},this.nodes=[],this.links=[],this.nbr=new Map,this.hover=null,this.selected=null,this.dragging=null,this.hits=null,this.focus=null,this.pulses=new Map,this.rings=[],this.theme={light:!1,bg:"#0b0e14",ink:"#e6e9ef",muted:"#8b98ad",accent:"#5eead4",panel:"#12161f"},this.dpr=1,this.raf=0,this.active=!1,this.dirty=!0,this.frame=0,this.loaded=!1,this.loading=null,this.refreshTimer=0,this.userMoved=!1,this.unsubs=[],this.pointers=new Map,this.gesture=null,this.pinch=null,this.lastTap={node:null,t:0},this.miniMap={x0:0,y0:0,s:1},this.flashTimer=0,this.fading=!1,this.tickMs=0,this.asLink=i=>({path:i.path,name:i.label,color:i.color,degree:i.degree}),RR(),this.filters={hiddenGroups:new Set,tags:new Set,folders:this.prefs.folders,orphans:this.prefs.orphans},this.sim.spacing=this.prefs.spacingBy[this.prefs.mode],e.innerHTML="";const t=document.createElement("div");t.className="gx",t.innerHTML=this.template(),e.appendChild(t),this.root=t,this.cv=t.querySelector(".gx-cv"),this.ctx=this.cv.getContext("2d",{alpha:!1}),this.chrome=this.buildChrome(),this.card=this.buildCard(),this.mini=this.chrome.miniCanvas,this.renderer=new _R(this.ctx),this.wireCanvas()}clientPoint(e){const t=this.nodes.find(s=>s.path===e);if(!t||!this.root.isConnected)return null;const i=this.cv.getBoundingClientRect(),a=this.cam.toScreen(t.x,t.y);return{x:i.left+a.x,y:i.top+a.y}}show(){this.chrome.shown();const e=!this.active;this.active||this.resume(),this.loaded?(this.refreshSoon(150),e&&(this.userMoved=!1,window.setTimeout(()=>this.fitAll(500),60))):this.load(!1),this.dirty=!0,this.resize(),this.kick()}resume(){this.active=!0,this.readTheme(),this.model.recolor(this.theme.light),this.resize();const e=new ResizeObserver(()=>this.resize());e.observe(this.root);const t=new MutationObserver(()=>{this.readTheme(),this.model.recolor(this.theme.light),this.renderer.hullsDirty=!0,this.kick()});t.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","class","style"]});const i=()=>{if(!document.hidden){this.kick();return}cancelAnimationFrame(this.raf),this.raf=0};document.addEventListener("visibilitychange",i);const a=s=>this.onKey(s);window.addEventListener("keydown",a),this.unsubs.push(()=>e.disconnect(),()=>t.disconnect(),()=>document.removeEventListener("visibilitychange",i),()=>window.removeEventListener("keydown",a),jn("mutation",s=>this.onMutation(s)),jn("activity",s=>this.onActivity(s.actor,s.phase,s.paths||[]))),this.kick()}suspend(){this.active=!1,cancelAnimationFrame(this.raf),this.raf=0,clearTimeout(this.refreshTimer),clearTimeout(this.flashTimer),this.unsubs.forEach(e=>e()),this.unsubs=[],this.pointers.clear(),this.gesture=null,this.pinch=null,this.dragging&&this.endDrag(),this.setHover(null)}async load(e){return this.loading?this.loading:(this.loading=(async()=>{let t;try{const[r,l]=await Promise.all([tt("/api/graph"),this.loaded?Promise.resolve(this.layout):vR()]);t=r,this.layout=l}catch(r){this.showEmpty("Could not load the graph",r.message);return}const i=!this.loaded,a=performance.now(),{added:s,removed:o}=this.model.ingest(t,a,e&&!i);i&&this.importCachedTags(),this.model.recolor(this.theme.light);for(const r of s){const l=this.layout.pins[r.id]||(r.kind==="note"?this.layout.pins[r.label]:void 0);l&&(r.pinned=!0,r.x=r.fx=l[0],r.y=r.fy=l[1])}if(this.loaded=!0,this.rebuild(),i){Rw(this.nodes),this.applyMode(!1);const r=Math.min(220,Math.floor(4e5/Math.max(200,this.nodes.length)));for(let l=0;l<r&&this.sim.alpha>.12;l++)this.sim.tick();this.fitAll(0),window.setTimeout(()=>!this.userMoved&&this.fitAll(900),1600)}else(s.length||o.length)&&this.sim.reheat(.35);this.renderPanel(),this.updateHud(),this.selected&&this.paintCard(this.selected),this.showEmpty(this.model.all.size?"":"No nodes yet","Nodes and their [[wikilinks]] show up here."),this.kick()})().finally(()=>{this.loading=null}),this.loading)}refreshSoon(e=350){clearTimeout(this.refreshTimer),this.refreshTimer=window.setTimeout(()=>{this.load(!0)},e)}rebuild(){const{nodes:e,links:t}=this.model.visible(this.filters);this.nodes=e,this.links=t;for(const i of e)i.pinned&&i.fx==null&&(i.fx=i.x,i.fy=i.y);Rw(e),this.sim.setData(e,t),this.nbr.clear();for(const i of e)this.nbr.set(i,new Set);for(const i of t)this.nbr.get(i.s).add(i.t),this.nbr.get(i.t).add(i.s);this.selected&&!this.nbr.has(this.selected)&&this.closeCard(),this.hover&&!this.nbr.has(this.hover)&&(this.hover=null),this.prefs.mode!=="force"&&this.computeTargets(),this.renderer.hullsDirty=!0,this.hits&&this.chrome?.finder?.update(),this.updateFocus(),this.dirty=!0}computeTargets(){if(this.prefs.mode==="radial")this.rings=mR(this.nodes).rings;else if(this.prefs.mode==="clusters")gR(this.nodes);else return;const e=this.prefs.spacingBy[this.prefs.mode];if(e!==1){for(const t of this.nodes)t.tx*=e,t.ty*=e;this.rings=this.rings.map(t=>t*e)}}applyMode(e){const t=this.prefs.mode;if(this.sim.mode=t,this.sim.spacing=this.prefs.spacingBy[t],this.sim.targetPull=t==="force"?0:t==="radial"?.16:.12,t!=="force"&&this.computeTargets(),this.sim.alpha=1,this.renderer.hullsDirty=!0,this.root.querySelectorAll(".gx-layouts button").forEach(i=>i.classList.toggle("on",i.dataset.mode===t)),e)if(t!=="force"){const i=this.bounds(!0);i&&this.cam.fit(i,40,1e3,1.6,this.topInset(),10)}else window.setTimeout(()=>this.fitAll(900),900);this.kick()}setMode(e){e!==this.prefs.mode&&(this.prefs.mode=e,yc(this.prefs),this.applyMode(!0))}topInset(){const e=this.root.querySelector(".vc-search");return e?e.getBoundingClientRect().bottom-this.root.getBoundingClientRect().top+4:56}bounds(e=!1){let t=1/0,i=1/0,a=-1/0,s=-1/0;for(const o of this.nodes){if(o.dying)continue;const r=e&&o.fx==null?o.tx:o.x,l=e&&o.fy==null?o.ty:o.y;t=Math.min(t,r-o.r),i=Math.min(i,l-o.r),a=Math.max(a,r+o.r),s=Math.max(s,l+o.r)}return t===1/0?null:{x0:t,y0:i,x1:a,y1:s}}fitAll(e=650){const t=this.bounds();if(!t)return;const i=this.cam.w<760;this.cam.fit(t,i?20:48,e,1.6,this.topInset(),i?40:10),this.kick()}kick(){!this.active||this.raf||document.hidden||(this.raf=requestAnimationFrame(e=>this.frameStep(e)))}frameStep(e){if(this.raf=0,!this.active||!this.root.isConnected||this.root.offsetParent===null)return;this.frame++;let t=!1;if(this.sim.running&&this.nodes.length){if(this.tickMs<9||this.frame%2===0){const s=performance.now();this.sim.tick(),this.tickMs=this.tickMs*.8+(performance.now()-s)*.2}t=!0,this.frame%3===0&&(this.renderer.hullsDirty=!0)}this.cam.step(e)&&(t=!0),this.model.reap(e,Uw)&&this.rebuild();let i=!1;for(const s of this.nodes)if(s.born||s.dying){i=!0;break}this.pulses.size&&(i=!0,this.pulses.forEach((s,o)=>{for(const l of s)!l.end&&e-l.start>3e4&&(l.end=e);const r=s.filter(l=>!l.end||e-l.end<2600);r.length?this.pulses.set(o,r):this.pulses.delete(o)}));const a=!!(this.hover||this.selected);if(t||i||a||this.dirty||this.fading){try{this.fading=this.draw(e)}catch(s){console.error("graph draw failed",s),this.fading=!1}this.chrome.prefs.minimap&&(this.frame%4===0||this.dirty)&&this.drawMini(),this.dirty=!1}(t||i||a||this.fading)&&this.kick()}draw(e){const t=this.nodes.reduce((a,s)=>a+s.fade,0);this.renderer.draw(this.cam,{nodes:this.nodes,links:this.links,hover:this.hover,selected:this.selected,focus:this.focus,pulses:this.pulses,mode:this.prefs.mode,rings:this.rings,labelDensity:this.prefs.labels,noteLabels:this.prefs.noteLabels,folderLabels:this.prefs.folderLabels,hulls:this.prefs.hulls,now:e,dragging:this.dragging,reserveTop:this.topInset()},this.theme,this.dpr);const i=this.nodes.reduce((a,s)=>a+s.fade,0);return Math.abs(i-t)>.01}drawMini(){this.chrome.redrawMini()}resize(){const e=this.root.getBoundingClientRect();if(!e.width||!e.height)return;this.dpr=Math.min(window.devicePixelRatio||1,2),this.cv.width=Math.round(e.width*this.dpr),this.cv.height=Math.round(e.height*this.dpr);const t=this.cam.w<=1||this.cam.h<=1;this.cam.w=e.width,this.cam.h=e.height,t&&this.loaded&&!this.userMoved&&this.fitAll(0),this.dirty=!0,this.kick()}readTheme(){const e=getComputedStyle(this.root),t=document.documentElement.dataset.theme==="light",i=(a,s)=>e.getPropertyValue(a).trim()||s;this.theme={light:t,bg:i("--bg",t?"#f3f5f9":"#0b0e14"),ink:i("--fg",t?"#111827":"#e6e9ef"),muted:i("--muted",t?"#5b6678":"#8b98ad"),accent:i("--accent",t?"#0d9488":"#5eead4"),panel:i("--panel",t?"#ffffff":"#12161f")};for(const a of["bg","ink","muted","accent","panel"]){const s=this.theme[a];/^#|^rgb/.test(s)||(this.ctx.fillStyle=s,this.theme[a]=String(this.ctx.fillStyle))}this.dirty=!0}q(e){return this.root.querySelector(e)||document.createElement("div")}template(){return`
3906
+ </div></div>`,this.wireRows(this.el.querySelector(".nc-body")),this.wireCommon([]),this.on("open",()=>{he.go("vault"),mt.selectFolder(r?"":e)}),this.on("folder",()=>{this.host.focusFolder(e),this.collapse()}),this.on("only",()=>{this.host.onlyFolder?.(e),this.collapse()}),this.on("new",()=>mt.newNote(r?"":e)),this.on("menu",p=>es(e,p)),this.el.classList.add("open")}crumb(e){return!e||e==="Root"?"Vault root":e.split("/").join(" / ")}tagChips(e){return e.map(t=>`<button type="button" class="nc-tag" data-tag="${O(t)}" title="Find #${O(t)} on the map">#${b(t)}</button>`).join("")}rows(e,t){return e.length?`<div class="nc-list">${e.slice(0,80).map(i=>`<button type="button" class="nc-row" data-path="${O(i.path)}" title="${O(i.path)}" style="--c:${O(i.color)}"><i></i><span>${b(i.name)}</span>${i.degree!==void 0?`<em>${i.degree}</em>`:""}</button>`).join("")}</div>${e.length>80?`<div class="nc-empty">and ${e.length-80} more</div>`:""}`:`<div class="nc-empty">${b(t)}</div>`}wireRows(e){e.querySelectorAll("[data-path]").forEach(t=>t.onclick=()=>this.host.pick(t.dataset.path||""))}wireTags(e){e.querySelectorAll("[data-tag]").forEach(t=>t.onclick=()=>this.host.tag(t.dataset.tag||""))}wireCommon(e){this.on("close",()=>this.close(!0)),this.on("fold",()=>this.el.classList.contains("peek")?this.expand():this.collapse()),this.wireTags(this.el);for(const t of e){const i=Array.from(this.el.querySelectorAll("[data-x]")).find(a=>a.dataset.x===t.id);i&&(i.onclick=()=>t.run())}}on(e,t){const i=this.el.querySelector(`[data-a="${e}"]`);i&&(i.onclick=()=>t(i))}wireSwipe(){let e=-1,t=0;this.el.addEventListener("pointerdown",a=>{const s=a.target;window.matchMedia("(max-width:760px)").matches&&(!s.closest(".nc-grab,.nc-head")||s.closest("button")||(e=a.clientY,t=0,this.el.classList.add("dragging"),this.el.setPointerCapture(a.pointerId)))}),this.el.addEventListener("pointermove",a=>{e<0||(t=a.clientY-e,this.el.style.setProperty("--nc-drag",Math.max(0,t)+"px"))});const i=()=>{if(e<0)return;e=-1,this.el.classList.remove("dragging"),this.el.style.removeProperty("--nc-drag");const a=this.el.classList.contains("peek");t>60?a?this.close(!0):this.collapse():t<-30&&a&&this.expand()};this.el.addEventListener("pointerup",i),this.el.addEventListener("pointercancel",i)}}function Sg(){return window.matchMedia("(max-width:760px)").matches}const H4=700;function G4(n){const e=document.createElement("div");e.innerHTML=n;const t=Array.from(e.children);let i=0,a=0;for(const s of t)if(i+=(s.textContent||"").length,a++,i>=H4||a>=6)break;return a>=t.length?n:(t.slice(a).forEach(s=>s.remove()),e.innerHTML+'<button type="button" class="nc-more" data-a="more">Read more</button>')}const q4={brain:'<path d="M9.5 4.5A2.5 2.5 0 0 0 7 7a2.6 2.6 0 0 0-2.5 3.2A3 3 0 0 0 5 15.6 2.8 2.8 0 0 0 9.5 19.5V4.5z"/><path d="M14.5 4.5A2.5 2.5 0 0 1 17 7a2.6 2.6 0 0 1 2.5 3.2 3 3 0 0 1-.5 5.4 2.8 2.8 0 0 1-4.5 3.9V4.5z"/>',graph:'<circle cx="6" cy="17" r="2.4"/><circle cx="17.5" cy="6.5" r="2.4"/><circle cx="17.5" cy="17.5" r="2.2"/><path d="M7.9 15.3 15.4 8.4M8.8 17.4h6.3"/>',canvas:'<rect x="3.5" y="3.5" width="17" height="17" rx="3"/><rect x="6.5" y="7" width="5" height="4" rx="1"/><rect x="12.5" y="12.5" width="5" height="4.5" rx="1"/>',force:'<circle cx="12" cy="12" r="2.5"/><circle cx="5" cy="6" r="1.6"/><circle cx="19" cy="7" r="1.6"/><circle cx="7" cy="19" r="1.6"/><path d="M10 10.5 6.3 7M14 11l3.6-3M10.4 14 8 17.6"/>',radial:'<circle cx="12" cy="12" r="2"/><circle cx="12" cy="12" r="5.5"/><circle cx="12" cy="12" r="9"/>',clusters:'<circle cx="7.5" cy="8" r="3.5"/><circle cx="16.5" cy="9" r="3"/><circle cx="11" cy="17" r="3.5"/>',search:'<circle cx="11" cy="11" r="7"/><path d="m20.5 20.5-4.3-4.3"/>',filter:'<path d="M4 5h16M7 12h10M10 19h4"/>',plus:'<path d="M12 5v14M5 12h14"/>',minus:'<path d="M5 12h14"/>',fit:'<path d="M4 9V5a1 1 0 0 1 1-1h4M15 4h4a1 1 0 0 1 1 1v4M20 15v4a1 1 0 0 1-1 1h-4M9 20H5a1 1 0 0 1-1-1v-4"/>',open:'<path d="M14 4h6v6M20 4l-8.5 8.5M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5"/>',pin:'<path d="M9 4h6l-1 5 3 3H7l3-3zM12 15v5"/>',target:'<circle cx="12" cy="12" r="7"/><circle cx="12" cy="12" r="2"/>',map:'<path d="m9 5-5 2v12l5-2 6 2 5-2V5l-5 2z"/><path d="M9 5v12M15 7v12"/>'},Yw=n=>`<svg viewBox="0 0 24 24">${q4[n]||""}</svg>`;class V4{constructor(e){this.cam=new c4,this.sim=new E4,this.model=new u4,this.prefs=x4(),this.layout={v:1,pins:{}},this.nodes=[],this.links=[],this.nbr=new Map,this.hover=null,this.selected=null,this.dragging=null,this.hits=null,this.focus=null,this.pulses=new Map,this.rings=[],this.theme={light:!1,bg:"#0b0e14",ink:"#e6e9ef",muted:"#8b98ad",accent:"#5eead4",panel:"#12161f"},this.dpr=1,this.raf=0,this.active=!1,this.dirty=!0,this.frame=0,this.loaded=!1,this.loading=null,this.refreshTimer=0,this.userMoved=!1,this.unsubs=[],this.pointers=new Map,this.gesture=null,this.pinch=null,this.lastTap={node:null,t:0},this.miniMap={x0:0,y0:0,s:1},this.flashTimer=0,this.fading=!1,this.tickMs=0,this.asLink=i=>({path:i.path,name:i.label,color:i.color,degree:i.degree}),R4(),this.filters={hiddenGroups:new Set,tags:new Set,folders:this.prefs.folders,orphans:this.prefs.orphans},this.sim.spacing=this.prefs.spacingBy[this.prefs.mode],e.innerHTML="";const t=document.createElement("div");t.className="gx",t.innerHTML=this.template(),e.appendChild(t),this.root=t,this.cv=t.querySelector(".gx-cv"),this.ctx=this.cv.getContext("2d",{alpha:!1}),this.chrome=this.buildChrome(),this.card=this.buildCard(),this.mini=this.chrome.miniCanvas,this.renderer=new _4(this.ctx),this.wireCanvas()}clientPoint(e){const t=this.nodes.find(s=>s.path===e);if(!t||!this.root.isConnected)return null;const i=this.cv.getBoundingClientRect(),a=this.cam.toScreen(t.x,t.y);return{x:i.left+a.x,y:i.top+a.y}}show(){this.chrome.shown();const e=!this.active;this.active||this.resume(),this.loaded?(this.refreshSoon(150),e&&(this.userMoved=!1,window.setTimeout(()=>this.fitAll(500),60))):this.load(!1),this.dirty=!0,this.resize(),this.kick()}resume(){this.active=!0,this.readTheme(),this.model.recolor(this.theme.light),this.resize();const e=new ResizeObserver(()=>this.resize());e.observe(this.root);const t=new MutationObserver(()=>{this.readTheme(),this.model.recolor(this.theme.light),this.renderer.hullsDirty=!0,this.kick()});t.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","class","style"]});const i=()=>{if(!document.hidden){this.kick();return}cancelAnimationFrame(this.raf),this.raf=0};document.addEventListener("visibilitychange",i);const a=s=>this.onKey(s);window.addEventListener("keydown",a),this.unsubs.push(()=>e.disconnect(),()=>t.disconnect(),()=>document.removeEventListener("visibilitychange",i),()=>window.removeEventListener("keydown",a),jn("mutation",s=>this.onMutation(s)),jn("activity",s=>this.onActivity(s.actor,s.phase,s.paths||[]))),this.kick()}suspend(){this.active=!1,cancelAnimationFrame(this.raf),this.raf=0,clearTimeout(this.refreshTimer),clearTimeout(this.flashTimer),this.unsubs.forEach(e=>e()),this.unsubs=[],this.pointers.clear(),this.gesture=null,this.pinch=null,this.dragging&&this.endDrag(),this.setHover(null)}async load(e){return this.loading?this.loading:(this.loading=(async()=>{let t;try{const[r,l]=await Promise.all([tt("/api/graph"),this.loaded?Promise.resolve(this.layout):v4()]);t=r,this.layout=l}catch(r){this.showEmpty("Could not load the graph",r.message);return}const i=!this.loaded,a=performance.now(),{added:s,removed:o}=this.model.ingest(t,a,e&&!i);i&&this.importCachedTags(),this.model.recolor(this.theme.light);for(const r of s){const l=this.layout.pins[r.id]||(r.kind==="note"?this.layout.pins[r.label]:void 0);l&&(r.pinned=!0,r.x=r.fx=l[0],r.y=r.fy=l[1])}if(this.loaded=!0,this.rebuild(),i){Rw(this.nodes),this.applyMode(!1);const r=Math.min(220,Math.floor(4e5/Math.max(200,this.nodes.length)));for(let l=0;l<r&&this.sim.alpha>.12;l++)this.sim.tick();this.fitAll(0),window.setTimeout(()=>!this.userMoved&&this.fitAll(900),1600)}else(s.length||o.length)&&this.sim.reheat(.35);this.renderPanel(),this.updateHud(),this.selected&&this.paintCard(this.selected),this.showEmpty(this.model.all.size?"":"No nodes yet","Nodes and their [[wikilinks]] show up here."),this.kick()})().finally(()=>{this.loading=null}),this.loading)}refreshSoon(e=350){clearTimeout(this.refreshTimer),this.refreshTimer=window.setTimeout(()=>{this.load(!0)},e)}rebuild(){const{nodes:e,links:t}=this.model.visible(this.filters);this.nodes=e,this.links=t;for(const i of e)i.pinned&&i.fx==null&&(i.fx=i.x,i.fy=i.y);Rw(e),this.sim.setData(e,t),this.nbr.clear();for(const i of e)this.nbr.set(i,new Set);for(const i of t)this.nbr.get(i.s).add(i.t),this.nbr.get(i.t).add(i.s);this.selected&&!this.nbr.has(this.selected)&&this.closeCard(),this.hover&&!this.nbr.has(this.hover)&&(this.hover=null),this.prefs.mode!=="force"&&this.computeTargets(),this.renderer.hullsDirty=!0,this.hits&&this.chrome?.finder?.update(),this.updateFocus(),this.dirty=!0}computeTargets(){if(this.prefs.mode==="radial")this.rings=m4(this.nodes).rings;else if(this.prefs.mode==="clusters")g4(this.nodes);else return;const e=this.prefs.spacingBy[this.prefs.mode];if(e!==1){for(const t of this.nodes)t.tx*=e,t.ty*=e;this.rings=this.rings.map(t=>t*e)}}applyMode(e){const t=this.prefs.mode;if(this.sim.mode=t,this.sim.spacing=this.prefs.spacingBy[t],this.sim.targetPull=t==="force"?0:t==="radial"?.16:.12,t!=="force"&&this.computeTargets(),this.sim.alpha=1,this.renderer.hullsDirty=!0,this.root.querySelectorAll(".gx-layouts button").forEach(i=>i.classList.toggle("on",i.dataset.mode===t)),e)if(t!=="force"){const i=this.bounds(!0);i&&this.cam.fit(i,40,1e3,1.6,this.topInset(),10)}else window.setTimeout(()=>this.fitAll(900),900);this.kick()}setMode(e){e!==this.prefs.mode&&(this.prefs.mode=e,yc(this.prefs),this.applyMode(!0))}topInset(){const e=this.root.querySelector(".vc-search");return e?e.getBoundingClientRect().bottom-this.root.getBoundingClientRect().top+4:56}bounds(e=!1){let t=1/0,i=1/0,a=-1/0,s=-1/0;for(const o of this.nodes){if(o.dying)continue;const r=e&&o.fx==null?o.tx:o.x,l=e&&o.fy==null?o.ty:o.y;t=Math.min(t,r-o.r),i=Math.min(i,l-o.r),a=Math.max(a,r+o.r),s=Math.max(s,l+o.r)}return t===1/0?null:{x0:t,y0:i,x1:a,y1:s}}fitAll(e=650){const t=this.bounds();if(!t)return;const i=this.cam.w<760;this.cam.fit(t,i?20:48,e,1.6,this.topInset(),i?40:10),this.kick()}kick(){!this.active||this.raf||document.hidden||(this.raf=requestAnimationFrame(e=>this.frameStep(e)))}frameStep(e){if(this.raf=0,!this.active||!this.root.isConnected||this.root.offsetParent===null)return;this.frame++;let t=!1;if(this.sim.running&&this.nodes.length){if(this.tickMs<9||this.frame%2===0){const s=performance.now();this.sim.tick(),this.tickMs=this.tickMs*.8+(performance.now()-s)*.2}t=!0,this.frame%3===0&&(this.renderer.hullsDirty=!0)}this.cam.step(e)&&(t=!0),this.model.reap(e,Uw)&&this.rebuild();let i=!1;for(const s of this.nodes)if(s.born||s.dying){i=!0;break}this.pulses.size&&(i=!0,this.pulses.forEach((s,o)=>{for(const l of s)!l.end&&e-l.start>3e4&&(l.end=e);const r=s.filter(l=>!l.end||e-l.end<2600);r.length?this.pulses.set(o,r):this.pulses.delete(o)}));const a=!!(this.hover||this.selected);if(t||i||a||this.dirty||this.fading){try{this.fading=this.draw(e)}catch(s){console.error("graph draw failed",s),this.fading=!1}this.chrome.prefs.minimap&&(this.frame%4===0||this.dirty)&&this.drawMini(),this.dirty=!1}(t||i||a||this.fading)&&this.kick()}draw(e){const t=this.nodes.reduce((a,s)=>a+s.fade,0);this.renderer.draw(this.cam,{nodes:this.nodes,links:this.links,hover:this.hover,selected:this.selected,focus:this.focus,pulses:this.pulses,mode:this.prefs.mode,rings:this.rings,labelDensity:this.prefs.labels,noteLabels:this.prefs.noteLabels,folderLabels:this.prefs.folderLabels,hulls:this.prefs.hulls,now:e,dragging:this.dragging,reserveTop:this.topInset()},this.theme,this.dpr);const i=this.nodes.reduce((a,s)=>a+s.fade,0);return Math.abs(i-t)>.01}drawMini(){this.chrome.redrawMini()}resize(){const e=this.root.getBoundingClientRect();if(!e.width||!e.height)return;this.dpr=Math.min(window.devicePixelRatio||1,2),this.cv.width=Math.round(e.width*this.dpr),this.cv.height=Math.round(e.height*this.dpr);const t=this.cam.w<=1||this.cam.h<=1;this.cam.w=e.width,this.cam.h=e.height,t&&this.loaded&&!this.userMoved&&this.fitAll(0),this.dirty=!0,this.kick()}readTheme(){const e=getComputedStyle(this.root),t=document.documentElement.dataset.theme==="light",i=(a,s)=>e.getPropertyValue(a).trim()||s;this.theme={light:t,bg:i("--bg",t?"#f3f5f9":"#0b0e14"),ink:i("--fg",t?"#111827":"#e6e9ef"),muted:i("--muted",t?"#5b6678":"#8b98ad"),accent:i("--accent",t?"#0d9488":"#5eead4"),panel:i("--panel",t?"#ffffff":"#12161f")};for(const a of["bg","ink","muted","accent","panel"]){const s=this.theme[a];/^#|^rgb/.test(s)||(this.ctx.fillStyle=s,this.theme[a]=String(this.ctx.fillStyle))}this.dirty=!0}q(e){return this.root.querySelector(e)||document.createElement("div")}template(){return`
3907
3907
  <canvas class="gx-cv" tabindex="0" aria-label="Knowledge graph"></canvas>
3908
3908
  <div class="gx-empty gx-hide"><b></b><span></span></div>
3909
3909
  <div class="gx-tip gx-glass gx-hide"></div>
3910
- `}buildChrome(){return new wg({page:"graph",root:this.root,search:{placeholder:"Find a node, #tag or in:folder",find:{items:()=>this.nodes.filter(e=>e.kind!=="folder"&&!e.dying).map(e=>({id:e.path,name:e.label,folder:e.dir||"Root",region:e.group,color:e.color,tags:this.model.tagsByPath.get(e.path)||e.tags,degree:e.degree})),highlight:e=>{this.hits=e?new Set(this.nodes.filter(t=>e.has(t.path))):null,this.updateFocus()},pick:e=>{const t=this.nodes.find(i=>i.path===e.id&&i.kind!=="folder");t&&this.select(t,!0)},folder:e=>{this.focusGroup(e),this.showFolderCard(this.groupDir(e))}}},changed:()=>JSON.stringify(this.prefs)!==JSON.stringify(zw())||this.filters.hiddenGroups.size>0||this.filters.tags.size>0||!!this.hits||!!this.selected||!!this.card?.isOpen||this.userMoved,labels:{get:()=>({nodes:this.prefs.noteLabels,folders:this.prefs.folderLabels}),set:(e,t)=>{e==="nodes"?this.prefs.noteLabels=t:this.prefs.folderLabels=t,yc(this.prefs),this.dirty=!0,this.kick()},help:{nodes:"Names next to the nodes. The node under the pointer and its neighbours always show theirs.",folders:"Folder names: the hub of each folder and the title over each folder hull."}},filter:e=>this.renderPanel(e),reset:()=>{this.prefs=bR(),yc(this.prefs),this.filters.hiddenGroups=new Set,this.filters.tags=new Set,this.filters.folders=this.prefs.folders,this.filters.orphans=this.prefs.orphans,this.chrome.finder?.clear(),this.closeCard(),this.rebuild(),this.applyMode(!1),this.sim.reheat(.6),this.userMoved=!1,window.setTimeout(()=>this.fitAll(700),350),this.updateHud()},regions:{list:()=>this.model.groups().map(([e,t,i])=>({name:e,count:t,color:i,hidden:this.filters.hiddenGroups.has(e)})),toggle:e=>{this.filters.hiddenGroups.has(e)?this.filters.hiddenGroups.delete(e):this.filters.hiddenGroups.add(e),this.applyFilters()},setAll:e=>{this.filters.hiddenGroups=e?new Set(this.model.groups().map(t=>t[0])):new Set,this.applyFilters()},focus:e=>{this.focusGroup(e),this.showFolderCard(this.groupDir(e))}},nav:{zoom:e=>{this.userMoved=!0,this.cam.animateTo(this.cam.x,this.cam.y,this.cam.k*e,300),this.kick()},fit:()=>{this.userMoved=!0,this.fitAll()},nudge:(e,t)=>{this.userMoved=!0,this.cam.animateTo(this.cam.x+e*this.cam.w*.16/this.cam.k,this.cam.y+t*this.cam.h*.16/this.cam.k,this.cam.k,200),this.kick()},home:()=>{this.userMoved=!1,this.fitAll()}},minimap:(e,t,i,a)=>{const s=e.getContext("2d");s&&(this.miniMap=MR(s,t,i,a,this.nodes,this.cam,this.theme))},minimapNav:(e,t)=>{const i=this.mini.getBoundingClientRect();this.userMoved=!0,this.cam.stop(),this.cam.x=(e*i.width-this.miniMap.x0)/this.miniMap.s,this.cam.y=(t*i.height-this.miniMap.y0)/this.miniMap.s,this.dirty=!0,this.kick()},onPrefs:()=>{this.dirty=!0,this.kick()},onOverlay:()=>this.closeCard()})}focusGroup(e){const t=this.nodes.filter(a=>!a.dying&&a.group===e);if(!t.length)return;const i={x0:1/0,y0:1/0,x1:-1/0,y1:-1/0};for(const a of t)i.x0=Math.min(i.x0,a.x-a.r),i.y0=Math.min(i.y0,a.y-a.r),i.x1=Math.max(i.x1,a.x+a.r),i.y1=Math.max(i.y1,a.y+a.r);this.userMoved=!0,this.cam.fit(i,60,700,1.8,this.topInset(),10),this.focus=new Set(t),this.dirty=!0,clearTimeout(this.flashTimer),this.flashTimer=window.setTimeout(()=>this.updateFocus(),1800),this.kick()}showEmpty(e,t){const i=this.q(".gx-empty");i.classList.toggle("gx-hide",!e),i.querySelector("b").textContent=e,i.querySelector("span").textContent=t}updateHud(){this.chrome.setBadge(this.filters.tags.size),this.chrome.refreshRegions()}updateFocus(){const e=this.dragging||this.hover||this.selected;if(e){const t=new Set([e]);this.nbr.get(e)?.forEach(i=>t.add(i)),this.focus=t}else this.focus=this.hits;this.dirty=!0,this.kick()}setHover(e,t=0,i=0){const a=this.q(".gx-tip");if(e&&!this.dragging){const s=this.nbr.get(e)?.size||0,o=e.kind==="folder"?`Folder · ${e.degree} item${e.degree===1?"":"s"}`:`${b(e.dir||"Vault root")} · ${s} connection${s===1?"":"s"}`;a.innerHTML=`<b>${b(e.label)}</b><span>${o}${e.pinned?" · pinned":""}</span>`,a.style.left=Math.min(t,this.cam.w-270)+"px",a.style.top=Math.min(i,this.cam.h-70)+"px",a.classList.remove("gx-hide")}else a.classList.add("gx-hide");e!==this.hover&&(this.hover=e,this.cv.classList.toggle("pointing",!!e),this.updateFocus())}local(e){const t=this.cv.getBoundingClientRect();return{x:e.clientX-t.left,y:e.clientY-t.top}}pick(e,t,i=!1){const a=this.cam.toWorld(e,t),s=(i?14:5)/this.cam.k;let o=null,r=1/0;for(let l=this.nodes.length-1;l>=0;l--){const c=this.nodes[l];if(c.dying||c.fade<.3)continue;const p=c.x-a.x,h=c.y-a.y,d=Math.sqrt(p*p+h*h),u=Math.max(c.r,3/this.cam.k)+s;d<u&&d-c.r<r&&(r=d-c.r,o=c)}return o}wireCanvas(){const e=this.cv;e.addEventListener("pointerdown",i=>{e.focus({preventScroll:!0});const a=this.local(i);try{e.setPointerCapture(i.pointerId)}catch{}if(this.pointers.set(i.pointerId,a),this.cam.stop(),this.userMoved=!0,this.pointers.size===2){this.dragging&&this.endDrag(),this.gesture=null;const[o,r]=Array.from(this.pointers.values());this.pinch={d0:Math.hypot(o.x-r.x,o.y-r.y)||1,k0:this.cam.k,mx:(o.x+r.x)/2,my:(o.y+r.y)/2};return}if(this.pointers.size>2)return;const s=i.pointerType!=="mouse";this.gesture={id:i.pointerId,sx:a.x,sy:a.y,lx:a.x,ly:a.y,lt:performance.now(),vx:0,vy:0,node:this.pick(a.x,a.y,s),moved:!1,touch:s}}),e.addEventListener("pointermove",i=>{const a=this.local(i);if(this.pointers.has(i.pointerId)&&this.pointers.set(i.pointerId,a),this.pinch&&this.pointers.size>=2){const[r,l]=Array.from(this.pointers.values()),c=Math.hypot(r.x-l.x,r.y-l.y)||1,p=(r.x+l.x)/2,h=(r.y+l.y)/2;this.cam.panBy(p-this.pinch.mx,h-this.pinch.my),this.cam.zoomAt(p,h,this.pinch.k0*(c/this.pinch.d0)/this.cam.k),this.pinch.mx=p,this.pinch.my=h,this.dirty=!0,this.kick();return}const s=this.gesture;if(!s||s.id!==i.pointerId){i.pointerType==="mouse"&&!this.pointers.size&&this.setHover(this.pick(a.x,a.y),a.x,a.y);return}if(!s.moved&&Math.hypot(a.x-s.sx,a.y-s.sy)>(s.touch?7:3)&&(s.moved=!0,s.node?this.startDrag(s.node):this.cv.classList.add("grabbing")),!s.moved)return;const o=performance.now();if(this.dragging){const r=this.cam.toWorld(a.x,a.y);this.dragging.fx=this.dragging.x=r.x,this.dragging.fy=this.dragging.y=r.y,this.sim.reheat(.25),this.edgePan(a.x,a.y)}else{const r=a.x-s.lx,l=a.y-s.ly;this.cam.panBy(r,l);const p=16/Math.max(1,o-s.lt);s.vx=s.vx*.6+r*p*.4,s.vy=s.vy*.6+l*p*.4,this.dirty=!0}s.lx=a.x,s.ly=a.y,s.lt=o,this.kick()});const t=i=>{if(this.pointers.delete(i.pointerId),this.pinch){this.pointers.size<2&&(this.pinch=null),this.gesture=null;return}const a=this.gesture;if(!(!a||a.id!==i.pointerId)){if(this.gesture=null,this.cv.classList.remove("grabbing"),this.dragging){this.endDrag();return}if(a.moved){i.type==="pointerup"&&performance.now()-a.lt<70&&(this.cam.vx=a.vx,this.cam.vy=a.vy,this.kick());return}i.type==="pointerup"&&this.tap(a.node)}};e.addEventListener("pointerup",t),e.addEventListener("pointercancel",t),e.addEventListener("pointerleave",i=>{i.pointerType==="mouse"&&!this.pointers.size&&this.setHover(null)}),e.addEventListener("wheel",i=>{i.preventDefault(),this.userMoved=!0;const a=this.local(i),s=i.deltaMode===1?16:i.deltaMode===2?400:1,o=i.deltaY*s;i.ctrlKey||Math.abs(i.deltaX)<1||i.deltaMode!==0||Math.abs(o)>=40?this.cam.zoomAt(a.x,a.y,Math.exp(-o*(i.ctrlKey?.012:.0018))):this.cam.panBy(-i.deltaX*s,-o),this.dirty=!0,this.kick()},{passive:!1}),e.addEventListener("dblclick",i=>i.preventDefault())}edgePan(e,t){const a=e<36?36-e:e>this.cam.w-36?this.cam.w-36-e:0,s=t<86?86-t:t>this.cam.h-36?this.cam.h-36-t:0;(a||s)&&this.cam.panBy(a*.15,s*.15)}startDrag(e){this.dragging=e,e.fx=e.x,e.fy=e.y,this.sim.alphaTarget=.28,this.sim.reheat(.3),this.cv.classList.add("grabbing"),this.q(".gx-tip").classList.add("gx-hide"),this.updateFocus()}endDrag(){const e=this.dragging;e&&(this.dragging=null,this.sim.alphaTarget=0,e.pinned?(e.fx=e.x,e.fy=e.y,this.layout.pins[e.id]=[Math.round(e.x*10)/10,Math.round(e.y*10)/10],Dw(this.layout)):(e.fx=null,e.fy=null),this.cv.classList.remove("grabbing"),this.updateFocus(),this.kick())}tap(e){const t=performance.now(),i=e&&this.lastTap.node===e&&t-this.lastTap.t<340;if(this.lastTap={node:e,t:i?0:t},i&&e){this.togglePin(e);return}e?this.select(e,!1):(this.closeCard(),this.chrome.closePanel())}togglePin(e){e.pinned=!e.pinned,e.pinned?(e.fx=e.x,e.fy=e.y,this.layout.pins[e.id]=[Math.round(e.x*10)/10,Math.round(e.y*10)/10]):(e.fx=null,e.fy=null,delete this.layout.pins[e.id],this.sim.reheat(.2)),Dw(this.layout),this.selected===e&&this.paintCard(e),this.dirty=!0,this.kick()}onKey(e){if(!this.active||this.root.offsetParent===null)return;const t=e.target;t&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable)||e.metaKey||e.ctrlKey||e.altKey||(e.key==="/"?(e.preventDefault(),this.chrome.focusSearch()):e.key==="Escape"?(this.closeCard(),this.chrome.closePanel()):e.key==="f"||e.key==="F"?this.fitAll():e.key==="1"?this.setMode("force"):e.key==="2"?this.setMode("radial"):e.key==="3"?this.setMode("clusters"):(e.key==="p"||e.key==="P")&&this.selected&&this.togglePin(this.selected))}select(e,t){if(this.selected=e,this.chrome.close(),this.paintCard(e),t){this.userMoved=!0;const i=Math.max(this.cam.k,1.1),a=this.cam.w<760?this.cam.h*.22:-Math.min(160,this.cam.w*.12);this.cam.animateTo(e.x+(this.cam.w<760?0:-a/i),e.y+(this.cam.w<760?a/i:0),i,600)}this.updateFocus()}closeCard(){this.card.close(),this.selected&&(this.selected=null,this.updateFocus())}groupDir(e){return this.nodes.find(t=>t.kind==="folder"&&t.group===e&&!t.dir)?.path??e}groupOf(e){return this.nodes.find(t=>t.dir===e||t.path===e)?.group??(e.split("/")[0]||e)}nodeAt(e){return this.nodes.find(t=>t.path===e&&!t.dying)}showFolderCard(e){const i=this.nodes.find(a=>a.kind==="folder"&&a.path===e)?.color||this.nodes.find(a=>a.dir===e)?.color||"#888";this.card.showFolder(e,i)}paintCard(e){e.kind==="note"?this.card.showNote(e.path,e.label,e.dir||"Root",e.color,this.model.tagsByPath.get(e.path)||e.tags):this.card.showFolder(e.path,e.color)}buildCard(){const e=t=>Array.from(t||[]).map(i=>this.model.all.get(i)).filter(i=>!!i&&!i.dying).sort((i,a)=>a.degree-i.degree).map(this.asLink);return new _g({root:this.root,focusNode:t=>{const i=this.nodeAt(t);i&&this.select(i,!0)},focusFolder:t=>this.focusGroup(this.groupOf(t)),onlyFolder:t=>{const i=this.groupOf(t);this.filters.hiddenGroups=new Set(this.model.groups().map(a=>a[0]).filter(a=>a!==i)),this.applyFilters()},pick:t=>{const i=this.nodeAt(t);i&&this.nbr.has(i)&&this.select(i,!0)},links:t=>{const i=this.nodeAt(t);if(!i)return{out:[],in:[]};const a=e(this.model.outgoing.get(i.id)),s=new Set(a.map(o=>o.path));return{out:a,in:e(this.model.incoming.get(i.id)).filter(o=>!s.has(o.path))}},folderItems:t=>this.nodes.filter(i=>i.kind==="note"&&!i.dying&&(i.dir||"Root")===(t||"Root")).sort((i,a)=>a.degree-i.degree).map(this.asLink),tag:t=>this.chrome.setQuery("#"+t+" "),extras:t=>{const i=this.nodeAt(t);return i?[{id:"pin",label:i.pinned?"Unpin (P): let it move again":"Pin (P): keep it where it is",icon:Yw("pin"),on:!!i.pinned,run:()=>this.togglePin(i)}]:[]},home:()=>{this.userMoved=!1,this.fitAll(700)},closed:()=>{this.selected&&(this.selected=null,this.updateFocus())}})}applyFilters(){this.rebuild(),this.sim.reheat(.5),this.updateHud(),this.renderPanel(),this.selected&&this.paintCard(this.selected),window.setTimeout(()=>this.fitAll(800),500),this.kick()}renderPanel(e){if(!e){this.chrome.renderPanel();return}const t=(r,l)=>`<button type="button" data-mode="${r}" class="${this.prefs.mode===r?"on":""}" title="${l} layout (${r==="force"?1:r==="radial"?2:3})">${Yw(r)}${l}</button>`,i=this.prefs.mode,a={force:"Force: linked nodes pull together and the rest push apart, so clusters form by themselves.",radial:"Radial: folders sit on rings around the vault, their notes fanned out beneath them.",clusters:"Clusters: each folder gathers into its own island."},s={force:"How hard nodes push each other apart in the Force layout.",radial:"How far apart the rings of the Radial layout are.",clusters:"How far apart the folder islands of the Clusters layout are."};e.innerHTML=`
3910
+ `}buildChrome(){return new wg({page:"graph",root:this.root,search:{placeholder:"Find a node, #tag or in:folder",find:{items:()=>this.nodes.filter(e=>e.kind!=="folder"&&!e.dying).map(e=>({id:e.path,name:e.label,folder:e.dir||"Root",region:e.group,color:e.color,tags:this.model.tagsByPath.get(e.path)||e.tags,degree:e.degree})),highlight:e=>{this.hits=e?new Set(this.nodes.filter(t=>e.has(t.path))):null,this.updateFocus()},pick:e=>{const t=this.nodes.find(i=>i.path===e.id&&i.kind!=="folder");t&&this.select(t,!0)},folder:e=>{this.focusGroup(e),this.showFolderCard(this.groupDir(e))}}},changed:()=>JSON.stringify(this.prefs)!==JSON.stringify(zw())||this.filters.hiddenGroups.size>0||this.filters.tags.size>0||!!this.hits||!!this.selected||!!this.card?.isOpen||this.userMoved,labels:{get:()=>({nodes:this.prefs.noteLabels,folders:this.prefs.folderLabels}),set:(e,t)=>{e==="nodes"?this.prefs.noteLabels=t:this.prefs.folderLabels=t,yc(this.prefs),this.dirty=!0,this.kick()},help:{nodes:"Names next to the nodes. The node under the pointer and its neighbours always show theirs.",folders:"Folder names: the hub of each folder and the title over each folder hull."}},filter:e=>this.renderPanel(e),reset:()=>{this.prefs=b4(),yc(this.prefs),this.filters.hiddenGroups=new Set,this.filters.tags=new Set,this.filters.folders=this.prefs.folders,this.filters.orphans=this.prefs.orphans,this.chrome.finder?.clear(),this.closeCard(),this.rebuild(),this.applyMode(!1),this.sim.reheat(.6),this.userMoved=!1,window.setTimeout(()=>this.fitAll(700),350),this.updateHud()},regions:{list:()=>this.model.groups().map(([e,t,i])=>({name:e,count:t,color:i,hidden:this.filters.hiddenGroups.has(e)})),toggle:e=>{this.filters.hiddenGroups.has(e)?this.filters.hiddenGroups.delete(e):this.filters.hiddenGroups.add(e),this.applyFilters()},setAll:e=>{this.filters.hiddenGroups=e?new Set(this.model.groups().map(t=>t[0])):new Set,this.applyFilters()},focus:e=>{this.focusGroup(e),this.showFolderCard(this.groupDir(e))}},nav:{zoom:e=>{this.userMoved=!0,this.cam.animateTo(this.cam.x,this.cam.y,this.cam.k*e,300),this.kick()},fit:()=>{this.userMoved=!0,this.fitAll()},nudge:(e,t)=>{this.userMoved=!0,this.cam.animateTo(this.cam.x+e*this.cam.w*.16/this.cam.k,this.cam.y+t*this.cam.h*.16/this.cam.k,this.cam.k,200),this.kick()},home:()=>{this.userMoved=!1,this.fitAll()}},minimap:(e,t,i,a)=>{const s=e.getContext("2d");s&&(this.miniMap=M4(s,t,i,a,this.nodes,this.cam,this.theme))},minimapNav:(e,t)=>{const i=this.mini.getBoundingClientRect();this.userMoved=!0,this.cam.stop(),this.cam.x=(e*i.width-this.miniMap.x0)/this.miniMap.s,this.cam.y=(t*i.height-this.miniMap.y0)/this.miniMap.s,this.dirty=!0,this.kick()},onPrefs:()=>{this.dirty=!0,this.kick()},onOverlay:()=>this.closeCard()})}focusGroup(e){const t=this.nodes.filter(a=>!a.dying&&a.group===e);if(!t.length)return;const i={x0:1/0,y0:1/0,x1:-1/0,y1:-1/0};for(const a of t)i.x0=Math.min(i.x0,a.x-a.r),i.y0=Math.min(i.y0,a.y-a.r),i.x1=Math.max(i.x1,a.x+a.r),i.y1=Math.max(i.y1,a.y+a.r);this.userMoved=!0,this.cam.fit(i,60,700,1.8,this.topInset(),10),this.focus=new Set(t),this.dirty=!0,clearTimeout(this.flashTimer),this.flashTimer=window.setTimeout(()=>this.updateFocus(),1800),this.kick()}showEmpty(e,t){const i=this.q(".gx-empty");i.classList.toggle("gx-hide",!e),i.querySelector("b").textContent=e,i.querySelector("span").textContent=t}updateHud(){this.chrome.setBadge(this.filters.tags.size),this.chrome.refreshRegions()}updateFocus(){const e=this.dragging||this.hover||this.selected;if(e){const t=new Set([e]);this.nbr.get(e)?.forEach(i=>t.add(i)),this.focus=t}else this.focus=this.hits;this.dirty=!0,this.kick()}setHover(e,t=0,i=0){const a=this.q(".gx-tip");if(e&&!this.dragging){const s=this.nbr.get(e)?.size||0,o=e.kind==="folder"?`Folder · ${e.degree} item${e.degree===1?"":"s"}`:`${b(e.dir||"Vault root")} · ${s} connection${s===1?"":"s"}`;a.innerHTML=`<b>${b(e.label)}</b><span>${o}${e.pinned?" · pinned":""}</span>`,a.style.left=Math.min(t,this.cam.w-270)+"px",a.style.top=Math.min(i,this.cam.h-70)+"px",a.classList.remove("gx-hide")}else a.classList.add("gx-hide");e!==this.hover&&(this.hover=e,this.cv.classList.toggle("pointing",!!e),this.updateFocus())}local(e){const t=this.cv.getBoundingClientRect();return{x:e.clientX-t.left,y:e.clientY-t.top}}pick(e,t,i=!1){const a=this.cam.toWorld(e,t),s=(i?14:5)/this.cam.k;let o=null,r=1/0;for(let l=this.nodes.length-1;l>=0;l--){const c=this.nodes[l];if(c.dying||c.fade<.3)continue;const p=c.x-a.x,h=c.y-a.y,d=Math.sqrt(p*p+h*h),u=Math.max(c.r,3/this.cam.k)+s;d<u&&d-c.r<r&&(r=d-c.r,o=c)}return o}wireCanvas(){const e=this.cv;e.addEventListener("pointerdown",i=>{e.focus({preventScroll:!0});const a=this.local(i);try{e.setPointerCapture(i.pointerId)}catch{}if(this.pointers.set(i.pointerId,a),this.cam.stop(),this.userMoved=!0,this.pointers.size===2){this.dragging&&this.endDrag(),this.gesture=null;const[o,r]=Array.from(this.pointers.values());this.pinch={d0:Math.hypot(o.x-r.x,o.y-r.y)||1,k0:this.cam.k,mx:(o.x+r.x)/2,my:(o.y+r.y)/2};return}if(this.pointers.size>2)return;const s=i.pointerType!=="mouse";this.gesture={id:i.pointerId,sx:a.x,sy:a.y,lx:a.x,ly:a.y,lt:performance.now(),vx:0,vy:0,node:this.pick(a.x,a.y,s),moved:!1,touch:s}}),e.addEventListener("pointermove",i=>{const a=this.local(i);if(this.pointers.has(i.pointerId)&&this.pointers.set(i.pointerId,a),this.pinch&&this.pointers.size>=2){const[r,l]=Array.from(this.pointers.values()),c=Math.hypot(r.x-l.x,r.y-l.y)||1,p=(r.x+l.x)/2,h=(r.y+l.y)/2;this.cam.panBy(p-this.pinch.mx,h-this.pinch.my),this.cam.zoomAt(p,h,this.pinch.k0*(c/this.pinch.d0)/this.cam.k),this.pinch.mx=p,this.pinch.my=h,this.dirty=!0,this.kick();return}const s=this.gesture;if(!s||s.id!==i.pointerId){i.pointerType==="mouse"&&!this.pointers.size&&this.setHover(this.pick(a.x,a.y),a.x,a.y);return}if(!s.moved&&Math.hypot(a.x-s.sx,a.y-s.sy)>(s.touch?7:3)&&(s.moved=!0,s.node?this.startDrag(s.node):this.cv.classList.add("grabbing")),!s.moved)return;const o=performance.now();if(this.dragging){const r=this.cam.toWorld(a.x,a.y);this.dragging.fx=this.dragging.x=r.x,this.dragging.fy=this.dragging.y=r.y,this.sim.reheat(.25),this.edgePan(a.x,a.y)}else{const r=a.x-s.lx,l=a.y-s.ly;this.cam.panBy(r,l);const p=16/Math.max(1,o-s.lt);s.vx=s.vx*.6+r*p*.4,s.vy=s.vy*.6+l*p*.4,this.dirty=!0}s.lx=a.x,s.ly=a.y,s.lt=o,this.kick()});const t=i=>{if(this.pointers.delete(i.pointerId),this.pinch){this.pointers.size<2&&(this.pinch=null),this.gesture=null;return}const a=this.gesture;if(!(!a||a.id!==i.pointerId)){if(this.gesture=null,this.cv.classList.remove("grabbing"),this.dragging){this.endDrag();return}if(a.moved){i.type==="pointerup"&&performance.now()-a.lt<70&&(this.cam.vx=a.vx,this.cam.vy=a.vy,this.kick());return}i.type==="pointerup"&&this.tap(a.node)}};e.addEventListener("pointerup",t),e.addEventListener("pointercancel",t),e.addEventListener("pointerleave",i=>{i.pointerType==="mouse"&&!this.pointers.size&&this.setHover(null)}),e.addEventListener("wheel",i=>{i.preventDefault(),this.userMoved=!0;const a=this.local(i),s=i.deltaMode===1?16:i.deltaMode===2?400:1,o=i.deltaY*s;i.ctrlKey||Math.abs(i.deltaX)<1||i.deltaMode!==0||Math.abs(o)>=40?this.cam.zoomAt(a.x,a.y,Math.exp(-o*(i.ctrlKey?.012:.0018))):this.cam.panBy(-i.deltaX*s,-o),this.dirty=!0,this.kick()},{passive:!1}),e.addEventListener("dblclick",i=>i.preventDefault())}edgePan(e,t){const a=e<36?36-e:e>this.cam.w-36?this.cam.w-36-e:0,s=t<86?86-t:t>this.cam.h-36?this.cam.h-36-t:0;(a||s)&&this.cam.panBy(a*.15,s*.15)}startDrag(e){this.dragging=e,e.fx=e.x,e.fy=e.y,this.sim.alphaTarget=.28,this.sim.reheat(.3),this.cv.classList.add("grabbing"),this.q(".gx-tip").classList.add("gx-hide"),this.updateFocus()}endDrag(){const e=this.dragging;e&&(this.dragging=null,this.sim.alphaTarget=0,e.pinned?(e.fx=e.x,e.fy=e.y,this.layout.pins[e.id]=[Math.round(e.x*10)/10,Math.round(e.y*10)/10],Dw(this.layout)):(e.fx=null,e.fy=null),this.cv.classList.remove("grabbing"),this.updateFocus(),this.kick())}tap(e){const t=performance.now(),i=e&&this.lastTap.node===e&&t-this.lastTap.t<340;if(this.lastTap={node:e,t:i?0:t},i&&e){this.togglePin(e);return}e?this.select(e,!1):(this.closeCard(),this.chrome.closePanel())}togglePin(e){e.pinned=!e.pinned,e.pinned?(e.fx=e.x,e.fy=e.y,this.layout.pins[e.id]=[Math.round(e.x*10)/10,Math.round(e.y*10)/10]):(e.fx=null,e.fy=null,delete this.layout.pins[e.id],this.sim.reheat(.2)),Dw(this.layout),this.selected===e&&this.paintCard(e),this.dirty=!0,this.kick()}onKey(e){if(!this.active||this.root.offsetParent===null)return;const t=e.target;t&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable)||e.metaKey||e.ctrlKey||e.altKey||(e.key==="/"?(e.preventDefault(),this.chrome.focusSearch()):e.key==="Escape"?(this.closeCard(),this.chrome.closePanel()):e.key==="f"||e.key==="F"?this.fitAll():e.key==="1"?this.setMode("force"):e.key==="2"?this.setMode("radial"):e.key==="3"?this.setMode("clusters"):(e.key==="p"||e.key==="P")&&this.selected&&this.togglePin(this.selected))}select(e,t){if(this.selected=e,this.chrome.close(),this.paintCard(e),t){this.userMoved=!0;const i=Math.max(this.cam.k,1.1),a=this.cam.w<760?this.cam.h*.22:-Math.min(160,this.cam.w*.12);this.cam.animateTo(e.x+(this.cam.w<760?0:-a/i),e.y+(this.cam.w<760?a/i:0),i,600)}this.updateFocus()}closeCard(){this.card.close(),this.selected&&(this.selected=null,this.updateFocus())}groupDir(e){return this.nodes.find(t=>t.kind==="folder"&&t.group===e&&!t.dir)?.path??e}groupOf(e){return this.nodes.find(t=>t.dir===e||t.path===e)?.group??(e.split("/")[0]||e)}nodeAt(e){return this.nodes.find(t=>t.path===e&&!t.dying)}showFolderCard(e){const i=this.nodes.find(a=>a.kind==="folder"&&a.path===e)?.color||this.nodes.find(a=>a.dir===e)?.color||"#888";this.card.showFolder(e,i)}paintCard(e){e.kind==="note"?this.card.showNote(e.path,e.label,e.dir||"Root",e.color,this.model.tagsByPath.get(e.path)||e.tags):this.card.showFolder(e.path,e.color)}buildCard(){const e=t=>Array.from(t||[]).map(i=>this.model.all.get(i)).filter(i=>!!i&&!i.dying).sort((i,a)=>a.degree-i.degree).map(this.asLink);return new _g({root:this.root,focusNode:t=>{const i=this.nodeAt(t);i&&this.select(i,!0)},focusFolder:t=>this.focusGroup(this.groupOf(t)),onlyFolder:t=>{const i=this.groupOf(t);this.filters.hiddenGroups=new Set(this.model.groups().map(a=>a[0]).filter(a=>a!==i)),this.applyFilters()},pick:t=>{const i=this.nodeAt(t);i&&this.nbr.has(i)&&this.select(i,!0)},links:t=>{const i=this.nodeAt(t);if(!i)return{out:[],in:[]};const a=e(this.model.outgoing.get(i.id)),s=new Set(a.map(o=>o.path));return{out:a,in:e(this.model.incoming.get(i.id)).filter(o=>!s.has(o.path))}},folderItems:t=>this.nodes.filter(i=>i.kind==="note"&&!i.dying&&(i.dir||"Root")===(t||"Root")).sort((i,a)=>a.degree-i.degree).map(this.asLink),tag:t=>this.chrome.setQuery("#"+t+" "),extras:t=>{const i=this.nodeAt(t);return i?[{id:"pin",label:i.pinned?"Unpin (P): let it move again":"Pin (P): keep it where it is",icon:Yw("pin"),on:!!i.pinned,run:()=>this.togglePin(i)}]:[]},home:()=>{this.userMoved=!1,this.fitAll(700)},closed:()=>{this.selected&&(this.selected=null,this.updateFocus())}})}applyFilters(){this.rebuild(),this.sim.reheat(.5),this.updateHud(),this.renderPanel(),this.selected&&this.paintCard(this.selected),window.setTimeout(()=>this.fitAll(800),500),this.kick()}renderPanel(e){if(!e){this.chrome.renderPanel();return}const t=(r,l)=>`<button type="button" data-mode="${r}" class="${this.prefs.mode===r?"on":""}" title="${l} layout (${r==="force"?1:r==="radial"?2:3})">${Yw(r)}${l}</button>`,i=this.prefs.mode,a={force:"Force: linked nodes pull together and the rest push apart, so clusters form by themselves.",radial:"Radial: folders sit on rings around the vault, their notes fanned out beneath them.",clusters:"Clusters: each folder gathers into its own island."},s={force:"How hard nodes push each other apart in the Force layout.",radial:"How far apart the rings of the Radial layout are.",clusters:"How far apart the folder islands of the Clusters layout are."};e.innerHTML=`
3911
3911
  <h4>Layout ${kg(a[i])}</h4>
3912
3912
  <div class="vc-seg" role="group" aria-label="Layout">${t("force","Force")}${t("radial","Radial")}${t("clusters","Clusters")}</div>
3913
- ${FR("spacing","Spacing",.4,2.5,.05,this.prefs.spacingBy[i],s[i])}
3913
+ ${F4("spacing","Spacing",.4,2.5,.05,this.prefs.spacingBy[i],s[i])}
3914
3914
  <h4>Graph</h4>
3915
3915
  ${Ia("folders","Folder hubs",this.prefs.folders,"A node for every folder, linked to the notes inside it.")}
3916
3916
  ${Ia("hulls","Folder hulls",this.prefs.hulls,"A soft shape around the notes of each folder (Force and Clusters).")}
3917
3917
  ${Ia("orphans","Nodes without links",this.prefs.orphans,"Notes that link nowhere and are linked from nowhere.")}
3918
3918
  ${this.filters.tags.size?`<button type="button" class="vc-act" data-clear>Clear tag filter (${this.filters.tags.size})</button>`:""}
3919
- <div class="vc-hint">Drag nodes · double-click to pin · / search · #tag finds tags · F fit · 1 2 3 layouts</div>`,e.querySelectorAll("[data-mode]").forEach(r=>{r.onclick=()=>{this.setMode(r.dataset.mode),this.chrome.renderPanel()}});const o=e.querySelector("[data-clear]");o&&(o.onclick=()=>{this.filters.tags.clear(),this.applyFilters()}),e.querySelectorAll("input[data-s]").forEach(r=>{r.oninput=()=>{const l=Number(r.value),c=this.prefs.mode;this.prefs.spacingBy[c]=l,c==="force"&&(this.prefs.spacing=l),this.sim.spacing=l,c!=="force"&&this.computeTargets(),this.sim.reheat(.4),yc(this.prefs),this.dirty=!0,this.kick()}}),e.querySelectorAll("[data-t]").forEach(r=>{r.onclick=()=>{const l=r.dataset.t;if(this.prefs[l]=!this.prefs[l],yc(this.prefs),l==="folders"||l==="orphans"){this.filters.folders=this.prefs.folders,this.filters.orphans=this.prefs.orphans,this.applyFilters();return}this.chrome.renderPanel(),this.dirty=!0,this.kick()}})}importCachedTags(){const e=$b();if(!e||!Array.isArray(e.tags))return;const t=new Map;for(const[i,a]of e.tags)for(const s of a){if(!s||!s.path)continue;const o=t.get(s.path)||[];o.push(i),t.set(s.path,o)}t.forEach((i,a)=>{this.model.tagsByPath.has(a)||this.model.tagsByPath.set(a,i)})}nodeForPath(e){const t=e.replace(/^\/+/,"");return this.model.byPath.get(t)||this.model.byPath.get(t+".md")||this.model.all.get(this.model.byName.get(t.replace(/\.md$/,"").split("/").pop()||"")||"")}onMutation(e){this.refreshSoon(300);const t=typeof e.actor=="string"?e.actor:"",i=[e.path,e.to,e.new_path].find(a=>typeof a=="string");t&&i&&e.type!=="node_deleted"&&window.setTimeout(()=>{const a=this.nodeForPath(i);a&&this.addPulse(a.id,t,!0)},450)}onActivity(e,t,i){const a=performance.now(),s=i.map(o=>this.nodeForPath(o)?.id).filter(o=>!!o);if(t==="end"){const o=s.length?s:Array.from(this.pulses.keys());for(const r of o)for(const l of this.pulses.get(r)||[])l.actor===e&&!l.end&&(l.end=a);if(!s.length)return;for(const r of s)(this.pulses.get(r)||[]).some(l=>l.actor===e)||this.addPulse(r,e,!0);return}for(const o of s)this.addPulse(o,e,!1)}addPulse(e,t,i){const a=performance.now(),s=(this.pulses.get(e)||[]).filter(o=>o.actor!==t);s.push({id:e,actor:t,color:zn(t||"agent"),start:a,end:i?a+1200:0}),this.pulses.set(e,s.slice(-3)),this.kick()}}let kr=null;async function jw(){const n=document.getElementById("view-graph");if(!n)return;if(!kr||!n.contains(kr.root)){kr?.suspend(),kr=new VR(n);const t=kr;Kd("graph",(i,a,s)=>{for(const o of s){const r=t.clientPoint(o);if(r)return r}return null})}const e=kr;D.graph.stop=()=>e.suspend(),e.show()}const Nt={q:"",sort:"count",sel:[]};async function WR(n,e){if(D.tags.built&&D.tags.index)return D.tags.index;const t=Mn(),i=new Map,a=t.map(c=>c.path+":"+c.mtime).join("|"),s=$b();if(s&&s.sig===a){const c=new Map;for(const[p,h]of s.tags)c.set(p,h);return D.tags.index=c,D.tags.built=!0,c}let o=0;const r=t.slice(),l=async()=>{for(;r.length;){const c=r.shift();try{const p=await tt("/api/note?path="+encodeURIComponent(c.path)),h=new Set([...p.tags||[],...Au(p.content)].map(d=>d.replace(/^#/,"")));for(const d of h)d&&(i.has(d)||i.set(d,[]),i.get(d).push({path:c.path,name:c.name,folder:c.folder,mtime:c.mtime}))}catch{}o++,D.tags.progress=Math.round(o/Math.max(1,t.length)*100),e(o,t.length)}};return await Promise.all([l(),l(),l(),l(),l(),l()]),D.tags.index=i,D.tags.built=!0,VS(a,Array.from(i.entries())),i}async function Zw(){it("tg-styles",XR);const n=U("#view-tags");D.tags.active&&(Nt.sel=[D.tags.active],D.tags.active=null),n.innerHTML=`<div class="tg">
3919
+ <div class="vc-hint">Drag nodes · double-click to pin · / search · #tag finds tags · F fit · 1 2 3 layouts</div>`,e.querySelectorAll("[data-mode]").forEach(r=>{r.onclick=()=>{this.setMode(r.dataset.mode),this.chrome.renderPanel()}});const o=e.querySelector("[data-clear]");o&&(o.onclick=()=>{this.filters.tags.clear(),this.applyFilters()}),e.querySelectorAll("input[data-s]").forEach(r=>{r.oninput=()=>{const l=Number(r.value),c=this.prefs.mode;this.prefs.spacingBy[c]=l,c==="force"&&(this.prefs.spacing=l),this.sim.spacing=l,c!=="force"&&this.computeTargets(),this.sim.reheat(.4),yc(this.prefs),this.dirty=!0,this.kick()}}),e.querySelectorAll("[data-t]").forEach(r=>{r.onclick=()=>{const l=r.dataset.t;if(this.prefs[l]=!this.prefs[l],yc(this.prefs),l==="folders"||l==="orphans"){this.filters.folders=this.prefs.folders,this.filters.orphans=this.prefs.orphans,this.applyFilters();return}this.chrome.renderPanel(),this.dirty=!0,this.kick()}})}importCachedTags(){const e=$b();if(!e||!Array.isArray(e.tags))return;const t=new Map;for(const[i,a]of e.tags)for(const s of a){if(!s||!s.path)continue;const o=t.get(s.path)||[];o.push(i),t.set(s.path,o)}t.forEach((i,a)=>{this.model.tagsByPath.has(a)||this.model.tagsByPath.set(a,i)})}nodeForPath(e){const t=e.replace(/^\/+/,"");return this.model.byPath.get(t)||this.model.byPath.get(t+".md")||this.model.all.get(this.model.byName.get(t.replace(/\.md$/,"").split("/").pop()||"")||"")}onMutation(e){this.refreshSoon(300);const t=typeof e.actor=="string"?e.actor:"",i=[e.path,e.to,e.new_path].find(a=>typeof a=="string");t&&i&&e.type!=="node_deleted"&&window.setTimeout(()=>{const a=this.nodeForPath(i);a&&this.addPulse(a.id,t,!0)},450)}onActivity(e,t,i){const a=performance.now(),s=i.map(o=>this.nodeForPath(o)?.id).filter(o=>!!o);if(t==="end"){const o=s.length?s:Array.from(this.pulses.keys());for(const r of o)for(const l of this.pulses.get(r)||[])l.actor===e&&!l.end&&(l.end=a);if(!s.length)return;for(const r of s)(this.pulses.get(r)||[]).some(l=>l.actor===e)||this.addPulse(r,e,!0);return}for(const o of s)this.addPulse(o,e,!1)}addPulse(e,t,i){const a=performance.now(),s=(this.pulses.get(e)||[]).filter(o=>o.actor!==t);s.push({id:e,actor:t,color:zn(t||"agent"),start:a,end:i?a+1200:0}),this.pulses.set(e,s.slice(-3)),this.kick()}}let kr=null;async function jw(){const n=document.getElementById("view-graph");if(!n)return;if(!kr||!n.contains(kr.root)){kr?.suspend(),kr=new V4(n);const t=kr;Kd("graph",(i,a,s)=>{for(const o of s){const r=t.clientPoint(o);if(r)return r}return null})}const e=kr;D.graph.stop=()=>e.suspend(),e.show()}const Nt={q:"",sort:"count",sel:[]};async function W4(n,e){if(D.tags.built&&D.tags.index)return D.tags.index;const t=Mn(),i=new Map,a=t.map(c=>c.path+":"+c.mtime).join("|"),s=$b();if(s&&s.sig===a){const c=new Map;for(const[p,h]of s.tags)c.set(p,h);return D.tags.index=c,D.tags.built=!0,c}let o=0;const r=t.slice(),l=async()=>{for(;r.length;){const c=r.shift();try{const p=await tt("/api/note?path="+encodeURIComponent(c.path)),h=new Set([...p.tags||[],...Au(p.content)].map(d=>d.replace(/^#/,"")));for(const d of h)d&&(i.has(d)||i.set(d,[]),i.get(d).push({path:c.path,name:c.name,folder:c.folder,mtime:c.mtime}))}catch{}o++,D.tags.progress=Math.round(o/Math.max(1,t.length)*100),e(o,t.length)}};return await Promise.all([l(),l(),l(),l(),l(),l()]),D.tags.index=i,D.tags.built=!0,VS(a,Array.from(i.entries())),i}async function Zw(){it("tg-styles",X4);const n=U("#view-tags");D.tags.active&&(Nt.sel=[D.tags.active],D.tags.active=null),n.innerHTML=`<div class="tg">
3920
3920
  <header class="tg-head">
3921
3921
  <div><h1 class="page-title">Tags</h1><p class="page-sub" id="tgSub">Reading nodes…</p></div>
3922
3922
  <span style="flex:1"></span>
@@ -3932,7 +3932,7 @@ ${this.filters.tags.size?`<button type="button" class="vc-act" data-clear>Clear
3932
3932
  <div class="tg-body">
3933
3933
  <section class="tg-cloud-wrap" aria-label="All tags"><div id="tgCloud" class="tg-cloud"><div class="empty">Building the tag index…</div></div></section>
3934
3934
  <section class="tg-results" id="tgRes" aria-live="polite"></section>
3935
- </div></div>`,n.querySelector("#tgRebuild").onclick=()=>{Lu(),D.tags.built=!1,D.tags.index=null,Zw()};let e=null;n.querySelectorAll(".tg-seg button").forEach(r=>{r.onclick=()=>{Nt.sort=r.dataset.s==="name"?"name":"count",n.querySelectorAll(".tg-seg button").forEach(l=>{l.classList.toggle("on",l===r),l.setAttribute("aria-pressed",String(l===r))}),e&&yo(e)}});const t=n.querySelector("#tgProg i"),i=n.querySelector("#tgSub"),a=await WR(!1,(r,l)=>{t.style.width=Math.round(r/Math.max(1,l)*100)+"%",i.textContent=`Reading nodes… ${r}/${l}`});if(!n.contains(t))return;e=a,t.style.width="100%",setTimeout(()=>n.querySelector("#tgProg")?.classList.add("done"),300);const s=new Set;a.forEach(r=>r.forEach(l=>s.add(l.path))),i.textContent=`${a.size} tags across ${s.size} nodes`;const o=n.querySelector("#tgQ");o.oninput=()=>{Nt.q=o.value,yo(a)},Nt.sel=Nt.sel.filter(r=>a.has(r)),yo(a),Mc(a)}function yo(n){const e=U("#tgCloud"),t=Nt.q.trim().toLowerCase().replace(/^#/,""),i=Array.from(n.entries()).filter(([s,o])=>o.length&&(!t||s.toLowerCase().includes(t))).sort((s,o)=>Nt.sort==="name"?s[0].localeCompare(o[0]):o[1].length-s[1].length||s[0].localeCompare(o[0]));if(!n.size){e.innerHTML='<div class="empty">This vault has no tags yet. Add <code>#tags</code> or a <code>tags:</code> line to a node.</div>';return}if(!i.length){e.innerHTML=`<div class="empty">No tag matches "${b(Nt.q)}".</div>`;return}const a=Math.max(...i.map(([,s])=>s.length));e.innerHTML=i.map(([s,o])=>{const r=a>1?Math.log(o.length)/Math.log(a):0,l=Nt.sel.includes(s);return`<button class="tg-tag${l?" on":""}" data-tag="${O(s)}" aria-pressed="${l}" style="--tc:${zn(s)};--w:${r.toFixed(2)}"><span>#${b(s)}</span><em>${o.length}</em></button>`}).join(""),e.querySelectorAll(".tg-tag").forEach(s=>{s.onclick=o=>{const r=s.dataset.tag||"";o.shiftKey||o.metaKey||o.ctrlKey?Nt.sel=Nt.sel.includes(r)?Nt.sel.filter(l=>l!==r):[...Nt.sel,r]:Nt.sel=Nt.sel.length===1&&Nt.sel[0]===r?[]:[r],yo(n),Mc(n)}})}function Mc(n){const e=U("#tgRes");if(!Nt.sel.length){const r=Array.from(n.entries()).sort((l,c)=>c[1].length-l[1].length).slice(0,6);e.innerHTML=`<div class="tg-hint"><h2>Pick a tag</h2><p>Click a tag to see its nodes. <kbd>Shift</kbd>+click adds more tags: nodes must carry all of them.</p>${r.length?`<div class="tg-top">${r.map(([l,c])=>`<button class="tg-card" data-tag="${O(l)}" style="--tc:${zn(l)}"><b>#${b(l)}</b><span>${c.length} nodes</span><small>${b(c.slice(0,3).map(p=>p.name).join(", "))}</small></button>`).join("")}</div>`:""}</div>`,e.querySelectorAll(".tg-card").forEach(l=>{l.onclick=()=>{Nt.sel=[l.dataset.tag||""],yo(n),Mc(n)}});return}const t=Nt.sel.map(r=>n.get(r)||[]);let i=t[0].slice();for(const r of t.slice(1)){const l=new Set(r.map(c=>c.path));i=i.filter(c=>l.has(c.path))}i.sort((r,l)=>(l.mtime||0)-(r.mtime||0));const a=new Map;n.forEach((r,l)=>r.forEach(c=>a.set(c.path,[...a.get(c.path)||[],l])));const s=new Map;for(const r of i)for(const l of a.get(r.path)||[])Nt.sel.includes(l)||s.set(l,(s.get(l)||0)+1);const o=Array.from(s.entries()).sort((r,l)=>l[1]-r[1]).slice(0,12);e.innerHTML=`<div class="tg-res-head">
3935
+ </div></div>`,n.querySelector("#tgRebuild").onclick=()=>{Lu(),D.tags.built=!1,D.tags.index=null,Zw()};let e=null;n.querySelectorAll(".tg-seg button").forEach(r=>{r.onclick=()=>{Nt.sort=r.dataset.s==="name"?"name":"count",n.querySelectorAll(".tg-seg button").forEach(l=>{l.classList.toggle("on",l===r),l.setAttribute("aria-pressed",String(l===r))}),e&&yo(e)}});const t=n.querySelector("#tgProg i"),i=n.querySelector("#tgSub"),a=await W4(!1,(r,l)=>{t.style.width=Math.round(r/Math.max(1,l)*100)+"%",i.textContent=`Reading nodes… ${r}/${l}`});if(!n.contains(t))return;e=a,t.style.width="100%",setTimeout(()=>n.querySelector("#tgProg")?.classList.add("done"),300);const s=new Set;a.forEach(r=>r.forEach(l=>s.add(l.path))),i.textContent=`${a.size} tags across ${s.size} nodes`;const o=n.querySelector("#tgQ");o.oninput=()=>{Nt.q=o.value,yo(a)},Nt.sel=Nt.sel.filter(r=>a.has(r)),yo(a),Mc(a)}function yo(n){const e=U("#tgCloud"),t=Nt.q.trim().toLowerCase().replace(/^#/,""),i=Array.from(n.entries()).filter(([s,o])=>o.length&&(!t||s.toLowerCase().includes(t))).sort((s,o)=>Nt.sort==="name"?s[0].localeCompare(o[0]):o[1].length-s[1].length||s[0].localeCompare(o[0]));if(!n.size){e.innerHTML='<div class="empty">This vault has no tags yet. Add <code>#tags</code> or a <code>tags:</code> line to a node.</div>';return}if(!i.length){e.innerHTML=`<div class="empty">No tag matches "${b(Nt.q)}".</div>`;return}const a=Math.max(...i.map(([,s])=>s.length));e.innerHTML=i.map(([s,o])=>{const r=a>1?Math.log(o.length)/Math.log(a):0,l=Nt.sel.includes(s);return`<button class="tg-tag${l?" on":""}" data-tag="${O(s)}" aria-pressed="${l}" style="--tc:${zn(s)};--w:${r.toFixed(2)}"><span>#${b(s)}</span><em>${o.length}</em></button>`}).join(""),e.querySelectorAll(".tg-tag").forEach(s=>{s.onclick=o=>{const r=s.dataset.tag||"";o.shiftKey||o.metaKey||o.ctrlKey?Nt.sel=Nt.sel.includes(r)?Nt.sel.filter(l=>l!==r):[...Nt.sel,r]:Nt.sel=Nt.sel.length===1&&Nt.sel[0]===r?[]:[r],yo(n),Mc(n)}})}function Mc(n){const e=U("#tgRes");if(!Nt.sel.length){const r=Array.from(n.entries()).sort((l,c)=>c[1].length-l[1].length).slice(0,6);e.innerHTML=`<div class="tg-hint"><h2>Pick a tag</h2><p>Click a tag to see its nodes. <kbd>Shift</kbd>+click adds more tags: nodes must carry all of them.</p>${r.length?`<div class="tg-top">${r.map(([l,c])=>`<button class="tg-card" data-tag="${O(l)}" style="--tc:${zn(l)}"><b>#${b(l)}</b><span>${c.length} nodes</span><small>${b(c.slice(0,3).map(p=>p.name).join(", "))}</small></button>`).join("")}</div>`:""}</div>`,e.querySelectorAll(".tg-card").forEach(l=>{l.onclick=()=>{Nt.sel=[l.dataset.tag||""],yo(n),Mc(n)}});return}const t=Nt.sel.map(r=>n.get(r)||[]);let i=t[0].slice();for(const r of t.slice(1)){const l=new Set(r.map(c=>c.path));i=i.filter(c=>l.has(c.path))}i.sort((r,l)=>(l.mtime||0)-(r.mtime||0));const a=new Map;n.forEach((r,l)=>r.forEach(c=>a.set(c.path,[...a.get(c.path)||[],l])));const s=new Map;for(const r of i)for(const l of a.get(r.path)||[])Nt.sel.includes(l)||s.set(l,(s.get(l)||0)+1);const o=Array.from(s.entries()).sort((r,l)=>l[1]-r[1]).slice(0,12);e.innerHTML=`<div class="tg-res-head">
3936
3936
  <div class="tg-sel">${Nt.sel.map(r=>`<span class="tg-pill" style="--tc:${zn(r)}">#${b(r)}<button data-rm="${O(r)}" aria-label="Remove ${O(r)}">✕</button></span>`).join('<span class="tg-and">and</span>')}</div>
3937
3937
  <span class="tg-count">${i.length} node${i.length===1?"":"s"}</span>
3938
3938
  </div>
@@ -3941,7 +3941,7 @@ ${this.filters.tags.size?`<button type="button" class="vc-act" data-clear>Clear
3941
3941
  <div class="tg-note-main"><b>${b(r.name)}</b><small>${b(r.folder||xb(r.path))} · ${b(si(r.mtime))}</small>
3942
3942
  <div class="tg-note-tags">${(a.get(r.path)||[]).filter(l=>!Nt.sel.includes(l)).slice(0,6).map(l=>`<span style="--tc:${zn(l)}">#${b(l)}</span>`).join("")}</div></div>
3943
3943
  <button class="btn sm ghost" data-peek="${O(r.path)}" title="Preview without leaving Tags">Preview</button>
3944
- </div>`).join("")||'<div class="empty">No node carries all of these tags.</div>'}</div>`,e.querySelectorAll("[data-rm]").forEach(r=>{r.onclick=()=>{Nt.sel=Nt.sel.filter(l=>l!==r.dataset.rm),yo(n),Mc(n)}}),e.querySelectorAll("[data-add]").forEach(r=>{r.onclick=()=>{Nt.sel=[...Nt.sel,r.dataset.add||""],yo(n),Mc(n)}}),e.querySelectorAll(".tg-note").forEach(r=>{const l=()=>he.openNote(r.dataset.path||"");r.onclick=c=>{c.target.closest("[data-peek]")||l()},r.onkeydown=c=>{c.target===r&&(c.key==="Enter"&&l(),c.key===" "&&(c.preventDefault(),Ju(r.dataset.path||"")))}}),e.querySelectorAll("[data-peek]").forEach(r=>{r.onclick=l=>{l.stopPropagation(),Ju(r.dataset.peek||"")}})}const XR=`
3944
+ </div>`).join("")||'<div class="empty">No node carries all of these tags.</div>'}</div>`,e.querySelectorAll("[data-rm]").forEach(r=>{r.onclick=()=>{Nt.sel=Nt.sel.filter(l=>l!==r.dataset.rm),yo(n),Mc(n)}}),e.querySelectorAll("[data-add]").forEach(r=>{r.onclick=()=>{Nt.sel=[...Nt.sel,r.dataset.add||""],yo(n),Mc(n)}}),e.querySelectorAll(".tg-note").forEach(r=>{const l=()=>he.openNote(r.dataset.path||"");r.onclick=c=>{c.target.closest("[data-peek]")||l()},r.onkeydown=c=>{c.target===r&&(c.key==="Enter"&&l(),c.key===" "&&(c.preventDefault(),Ju(r.dataset.path||"")))}}),e.querySelectorAll("[data-peek]").forEach(r=>{r.onclick=l=>{l.stopPropagation(),Ju(r.dataset.peek||"")}})}const X4=`
3945
3945
  .tg{max-width:1280px;margin:0 auto}
3946
3946
  .tg-head{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:12px}
3947
3947
  .tg-search{display:flex;align-items:center;gap:7px;height:34px;padding:0 10px;border:1px solid var(--line);border-radius:10px;
@@ -4006,7 +4006,7 @@ ${this.filters.tags.size?`<button type="button" class="vc-act" data-clear>Clear
4006
4006
  .tg-cloud-wrap{position:static;max-height:none}
4007
4007
  .tg-search{flex:1 1 100%;order:3}
4008
4008
  }
4009
- `,KR=`
4009
+ `,K4=`
4010
4010
  ::view-transition-group(root),::view-transition-group(ad-card),::view-transition-group(ad-av),::view-transition-group(ad-nm){
4011
4011
  animation-duration:.42s;animation-timing-function:cubic-bezier(.2,.8,.2,1)}
4012
4012
  ::view-transition-group(ad-card){overflow:clip;border-radius:var(--r-lg,16px)}
@@ -4017,7 +4017,7 @@ ${this.filters.tags.size?`<button type="button" class="vc-act" data-clear>Clear
4017
4017
  @media (prefers-reduced-motion:reduce){
4018
4018
  ::view-transition-group(*),::view-transition-old(*),::view-transition-new(*){animation:none!important}
4019
4019
  }
4020
- `,YR=[["[data-vt-card]","ad-card"],["[data-vt-av]","ad-av"],["[data-vt-nm]","ad-nm"]];function Xp(n,e){if(n)for(const[t,i]of YR){const a=n.matches(t)?n:n.querySelector(t);a&&(a.style.viewTransitionName=e?i:"")}}function jR(){return window.matchMedia("(prefers-reduced-motion: reduce)").matches}let Ac=null;async function Jw(n){if(it("ad-vt-css",KR),Ac?.skipTransition(),Ac=null,jR()||document.visibilityState==="hidden"){n.update();return}if(typeof document.startViewTransition=="function"){Xp(n.from,!0);let l=null;const c=document.startViewTransition(()=>{Xp(n.from,!1),n.update(),l=n.to(),Xp(l,!0)});Ac=c;try{await c.finished}catch{}Xp(l,!1),Ac===c&&(Ac=null);return}const e=n.from?.getBoundingClientRect()||null;n.update();const i=n.to()?.getBoundingClientRect()||null;if(n.reveal()?.animate([{opacity:0,transform:"translateY(6px)"},{opacity:1,transform:"none"}],{duration:300,delay:90,easing:"cubic-bezier(.2,.8,.2,1)",fill:"backwards"}),!e||!i)return;const s=document.createElement("div");s.className="ad-zoom",Object.assign(s.style,{left:"0",top:"0",width:e.width+"px",height:e.height+"px"}),document.body.append(s);const o=l=>`translate(${l.left}px,${l.top}px)`;await s.animate([{transform:o(e),width:e.width+"px",height:e.height+"px",opacity:1},{transform:o(i),width:i.width+"px",height:i.height+"px",opacity:0}],{duration:380,easing:"cubic-bezier(.2,.8,.2,1)",fill:"forwards"}).finished.catch(()=>{}),s.remove()}const ZR=`
4020
+ `,Y4=[["[data-vt-card]","ad-card"],["[data-vt-av]","ad-av"],["[data-vt-nm]","ad-nm"]];function Xp(n,e){if(n)for(const[t,i]of Y4){const a=n.matches(t)?n:n.querySelector(t);a&&(a.style.viewTransitionName=e?i:"")}}function j4(){return window.matchMedia("(prefers-reduced-motion: reduce)").matches}let Ac=null;async function Jw(n){if(it("ad-vt-css",K4),Ac?.skipTransition(),Ac=null,j4()||document.visibilityState==="hidden"){n.update();return}if(typeof document.startViewTransition=="function"){Xp(n.from,!0);let l=null;const c=document.startViewTransition(()=>{Xp(n.from,!1),n.update(),l=n.to(),Xp(l,!0)});Ac=c;try{await c.finished}catch{}Xp(l,!1),Ac===c&&(Ac=null);return}const e=n.from?.getBoundingClientRect()||null;n.update();const i=n.to()?.getBoundingClientRect()||null;if(n.reveal()?.animate([{opacity:0,transform:"translateY(6px)"},{opacity:1,transform:"none"}],{duration:300,delay:90,easing:"cubic-bezier(.2,.8,.2,1)",fill:"backwards"}),!e||!i)return;const s=document.createElement("div");s.className="ad-zoom",Object.assign(s.style,{left:"0",top:"0",width:e.width+"px",height:e.height+"px"}),document.body.append(s);const o=l=>`translate(${l.left}px,${l.top}px)`;await s.animate([{transform:o(e),width:e.width+"px",height:e.height+"px",opacity:1},{transform:o(i),width:i.width+"px",height:i.height+"px",opacity:0}],{duration:380,easing:"cubic-bezier(.2,.8,.2,1)",fill:"forwards"}).finished.catch(()=>{}),s.remove()}const Z4=`
4021
4021
  .ax{--ax-stick:64px;--ax-gut:28px}
4022
4022
  /* sticky search bar: solid page colour, full bleed over the view padding */
4023
4023
  .ax-sbar{position:sticky;top:calc(-1 * var(--ax-pt,24px));z-index:6;margin:0;padding:10px 0;background:transparent;
@@ -4268,7 +4268,7 @@ ${this.filters.tags.size?`<button type="button" class="vc-act" data-clear>Clear
4268
4268
  @media (prefers-reduced-motion:reduce){
4269
4269
  .ax-ag,.ax-go,.ax-tgl i,.ax-tgl i::after{transition:none}
4270
4270
  }
4271
- `,Ss=120,Mg=800;let ea=[],_r=[],ta="list",Qw=0,Ag=!0;yl(n=>{n!=="logs"&&(Ag=!0)});function JR(){const n=/^\/activity\/([A-Za-z0-9_-]{1,64})\/?$/.exec(location.pathname);return n?n[1]:null}let Ms=[];const Kp=new Set;let $a=D3(),As=Ss,Yp=Mg,e2=!1,jp=!0,Pi=!0,Zp=!0,Tg=0,Eg=!1,Jp=null;function Ts(){return U("#view-logs")}function Tc(){return L3(ea)}function t2(n){return N3(ea,n.filter(e=>Ra(e,"agents")),_r)}function n2(){return!!(ue.q||ue.cats.size||ue.actions.size||ue.srcs.size||ue.agents.size||ue.status.size)}async function i2(){_a(),Wd(),it("cc-logs-css",ZR);const n=Ts();if(!n.classList)return;uM();const e=!Ag;Ag=!1;try{const i=sessionStorage.getItem("memora.activity.agent");i&&(sessionStorage.removeItem("memora.activity.agent"),ue.agents=new Set([i]),$a="day",o2())}catch{}n.querySelector("#axRoot")||(n.innerHTML='<div id="axRoot"></div><div id="adRoot" hidden></div>',ta="list",document.addEventListener("keydown",i=>{if(i.key!=="/"||i.metaKey||i.ctrlKey||i.altKey||n.classList.contains("hidden")||i.target.closest("input,textarea,select,[contenteditable=true],.cc-drawer,.modal"))return;if(i.preventDefault(),ta==="agent"){mC();return}const s=document.getElementById("axQ");s?.focus(),s?.select()})),a4(n);const t=JR();t?await a2(t,e):await s2(e)}function QR(n){try{history.pushState({page:"logs",adFrom:"list"},"","/activity/"+encodeURIComponent(n))}catch{}a2(n,!0)}function e4(){if(history.state?.adFrom==="list"){history.back();return}try{history.pushState({page:"logs"},"","/activity")}catch{}s2(!0)}async function a2(n,e){const t=Ts(),i=U("#axRoot"),a=U("#adRoot"),s={keys:_r,items:ea,time:{time:ue.time,from:ue.from,to:ue.to},back:e4};if(ta==="agent"&&!a.hidden&&Z1()===n){J1(a,t,n,s);return}const o=ta==="list"&&!i.hidden&&!!i.querySelector("#axBody");o&&(Qw=t.scrollTop),ta="agent";const r=()=>{i.hidden=!0,a.hidden=!1,J1(a,t,n,s),t.scrollTop=0};if(e&&o){const l=i.querySelector(`#axBody [data-go="${window.CSS.escape(n)}"]`);await Jw({from:l,to:j1,update:r,reveal:()=>a})}else r()}async function s2(n){const e=Ts(),t=U("#axRoot"),i=U("#adRoot"),a=ta==="agent"&&!i.hidden,s=a?j1():null,o=a?Z1():"";ta==="agent"&&gC(),ta="list";const r=!t.querySelector("#axBody");r?t4(t):qn(!1);const l=()=>{i.hidden=!0,t.hidden=!1,a&&(e.scrollTop=Qw),md()};n&&a?await Jw({from:s,to:()=>o?t.querySelector(`#axBody [data-go="${window.CSS.escape(o)}"]`):null,update:l,reveal:()=>t}):l(),r?await Es():Pi&&Rg()}function t4(n){const e=Ts();n.innerHTML=`<div class="cc ax">
4271
+ `,Ss=120,Mg=800;let ea=[],_r=[],ta="list",Qw=0,Ag=!0;yl(n=>{n!=="logs"&&(Ag=!0)});function J4(){const n=/^\/activity\/([A-Za-z0-9_-]{1,64})\/?$/.exec(location.pathname);return n?n[1]:null}let Ms=[];const Kp=new Set;let $a=D3(),As=Ss,Yp=Mg,e2=!1,jp=!0,Pi=!0,Zp=!0,Tg=0,Eg=!1,Jp=null;function Ts(){return U("#view-logs")}function Tc(){return L3(ea)}function t2(n){return N3(ea,n.filter(e=>Ra(e,"agents")),_r)}function n2(){return!!(ue.q||ue.cats.size||ue.actions.size||ue.srcs.size||ue.agents.size||ue.status.size)}async function i2(){_a(),Wd(),it("cc-logs-css",Z4);const n=Ts();if(!n.classList)return;uM();const e=!Ag;Ag=!1;try{const i=sessionStorage.getItem("memora.activity.agent");i&&(sessionStorage.removeItem("memora.activity.agent"),ue.agents=new Set([i]),$a="day",o2())}catch{}n.querySelector("#axRoot")||(n.innerHTML='<div id="axRoot"></div><div id="adRoot" hidden></div>',ta="list",document.addEventListener("keydown",i=>{if(i.key!=="/"||i.metaKey||i.ctrlKey||i.altKey||n.classList.contains("hidden")||i.target.closest("input,textarea,select,[contenteditable=true],.cc-drawer,.modal"))return;if(i.preventDefault(),ta==="agent"){mC();return}const s=document.getElementById("axQ");s?.focus(),s?.select()})),aR(n);const t=J4();t?await a2(t,e):await s2(e)}function Q4(n){try{history.pushState({page:"logs",adFrom:"list"},"","/activity/"+encodeURIComponent(n))}catch{}a2(n,!0)}function eR(){if(history.state?.adFrom==="list"){history.back();return}try{history.pushState({page:"logs"},"","/activity")}catch{}s2(!0)}async function a2(n,e){const t=Ts(),i=U("#axRoot"),a=U("#adRoot"),s={keys:_r,items:ea,time:{time:ue.time,from:ue.from,to:ue.to},back:eR};if(ta==="agent"&&!a.hidden&&Z1()===n){J1(a,t,n,s);return}const o=ta==="list"&&!i.hidden&&!!i.querySelector("#axBody");o&&(Qw=t.scrollTop),ta="agent";const r=()=>{i.hidden=!0,a.hidden=!1,J1(a,t,n,s),t.scrollTop=0};if(e&&o){const l=i.querySelector(`#axBody [data-go="${window.CSS.escape(n)}"]`);await Jw({from:l,to:j1,update:r,reveal:()=>a})}else r()}async function s2(n){const e=Ts(),t=U("#axRoot"),i=U("#adRoot"),a=ta==="agent"&&!i.hidden,s=a?j1():null,o=a?Z1():"";ta==="agent"&&gC(),ta="list";const r=!t.querySelector("#axBody");r?tR(t):qn(!1);const l=()=>{i.hidden=!0,t.hidden=!1,a&&(e.scrollTop=Qw),md()};n&&a?await Jw({from:s,to:()=>o?t.querySelector(`#axBody [data-go="${window.CSS.escape(o)}"]`):null,update:l,reveal:()=>t}):l(),r?await Es():Pi&&Rg()}function tR(n){const e=Ts();n.innerHTML=`<div class="cc ax">
4272
4272
  ${zl("logs","Activity","Every read, write, search and sign-in in this brain, newest first.",`<button type="button" class="lg-live" id="lgLive" aria-pressed="${Pi}"></button>
4273
4273
  <button type="button" class="btn" id="axExport" aria-haspopup="menu">${pe.download}Export</button>
4274
4274
  <button type="button" class="cc-ibtn" id="axReload" aria-label="Reload" title="Reload">${pe.refresh}</button>`)}
@@ -4282,11 +4282,11 @@ ${this.filters.tags.size?`<button type="button" class="vc-act" data-clear>Clear
4282
4282
  </div></div>
4283
4283
  <div class="ax-sub"><div class="ax-chips" id="axChips" aria-label="Active filters"></div><div class="ax-sum" id="axSum" aria-live="polite"></div></div>
4284
4284
  <div class="ax-body" id="axBody">${Um($a)}</div>
4285
- </div>`,n4(e),Qp()}function n4(n){const e=U("#axQ"),t=U("#axQx"),i=()=>{t.hidden=!e.value,U("#axQWrap").classList.toggle("has",!!e.value)};i();const a=ol(()=>{ue.q=e.value.trim(),As=Ss,qn(!1)},140);e.oninput=()=>{i(),a()},e.onkeydown=p=>{p.key==="Escape"&&e.value&&(p.stopPropagation(),e.value="",i(),ue.q="",qn(!1))},t.onclick=()=>{e.value="",i(),ue.q="",qn(!1),e.focus()},U("#axFilt").onclick=()=>J3({scoped:Tc,agents:()=>t2(Tc()),changed:p=>{As=Ss,p==="time"?(Yp=Mg,Es()):qn(!1)}}),U("#axViews").onclick=p=>{const h=p.target.closest("[data-view]");h&&Cg(h.dataset.view)},U("#axChips").onclick=p=>{const h=p.target;if(h.closest("[data-open]"))return U("#axFilt").click();if(h.closest("[data-clear]")){const u=ue.time!=="7d";Om(),ue.q="",e.value="",i(),As=Ss,u?Es():qn(!1);return}const d=h.closest("[data-rm]");d&&i4(d.dataset.rm)},U("#axSum").onclick=p=>{p.target.closest("#axCompact")&&(jp=!jp,qn(!1))};const s=U("#axBody");ar(s,p=>ea.find(h=>h.id===p),r2),s.addEventListener("click",p=>{const h=p.target,d=f=>h.closest(f);let u;if(d("[data-more]"))As+=Ss,qn(!0);else if(d("[data-older]"))Yp+=Mg,Es(!0);else if(u=d("a[data-go]")){const f=p;if(f.metaKey||f.ctrlKey||f.shiftKey||f.button!==0)return;p.preventDefault(),QR(u.dataset.go)}else if(u=d("[data-only]"))r2(u.dataset.only);else if(u=d("[data-f]")){const[f,...v]=u.dataset.f.split(":"),g=v.join(":");f==="cats"?ue.cats=new Set([g]):f==="actions"?ue.actions=new Set([g]):f==="agents"?ue.agents=new Set([g]):f==="srcs"&&(ue.srcs=new Set([g])),Cg("day")}else(u=d("[data-time]"))?(ue.time="all",ue.from=ue.to="",Es()):d("[data-clear]")&&(Om(!0),ue.q="",e.value="",i(),qn(!1))}),U("#axReload").onclick=()=>{_r=[],Es()},U("#lgLive").onclick=()=>{Pi=!Pi,Pi&&(c2(),Rg()),Qp()},U("#axExport").onclick=p=>so(p.currentTarget,[{label:"Export shown as JSON",icon:pe.download,run:()=>Np(Tc().filter(h=>Ra(h)),"json")},{label:"Export shown as CSV",icon:pe.download,run:()=>Np(Tc().filter(h=>Ra(h)),"csv")}]);const o=U("#axBar"),r=n.querySelector(".ax"),l=()=>{const p=parseFloat(getComputedStyle(n).paddingTop)||0;r.style.setProperty("--ax-pt",p+"px"),r.style.setProperty("--ax-stick",o.offsetHeight-p+"px")};l(),new ResizeObserver(l).observe(o);const c=()=>{if(ta!=="list")return;const h=n.scrollTop>0&&o.getBoundingClientRect().top<=n.getBoundingClientRect().top+1;o.classList.toggle("stuck",h)};n.addEventListener("scroll",c,{passive:!0})}function Cg(n){$a=n,z3(n),As=Ss,o2(),qn(!1);const e=Ts(),t=U("#axBar"),i=e.querySelector(".ax-sub");i&&e.scrollTop>i.offsetTop&&(e.scrollTop=Math.max(0,t.offsetTop))}function o2(){document.querySelectorAll("#axViews [data-view]").forEach(n=>n.setAttribute("aria-pressed",String(n.dataset.view===$a)))}function i4(n){const[e,...t]=n.split(":"),i=t.join(":");if(As=Ss,e==="time"){ue.time="7d",ue.from=ue.to="",Es();return}e==="cats"?ue.cats.delete(i):e==="actions"?ue.actions.delete(i):e==="srcs"?ue.srcs.delete(i):e==="agents"?ue.agents.delete(i):e==="status"&&ue.status.delete(i),qn(!1)}function r2(n){ue.agents=new Set([n]),Cg("day")}function a4(n){Dl(n,()=>zf(e=>{if(nC(e,ta==="agent"),!Pi){Ms.push(e),Qp();return}l2(e)}))}function l2(n){Kp.add(n.id),Fd(ea,n),!Eg&&(Eg=!0,setTimeout(()=>{Eg=!1,qn(!0)},150))}function c2(){const n=Ms;Ms=[],n.forEach(l2)}function Qp(){const n=document.getElementById("lgLive");if(!n)return;n.setAttribute("aria-pressed",String(Pi)),n.innerHTML=Pi?'<span class="cc-dot ok"></span>Live':`<span class="cc-dot idle"></span>Paused${Ms.length?` · ${Ms.length} new`:""}`,n.title=Pi?"Pause the live stream":"Resume the live stream";const e=U("#axNew");e.hidden=Pi||!Ms.length,e.textContent=`${Ms.length} new`,e.setAttribute("aria-label",`Show ${bn(Ms.length,"new event")}`),e.onclick=()=>{Pi=!0,c2(),Rg(),Qp(),Ts().scrollTo({top:0})}}const Rg=ol(()=>{Es(!0)},900);async function Es(n=!1){const e=++Tg;n||(Zp=!0,qn(!1));try{const t=_r.length?Promise.resolve(_r):tt("/api/keys").then(r=>Array.isArray(r)?r:r.keys||[]).catch(()=>[]),[i,a]=await Promise.all([Ud(R3(),Yp),t]);if(e!==Tg)return;_r=a;const s=i.length?i[0].ts:0,o=ea.filter(r=>r.live&&r.ts>s-15&&!i.some(l=>l.actor===r.actor&&l.action===r.action&&Math.abs(l.ts-r.ts)<15));for(const r of i){if(r.ok!==void 0&&!r.running)continue;const l=ea.find(c=>c.live&&c.actor===r.actor&&c.action===r.action&&Math.abs(c.ts-r.ts)<5);l&&!l.running&&(r.running=!1,r.ok=l.ok,r.ms=l.ms)}if(n&&ea.length){const r=new Set(ea.map(l=>l.actor+l.action+Math.round(l.ts)));i.forEach(l=>{r.has(l.actor+l.action+Math.round(l.ts))||Kp.add(l.id)})}e2=ue.time!=="1h"&&ue.time!=="today"&&i.filter(r=>r.source!=="auth").length>=Yp*.9,ea=[...o,...i]}catch(t){if(e!==Tg)return;Be("Could not load activity: "+t.message,"err")}Zp=!1,qn(n)}function s4(){const n=[`<button type="button" class="ax-chip time" data-open aria-label="${O(`Time: ${U1()}. Change filters`)}">${H1}<span class="t">${b(U1())}</span></button>`];ue.status.forEach(i=>n.push(gs("status:"+i,Ep.find(a=>a.id===i).label,"","Status "))),ue.cats.forEach(i=>n.push(gs("cats:"+i,rc.find(a=>a.id===i).label,`<i class="sw" style="--c:${ms[i]}"></i>`))),ue.actions.forEach(i=>n.push(gs("actions:"+i,cn(i),"","Action "))),ue.srcs.forEach(i=>n.push(gs("srcs:"+i,Nm.find(a=>a.id===i).label,"","Source "))),ue.agents.forEach(i=>n.push(gs("agents:"+i,i,qt(i,22)))),(n2()||ue.time!=="7d")&&n.push('<button type="button" class="ax-clear" data-clear>Clear all</button>'),U("#axChips").innerHTML=n.join("");const e=P3(),t=U("#axBadge");t.hidden=!e,t.textContent=String(e),U("#axFilt").setAttribute("aria-label",e?`Filters, ${e} active`:"Filters")}function o4(n){const e=n.filter(i=>lc(i)==="fail").length,t=new Set(n.map(i=>i.actor)).size;U("#axSum").innerHTML=Zp?"<span>Loading…</span>":`<span><b>${n.length}</b> ${n.length===1?"event":"events"}</span><span><b>${t}</b> ${t===1?"actor":"actors"}</span>${e?`<span class="bad"><b>${e}</b> failed</span>`:""}${$a==="day"?`<button type="button" class="ax-tgl" id="axCompact" aria-pressed="${jp}" title="Collapse repeated calls by the same agent"><i></i>Group repeats</button>`:""}`}function r4(){const n=Ts(),e=n.querySelector("#axBar")?.offsetHeight||0,t=n.getBoundingClientRect().top+e,i=n.querySelectorAll("#axBody [data-act],#axBody .ax-ag");let a=null;for(const l of i)if(l.getBoundingClientRect().bottom>t+40){a=l;break}if(!a||n.scrollTop<40)return()=>{};const s=a.dataset.act?`[data-act="${window.CSS.escape(a.dataset.act)}"]`:null,o=a.querySelector("[data-agent]")?.dataset.agent,r=a.getBoundingClientRect().top;return()=>{const l=s?n.querySelector(`#axBody ${s}`):o&&n.querySelector(`#axBody [data-agent="${window.CSS.escape(o)}"]`)?.closest(".ax-ag")||null;l&&(n.scrollTop+=l.getBoundingClientRect().top-r)}}function qn(n=!0){const e=document.getElementById("axBody");if(!e)return;s4();const t=Tc(),i=t.filter(o=>Ra(o));if(o4(i),Z3(),Zp){e.setAttribute("aria-busy","true"),e.innerHTML=Um($a);return}e.removeAttribute("aria-busy");const a={rows:i,agents:t2(t),fresh:Kp,limit:As,compact:jp,older:e2,narrowed:n2(),none:!t.length},s=n?r4():()=>{};e.innerHTML=$a==="agent"?X3(a):$a==="board"?K3(a):q1(a),s(),Kp.clear(),l4(e)}function l4(n){Jp?.disconnect();const e=n.querySelector("[data-more]");!e||typeof IntersectionObserver>"u"||(Jp=new IntersectionObserver(t=>{t.some(i=>i.isIntersecting)&&(Jp?.disconnect(),As+=Ss,qn(!0))},{root:Ts(),rootMargin:"0px 0px 300px 0px"}),Jp.observe(e))}const d2=["#5eead4","#7dd3fc","#a78bfa","#f472b6","#fbbf24","#86efac","#fb923c","#93c5fd","#e879f9","#facc15","#67e8f9","#fca5a5","#c4b5fd","#bef264"];function c4(n,e){return e&&/^#[0-9a-f]{6}$/i.test(e)?e:d2[n%d2.length]}function p2(n){const e=/^#?([0-9a-f]{6})$/i.exec(n.trim());if(!e)return[.6,.8,.9];const t=parseInt(e[1],16);return[(t>>16&255)/255,(t>>8&255)/255,(t&255)/255]}const Lg="186",Sr={ROTATE:0,DOLLY:1,PAN:2},Mr={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},d4=0,h2=1,p4=2,eh=1,h4=2,Ec=3,wo=0,ei=1,Na=2,Da=0,Ar=1,za=2,u2=3,f2=4,u4=5,Tr=100,f4=101,m4=102,g4=103,v4=104,x4=200,b4=201,y4=202,w4=203,m2=204,g2=205,k4=206,_4=207,S4=208,M4=209,A4=210,T4=211,E4=212,C4=213,R4=214,Pg=0,Ig=1,$g=2,Cc=3,Ng=4,Dg=5,zg=6,Og=7,v2=0,L4=1,P4=2,na=0,x2=1,b2=2,y2=3,w2=4,k2=5,_2=6,S2=7,M2=300,ko=301,Er=302,Ug=303,Fg=304,th=306,Bg=1e3,Oa=1001,Hg=1002,Sn=1003,I4=1004,nh=1005,Cn=1006,Gg=1007,_o=1008,xi=1009,A2=1010,T2=1011,Rc=1012,qg=1013,ia=1014,aa=1015,sa=1016,Vg=1017,Wg=1018,Lc=1020,E2=35902,C2=35899,R2=1021,L2=1022,Ii=1023,Ua=1026,So=1027,P2=1028,Xg=1029,Mo=1030,Kg=1031,Yg=1033,ih=33776,ah=33777,sh=33778,oh=33779,jg=35840,Zg=35841,Jg=35842,Qg=35843,ev=36196,tv=37492,nv=37496,iv=37488,av=37489,rh=37490,sv=37491,ov=37808,rv=37809,lv=37810,cv=37811,dv=37812,pv=37813,hv=37814,uv=37815,fv=37816,mv=37817,gv=37818,vv=37819,xv=37820,bv=37821,yv=36492,wv=36494,kv=36495,_v=36283,Sv=36284,lh=36285,Mv=36286,$4=3200,I2=0,N4=1,Cs="",bi="srgb",ch="srgb-linear",dh="linear",Bt="srgb",Av=7680,D4=519,z4=512,O4=513,U4=514,Tv=515,F4=516,B4=517,Ev=518,H4=519,G4=35044,q4=35048,$2="300 es",oa=2e3,ph=2001;function V4(n){for(let e=n.length-1;e>=0;--e)if(n[e]>=65535)return!0;return!1}function hh(n){return document.createElementNS("http://www.w3.org/1999/xhtml",n)}function W4(){const n=hh("canvas");return n.style.display="block",n}const N2={};function D2(...n){const e="THREE."+n.shift();console.log(e,...n)}function z2(n){const e=n[0];if(typeof e=="string"&&e.startsWith("TSL:")){const t=n[1];t&&t.isStackTrace?n[0]+=" "+t.getLocation():n[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return n}function rt(...n){n=z2(n);const e="THREE."+n.shift();{const t=n[0];t&&t.isStackTrace?console.warn(t.getError(e)):console.warn(e,...n)}}function Pt(...n){n=z2(n);const e="THREE."+n.shift();{const t=n[0];t&&t.isStackTrace?console.error(t.getError(e)):console.error(e,...n)}}function Cr(...n){const e=n.join(" ");e in N2||(N2[e]=!0,rt(...n))}function X4(n,e,t){return new Promise(function(i,a){function s(){switch(n.clientWaitSync(e,n.SYNC_FLUSH_COMMANDS_BIT,0)){case n.WAIT_FAILED:a();break;case n.TIMEOUT_EXPIRED:setTimeout(s,t);break;default:i()}}setTimeout(s,t)})}const K4={[Pg]:Ig,[$g]:zg,[Ng]:Og,[Cc]:Dg,[Ig]:Pg,[zg]:$g,[Og]:Ng,[Dg]:Cc};class Rs{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const i=this._listeners;i[e]===void 0&&(i[e]=[]),i[e].indexOf(t)===-1&&i[e].push(t)}hasEventListener(e,t){const i=this._listeners;return i===void 0?!1:i[e]!==void 0&&i[e].indexOf(t)!==-1}removeEventListener(e,t){const i=this._listeners;if(i===void 0)return;const a=i[e];if(a!==void 0){const s=a.indexOf(t);s!==-1&&a.splice(s,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const i=t[e.type];if(i!==void 0){e.target=this;const a=i.slice(0);for(let s=0,o=a.length;s<o;s++)a[s].call(this,e);e.target=null}}}const Rn=["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"],uh=Math.PI/180,Cv=180/Math.PI;function Pc(){const n=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,i=Math.random()*4294967295|0;return(Rn[n&255]+Rn[n>>8&255]+Rn[n>>16&255]+Rn[n>>24&255]+"-"+Rn[e&255]+Rn[e>>8&255]+"-"+Rn[e>>16&15|64]+Rn[e>>24&255]+"-"+Rn[t&63|128]+Rn[t>>8&255]+"-"+Rn[t>>16&255]+Rn[t>>24&255]+Rn[i&255]+Rn[i>>8&255]+Rn[i>>16&255]+Rn[i>>24&255]).toLowerCase()}function yt(n,e,t){return Math.max(e,Math.min(t,n))}function Y4(n,e){return(n%e+e)%e}function Rv(n,e,t){return(1-t)*n+t*e}function Ic(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return n/4294967295;case Uint16Array:return n/65535;case Uint8Array:case Uint8ClampedArray:return n/255;case Int32Array:return Math.max(n/2147483647,-1);case Int16Array:return Math.max(n/32767,-1);case Int8Array:return Math.max(n/127,-1);default:throw new Error("THREE.MathUtils: Invalid component type.")}}function ti(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return Math.round(n*4294967295);case Uint16Array:return Math.round(n*65535);case Uint8Array:case Uint8ClampedArray:return Math.round(n*255);case Int32Array:return Math.round(n*2147483647);case Int16Array:return Math.round(n*32767);case Int8Array:return Math.round(n*127);default:throw new Error("THREE.MathUtils: Invalid component type.")}}const j4={DEG2RAD:uh},ab=class ab{constructor(e=0,t=0){this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("THREE.Vector2: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("THREE.Vector2: index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,i=this.y,a=e.elements;return this.x=a[0]*t+a[3]*i+a[6],this.y=a[1]*t+a[4]*i+a[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=yt(this.x,e.x,t.x),this.y=yt(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=yt(this.x,e,t),this.y=yt(this.y,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(yt(i,e,t))}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(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.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(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(yt(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y;return t*t+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const i=Math.cos(t),a=Math.sin(t),s=this.x-e.x,o=this.y-e.y;return this.x=s*i-o*a+e.x,this.y=s*a+o*i+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}};ab.prototype.isVector2=!0;let ut=ab;class Ls{constructor(e=0,t=0,i=0,a=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=i,this._w=a}static slerpFlat(e,t,i,a,s,o,r){let l=i[a+0],c=i[a+1],p=i[a+2],h=i[a+3],d=s[o+0],u=s[o+1],f=s[o+2],v=s[o+3];if(h!==v||l!==d||c!==u||p!==f){let g=l*d+c*u+p*f+h*v;g<0&&(d=-d,u=-u,f=-f,v=-v,g=-g);let m=1-r;if(g<.9995){const x=Math.acos(g),_=Math.sin(x);m=Math.sin(m*x)/_,r=Math.sin(r*x)/_,l=l*m+d*r,c=c*m+u*r,p=p*m+f*r,h=h*m+v*r}else{l=l*m+d*r,c=c*m+u*r,p=p*m+f*r,h=h*m+v*r;const x=1/Math.sqrt(l*l+c*c+p*p+h*h);l*=x,c*=x,p*=x,h*=x}}e[t]=l,e[t+1]=c,e[t+2]=p,e[t+3]=h}static multiplyQuaternionsFlat(e,t,i,a,s,o){const r=i[a],l=i[a+1],c=i[a+2],p=i[a+3],h=s[o],d=s[o+1],u=s[o+2],f=s[o+3];return e[t]=r*f+p*h+l*u-c*d,e[t+1]=l*f+p*d+c*h-r*u,e[t+2]=c*f+p*u+r*d-l*h,e[t+3]=p*f-r*h-l*d-c*u,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,i,a){return this._x=e,this._y=t,this._z=i,this._w=a,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){const i=e._x,a=e._y,s=e._z,o=e._order,r=Math.cos,l=Math.sin,c=r(i/2),p=r(a/2),h=r(s/2),d=l(i/2),u=l(a/2),f=l(s/2);switch(o){case"XYZ":this._x=d*p*h+c*u*f,this._y=c*u*h-d*p*f,this._z=c*p*f+d*u*h,this._w=c*p*h-d*u*f;break;case"YXZ":this._x=d*p*h+c*u*f,this._y=c*u*h-d*p*f,this._z=c*p*f-d*u*h,this._w=c*p*h+d*u*f;break;case"ZXY":this._x=d*p*h-c*u*f,this._y=c*u*h+d*p*f,this._z=c*p*f+d*u*h,this._w=c*p*h-d*u*f;break;case"ZYX":this._x=d*p*h-c*u*f,this._y=c*u*h+d*p*f,this._z=c*p*f-d*u*h,this._w=c*p*h+d*u*f;break;case"YZX":this._x=d*p*h+c*u*f,this._y=c*u*h+d*p*f,this._z=c*p*f-d*u*h,this._w=c*p*h-d*u*f;break;case"XZY":this._x=d*p*h-c*u*f,this._y=c*u*h-d*p*f,this._z=c*p*f+d*u*h,this._w=c*p*h+d*u*f;break;default:rt("Quaternion: .setFromEuler() encountered an unknown order: "+o)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const i=t/2,a=Math.sin(i);return this._x=e.x*a,this._y=e.y*a,this._z=e.z*a,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,i=t[0],a=t[4],s=t[8],o=t[1],r=t[5],l=t[9],c=t[2],p=t[6],h=t[10],d=i+r+h;if(d>0){const u=.5/Math.sqrt(d+1);this._w=.25/u,this._x=(p-l)*u,this._y=(s-c)*u,this._z=(o-a)*u}else if(i>r&&i>h){const u=2*Math.sqrt(1+i-r-h);this._w=(p-l)/u,this._x=.25*u,this._y=(a+o)/u,this._z=(s+c)/u}else if(r>h){const u=2*Math.sqrt(1+r-i-h);this._w=(s-c)/u,this._x=(a+o)/u,this._y=.25*u,this._z=(l+p)/u}else{const u=2*Math.sqrt(1+h-i-r);this._w=(o-a)/u,this._x=(s+c)/u,this._y=(l+p)/u,this._z=.25*u}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let i=e.dot(t)+1;return i<1e-8?(i=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=i):(this._x=0,this._y=-e.z,this._z=e.y,this._w=i)):(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=i),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(yt(this.dot(e),-1,1)))}rotateTowards(e,t){const i=this.angleTo(e);if(i===0)return this;const a=Math.min(1,t/i);return this.slerp(e,a),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){const i=e._x,a=e._y,s=e._z,o=e._w,r=t._x,l=t._y,c=t._z,p=t._w;return this._x=i*p+o*r+a*c-s*l,this._y=a*p+o*l+s*r-i*c,this._z=s*p+o*c+i*l-a*r,this._w=o*p-i*r-a*l-s*c,this._onChangeCallback(),this}slerp(e,t){let i=e._x,a=e._y,s=e._z,o=e._w,r=this.dot(e);r<0&&(i=-i,a=-a,s=-s,o=-o,r=-r);let l=1-t;if(r<.9995){const c=Math.acos(r),p=Math.sin(c);l=Math.sin(l*c)/p,t=Math.sin(t*c)/p,this._x=this._x*l+i*t,this._y=this._y*l+a*t,this._z=this._z*l+s*t,this._w=this._w*l+o*t,this._onChangeCallback()}else this._x=this._x*l+i*t,this._y=this._y*l+a*t,this._z=this._z*l+s*t,this._w=this._w*l+o*t,this.normalize();return this}slerpQuaternions(e,t,i){return this.copy(e).slerp(t,i)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),i=Math.random(),a=Math.sqrt(1-i),s=Math.sqrt(i);return this.set(a*Math.sin(e),a*Math.cos(e),s*Math.sin(t),s*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}}const sb=class sb{constructor(e=0,t=0,i=0){this.x=e,this.y=t,this.z=i}set(e,t,i){return i===void 0&&(i=this.z),this.x=e,this.y=t,this.z=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("THREE.Vector3: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("THREE.Vector3: index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(O2.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(O2.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,i=this.y,a=this.z,s=e.elements;return this.x=s[0]*t+s[3]*i+s[6]*a,this.y=s[1]*t+s[4]*i+s[7]*a,this.z=s[2]*t+s[5]*i+s[8]*a,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,i=this.y,a=this.z,s=e.elements,o=1/(s[3]*t+s[7]*i+s[11]*a+s[15]);return this.x=(s[0]*t+s[4]*i+s[8]*a+s[12])*o,this.y=(s[1]*t+s[5]*i+s[9]*a+s[13])*o,this.z=(s[2]*t+s[6]*i+s[10]*a+s[14])*o,this}applyQuaternion(e){const t=this.x,i=this.y,a=this.z,s=e.x,o=e.y,r=e.z,l=e.w,c=2*(o*a-r*i),p=2*(r*t-s*a),h=2*(s*i-o*t);return this.x=t+l*c+o*h-r*p,this.y=i+l*p+r*c-s*h,this.z=a+l*h+s*p-o*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,i=this.y,a=this.z,s=e.elements;return this.x=s[0]*t+s[4]*i+s[8]*a,this.y=s[1]*t+s[5]*i+s[9]*a,this.z=s[2]*t+s[6]*i+s[10]*a,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=yt(this.x,e.x,t.x),this.y=yt(this.y,e.y,t.y),this.z=yt(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=yt(this.x,e,t),this.y=yt(this.y,e,t),this.z=yt(this.z,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(yt(i,e,t))}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(e){return this.x*e.x+this.y*e.y+this.z*e.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(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const i=e.x,a=e.y,s=e.z,o=t.x,r=t.y,l=t.z;return this.x=a*l-s*r,this.y=s*o-i*l,this.z=i*r-a*o,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const i=e.dot(this)/t;return this.copy(e).multiplyScalar(i)}projectOnPlane(e){return Lv.copy(this).projectOnVector(e),this.sub(Lv)}reflect(e){return this.sub(Lv.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(yt(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y,a=this.z-e.z;return t*t+i*i+a*a}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,i){const a=Math.sin(t)*e;return this.x=a*Math.sin(i),this.y=Math.cos(t)*e,this.z=a*Math.cos(i),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,i){return this.x=e*Math.sin(t),this.y=i,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),i=this.setFromMatrixColumn(e,1).length(),a=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=i,this.z=a,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,i=Math.sqrt(1-t*t);return this.x=i*Math.cos(e),this.y=t,this.z=i*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}};sb.prototype.isVector3=!0;let X=sb;const Lv=new X,O2=new Ls,ob=class ob{constructor(e,t,i,a,s,o,r,l,c){this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,i,a,s,o,r,l,c)}set(e,t,i,a,s,o,r,l,c){const p=this.elements;return p[0]=e,p[1]=a,p[2]=r,p[3]=t,p[4]=s,p[5]=l,p[6]=i,p[7]=o,p[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],this}extractBasis(e,t,i){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,a=t.elements,s=this.elements,o=i[0],r=i[3],l=i[6],c=i[1],p=i[4],h=i[7],d=i[2],u=i[5],f=i[8],v=a[0],g=a[3],m=a[6],x=a[1],_=a[4],w=a[7],S=a[2],A=a[5],C=a[8];return s[0]=o*v+r*x+l*S,s[3]=o*g+r*_+l*A,s[6]=o*m+r*w+l*C,s[1]=c*v+p*x+h*S,s[4]=c*g+p*_+h*A,s[7]=c*m+p*w+h*C,s[2]=d*v+u*x+f*S,s[5]=d*g+u*_+f*A,s[8]=d*m+u*w+f*C,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[1],a=e[2],s=e[3],o=e[4],r=e[5],l=e[6],c=e[7],p=e[8];return t*o*p-t*r*c-i*s*p+i*r*l+a*s*c-a*o*l}invert(){const e=this.elements,t=e[0],i=e[1],a=e[2],s=e[3],o=e[4],r=e[5],l=e[6],c=e[7],p=e[8],h=p*o-r*c,d=r*l-p*s,u=c*s-o*l,f=t*h+i*d+a*u;if(f===0)return this.set(0,0,0,0,0,0,0,0,0);const v=1/f;return e[0]=h*v,e[1]=(a*c-p*i)*v,e[2]=(r*i-a*o)*v,e[3]=d*v,e[4]=(p*t-a*l)*v,e[5]=(a*s-r*t)*v,e[6]=u*v,e[7]=(i*l-c*t)*v,e[8]=(o*t-i*s)*v,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,i,a,s,o,r){const l=Math.cos(s),c=Math.sin(s);return this.set(i*l,i*c,-i*(l*o+c*r)+o+e,-a*c,a*l,-a*(-c*o+l*r)+r+t,0,0,1),this}scale(e,t){return Cr("Matrix3: .scale() is deprecated. Use .makeScale() instead."),this.premultiply(Pv.makeScale(e,t)),this}rotate(e){return Cr("Matrix3: .rotate() is deprecated. Use .makeRotation() instead."),this.premultiply(Pv.makeRotation(-e)),this}translate(e,t){return Cr("Matrix3: .translate() is deprecated. Use .makeTranslation() instead."),this.premultiply(Pv.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,i,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,i=e.elements;for(let a=0;a<9;a++)if(t[a]!==i[a])return!1;return!0}fromArray(e,t=0){for(let i=0;i<9;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e}clone(){return new this.constructor().fromArray(this.elements)}};ob.prototype.isMatrix3=!0;let pt=ob;const Pv=new pt,U2=new pt().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),F2=new pt().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function Z4(){const n={enabled:!0,workingColorSpace:ch,spaces:{},convert:function(a,s,o){return this.enabled===!1||s===o||!s||!o||(this.spaces[s].transfer===Bt&&(a.r=Fa(a.r),a.g=Fa(a.g),a.b=Fa(a.b)),this.spaces[s].primaries!==this.spaces[o].primaries&&(a.applyMatrix3(this.spaces[s].toXYZ),a.applyMatrix3(this.spaces[o].fromXYZ)),this.spaces[o].transfer===Bt&&(a.r=Rr(a.r),a.g=Rr(a.g),a.b=Rr(a.b))),a},workingToColorSpace:function(a,s){return this.convert(a,this.workingColorSpace,s)},colorSpaceToWorking:function(a,s){return this.convert(a,s,this.workingColorSpace)},getPrimaries:function(a){return this.spaces[a].primaries},getTransfer:function(a){return a===Cs?dh:this.spaces[a].transfer},getToneMappingMode:function(a){return this.spaces[a].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(a,s=this.workingColorSpace){return a.fromArray(this.spaces[s].luminanceCoefficients)},define:function(a){Object.assign(this.spaces,a)},_getMatrix:function(a,s,o){return a.copy(this.spaces[s].toXYZ).multiply(this.spaces[o].fromXYZ)},_getDrawingBufferColorSpace:function(a){return this.spaces[a].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(a=this.workingColorSpace){return this.spaces[a].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(a,s){return Cr("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),n.workingToColorSpace(a,s)},toWorkingColorSpace:function(a,s){return Cr("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),n.colorSpaceToWorking(a,s)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],i=[.3127,.329];return n.define({[ch]:{primaries:e,whitePoint:i,transfer:dh,toXYZ:U2,fromXYZ:F2,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:bi},outputColorSpaceConfig:{drawingBufferColorSpace:bi}},[bi]:{primaries:e,whitePoint:i,transfer:Bt,toXYZ:U2,fromXYZ:F2,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:bi}}}),n}const St=Z4();function Fa(n){return n<.04045?n*.0773993808:Math.pow(n*.9478672986+.0521327014,2.4)}function Rr(n){return n<.0031308?n*12.92:1.055*Math.pow(n,.41666)-.055}let Lr;class J4{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let i;if(e instanceof HTMLCanvasElement)i=e;else{Lr===void 0&&(Lr=hh("canvas")),Lr.width=e.width,Lr.height=e.height;const a=Lr.getContext("2d");e instanceof ImageData?a.putImageData(e,0,0):a.drawImage(e,0,0,e.width,e.height),i=Lr}return i.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=hh("canvas");t.width=e.width,t.height=e.height;const i=t.getContext("2d");i.drawImage(e,0,0,e.width,e.height);const a=i.getImageData(0,0,e.width,e.height),s=a.data;for(let o=0;o<s.length;o++)s[o]=Fa(s[o]/255)*255;return i.putImageData(a,0,0),t}else if(e.data){const t=e.data.slice(0);for(let i=0;i<t.length;i++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[i]=Math.floor(Fa(t[i]/255)*255):t[i]=Fa(t[i]);return{data:t,width:e.width,height:e.height}}else return rt("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let Q4=0;class Iv{constructor(e=null){this.isTextureSource=!0,Object.defineProperty(this,"id",{value:Q4++}),this.uuid=Pc(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){const t=this.data;return typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):typeof VideoFrame<"u"&&t instanceof VideoFrame?e.set(t.displayWidth,t.displayHeight,0):t!==null?e.set(t.width,t.height,t.depth||0):e.set(0,0,0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];const i={uuid:this.uuid,url:""},a=this.data;if(a!==null){let s;if(Array.isArray(a)){s=[];for(let o=0,r=a.length;o<r;o++)a[o].isDataTexture?s.push($v(a[o].image)):s.push($v(a[o]))}else s=$v(a);i.url=s}return t||(e.images[this.uuid]=i),i}}function $v(n){return typeof HTMLImageElement<"u"&&n instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&n instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&n instanceof ImageBitmap?J4.getDataURL(n):n.data?{data:Array.from(n.data),width:n.width,height:n.height,type:n.data.constructor.name}:(rt("Texture: Unable to serialize Texture."),{})}let e5=0;const Nv=new X;class Vn extends Rs{constructor(e=Vn.DEFAULT_IMAGE,t=Vn.DEFAULT_MAPPING,i=Oa,a=Oa,s=Cn,o=_o,r=Ii,l=xi,c=Vn.DEFAULT_ANISOTROPY,p=Cs){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:e5++}),this.uuid=Pc(),this.name="",this.source=new Iv(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=i,this.wrapT=a,this.magFilter=s,this.minFilter=o,this.anisotropy=c,this.format=r,this.internalFormat=null,this.type=l,this.offset=new ut(0,0),this.repeat=new ut(1,1),this.center=new ut(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new pt,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=p,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(Nv).x}get height(){return this.source.getSize(Nv).y}get depth(){return this.source.getSize(Nv).z}get image(){return this.source.data}set image(e){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.normalized=e.normalized,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const i=e[t];if(i===void 0){rt(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const a=this[t];if(a===void 0){rt(`Texture.setValues(): property '${t}' does not exist.`);continue}a&&i&&a.isVector2&&i.isVector2||a&&i&&a.isVector3&&i.isVector3||a&&i&&a.isMatrix3&&i.isMatrix3?a.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const i={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).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,normalized:this.normalized,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),t||(e.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==M2)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Bg:e.x=e.x-Math.floor(e.x);break;case Oa:e.x=e.x<0?0:1;break;case Hg:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case Bg:e.y=e.y-Math.floor(e.y);break;case Oa:e.y=e.y<0?0:1;break;case Hg:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}Vn.DEFAULT_IMAGE=null,Vn.DEFAULT_MAPPING=M2,Vn.DEFAULT_ANISOTROPY=1;const rb=class rb{constructor(e=0,t=0,i=0,a=1){this.x=e,this.y=t,this.z=i,this.w=a}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,i,a){return this.x=e,this.y=t,this.z=i,this.w=a,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("THREE.Vector4: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("THREE.Vector4: index is out of range: "+e)}}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!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,i=this.y,a=this.z,s=this.w,o=e.elements;return this.x=o[0]*t+o[4]*i+o[8]*a+o[12]*s,this.y=o[1]*t+o[5]*i+o[9]*a+o[13]*s,this.z=o[2]*t+o[6]*i+o[10]*a+o[14]*s,this.w=o[3]*t+o[7]*i+o[11]*a+o[15]*s,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,i,a,s;const l=e.elements,c=l[0],p=l[4],h=l[8],d=l[1],u=l[5],f=l[9],v=l[2],g=l[6],m=l[10];if(Math.abs(p-d)<.01&&Math.abs(h-v)<.01&&Math.abs(f-g)<.01){if(Math.abs(p+d)<.1&&Math.abs(h+v)<.1&&Math.abs(f+g)<.1&&Math.abs(c+u+m-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const _=(c+1)/2,w=(u+1)/2,S=(m+1)/2,A=(p+d)/4,C=(h+v)/4,y=(f+g)/4;return _>w&&_>S?_<.01?(i=0,a=.707106781,s=.707106781):(i=Math.sqrt(_),a=A/i,s=C/i):w>S?w<.01?(i=.707106781,a=0,s=.707106781):(a=Math.sqrt(w),i=A/a,s=y/a):S<.01?(i=.707106781,a=.707106781,s=0):(s=Math.sqrt(S),i=C/s,a=y/s),this.set(i,a,s,t),this}let x=Math.sqrt((g-f)*(g-f)+(h-v)*(h-v)+(d-p)*(d-p));return Math.abs(x)<.001&&(x=1),this.x=(g-f)/x,this.y=(h-v)/x,this.z=(d-p)/x,this.w=Math.acos((c+u+m-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=yt(this.x,e.x,t.x),this.y=yt(this.y,e.y,t.y),this.z=yt(this.z,e.z,t.z),this.w=yt(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=yt(this.x,e,t),this.y=yt(this.y,e,t),this.z=yt(this.z,e,t),this.w=yt(this.w,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(yt(i,e,t))}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(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)}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(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this.w=e.w+(t.w-e.w)*i,this}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}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}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}};rb.prototype.isVector4=!0;let nn=rb;class t5 extends Rs{constructor(e=1,t=1,i={}){super(),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Cn,depthBuffer:!0,stencilBuffer:!1,resolveColorBuffer:!0,resolveDepthBuffer:!0,resolveStencilBuffer:!0,storeMultisampledColorBuffer:!0,storeMultisampledDepthBuffer:!0,storeMultisampledStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},i),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=i.depth,this.scissor=new nn(0,0,e,t),this.scissorTest=!1,this.viewport=new nn(0,0,e,t),this.textures=[];const a={width:e,height:t,depth:i.depth},s=new Vn(a),o=i.count;for(let r=0;r<o;r++)this.textures[r]=s.clone(),this.textures[r].isRenderTargetTexture=!0,this.textures[r].renderTarget=this;this._setTextureOptions(i),this.depthBuffer=i.depthBuffer,this.stencilBuffer=i.stencilBuffer,this.resolveColorBuffer=i.resolveColorBuffer,this.resolveDepthBuffer=i.resolveDepthBuffer,this.resolveStencilBuffer=i.resolveStencilBuffer,this.storeMultisampledColorBuffer=i.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=i.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=i.storeMultisampledStencilBuffer,this._depthTexture=null,this.depthTexture=i.depthTexture,this.samples=i.samples,this.multiview=i.multiview,this.useArrayDepthTexture=i.useArrayDepthTexture}_setTextureOptions(e={}){const t={minFilter:Cn,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let i=0;i<this.textures.length;i++)this.textures[i].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&this._depthTexture.renderTarget===this&&(this._depthTexture.renderTarget=null),e!==null&&e.renderTarget===null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,i=1){if(this.width!==e||this.height!==t||this.depth!==i){this.width=e,this.height=t,this.depth=i;for(let a=0,s=this.textures.length;a<s;a++)this.textures[a].image.width=e,this.textures[a].image.height=t,this.textures[a].image.depth=i,this.textures[a].isData3DTexture!==!0&&(this.textures[a].isArrayTexture=this.textures[a].image.depth>1);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 t=0,i=e.textures.length;t<i;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;const a=Object.assign({},e.textures[t].image);this.textures[t].source=new Iv(a)}if(this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveColorBuffer=e.resolveColorBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,this.storeMultisampledColorBuffer=e.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=e.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=e.storeMultisampledStencilBuffer,e.depthTexture!==null)if(e.depthTexture.renderTarget===e){const t=e.depthTexture.clone();t.renderTarget=null,this.depthTexture=t}else this.depthTexture=e.depthTexture;return this.samples=e.samples,this.multiview=e.multiview,this.useArrayDepthTexture=e.useArrayDepthTexture,this}dispose(){this.dispatchEvent({type:"dispose"})}}class $i extends t5{constructor(e=1,t=1,i={}){super(e,t,i),this.isWebGLRenderTarget=!0}}class B2 extends Vn{constructor(e=null,t=1,i=1,a=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:i,depth:a},this.magFilter=Sn,this.minFilter=Sn,this.wrapR=Oa,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class n5 extends Vn{constructor(e=null,t=1,i=1,a=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:i,depth:a},this.magFilter=Sn,this.minFilter=Sn,this.wrapR=Oa,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}}const xu=class xu{constructor(e,t,i,a,s,o,r,l,c,p,h,d,u,f,v,g){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,i,a,s,o,r,l,c,p,h,d,u,f,v,g)}set(e,t,i,a,s,o,r,l,c,p,h,d,u,f,v,g){const m=this.elements;return m[0]=e,m[4]=t,m[8]=i,m[12]=a,m[1]=s,m[5]=o,m[9]=r,m[13]=l,m[2]=c,m[6]=p,m[10]=h,m[14]=d,m[3]=u,m[7]=f,m[11]=v,m[15]=g,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new xu().fromArray(this.elements)}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],t[9]=i[9],t[10]=i[10],t[11]=i[11],t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],this}copyPosition(e){const t=this.elements,i=e.elements;return t[12]=i[12],t[13]=i[13],t[14]=i[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,i){return this.determinantAffine()===0?(e.set(1,0,0),t.set(0,1,0),i.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this)}makeBasis(e,t,i){return this.set(e.x,t.x,i.x,0,e.y,t.y,i.y,0,e.z,t.z,i.z,0,0,0,0,1),this}extractRotation(e){if(e.determinantAffine()===0)return this.identity();const t=this.elements,i=e.elements,a=1/Pr.setFromMatrixColumn(e,0).length(),s=1/Pr.setFromMatrixColumn(e,1).length(),o=1/Pr.setFromMatrixColumn(e,2).length();return t[0]=i[0]*a,t[1]=i[1]*a,t[2]=i[2]*a,t[3]=0,t[4]=i[4]*s,t[5]=i[5]*s,t[6]=i[6]*s,t[7]=0,t[8]=i[8]*o,t[9]=i[9]*o,t[10]=i[10]*o,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,i=e.x,a=e.y,s=e.z,o=Math.cos(i),r=Math.sin(i),l=Math.cos(a),c=Math.sin(a),p=Math.cos(s),h=Math.sin(s);if(e.order==="XYZ"){const d=o*p,u=o*h,f=r*p,v=r*h;t[0]=l*p,t[4]=-l*h,t[8]=c,t[1]=u+f*c,t[5]=d-v*c,t[9]=-r*l,t[2]=v-d*c,t[6]=f+u*c,t[10]=o*l}else if(e.order==="YXZ"){const d=l*p,u=l*h,f=c*p,v=c*h;t[0]=d+v*r,t[4]=f*r-u,t[8]=o*c,t[1]=o*h,t[5]=o*p,t[9]=-r,t[2]=u*r-f,t[6]=v+d*r,t[10]=o*l}else if(e.order==="ZXY"){const d=l*p,u=l*h,f=c*p,v=c*h;t[0]=d-v*r,t[4]=-o*h,t[8]=f+u*r,t[1]=u+f*r,t[5]=o*p,t[9]=v-d*r,t[2]=-o*c,t[6]=r,t[10]=o*l}else if(e.order==="ZYX"){const d=o*p,u=o*h,f=r*p,v=r*h;t[0]=l*p,t[4]=f*c-u,t[8]=d*c+v,t[1]=l*h,t[5]=v*c+d,t[9]=u*c-f,t[2]=-c,t[6]=r*l,t[10]=o*l}else if(e.order==="YZX"){const d=o*l,u=o*c,f=r*l,v=r*c;t[0]=l*p,t[4]=v-d*h,t[8]=f*h+u,t[1]=h,t[5]=o*p,t[9]=-r*p,t[2]=-c*p,t[6]=u*h+f,t[10]=d-v*h}else if(e.order==="XZY"){const d=o*l,u=o*c,f=r*l,v=r*c;t[0]=l*p,t[4]=-h,t[8]=c*p,t[1]=d*h+v,t[5]=o*p,t[9]=u*h-f,t[2]=f*h-u,t[6]=r*p,t[10]=v*h+d}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(i5,e,a5)}lookAt(e,t,i){const a=this.elements;return ui.subVectors(e,t),ui.lengthSq()===0&&(ui.z=1),ui.normalize(),Ps.crossVectors(i,ui),Ps.lengthSq()===0&&(Math.abs(i.z)===1?ui.x+=1e-4:ui.z+=1e-4,ui.normalize(),Ps.crossVectors(i,ui)),Ps.normalize(),fh.crossVectors(ui,Ps),a[0]=Ps.x,a[4]=fh.x,a[8]=ui.x,a[1]=Ps.y,a[5]=fh.y,a[9]=ui.y,a[2]=Ps.z,a[6]=fh.z,a[10]=ui.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,a=t.elements,s=this.elements,o=i[0],r=i[4],l=i[8],c=i[12],p=i[1],h=i[5],d=i[9],u=i[13],f=i[2],v=i[6],g=i[10],m=i[14],x=i[3],_=i[7],w=i[11],S=i[15],A=a[0],C=a[4],y=a[8],M=a[12],T=a[1],L=a[5],P=a[9],z=a[13],R=a[2],B=a[6],K=a[10],N=a[14],V=a[3],Z=a[7],te=a[11],ce=a[15];return s[0]=o*A+r*T+l*R+c*V,s[4]=o*C+r*L+l*B+c*Z,s[8]=o*y+r*P+l*K+c*te,s[12]=o*M+r*z+l*N+c*ce,s[1]=p*A+h*T+d*R+u*V,s[5]=p*C+h*L+d*B+u*Z,s[9]=p*y+h*P+d*K+u*te,s[13]=p*M+h*z+d*N+u*ce,s[2]=f*A+v*T+g*R+m*V,s[6]=f*C+v*L+g*B+m*Z,s[10]=f*y+v*P+g*K+m*te,s[14]=f*M+v*z+g*N+m*ce,s[3]=x*A+_*T+w*R+S*V,s[7]=x*C+_*L+w*B+S*Z,s[11]=x*y+_*P+w*K+S*te,s[15]=x*M+_*z+w*N+S*ce,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[4],a=e[8],s=e[12],o=e[1],r=e[5],l=e[9],c=e[13],p=e[2],h=e[6],d=e[10],u=e[14],f=e[3],v=e[7],g=e[11],m=e[15],x=l*u-c*d,_=r*u-c*h,w=r*d-l*h,S=o*u-c*p,A=o*d-l*p,C=o*h-r*p;return t*(v*x-g*_+m*w)-i*(f*x-g*S+m*A)+a*(f*_-v*S+m*C)-s*(f*w-v*A+g*C)}determinantAffine(){const e=this.elements,t=e[0],i=e[4],a=e[8],s=e[1],o=e[5],r=e[9],l=e[2],c=e[6],p=e[10];return t*(o*p-r*c)-i*(s*p-r*l)+a*(s*c-o*l)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,i){const a=this.elements;return e.isVector3?(a[12]=e.x,a[13]=e.y,a[14]=e.z):(a[12]=e,a[13]=t,a[14]=i),this}invert(){const e=this.elements,t=e[0],i=e[1],a=e[2],s=e[3],o=e[4],r=e[5],l=e[6],c=e[7],p=e[8],h=e[9],d=e[10],u=e[11],f=e[12],v=e[13],g=e[14],m=e[15],x=t*r-i*o,_=t*l-a*o,w=t*c-s*o,S=i*l-a*r,A=i*c-s*r,C=a*c-s*l,y=p*v-h*f,M=p*g-d*f,T=p*m-u*f,L=h*g-d*v,P=h*m-u*v,z=d*m-u*g,R=x*z-_*P+w*L+S*T-A*M+C*y;if(R===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const B=1/R;return e[0]=(r*z-l*P+c*L)*B,e[1]=(a*P-i*z-s*L)*B,e[2]=(v*C-g*A+m*S)*B,e[3]=(d*A-h*C-u*S)*B,e[4]=(l*T-o*z-c*M)*B,e[5]=(t*z-a*T+s*M)*B,e[6]=(g*w-f*C-m*_)*B,e[7]=(p*C-d*w+u*_)*B,e[8]=(o*P-r*T+c*y)*B,e[9]=(i*T-t*P-s*y)*B,e[10]=(f*A-v*w+m*x)*B,e[11]=(h*w-p*A-u*x)*B,e[12]=(r*M-o*L-l*y)*B,e[13]=(t*L-i*M+a*y)*B,e[14]=(v*_-f*S-g*x)*B,e[15]=(p*S-h*_+d*x)*B,this}scale(e){const t=this.elements,i=e.x,a=e.y,s=e.z;return t[0]*=i,t[4]*=a,t[8]*=s,t[1]*=i,t[5]*=a,t[9]*=s,t[2]*=i,t[6]*=a,t[10]*=s,t[3]*=i,t[7]*=a,t[11]*=s,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],i=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],a=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,i,a))}makeTranslation(e,t,i){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,i,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),i=Math.sin(e);return this.set(1,0,0,0,0,t,-i,0,0,i,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,0,i,0,0,1,0,0,-i,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,0,i,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const i=Math.cos(t),a=Math.sin(t),s=1-i,o=e.x,r=e.y,l=e.z,c=s*o,p=s*r;return this.set(c*o+i,c*r-a*l,c*l+a*r,0,c*r+a*l,p*r+i,p*l-a*o,0,c*l-a*r,p*l+a*o,s*l*l+i,0,0,0,0,1),this}makeScale(e,t,i){return this.set(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1),this}makeShear(e,t,i,a,s,o){return this.set(1,i,s,0,e,1,o,0,t,a,1,0,0,0,0,1),this}compose(e,t,i){const a=this.elements,s=t._x,o=t._y,r=t._z,l=t._w,c=s+s,p=o+o,h=r+r,d=s*c,u=s*p,f=s*h,v=o*p,g=o*h,m=r*h,x=l*c,_=l*p,w=l*h,S=i.x,A=i.y,C=i.z;return a[0]=(1-(v+m))*S,a[1]=(u+w)*S,a[2]=(f-_)*S,a[3]=0,a[4]=(u-w)*A,a[5]=(1-(d+m))*A,a[6]=(g+x)*A,a[7]=0,a[8]=(f+_)*C,a[9]=(g-x)*C,a[10]=(1-(d+v))*C,a[11]=0,a[12]=e.x,a[13]=e.y,a[14]=e.z,a[15]=1,this}decompose(e,t,i){const a=this.elements;e.x=a[12],e.y=a[13],e.z=a[14];const s=this.determinantAffine();if(s===0)return i.set(1,1,1),t.identity(),this;let o=Pr.set(a[0],a[1],a[2]).length();const r=Pr.set(a[4],a[5],a[6]).length(),l=Pr.set(a[8],a[9],a[10]).length();s<0&&(o=-o),Ni.copy(this);const c=1/o,p=1/r,h=1/l;return Ni.elements[0]*=c,Ni.elements[1]*=c,Ni.elements[2]*=c,Ni.elements[4]*=p,Ni.elements[5]*=p,Ni.elements[6]*=p,Ni.elements[8]*=h,Ni.elements[9]*=h,Ni.elements[10]*=h,t.setFromRotationMatrix(Ni),i.x=o,i.y=r,i.z=l,this}makePerspective(e,t,i,a,s,o,r=oa,l=!1){const c=this.elements,p=2*s/(t-e),h=2*s/(i-a),d=(t+e)/(t-e),u=(i+a)/(i-a);let f,v;if(l)f=s/(o-s),v=o*s/(o-s);else if(r===oa)f=-(o+s)/(o-s),v=-2*o*s/(o-s);else if(r===ph)f=-o/(o-s),v=-o*s/(o-s);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+r);return c[0]=p,c[4]=0,c[8]=d,c[12]=0,c[1]=0,c[5]=h,c[9]=u,c[13]=0,c[2]=0,c[6]=0,c[10]=f,c[14]=v,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,i,a,s,o,r=oa,l=!1){const c=this.elements,p=2/(t-e),h=2/(i-a),d=-(t+e)/(t-e),u=-(i+a)/(i-a);let f,v;if(l)f=1/(o-s),v=o/(o-s);else if(r===oa)f=-2/(o-s),v=-(o+s)/(o-s);else if(r===ph)f=-1/(o-s),v=-s/(o-s);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+r);return c[0]=p,c[4]=0,c[8]=0,c[12]=d,c[1]=0,c[5]=h,c[9]=0,c[13]=u,c[2]=0,c[6]=0,c[10]=f,c[14]=v,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){const t=this.elements,i=e.elements;for(let a=0;a<16;a++)if(t[a]!==i[a])return!1;return!0}fromArray(e,t=0){for(let i=0;i<16;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],e}};xu.prototype.isMatrix4=!0;let en=xu;const Pr=new X,Ni=new en,i5=new X(0,0,0),a5=new X(1,1,1),Ps=new X,fh=new X,ui=new X,H2=new en,G2=new Ls;class Ao{constructor(e=0,t=0,i=0,a=Ao.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=i,this._order=a}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 order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,i,a=this._order){return this._x=e,this._y=t,this._z=i,this._order=a,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,i=!0){const a=e.elements,s=a[0],o=a[4],r=a[8],l=a[1],c=a[5],p=a[9],h=a[2],d=a[6],u=a[10];switch(t){case"XYZ":this._y=Math.asin(yt(r,-1,1)),Math.abs(r)<.9999999?(this._x=Math.atan2(-p,u),this._z=Math.atan2(-o,s)):(this._x=Math.atan2(d,c),this._z=0);break;case"YXZ":this._x=Math.asin(-yt(p,-1,1)),Math.abs(p)<.9999999?(this._y=Math.atan2(r,u),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-h,s),this._z=0);break;case"ZXY":this._x=Math.asin(yt(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-h,u),this._z=Math.atan2(-o,c)):(this._y=0,this._z=Math.atan2(l,s));break;case"ZYX":this._y=Math.asin(-yt(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(d,u),this._z=Math.atan2(l,s)):(this._x=0,this._z=Math.atan2(-o,c));break;case"YZX":this._z=Math.asin(yt(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-p,c),this._y=Math.atan2(-h,s)):(this._x=0,this._y=Math.atan2(r,u));break;case"XZY":this._z=Math.asin(-yt(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(r,s)):(this._x=Math.atan2(-p,u),this._y=0);break;default:rt("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,i===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,i){return H2.makeRotationFromQuaternion(e),this.setFromRotationMatrix(H2,t,i)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return G2.setFromEuler(this),this.setFromQuaternion(G2,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[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._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Ao.DEFAULT_ORDER="XYZ";class q2{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}}let s5=0;const V2=new X,Ir=new Ls,Ba=new en,mh=new X,$c=new X,o5=new X,r5=new Ls,W2=new X(1,0,0),X2=new X(0,1,0),K2=new X(0,0,1),Y2={type:"added"},l5={type:"removed"},$r={type:"childadded",child:null},Dv={type:"childremoved",child:null};class Wn extends Rs{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:s5++}),this.uuid=Pc(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Wn.DEFAULT_UP.clone();const e=new X,t=new Ao,i=new Ls,a=new X(1,1,1);function s(){i.setFromEuler(t,!1)}function o(){t.setFromQuaternion(i,void 0,!1)}t._onChange(s),i._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:i},scale:{configurable:!0,enumerable:!0,value:a},modelViewMatrix:{value:new en},normalMatrix:{value:new pt}}),this.matrix=new en,this.matrixWorld=new en,this.matrixAutoUpdate=Wn.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Wn.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new q2,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.static=!1,this.userData={},this.pivot=null}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return Ir.setFromAxisAngle(e,t),this.quaternion.multiply(Ir),this}rotateOnWorldAxis(e,t){return Ir.setFromAxisAngle(e,t),this.quaternion.premultiply(Ir),this}rotateX(e){return this.rotateOnAxis(W2,e)}rotateY(e){return this.rotateOnAxis(X2,e)}rotateZ(e){return this.rotateOnAxis(K2,e)}translateOnAxis(e,t){return V2.copy(e).applyQuaternion(this.quaternion),this.position.add(V2.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(W2,e)}translateY(e){return this.translateOnAxis(X2,e)}translateZ(e){return this.translateOnAxis(K2,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Ba.copy(this.matrixWorld).invert())}lookAt(e,t,i){e.isVector3?mh.copy(e):mh.set(e,t,i);const a=this.parent;this.updateWorldMatrix(!0,!1),$c.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Ba.lookAt($c,mh,this.up):Ba.lookAt(mh,$c,this.up),this.quaternion.setFromRotationMatrix(Ba),a&&(Ba.extractRotation(a.matrixWorld),Ir.setFromRotationMatrix(Ba),this.quaternion.premultiply(Ir.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(Pt("Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(Y2),$r.child=e,this.dispatchEvent($r),$r.child=null):Pt("Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let i=0;i<arguments.length;i++)this.remove(arguments[i]);return this}const t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(l5),Dv.child=e,this.dispatchEvent(Dv),Dv.child=null),this}removeFromParent(){const e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),Ba.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),Ba.multiply(e.parent.matrixWorld)),e.applyMatrix4(Ba),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Y2),$r.child=e,this.dispatchEvent($r),$r.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let i=0,a=this.children.length;i<a;i++){const o=this.children[i].getObjectByProperty(e,t);if(o!==void 0)return o}}getObjectsByProperty(e,t,i=[]){this[e]===t&&i.push(this);const a=this.children;for(let s=0,o=a.length;s<o;s++)a[s].getObjectsByProperty(e,t,i);return i}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose($c,e,o5),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose($c,r5,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}intersectsFrustum(){}traverse(e){e(this);const t=this.children;for(let i=0,a=t.length;i<a;i++)t[i].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const t=this.children;for(let i=0,a=t.length;i<a;i++)t[i].traverseVisible(e)}traverseAncestors(e){const t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);const e=this.pivot;if(e!==null){const t=e.x,i=e.y,a=e.z,s=this.matrix.elements;s[12]+=t-s[0]*t-s[4]*i-s[8]*a,s[13]+=i-s[1]*t-s[5]*i-s[9]*a,s[14]+=a-s[2]*t-s[6]*i-s[10]*a}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let i=0,a=t.length;i<a;i++)t[i].updateMatrixWorld(e)}updateWorldMatrix(e,t,i=!1){const a=this.parent;if(e===!0&&a!==null&&a.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||i)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,i=!0),t===!0){const s=this.children;for(let o=0,r=s.length;o<r;o++)s[o].updateWorldMatrix(!1,!0,i)}}toJSON(e){const t=e===void 0||typeof e=="string",i={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},i.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const a={};a.uuid=this.uuid,a.type=this.type,a.name=this.name,a.castShadow=this.castShadow,a.receiveShadow=this.receiveShadow,a.visible=this.visible,a.frustumCulled=this.frustumCulled,a.renderOrder=this.renderOrder,a.static=this.static,a.matrixAutoUpdate=this.matrixAutoUpdate,Object.keys(this.userData).length>0&&(a.userData=this.userData),a.layers=this.layers.mask,a.matrix=this.matrix.toArray(),a.up=this.up.toArray(),this.pivot!==null&&(a.pivot=this.pivot.toArray()),this.morphTargetDictionary!==void 0&&(a.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(a.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(a.type="InstancedMesh",a.count=this.count,a.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(a.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(a.type="BatchedMesh",a.perObjectFrustumCulled=this.perObjectFrustumCulled,a.sortObjects=this.sortObjects,a.drawRanges=this._drawRanges,a.reservedRanges=this._reservedRanges,a.geometryInfo=this._geometryInfo.map(r=>({...r,boundingBox:r.boundingBox?r.boundingBox.toJSON():void 0,boundingSphere:r.boundingSphere?r.boundingSphere.toJSON():void 0})),a.instanceInfo=this._instanceInfo.map(r=>({...r})),a.availableInstanceIds=this._availableInstanceIds.slice(),a.availableGeometryIds=this._availableGeometryIds.slice(),a.nextIndexStart=this._nextIndexStart,a.nextVertexStart=this._nextVertexStart,a.geometryCount=this._geometryCount,a.maxInstanceCount=this._maxInstanceCount,a.maxVertexCount=this._maxVertexCount,a.maxIndexCount=this._maxIndexCount,a.geometryInitialized=this._geometryInitialized,a.matricesTexture=this._matricesTexture.toJSON(e),a.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(a.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(a.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(a.boundingBox=this.boundingBox.toJSON()));function s(r,l){return r[l.uuid]===void 0&&(r[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?a.background=this.background.toJSON():this.background.isTexture&&(a.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(a.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){a.geometry=s(e.geometries,this.geometry);const r=this.geometry.parameters;if(r!==void 0&&r.shapes!==void 0){const l=r.shapes;if(Array.isArray(l))for(let c=0,p=l.length;c<p;c++){const h=l[c];s(e.shapes,h)}else s(e.shapes,l)}}if(this.isSkinnedMesh&&(a.bindMode=this.bindMode,a.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(s(e.skeletons,this.skeleton),a.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const r=[];for(let l=0,c=this.material.length;l<c;l++)r.push(s(e.materials,this.material[l]));a.material=r}else a.material=s(e.materials,this.material);if(this.children.length>0){a.children=[];for(let r=0;r<this.children.length;r++)a.children.push(this.children[r].toJSON(e).object)}if(this.animations.length>0){a.animations=[];for(let r=0;r<this.animations.length;r++){const l=this.animations[r];a.animations.push(s(e.animations,l))}}if(t){const r=o(e.geometries),l=o(e.materials),c=o(e.textures),p=o(e.images),h=o(e.shapes),d=o(e.skeletons),u=o(e.animations),f=o(e.nodes);r.length>0&&(i.geometries=r),l.length>0&&(i.materials=l),c.length>0&&(i.textures=c),p.length>0&&(i.images=p),h.length>0&&(i.shapes=h),d.length>0&&(i.skeletons=d),u.length>0&&(i.animations=u),f.length>0&&(i.nodes=f)}return i.object=a,i;function o(r){const l=[];for(const c in r){const p=r[c];delete p.metadata,l.push(p)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.pivot=e.pivot!==null?e.pivot.clone():null,this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let i=0;i<e.children.length;i++){const a=e.children[i];this.add(a.clone())}return this}dispose(){this.dispatchEvent({type:"dispose"})}}Wn.DEFAULT_UP=new X(0,1,0),Wn.DEFAULT_MATRIX_AUTO_UPDATE=!0,Wn.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;class gh extends Wn{constructor(){super(),this.isGroup=!0,this.type="Group"}}const c5={type:"move"};class zv{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new gh,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 gh,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new X,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new X),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new gh,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new X,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new X,this._grip.eventsEnabled=!1),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){const t=this._hand;if(t)for(const i of e.hand.values())this._getHandJoint(t,i)}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,i){let a=null,s=null,o=null;const r=this._targetRay,l=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){o=!0;for(const v of e.hand.values()){const g=t.getJointPose(v,i),m=this._getHandJoint(c,v);g!==null&&(m.matrix.fromArray(g.transform.matrix),m.matrix.decompose(m.position,m.rotation,m.scale),m.matrixWorldNeedsUpdate=!0,m.jointRadius=g.radius),m.visible=g!==null}const p=c.joints["index-finger-tip"],h=c.joints["thumb-tip"],d=p.position.distanceTo(h.position),u=.02,f=.005;c.inputState.pinching&&d>u+f?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&d<=u-f&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(s=t.getPose(e.gripSpace,i),s!==null&&(l.matrix.fromArray(s.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,s.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(s.linearVelocity)):l.hasLinearVelocity=!1,s.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(s.angularVelocity)):l.hasAngularVelocity=!1,l.eventsEnabled&&l.dispatchEvent({type:"gripUpdated",data:e,target:this})));r!==null&&(a=t.getPose(e.targetRaySpace,i),a===null&&s!==null&&(a=s),a!==null&&(r.matrix.fromArray(a.transform.matrix),r.matrix.decompose(r.position,r.rotation,r.scale),r.matrixWorldNeedsUpdate=!0,a.linearVelocity?(r.hasLinearVelocity=!0,r.linearVelocity.copy(a.linearVelocity)):r.hasLinearVelocity=!1,a.angularVelocity?(r.hasAngularVelocity=!0,r.angularVelocity.copy(a.angularVelocity)):r.hasAngularVelocity=!1,this.dispatchEvent(c5)))}return r!==null&&(r.visible=a!==null),l!==null&&(l.visible=s!==null),c!==null&&(c.visible=o!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const i=new gh;i.matrixAutoUpdate=!1,i.visible=!1,e.joints[t.jointName]=i,e.add(i)}return e.joints[t.jointName]}}const j2={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},Is={h:0,s:0,l:0},vh={h:0,s:0,l:0};function Ov(n,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?n+(e-n)*6*t:t<1/2?e:t<2/3?n+(e-n)*6*(2/3-t):n}class It{constructor(e,t,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,i)}set(e,t,i){if(t===void 0&&i===void 0){const a=e;a&&a.isColor?this.copy(a):typeof a=="number"?this.setHex(a):typeof a=="string"&&this.setStyle(a)}else this.setRGB(e,t,i);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=bi){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,St.colorSpaceToWorking(this,t),this}setRGB(e,t,i,a=St.workingColorSpace){return this.r=e,this.g=t,this.b=i,St.colorSpaceToWorking(this,a),this}setHSL(e,t,i,a=St.workingColorSpace){if(e=Y4(e,1),t=yt(t,0,1),i=yt(i,0,1),t===0)this.r=this.g=this.b=i;else{const s=i<=.5?i*(1+t):i+t-i*t,o=2*i-s;this.r=Ov(o,s,e+1/3),this.g=Ov(o,s,e),this.b=Ov(o,s,e-1/3)}return St.colorSpaceToWorking(this,a),this}setStyle(e,t=bi){function i(s){s!==void 0&&parseFloat(s)<1&&rt("Color: Alpha component of "+e+" will be ignored.")}let a;if(a=/^(\w+)\(([^\)]*)\)/.exec(e)){let s;const o=a[1],r=a[2];switch(o){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(r))return i(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,t);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(r))return i(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,t);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(r))return i(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,t);break;default:rt("Color: Unknown color model "+e)}}else if(a=/^\#([A-Fa-f\d]+)$/.exec(e)){const s=a[1],o=s.length;if(o===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,t);if(o===6)return this.setHex(parseInt(s,16),t);rt("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=bi){const i=j2[e.toLowerCase()];return i!==void 0?this.setHex(i,t):rt("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=Fa(e.r),this.g=Fa(e.g),this.b=Fa(e.b),this}copyLinearToSRGB(e){return this.r=Rr(e.r),this.g=Rr(e.g),this.b=Rr(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=bi){return St.workingToColorSpace(Ln.copy(this),e),Math.round(yt(Ln.r*255,0,255))*65536+Math.round(yt(Ln.g*255,0,255))*256+Math.round(yt(Ln.b*255,0,255))}getHexString(e=bi){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=St.workingColorSpace){St.workingToColorSpace(Ln.copy(this),t);const i=Ln.r,a=Ln.g,s=Ln.b,o=Math.max(i,a,s),r=Math.min(i,a,s);let l,c;const p=(r+o)/2;if(r===o)l=0,c=0;else{const h=o-r;switch(c=p<=.5?h/(o+r):h/(2-o-r),o){case i:l=(a-s)/h+(a<s?6:0);break;case a:l=(s-i)/h+2;break;case s:l=(i-a)/h+4;break}l/=6}return e.h=l,e.s=c,e.l=p,e}getRGB(e,t=St.workingColorSpace){return St.workingToColorSpace(Ln.copy(this),t),e.r=Ln.r,e.g=Ln.g,e.b=Ln.b,e}getStyle(e=bi){St.workingToColorSpace(Ln.copy(this),e);const t=Ln.r,i=Ln.g,a=Ln.b;return e!==bi?`color(${e} ${t.toFixed(3)} ${i.toFixed(3)} ${a.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(i*255)},${Math.round(a*255)})`}offsetHSL(e,t,i){return this.getHSL(Is),this.setHSL(Is.h+e,Is.s+t,Is.l+i)}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,i){return this.r=e.r+(t.r-e.r)*i,this.g=e.g+(t.g-e.g)*i,this.b=e.b+(t.b-e.b)*i,this}lerpHSL(e,t){this.getHSL(Is),e.getHSL(vh);const i=Rv(Is.h,vh.h,t),a=Rv(Is.s,vh.s,t),s=Rv(Is.l,vh.l,t);return this.setHSL(i,a,s),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,i=this.g,a=this.b,s=e.elements;return this.r=s[0]*t+s[3]*i+s[6]*a,this.g=s[1]*t+s[4]*i+s[7]*a,this.b=s[2]*t+s[5]*i+s[8]*a,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}}const Ln=new It;It.NAMES=j2;class d5 extends Wn{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 Ao,this.environmentIntensity=1,this.environmentRotation=new Ao,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){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),t.object.backgroundBlurriness=this.backgroundBlurriness,t.object.backgroundIntensity=this.backgroundIntensity,t.object.backgroundRotation=this.backgroundRotation.toArray(),t.object.environmentIntensity=this.environmentIntensity,t.object.environmentRotation=this.environmentRotation.toArray(),t}}const Di=new X,Ha=new X,Uv=new X,Ga=new X,Nr=new X,Dr=new X,Z2=new X,Fv=new X,Bv=new X,Hv=new X,Gv=new nn,qv=new nn,Vv=new nn;class zi{constructor(e=new X,t=new X,i=new X){this.a=e,this.b=t,this.c=i}static getNormal(e,t,i,a){a.subVectors(i,t),Di.subVectors(e,t),a.cross(Di);const s=a.lengthSq();return s>0?a.multiplyScalar(1/Math.sqrt(s)):a.set(0,0,0)}static getBarycoord(e,t,i,a,s){Di.subVectors(a,t),Ha.subVectors(i,t),Uv.subVectors(e,t);const o=Di.dot(Di),r=Di.dot(Ha),l=Di.dot(Uv),c=Ha.dot(Ha),p=Ha.dot(Uv),h=o*c-r*r;if(h===0)return s.set(0,0,0),null;const d=1/h,u=(c*l-r*p)*d,f=(o*p-r*l)*d;return s.set(1-u-f,f,u)}static containsPoint(e,t,i,a){return this.getBarycoord(e,t,i,a,Ga)===null?!1:Ga.x>=0&&Ga.y>=0&&Ga.x+Ga.y<=1}static getInterpolation(e,t,i,a,s,o,r,l){return this.getBarycoord(e,t,i,a,Ga)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(s,Ga.x),l.addScaledVector(o,Ga.y),l.addScaledVector(r,Ga.z),l)}static getInterpolatedAttribute(e,t,i,a,s,o){return Gv.setScalar(0),qv.setScalar(0),Vv.setScalar(0),Gv.fromBufferAttribute(e,t),qv.fromBufferAttribute(e,i),Vv.fromBufferAttribute(e,a),o.setScalar(0),o.addScaledVector(Gv,s.x),o.addScaledVector(qv,s.y),o.addScaledVector(Vv,s.z),o}static isFrontFacing(e,t,i,a){return Di.subVectors(i,t),Ha.subVectors(e,t),Di.cross(Ha).dot(a)<0}set(e,t,i){return this.a.copy(e),this.b.copy(t),this.c.copy(i),this}setFromPointsAndIndices(e,t,i,a){return this.a.copy(e[t]),this.b.copy(e[i]),this.c.copy(e[a]),this}setFromAttributeAndIndices(e,t,i,a){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,i),this.c.fromBufferAttribute(e,a),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Di.subVectors(this.c,this.b),Ha.subVectors(this.a,this.b),Di.cross(Ha).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return zi.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return zi.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,i,a,s){return zi.getInterpolation(e,this.a,this.b,this.c,t,i,a,s)}containsPoint(e){return zi.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return zi.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const i=this.a,a=this.b,s=this.c;let o,r;Nr.subVectors(a,i),Dr.subVectors(s,i),Fv.subVectors(e,i);const l=Nr.dot(Fv),c=Dr.dot(Fv);if(l<=0&&c<=0)return t.copy(i);Bv.subVectors(e,a);const p=Nr.dot(Bv),h=Dr.dot(Bv);if(p>=0&&h<=p)return t.copy(a);const d=l*h-p*c;if(d<=0&&l>=0&&p<=0)return o=l/(l-p),t.copy(i).addScaledVector(Nr,o);Hv.subVectors(e,s);const u=Nr.dot(Hv),f=Dr.dot(Hv);if(f>=0&&u<=f)return t.copy(s);const v=u*c-l*f;if(v<=0&&c>=0&&f<=0)return r=c/(c-f),t.copy(i).addScaledVector(Dr,r);const g=p*f-u*h;if(g<=0&&h-p>=0&&u-f>=0)return Z2.subVectors(s,a),r=(h-p)/(h-p+(u-f)),t.copy(a).addScaledVector(Z2,r);const m=1/(g+v+d);return o=v*m,r=d*m,t.copy(i).addScaledVector(Nr,o).addScaledVector(Dr,r)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}class Nc{constructor(e=new X(1/0,1/0,1/0),t=new X(-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,i=e.length;t<i;t+=3)this.expandByPoint(Oi.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,i=e.count;t<i;t++)this.expandByPoint(Oi.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,i=e.length;t<i;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const i=Oi.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(i),this.max.copy(e).add(i),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);const i=e.geometry;if(i!==void 0){const s=i.getAttribute("position");if(t===!0&&s!==void 0&&e.isInstancedMesh!==!0)for(let o=0,r=s.count;o<r;o++)e.isMesh===!0?e.getVertexPosition(o,Oi):Oi.fromBufferAttribute(s,o),Oi.applyMatrix4(e.matrixWorld),this.expandByPoint(Oi);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),xh.copy(e.boundingBox)):(i.boundingBox===null&&i.computeBoundingBox(),xh.copy(i.boundingBox)),xh.applyMatrix4(e.matrixWorld),this.union(xh)}const a=e.children;for(let s=0,o=a.length;s<o;s++)this.expandByObject(a[s],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,Oi),Oi.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,i;return e.normal.x>0?(t=e.normal.x*this.min.x,i=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,i=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,i+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,i+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,i+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,i+=e.normal.z*this.min.z),t<=-e.constant&&i>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Dc),bh.subVectors(this.max,Dc),zr.subVectors(e.a,Dc),Or.subVectors(e.b,Dc),Ur.subVectors(e.c,Dc),$s.subVectors(Or,zr),Ns.subVectors(Ur,Or),To.subVectors(zr,Ur);let t=[0,-$s.z,$s.y,0,-Ns.z,Ns.y,0,-To.z,To.y,$s.z,0,-$s.x,Ns.z,0,-Ns.x,To.z,0,-To.x,-$s.y,$s.x,0,-Ns.y,Ns.x,0,-To.y,To.x,0];return!Wv(t,zr,Or,Ur,bh)||(t=[1,0,0,0,1,0,0,0,1],!Wv(t,zr,Or,Ur,bh))?!1:(yh.crossVectors($s,Ns),t=[yh.x,yh.y,yh.z],Wv(t,zr,Or,Ur,bh))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Oi).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Oi).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:(qa[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),qa[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),qa[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),qa[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),qa[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),qa[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),qa[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),qa[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(qa),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)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}}const qa=[new X,new X,new X,new X,new X,new X,new X,new X],Oi=new X,xh=new Nc,zr=new X,Or=new X,Ur=new X,$s=new X,Ns=new X,To=new X,Dc=new X,bh=new X,yh=new X,Eo=new X;function Wv(n,e,t,i,a){for(let s=0,o=n.length-3;s<=o;s+=3){Eo.fromArray(n,s);const r=a.x*Math.abs(Eo.x)+a.y*Math.abs(Eo.y)+a.z*Math.abs(Eo.z),l=e.dot(Eo),c=t.dot(Eo),p=i.dot(Eo);if(Math.max(-Math.max(l,c,p),Math.min(l,c,p))>r)return!1}return!0}const dn=new X,wh=new ut;let p5=0;class ra extends Rs{constructor(e,t,i=!1){if(super(),Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:p5++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=i,this.usage=G4,this.updateRanges=[],this.gpuType=aa,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,i){e*=this.itemSize,i*=t.itemSize;for(let a=0,s=this.itemSize;a<s;a++)this.array[e+a]=t.array[i+a];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,i=this.count;t<i;t++)wh.fromBufferAttribute(this,t),wh.applyMatrix3(e),this.setXY(t,wh.x,wh.y);else if(this.itemSize===3)for(let t=0,i=this.count;t<i;t++)dn.fromBufferAttribute(this,t),dn.applyMatrix3(e),this.setXYZ(t,dn.x,dn.y,dn.z);return this}applyMatrix4(e){for(let t=0,i=this.count;t<i;t++)dn.fromBufferAttribute(this,t),dn.applyMatrix4(e),this.setXYZ(t,dn.x,dn.y,dn.z);return this}applyNormalMatrix(e){for(let t=0,i=this.count;t<i;t++)dn.fromBufferAttribute(this,t),dn.applyNormalMatrix(e),this.setXYZ(t,dn.x,dn.y,dn.z);return this}transformDirection(e){for(let t=0,i=this.count;t<i;t++)dn.fromBufferAttribute(this,t),dn.transformDirection(e),this.setXYZ(t,dn.x,dn.y,dn.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let i=this.array[e*this.itemSize+t];return this.normalized&&(i=Ic(i,this.array)),i}setComponent(e,t,i){return this.normalized&&(i=ti(i,this.array)),this.array[e*this.itemSize+t]=i,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Ic(t,this.array)),t}setX(e,t){return this.normalized&&(t=ti(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Ic(t,this.array)),t}setY(e,t){return this.normalized&&(t=ti(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=Ic(t,this.array)),t}setZ(e,t){return this.normalized&&(t=ti(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=Ic(t,this.array)),t}setW(e,t){return this.normalized&&(t=ti(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,i){return e*=this.itemSize,this.normalized&&(t=ti(t,this.array),i=ti(i,this.array)),this.array[e+0]=t,this.array[e+1]=i,this}setXYZ(e,t,i,a){return e*=this.itemSize,this.normalized&&(t=ti(t,this.array),i=ti(i,this.array),a=ti(a,this.array)),this.array[e+0]=t,this.array[e+1]=i,this.array[e+2]=a,this}setXYZW(e,t,i,a,s){return e*=this.itemSize,this.normalized&&(t=ti(t,this.array),i=ti(i,this.array),a=ti(a,this.array),s=ti(s,this.array)),this.array[e+0]=t,this.array[e+1]=i,this.array[e+2]=a,this.array[e+3]=s,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return e.name=this.name,e.usage=this.usage,e.gpuType=this.gpuType,e}dispose(){this.dispatchEvent({type:"dispose"})}}class J2 extends ra{constructor(e,t,i){super(new Uint16Array(e),t,i)}}class Q2 extends ra{constructor(e,t,i){super(new Uint32Array(e),t,i)}}class Ui extends ra{constructor(e,t,i){super(new Float32Array(e),t,i)}}const h5=new Nc,zc=new X,Xv=new X;class Oc{constructor(e=new X,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){const i=this.center;t!==void 0?i.copy(t):h5.setFromPoints(e).getCenter(i);let a=0;for(let s=0,o=e.length;s<o;s++)a=Math.max(a,i.distanceToSquared(e[s]));return this.radius=Math.sqrt(a),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){const 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){const i=this.center.distanceToSquared(e);return t.copy(e),i>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;zc.subVectors(e,this.center);const t=zc.lengthSq();if(t>this.radius*this.radius){const i=Math.sqrt(t),a=(i-this.radius)*.5;this.center.addScaledVector(zc,a/i),this.radius+=a}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):(Xv.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(zc.copy(e.center).add(Xv)),this.expandByPoint(zc.copy(e.center).sub(Xv))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}let u5=0;const yi=new en,Kv=new Wn,Fr=new X,fi=new Nc,Uc=new Nc,yn=new X;class pn extends Rs{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:u5++}),this.uuid=Pc(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(V4(e)?Q2:J2)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,i=0){this.groups.push({start:e,count:t,materialIndex:i})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);const i=this.attributes.normal;if(i!==void 0){const s=new pt().getNormalMatrix(e);i.applyNormalMatrix(s),i.needsUpdate=!0}const a=this.attributes.tangent;return a!==void 0&&(a.transformDirection(e),a.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this._transformed=!0,this}applyQuaternion(e){return yi.makeRotationFromQuaternion(e),this.applyMatrix4(yi),this}rotateX(e){return yi.makeRotationX(e),this.applyMatrix4(yi),this}rotateY(e){return yi.makeRotationY(e),this.applyMatrix4(yi),this}rotateZ(e){return yi.makeRotationZ(e),this.applyMatrix4(yi),this}translate(e,t,i){return yi.makeTranslation(e,t,i),this.applyMatrix4(yi),this}scale(e,t,i){return yi.makeScale(e,t,i),this.applyMatrix4(yi),this}lookAt(e){return Kv.lookAt(e),Kv.updateMatrix(),this.applyMatrix4(Kv.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Fr).negate(),this.translate(Fr.x,Fr.y,Fr.z),this}setFromPoints(e){const t=this.getAttribute("position");if(t===void 0){const i=[];for(let a=0,s=e.length;a<s;a++){const o=e[a];i.push(o.x,o.y,o.z||0)}this.setAttribute("position",new Ui(i,3))}else{const i=Math.min(e.length,t.count);for(let a=0;a<i;a++){const s=e[a];t.setXYZ(a,s.x,s.y,s.z||0)}e.length>t.count&&rt("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Nc);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Pt("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new X(-1/0,-1/0,-1/0),new X(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let i=0,a=t.length;i<a;i++){const s=t[i];fi.setFromBufferAttribute(s),this.morphTargetsRelative?(yn.addVectors(this.boundingBox.min,fi.min),this.boundingBox.expandByPoint(yn),yn.addVectors(this.boundingBox.max,fi.max),this.boundingBox.expandByPoint(yn)):(this.boundingBox.expandByPoint(fi.min),this.boundingBox.expandByPoint(fi.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&Pt('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 Oc);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Pt("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new X,1/0);return}if(e){const i=this.boundingSphere.center;if(fi.setFromBufferAttribute(e),t)for(let s=0,o=t.length;s<o;s++){const r=t[s];Uc.setFromBufferAttribute(r),this.morphTargetsRelative?(yn.addVectors(fi.min,Uc.min),fi.expandByPoint(yn),yn.addVectors(fi.max,Uc.max),fi.expandByPoint(yn)):(fi.expandByPoint(Uc.min),fi.expandByPoint(Uc.max))}fi.getCenter(i);let a=0;for(let s=0,o=e.count;s<o;s++)yn.fromBufferAttribute(e,s),a=Math.max(a,i.distanceToSquared(yn));if(t)for(let s=0,o=t.length;s<o;s++){const r=t[s],l=this.morphTargetsRelative;for(let c=0,p=r.count;c<p;c++)yn.fromBufferAttribute(r,c),l&&(Fr.fromBufferAttribute(e,c),yn.add(Fr)),a=Math.max(a,i.distanceToSquared(yn))}this.boundingSphere.radius=Math.sqrt(a),isNaN(this.boundingSphere.radius)&&Pt('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){Pt("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const i=t.position,a=t.normal,s=t.uv;let o=this.getAttribute("tangent");(o===void 0||o.count!==i.count)&&(o=new ra(new Float32Array(4*i.count),4),this.setAttribute("tangent",o));const r=[],l=[];for(let y=0;y<i.count;y++)r[y]=new X,l[y]=new X;const c=new X,p=new X,h=new X,d=new ut,u=new ut,f=new ut,v=new X,g=new X;function m(y,M,T){c.fromBufferAttribute(i,y),p.fromBufferAttribute(i,M),h.fromBufferAttribute(i,T),d.fromBufferAttribute(s,y),u.fromBufferAttribute(s,M),f.fromBufferAttribute(s,T),p.sub(c),h.sub(c),u.sub(d),f.sub(d);const L=1/(u.x*f.y-f.x*u.y);isFinite(L)&&(v.copy(p).multiplyScalar(f.y).addScaledVector(h,-u.y).multiplyScalar(L),g.copy(h).multiplyScalar(u.x).addScaledVector(p,-f.x).multiplyScalar(L),r[y].add(v),r[M].add(v),r[T].add(v),l[y].add(g),l[M].add(g),l[T].add(g))}let x=this.groups;x.length===0&&(x=[{start:0,count:e.count}]);for(let y=0,M=x.length;y<M;++y){const T=x[y],L=T.start,P=T.count;for(let z=L,R=L+P;z<R;z+=3)m(e.getX(z+0),e.getX(z+1),e.getX(z+2))}const _=new X,w=new X,S=new X,A=new X;function C(y){S.fromBufferAttribute(a,y),A.copy(S);const M=r[y];_.copy(M),_.sub(S.multiplyScalar(S.dot(M))).normalize(),w.crossVectors(A,M);const L=w.dot(l[y])<0?-1:1;o.setXYZW(y,_.x,_.y,_.z,L)}for(let y=0,M=x.length;y<M;++y){const T=x[y],L=T.start,P=T.count;for(let z=L,R=L+P;z<R;z+=3)C(e.getX(z+0)),C(e.getX(z+1)),C(e.getX(z+2))}this._transformed=!0}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(t!==void 0){let i=this.getAttribute("normal");if(i===void 0||i.count!==t.count)i=new ra(new Float32Array(t.count*3),3),this.setAttribute("normal",i);else for(let d=0,u=i.count;d<u;d++)i.setXYZ(d,0,0,0);const a=new X,s=new X,o=new X,r=new X,l=new X,c=new X,p=new X,h=new X;if(e)for(let d=0,u=e.count;d<u;d+=3){const f=e.getX(d+0),v=e.getX(d+1),g=e.getX(d+2);a.fromBufferAttribute(t,f),s.fromBufferAttribute(t,v),o.fromBufferAttribute(t,g),p.subVectors(o,s),h.subVectors(a,s),p.cross(h),r.fromBufferAttribute(i,f),l.fromBufferAttribute(i,v),c.fromBufferAttribute(i,g),r.add(p),l.add(p),c.add(p),i.setXYZ(f,r.x,r.y,r.z),i.setXYZ(v,l.x,l.y,l.z),i.setXYZ(g,c.x,c.y,c.z)}else for(let d=0,u=t.count;d<u;d+=3)a.fromBufferAttribute(t,d+0),s.fromBufferAttribute(t,d+1),o.fromBufferAttribute(t,d+2),p.subVectors(o,s),h.subVectors(a,s),p.cross(h),i.setXYZ(d+0,p.x,p.y,p.z),i.setXYZ(d+1,p.x,p.y,p.z),i.setXYZ(d+2,p.x,p.y,p.z);this.normalizeNormals(),i.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,i=e.count;t<i;t++)yn.fromBufferAttribute(e,t),yn.normalize(),e.setXYZ(t,yn.x,yn.y,yn.z)}toNonIndexed(){function e(r,l){const c=r.array,p=r.itemSize,h=r.normalized,d=new c.constructor(l.length*p);let u=0,f=0;for(let v=0,g=l.length;v<g;v++){r.isInterleavedBufferAttribute?u=l[v]*r.data.stride+r.offset:u=l[v]*p;for(let m=0;m<p;m++)d[f++]=c[u++]}return new ra(d,p,h)}if(this.index===null)return rt("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new pn,i=this.index.array,a=this.attributes;for(const r in a){const l=a[r],c=e(l,i);t.setAttribute(r,c)}const s=this.morphAttributes;for(const r in s){const l=[],c=s[r];for(let p=0,h=c.length;p<h;p++){const d=c[p],u=e(d,i);l.push(u)}t.morphAttributes[r]=l}t.morphTargetsRelative=this.morphTargetsRelative;const o=this.groups;for(let r=0,l=o.length;r<l;r++){const c=o[r];t.addGroup(c.start,c.count,c.materialIndex)}return t}toJSON(){const e={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.parameters!==void 0&&this._transformed===!0?"BufferGeometry":this.type,e.name=this.name,Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0&&this._transformed!==!0){const l=this.parameters;for(const c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const i=this.attributes;for(const l in i){const c=i[l];e.data.attributes[l]=c.toJSON(e.data)}const a={};let s=!1;for(const l in this.morphAttributes){const c=this.morphAttributes[l],p=[];for(let h=0,d=c.length;h<d;h++){const u=c[h];p.push(u.toJSON(e.data))}p.length>0&&(a[l]=p,s=!0)}s&&(e.data.morphAttributes=a,e.data.morphTargetsRelative=this.morphTargetsRelative);const o=this.groups;o.length>0&&(e.data.groups=JSON.parse(JSON.stringify(o)));const r=this.boundingSphere;return r!==null&&(e.data.boundingSphere=r.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const i=e.index;i!==null&&this.setIndex(i.clone());const a=e.attributes;for(const c in a){const p=a[c];this.setAttribute(c,p.clone(t))}const s=e.morphAttributes;for(const c in s){const p=[],h=s[c];for(let d=0,u=h.length;d<u;d++)p.push(h[d].clone(t));this.morphAttributes[c]=p}this.morphTargetsRelative=e.morphTargetsRelative;const o=e.groups;for(let c=0,p=o.length;c<p;c++){const h=o[c];this.addGroup(h.start,h.count,h.materialIndex)}const r=e.boundingBox;r!==null&&(this.boundingBox=r.clone());const l=e.boundingSphere;return l!==null&&(this.boundingSphere=l.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this._transformed=e._transformed,this}dispose(){this.dispatchEvent({type:"dispose"})}}const Yv=new X,f5=new X,m5=new pt;class Va{constructor(e=new X(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,i,a){return this.normal.set(e,t,i),this.constant=a,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,i){const a=Yv.subVectors(i,t).cross(f5.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(a,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const 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,i=!0){const a=e.delta(Yv),s=this.normal.dot(a);if(s===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const o=-(e.start.dot(this.normal)+this.constant)/s;return i===!0&&(o<0||o>1)?null:t.copy(e.start).addScaledVector(a,o)}intersectsLine(e){const t=this.distanceToPoint(e.start),i=this.distanceToPoint(e.end);return t<0&&i>0||i<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){const i=t||m5.getNormalMatrix(e),a=this.coplanarPoint(Yv).applyMatrix4(e),s=this.normal.applyMatrix3(i).normalize();return this.constant=-a.dot(s),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)}toJSON(){return{normal:this.normal.toArray(),constant:this.constant}}fromJSON(e){return this.normal.fromArray(e.normal),this.constant=e.constant,this}}let g5=0;class Br extends Rs{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:g5++}),this.uuid=Pc(),this.name="",this.type="Material",this.blending=Ar,this.side=wo,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=m2,this.blendDst=g2,this.blendEquation=Tr,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new It(0,0,0),this.blendAlpha=0,this.depthFunc=Cc,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=D4,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Av,this.stencilZFail=Av,this.stencilZPass=Av,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.allowOverride=!0,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(const t in e){const i=e[t];if(i===void 0){rt(`Material: parameter '${t}' has value of undefined.`);continue}const a=this[t];if(a===void 0){rt(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}a&&a.isColor?a.set(i):a&&a.isVector2&&i&&i.isVector2||a&&a.isEuler&&i&&i.isEuler||a&&a.isVector3&&i&&i.isVector3?a.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const i={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};i.uuid=this.uuid,i.type=this.type,i.blending=this.blending,i.side=this.side,i.shadowSide=this.shadowSide,i.vertexColors=this.vertexColors,i.opacity=this.opacity,i.transparent=this.transparent,i.blendSrc=this.blendSrc,i.blendDst=this.blendDst,i.blendEquation=this.blendEquation,i.blendSrcAlpha=this.blendSrcAlpha,i.blendDstAlpha=this.blendDstAlpha,i.blendEquationAlpha=this.blendEquationAlpha,i.blendColor=this.blendColor.getHex(),i.blendAlpha=this.blendAlpha,i.depthFunc=this.depthFunc,i.depthTest=this.depthTest,i.depthWrite=this.depthWrite,i.colorWrite=this.colorWrite,i.clipIntersection=this.clipIntersection,i.clipShadows=this.clipShadows,i.stencilWriteMask=this.stencilWriteMask,i.stencilFunc=this.stencilFunc,i.stencilRef=this.stencilRef,i.stencilFuncMask=this.stencilFuncMask,i.stencilFail=this.stencilFail,i.stencilZFail=this.stencilZFail,i.stencilZPass=this.stencilZPass,i.stencilWrite=this.stencilWrite,i.polygonOffset=this.polygonOffset,i.polygonOffsetFactor=this.polygonOffsetFactor,i.polygonOffsetUnits=this.polygonOffsetUnits,i.dithering=this.dithering,i.alphaTest=this.alphaTest,i.alphaHash=this.alphaHash,i.alphaToCoverage=this.alphaToCoverage,i.premultipliedAlpha=this.premultipliedAlpha,i.forceSinglePass=this.forceSinglePass,i.allowOverride=this.allowOverride,i.visible=this.visible,i.toneMapped=this.toneMapped,i.name=this.name,this.color&&this.color.isColor&&(i.color=this.color.getHex()),this.roughness!==void 0&&(i.roughness=this.roughness),this.metalness!==void 0&&(i.metalness=this.metalness),this.sheen!==void 0&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(i.shininess=this.shininess),this.clearcoat!==void 0&&(i.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(i.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(i.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(i.dispersion=this.dispersion),this.retroreflectivity!==void 0&&(i.retroreflectivity=this.retroreflectivity),this.iridescence!==void 0&&(i.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(i.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(i.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(e).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(e).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(e).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(e).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(e).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(i.combine=this.combine)),this.envMapRotation!==void 0&&(i.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(i.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(i.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&(i.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(i.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(i.size=this.size),this.sizeAttenuation!==void 0&&(i.sizeAttenuation=this.sizeAttenuation),Array.isArray(this.clippingPlanes)&&this.clippingPlanes.length>0&&(i.clippingPlanes=this.clippingPlanes.map(s=>s.toJSON())),this.rotation!==void 0&&(i.rotation=this.rotation),this.depthPacking!==void 0&&(i.depthPacking=this.depthPacking),this.linewidth!==void 0&&(i.linewidth=this.linewidth),this.linecap!==void 0&&(i.linecap=this.linecap),this.linejoin!==void 0&&(i.linejoin=this.linejoin),this.dashSize!==void 0&&(i.dashSize=this.dashSize),this.gapSize!==void 0&&(i.gapSize=this.gapSize),this.scale!==void 0&&(i.scale=this.scale),this.wireframe!==void 0&&(i.wireframe=this.wireframe),this.wireframeLinewidth!==void 0&&(i.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!==void 0&&(i.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!==void 0&&(i.wireframeLinejoin=this.wireframeLinejoin),this.flatShading!==void 0&&(i.flatShading=this.flatShading),this.fog!==void 0&&(i.fog=this.fog),Object.keys(this.userData).length>0&&(i.userData=this.userData);function a(s){const o=[];for(const r in s){const l=s[r];delete l.metadata,o.push(l)}return o}if(t){const s=a(e.textures),o=a(e.images);s.length>0&&(i.textures=s),o.length>0&&(i.images=o)}return i}fromJSON(e,t){if(e.uuid!==void 0&&(this.uuid=e.uuid),e.name!==void 0&&(this.name=e.name),e.color!==void 0&&this.color!==void 0&&this.color.setHex(e.color),e.roughness!==void 0&&(this.roughness=e.roughness),e.metalness!==void 0&&(this.metalness=e.metalness),e.sheen!==void 0&&(this.sheen=e.sheen),e.sheenColor!==void 0&&(this.sheenColor=new It().setHex(e.sheenColor)),e.sheenRoughness!==void 0&&(this.sheenRoughness=e.sheenRoughness),e.emissive!==void 0&&this.emissive!==void 0&&this.emissive.setHex(e.emissive),e.specular!==void 0&&this.specular!==void 0&&this.specular.setHex(e.specular),e.specularIntensity!==void 0&&(this.specularIntensity=e.specularIntensity),e.specularColor!==void 0&&this.specularColor!==void 0&&this.specularColor.setHex(e.specularColor),e.shininess!==void 0&&(this.shininess=e.shininess),e.clearcoat!==void 0&&(this.clearcoat=e.clearcoat),e.clearcoatRoughness!==void 0&&(this.clearcoatRoughness=e.clearcoatRoughness),e.dispersion!==void 0&&(this.dispersion=e.dispersion),e.retroreflectivity!==void 0&&(this.retroreflectivity=e.retroreflectivity),e.iridescence!==void 0&&(this.iridescence=e.iridescence),e.iridescenceIOR!==void 0&&(this.iridescenceIOR=e.iridescenceIOR),e.iridescenceThicknessRange!==void 0&&(this.iridescenceThicknessRange=e.iridescenceThicknessRange),e.transmission!==void 0&&(this.transmission=e.transmission),e.thickness!==void 0&&(this.thickness=e.thickness),e.attenuationDistance!==void 0&&(this.attenuationDistance=e.attenuationDistance),e.attenuationColor!==void 0&&this.attenuationColor!==void 0&&this.attenuationColor.setHex(e.attenuationColor),e.anisotropy!==void 0&&(this.anisotropy=e.anisotropy),e.anisotropyRotation!==void 0&&(this.anisotropyRotation=e.anisotropyRotation),e.fog!==void 0&&(this.fog=e.fog),e.flatShading!==void 0&&(this.flatShading=e.flatShading),e.blending!==void 0&&(this.blending=e.blending),e.combine!==void 0&&(this.combine=e.combine),e.side!==void 0&&(this.side=e.side),e.shadowSide!==void 0&&(this.shadowSide=e.shadowSide),e.opacity!==void 0&&(this.opacity=e.opacity),e.transparent!==void 0&&(this.transparent=e.transparent),e.alphaTest!==void 0&&(this.alphaTest=e.alphaTest),e.alphaHash!==void 0&&(this.alphaHash=e.alphaHash),e.depthFunc!==void 0&&(this.depthFunc=e.depthFunc),e.depthTest!==void 0&&(this.depthTest=e.depthTest),e.depthWrite!==void 0&&(this.depthWrite=e.depthWrite),e.colorWrite!==void 0&&(this.colorWrite=e.colorWrite),e.clippingPlanes!==void 0&&(this.clippingPlanes=e.clippingPlanes.map(i=>new Va().fromJSON(i))),e.clipIntersection!==void 0&&(this.clipIntersection=e.clipIntersection),e.clipShadows!==void 0&&(this.clipShadows=e.clipShadows),e.depthPacking!==void 0&&(this.depthPacking=e.depthPacking),e.blendSrc!==void 0&&(this.blendSrc=e.blendSrc),e.blendDst!==void 0&&(this.blendDst=e.blendDst),e.blendEquation!==void 0&&(this.blendEquation=e.blendEquation),e.blendSrcAlpha!==void 0&&(this.blendSrcAlpha=e.blendSrcAlpha),e.blendDstAlpha!==void 0&&(this.blendDstAlpha=e.blendDstAlpha),e.blendEquationAlpha!==void 0&&(this.blendEquationAlpha=e.blendEquationAlpha),e.blendColor!==void 0&&this.blendColor!==void 0&&this.blendColor.setHex(e.blendColor),e.blendAlpha!==void 0&&(this.blendAlpha=e.blendAlpha),e.stencilWriteMask!==void 0&&(this.stencilWriteMask=e.stencilWriteMask),e.stencilFunc!==void 0&&(this.stencilFunc=e.stencilFunc),e.stencilRef!==void 0&&(this.stencilRef=e.stencilRef),e.stencilFuncMask!==void 0&&(this.stencilFuncMask=e.stencilFuncMask),e.stencilFail!==void 0&&(this.stencilFail=e.stencilFail),e.stencilZFail!==void 0&&(this.stencilZFail=e.stencilZFail),e.stencilZPass!==void 0&&(this.stencilZPass=e.stencilZPass),e.stencilWrite!==void 0&&(this.stencilWrite=e.stencilWrite),e.wireframe!==void 0&&(this.wireframe=e.wireframe),e.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=e.wireframeLinewidth),e.wireframeLinecap!==void 0&&(this.wireframeLinecap=e.wireframeLinecap),e.wireframeLinejoin!==void 0&&(this.wireframeLinejoin=e.wireframeLinejoin),e.rotation!==void 0&&(this.rotation=e.rotation),e.linewidth!==void 0&&(this.linewidth=e.linewidth),e.linecap!==void 0&&(this.linecap=e.linecap),e.linejoin!==void 0&&(this.linejoin=e.linejoin),e.dashSize!==void 0&&(this.dashSize=e.dashSize),e.gapSize!==void 0&&(this.gapSize=e.gapSize),e.scale!==void 0&&(this.scale=e.scale),e.polygonOffset!==void 0&&(this.polygonOffset=e.polygonOffset),e.polygonOffsetFactor!==void 0&&(this.polygonOffsetFactor=e.polygonOffsetFactor),e.polygonOffsetUnits!==void 0&&(this.polygonOffsetUnits=e.polygonOffsetUnits),e.dithering!==void 0&&(this.dithering=e.dithering),e.alphaToCoverage!==void 0&&(this.alphaToCoverage=e.alphaToCoverage),e.premultipliedAlpha!==void 0&&(this.premultipliedAlpha=e.premultipliedAlpha),e.forceSinglePass!==void 0&&(this.forceSinglePass=e.forceSinglePass),e.allowOverride!==void 0&&(this.allowOverride=e.allowOverride),e.visible!==void 0&&(this.visible=e.visible),e.toneMapped!==void 0&&(this.toneMapped=e.toneMapped),e.userData!==void 0&&(this.userData=e.userData),e.vertexColors!==void 0&&(typeof e.vertexColors=="number"?this.vertexColors=e.vertexColors>0:this.vertexColors=e.vertexColors),e.size!==void 0&&(this.size=e.size),e.sizeAttenuation!==void 0&&(this.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(this.map=t[e.map]||null),e.matcap!==void 0&&(this.matcap=t[e.matcap]||null),e.alphaMap!==void 0&&(this.alphaMap=t[e.alphaMap]||null),e.bumpMap!==void 0&&(this.bumpMap=t[e.bumpMap]||null),e.bumpScale!==void 0&&(this.bumpScale=e.bumpScale),e.normalMap!==void 0&&(this.normalMap=t[e.normalMap]||null),e.normalMapType!==void 0&&(this.normalMapType=e.normalMapType),e.normalScale!==void 0){let i=e.normalScale;Array.isArray(i)===!1&&(i=[i,i]),this.normalScale=new ut().fromArray(i)}return e.displacementMap!==void 0&&(this.displacementMap=t[e.displacementMap]||null),e.displacementScale!==void 0&&(this.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(this.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(this.roughnessMap=t[e.roughnessMap]||null),e.metalnessMap!==void 0&&(this.metalnessMap=t[e.metalnessMap]||null),e.emissiveMap!==void 0&&(this.emissiveMap=t[e.emissiveMap]||null),e.emissiveIntensity!==void 0&&(this.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(this.specularMap=t[e.specularMap]||null),e.specularIntensityMap!==void 0&&(this.specularIntensityMap=t[e.specularIntensityMap]||null),e.specularColorMap!==void 0&&(this.specularColorMap=t[e.specularColorMap]||null),e.envMap!==void 0&&(this.envMap=t[e.envMap]||null),e.envMapRotation!==void 0&&this.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(this.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(this.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(this.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(this.lightMap=t[e.lightMap]||null),e.lightMapIntensity!==void 0&&(this.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(this.aoMap=t[e.aoMap]||null),e.aoMapIntensity!==void 0&&(this.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(this.gradientMap=t[e.gradientMap]||null),e.clearcoatMap!==void 0&&(this.clearcoatMap=t[e.clearcoatMap]||null),e.clearcoatRoughnessMap!==void 0&&(this.clearcoatRoughnessMap=t[e.clearcoatRoughnessMap]||null),e.clearcoatNormalMap!==void 0&&(this.clearcoatNormalMap=t[e.clearcoatNormalMap]||null),e.clearcoatNormalScale!==void 0&&(this.clearcoatNormalScale=new ut().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(this.iridescenceMap=t[e.iridescenceMap]||null),e.iridescenceThicknessMap!==void 0&&(this.iridescenceThicknessMap=t[e.iridescenceThicknessMap]||null),e.transmissionMap!==void 0&&(this.transmissionMap=t[e.transmissionMap]||null),e.thicknessMap!==void 0&&(this.thicknessMap=t[e.thicknessMap]||null),e.anisotropyMap!==void 0&&(this.anisotropyMap=t[e.anisotropyMap]||null),e.sheenColorMap!==void 0&&(this.sheenColorMap=t[e.sheenColorMap]||null),e.sheenRoughnessMap!==void 0&&(this.sheenRoughnessMap=t[e.sheenRoughnessMap]||null),this}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;const t=e.clippingPlanes;let i=null;if(t!==null){const a=t.length;i=new Array(a);for(let s=0;s!==a;++s)i[s]=t[s].clone()}return this.clippingPlanes=i,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.allowOverride=e.allowOverride,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++}}const Wa=new X,jv=new X,kh=new X,_h=new X;class Sh{constructor(e=new X,t=new X(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,Wa)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const i=t.dot(this.direction);return i<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Wa.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Wa.copy(this.origin).addScaledVector(this.direction,t),Wa.distanceToSquared(e))}distanceSqToSegment(e,t,i,a){jv.copy(e).add(t).multiplyScalar(.5),kh.copy(t).sub(e).normalize(),_h.copy(this.origin).sub(jv);const s=e.distanceTo(t)*.5,o=-this.direction.dot(kh),r=_h.dot(this.direction),l=-_h.dot(kh),c=_h.lengthSq(),p=Math.abs(1-o*o);let h,d,u,f;if(p>0)if(h=o*l-r,d=o*r-l,f=s*p,h>=0)if(d>=-f)if(d<=f){const v=1/p;h*=v,d*=v,u=h*(h+o*d+2*r)+d*(o*h+d+2*l)+c}else d=s,h=Math.max(0,-(o*d+r)),u=-h*h+d*(d+2*l)+c;else d=-s,h=Math.max(0,-(o*d+r)),u=-h*h+d*(d+2*l)+c;else d<=-f?(h=Math.max(0,-(-o*s+r)),d=h>0?-s:Math.min(Math.max(-s,-l),s),u=-h*h+d*(d+2*l)+c):d<=f?(h=0,d=Math.min(Math.max(-s,-l),s),u=d*(d+2*l)+c):(h=Math.max(0,-(o*s+r)),d=h>0?s:Math.min(Math.max(-s,-l),s),u=-h*h+d*(d+2*l)+c);else d=o>0?-s:s,h=Math.max(0,-(o*d+r)),u=-h*h+d*(d+2*l)+c;return i&&i.copy(this.origin).addScaledVector(this.direction,h),a&&a.copy(jv).addScaledVector(kh,d),u}intersectSphere(e,t){if(e.radius<0)return null;Wa.subVectors(e.center,this.origin);const i=Wa.dot(this.direction),a=Wa.dot(Wa)-i*i,s=e.radius*e.radius;if(a>s)return null;const o=Math.sqrt(s-a),r=i-o,l=i+o;return l<0?null:r<0?this.at(l,t):this.at(r,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const i=-(this.origin.dot(e.normal)+e.constant)/t;return i>=0?i:null}intersectPlane(e,t){const i=this.distanceToPlane(e);return i===null?null:this.at(i,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let i,a,s,o,r,l;const c=1/this.direction.x,p=1/this.direction.y,h=1/this.direction.z,d=this.origin;return c>=0?(i=(e.min.x-d.x)*c,a=(e.max.x-d.x)*c):(i=(e.max.x-d.x)*c,a=(e.min.x-d.x)*c),p>=0?(s=(e.min.y-d.y)*p,o=(e.max.y-d.y)*p):(s=(e.max.y-d.y)*p,o=(e.min.y-d.y)*p),i>o||s>a||((s>i||isNaN(i))&&(i=s),(o<a||isNaN(a))&&(a=o),h>=0?(r=(e.min.z-d.z)*h,l=(e.max.z-d.z)*h):(r=(e.max.z-d.z)*h,l=(e.min.z-d.z)*h),i>l||r>a)||((r>i||i!==i)&&(i=r),(l<a||a!==a)&&(a=l),a<0)?null:this.at(i>=0?i:a,t)}intersectsBox(e){return this.intersectBox(e,Wa)!==null}intersectTriangle(e,t,i,a,s){const o=this.origin,r=this.direction,l=r.x,c=r.y,p=r.z,h=e.x-o.x,d=e.y-o.y,u=e.z-o.z,f=t.x-o.x,v=t.y-o.y,g=t.z-o.z,m=i.x-o.x,x=i.y-o.y,_=i.z-o.z,w=Math.abs(l),S=Math.abs(c),A=Math.abs(p);let C,y,M,T,L,P,z,R,B,K,N,V;if(w>=S&&w>=A?(M=l,P=h,B=f,V=m,l>=0?(C=c,y=p,T=d,L=u,z=v,R=g,K=x,N=_):(C=p,y=c,T=u,L=d,z=g,R=v,K=_,N=x)):S>=A?(M=c,P=d,B=v,V=x,c>=0?(C=p,y=l,T=u,L=h,z=g,R=f,K=_,N=m):(C=l,y=p,T=h,L=u,z=f,R=g,K=m,N=_)):(M=p,P=u,B=g,V=_,p>=0?(C=l,y=c,T=h,L=d,z=f,R=v,K=m,N=x):(C=c,y=l,T=d,L=h,z=v,R=f,K=x,N=m)),M===0)return null;const Z=C/M,te=y/M,ce=1/M,Ne=T-Z*P,He=L-te*P,ct=z-Z*B,ot=R-te*B,ft=K-Z*V,ne=N-te*V,oe=ft*ot-ne*ct,Te=Ne*ne-He*ft,We=ct*He-ot*Ne;if(a){if(oe<0||Te<0||We<0)return null}else if((oe<0||Te<0||We<0)&&(oe>0||Te>0||We>0))return null;const Re=oe+Te+We;if(Re===0)return null;const $=ce*(oe*P+Te*B+We*V);return(Re>0?$<0:$>0)?null:this.at($/Re,s)}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)}}class ek extends Br{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new It(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 Ao,this.combine=v2,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}}const tk=new en,Co=new Sh,Mh=new Oc,nk=new X,Ah=new X,Th=new X,Eh=new X,Zv=new X,Ch=new X,ik=new X,Rh=new X;class Xa extends Wn{constructor(e=new pn,t=new ek){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,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(){const t=this.geometry.morphAttributes,i=Object.keys(t);if(i.length>0){const a=t[i[0]];if(a!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=a.length;s<o;s++){const r=a[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[r]=s}}}}getVertexPosition(e,t){const i=this.geometry,a=i.attributes.position,s=i.morphAttributes.position,o=i.morphTargetsRelative;t.fromBufferAttribute(a,e);const r=this.morphTargetInfluences;if(s&&r){Ch.set(0,0,0);for(let l=0,c=s.length;l<c;l++){const p=r[l],h=s[l];p!==0&&(Zv.fromBufferAttribute(h,e),o?Ch.addScaledVector(Zv,p):Ch.addScaledVector(Zv.sub(t),p))}t.add(Ch)}return t}intersectsFrustum(e){return e.intersectsObject(this)}raycast(e,t){const i=this.geometry,a=this.material,s=this.matrixWorld;a!==void 0&&(i.boundingSphere===null&&i.computeBoundingSphere(),Mh.copy(i.boundingSphere),Mh.applyMatrix4(s),Co.copy(e.ray).recast(e.near),!(Mh.containsPoint(Co.origin)===!1&&(Co.intersectSphere(Mh,nk)===null||Co.origin.distanceToSquared(nk)>(e.far-e.near)**2))&&(tk.copy(s).invert(),Co.copy(e.ray).applyMatrix4(tk),!(i.boundingBox!==null&&Co.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(e,t,Co)))}_computeIntersections(e,t,i){let a;const s=this.geometry,o=this.material,r=s.index,l=s.attributes.position,c=s.attributes.uv,p=s.attributes.uv1,h=s.attributes.normal,d=s.groups,u=s.drawRange;if(r!==null)if(Array.isArray(o))for(let f=0,v=d.length;f<v;f++){const g=d[f],m=o[g.materialIndex],x=Math.max(g.start,u.start),_=Math.min(r.count,Math.min(g.start+g.count,u.start+u.count));for(let w=x,S=_;w<S;w+=3){const A=r.getX(w),C=r.getX(w+1),y=r.getX(w+2);a=Lh(this,m,e,i,c,p,h,A,C,y),a&&(a.faceIndex=Math.floor(w/3),a.face.materialIndex=g.materialIndex,t.push(a))}}else{const f=Math.max(0,u.start),v=Math.min(r.count,u.start+u.count);for(let g=f,m=v;g<m;g+=3){const x=r.getX(g),_=r.getX(g+1),w=r.getX(g+2);a=Lh(this,o,e,i,c,p,h,x,_,w),a&&(a.faceIndex=Math.floor(g/3),t.push(a))}}else if(l!==void 0)if(Array.isArray(o))for(let f=0,v=d.length;f<v;f++){const g=d[f],m=o[g.materialIndex],x=Math.max(g.start,u.start),_=Math.min(l.count,Math.min(g.start+g.count,u.start+u.count));for(let w=x,S=_;w<S;w+=3){const A=w,C=w+1,y=w+2;a=Lh(this,m,e,i,c,p,h,A,C,y),a&&(a.faceIndex=Math.floor(w/3),a.face.materialIndex=g.materialIndex,t.push(a))}}else{const f=Math.max(0,u.start),v=Math.min(l.count,u.start+u.count);for(let g=f,m=v;g<m;g+=3){const x=g,_=g+1,w=g+2;a=Lh(this,o,e,i,c,p,h,x,_,w),a&&(a.faceIndex=Math.floor(g/3),t.push(a))}}}}function v5(n,e,t,i,a,s,o,r){let l;if(e.side===ei?l=i.intersectTriangle(o,s,a,!0,r):l=i.intersectTriangle(a,s,o,e.side===wo,r),l===null)return null;Rh.copy(r),Rh.applyMatrix4(n.matrixWorld);const c=t.ray.origin.distanceTo(Rh);return c<t.near||c>t.far?null:{distance:c,point:Rh.clone(),object:n}}function Lh(n,e,t,i,a,s,o,r,l,c){n.getVertexPosition(r,Ah),n.getVertexPosition(l,Th),n.getVertexPosition(c,Eh);const p=v5(n,e,t,i,Ah,Th,Eh,ik);if(p){const h=new X;zi.getBarycoord(ik,Ah,Th,Eh,h),a&&(p.uv=zi.getInterpolatedAttribute(a,r,l,c,h,new ut)),s&&(p.uv1=zi.getInterpolatedAttribute(s,r,l,c,h,new ut)),o&&(p.normal=zi.getInterpolatedAttribute(o,r,l,c,h,new X),p.normal.dot(i.direction)>0&&p.normal.multiplyScalar(-1));const d={a:r,b:l,c,normal:new X,materialIndex:0};zi.getNormal(Ah,Th,Eh,d.normal),p.face=d,p.barycoord=h}return p}class x5 extends Vn{constructor(e=null,t=1,i=1,a,s,o,r,l,c=Sn,p=Sn,h,d){super(null,o,r,l,c,p,a,s,h,d),this.isDataTexture=!0,this.image={data:e,width:t,height:i},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const Ro=new Oc,b5=new ut(.5,.5),Ph=new X;class ak{constructor(e=new Va,t=new Va,i=new Va,a=new Va,s=new Va,o=new Va){this.planes=[e,t,i,a,s,o]}set(e,t,i,a,s,o){const r=this.planes;return r[0].copy(e),r[1].copy(t),r[2].copy(i),r[3].copy(a),r[4].copy(s),r[5].copy(o),this}copy(e){const t=this.planes;for(let i=0;i<6;i++)t[i].copy(e.planes[i]);return this}setFromProjectionMatrix(e,t=oa,i=!1){const a=this.planes,s=e.elements,o=s[0],r=s[1],l=s[2],c=s[3],p=s[4],h=s[5],d=s[6],u=s[7],f=s[8],v=s[9],g=s[10],m=s[11],x=s[12],_=s[13],w=s[14],S=s[15];if(a[0].setComponents(c-o,u-p,m-f,S-x).normalize(),a[1].setComponents(c+o,u+p,m+f,S+x).normalize(),a[2].setComponents(c+r,u+h,m+v,S+_).normalize(),a[3].setComponents(c-r,u-h,m-v,S-_).normalize(),i)a[4].setComponents(l,d,g,w).normalize(),a[5].setComponents(c-l,u-d,m-g,S-w).normalize();else if(a[4].setComponents(c-l,u-d,m-g,S-w).normalize(),t===oa)a[5].setComponents(c+l,u+d,m+g,S+w).normalize();else if(t===ph)a[5].setComponents(l,d,g,w).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(),Ro.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Ro.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Ro)}intersectsSprite(e){Ro.center.set(0,0,0);const t=b5.distanceTo(e.center);return Ro.radius=.7071067811865476+t,Ro.applyMatrix4(e.matrixWorld),this.intersectsSphere(Ro)}intersectsSphere(e){const t=this.planes,i=e.center,a=-e.radius;for(let s=0;s<6;s++)if(t[s].distanceToPoint(i)<a)return!1;return!0}intersectsBox(e){const t=this.planes;for(let i=0;i<6;i++){const a=t[i];if(Ph.x=a.normal.x>0?e.max.x:e.min.x,Ph.y=a.normal.y>0?e.max.y:e.min.y,Ph.z=a.normal.z>0?e.max.z:e.min.z,a.distanceToPoint(Ph)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let i=0;i<6;i++)if(t[i].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class y5 extends Br{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new It(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}}const Ih=new X,$h=new X,sk=new en,Fc=new Sh,Nh=new Oc,Jv=new X,ok=new X;class w5 extends Wn{constructor(e=new pn,t=new y5){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,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(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,i=[0];for(let a=1,s=t.count;a<s;a++)Ih.fromBufferAttribute(t,a-1),$h.fromBufferAttribute(t,a),i[a]=i[a-1],i[a]+=Ih.distanceTo($h);e.setAttribute("lineDistance",new Ui(i,1))}else rt("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}intersectsFrustum(e){return e.intersectsObject(this)}raycast(e,t){const i=this.geometry,a=this.matrixWorld,s=e.params.Line.threshold,o=i.drawRange;if(i.boundingSphere===null&&i.computeBoundingSphere(),Nh.copy(i.boundingSphere),Nh.applyMatrix4(a),Nh.radius+=s,e.ray.intersectsSphere(Nh)===!1)return;sk.copy(a).invert(),Fc.copy(e.ray).applyMatrix4(sk);const r=s/((this.scale.x+this.scale.y+this.scale.z)/3),l=r*r,c=this.isLineSegments?2:1,p=i.index,d=i.attributes.position;if(p!==null){const u=Math.max(0,o.start),f=Math.min(p.count,o.start+o.count);for(let v=u,g=f-1;v<g;v+=c){const m=p.getX(v),x=p.getX(v+1),_=Dh(this,e,Fc,l,m,x,v);_&&t.push(_)}if(this.isLineLoop){const v=p.getX(f-1),g=p.getX(u),m=Dh(this,e,Fc,l,v,g,f-1);m&&t.push(m)}}else{const u=Math.max(0,o.start),f=Math.min(d.count,o.start+o.count);for(let v=u,g=f-1;v<g;v+=c){const m=Dh(this,e,Fc,l,v,v+1,v);m&&t.push(m)}if(this.isLineLoop){const v=Dh(this,e,Fc,l,f-1,u,f-1);v&&t.push(v)}}}updateMorphTargets(){const t=this.geometry.morphAttributes,i=Object.keys(t);if(i.length>0){const a=t[i[0]];if(a!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=a.length;s<o;s++){const r=a[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[r]=s}}}}}function Dh(n,e,t,i,a,s,o){const r=n.geometry.attributes.position;if(Ih.fromBufferAttribute(r,a),$h.fromBufferAttribute(r,s),t.distanceSqToSegment(Ih,$h,Jv,ok)>i)return;Jv.applyMatrix4(n.matrixWorld);const c=e.ray.origin.distanceTo(Jv);if(!(c<e.near||c>e.far))return{distance:c,point:ok.clone().applyMatrix4(n.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:n}}const rk=new X,lk=new X;class Qv extends w5{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,i=[];for(let a=0,s=t.count;a<s;a+=2)rk.fromBufferAttribute(t,a),lk.fromBufferAttribute(t,a+1),i[a]=a===0?0:i[a-1],i[a+1]=i[a]+rk.distanceTo(lk);e.setAttribute("lineDistance",new Ui(i,1))}else rt("LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class k5 extends Br{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new It(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}}const ck=new en,ex=new Sh,zh=new Oc,Oh=new X;class tx extends Wn{constructor(e=new pn,t=new k5){super(),this.isPoints=!0,this.type="Points",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,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}intersectsFrustum(e){return e.intersectsObject(this)}raycast(e,t){const i=this.geometry,a=this.matrixWorld,s=e.params.Points.threshold,o=i.drawRange;if(i.boundingSphere===null&&i.computeBoundingSphere(),zh.copy(i.boundingSphere),zh.applyMatrix4(a),zh.radius+=s,e.ray.intersectsSphere(zh)===!1)return;ck.copy(a).invert(),ex.copy(e.ray).applyMatrix4(ck);const r=s/((this.scale.x+this.scale.y+this.scale.z)/3),l=r*r,c=i.index,h=i.attributes.position;if(c!==null){const d=Math.max(0,o.start),u=Math.min(c.count,o.start+o.count);for(let f=d,v=u;f<v;f++){const g=c.getX(f);Oh.fromBufferAttribute(h,g),dk(Oh,g,l,a,e,t,this)}}else{const d=Math.max(0,o.start),u=Math.min(h.count,o.start+o.count);for(let f=d,v=u;f<v;f++)Oh.fromBufferAttribute(h,f),dk(Oh,f,l,a,e,t,this)}}updateMorphTargets(){const t=this.geometry.morphAttributes,i=Object.keys(t);if(i.length>0){const a=t[i[0]];if(a!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=a.length;s<o;s++){const r=a[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[r]=s}}}}}function dk(n,e,t,i,a,s,o){const r=ex.distanceSqToPoint(n);if(r<t){const l=new X;ex.closestPointToPoint(n,l),l.applyMatrix4(i);const c=a.ray.origin.distanceTo(l);if(c<a.near||c>a.far)return;s.push({distance:c,distanceToRay:Math.sqrt(r),point:l,index:e,face:null,faceIndex:null,barycoord:null,object:o})}}class pk extends Vn{constructor(e=[],t=ko,i,a,s,o,r,l,c,p){super(e,t,i,a,s,o,r,l,c,p),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Bc extends Vn{constructor(e,t,i=ia,a,s,o,r=Sn,l=Sn,c,p=Ua,h=1){if(p!==Ua&&p!==So)throw new Error("THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const d={width:e,height:t,depth:h};super(d,a,s,o,r,l,p,i,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Iv(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return t.compareFunction=this.compareFunction,t}}class _5 extends Bc{constructor(e,t=ia,i=ko,a,s,o=Sn,r=Sn,l,c=Ua){const p={width:e,height:e,depth:1},h=[p,p,p,p,p,p];super(e,e,t,i,a,s,o,r,l,c),this.image=h,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class hk extends Vn{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class Hc extends pn{constructor(e=1,t=1,i=1,a=1,s=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:i,widthSegments:a,heightSegments:s,depthSegments:o};const r=this;a=Math.floor(a),s=Math.floor(s),o=Math.floor(o);const l=[],c=[],p=[],h=[];let d=0,u=0;f("z","y","x",-1,-1,i,t,e,o,s,0),f("z","y","x",1,-1,i,t,-e,o,s,1),f("x","z","y",1,1,e,i,t,a,o,2),f("x","z","y",1,-1,e,i,-t,a,o,3),f("x","y","z",1,-1,e,t,i,a,s,4),f("x","y","z",-1,-1,e,t,-i,a,s,5),this.setIndex(l),this.setAttribute("position",new Ui(c,3)),this.setAttribute("normal",new Ui(p,3)),this.setAttribute("uv",new Ui(h,2));function f(v,g,m,x,_,w,S,A,C,y,M){const T=w/C,L=S/y,P=w/2,z=S/2,R=A/2,B=C+1,K=y+1;let N=0,V=0;const Z=new X;for(let te=0;te<K;te++){const ce=te*L-z;for(let Ne=0;Ne<B;Ne++){const He=Ne*T-P;Z[v]=He*x,Z[g]=ce*_,Z[m]=R,c.push(Z.x,Z.y,Z.z),Z[v]=0,Z[g]=0,Z[m]=A>0?1:-1,p.push(Z.x,Z.y,Z.z),h.push(Ne/C),h.push(1-te/y),N+=1}}for(let te=0;te<y;te++)for(let ce=0;ce<C;ce++){const Ne=d+ce+B*te,He=d+ce+B*(te+1),ct=d+(ce+1)+B*(te+1),ot=d+(ce+1)+B*te;l.push(Ne,He,ot),l.push(He,ct,ot),V+=6}r.addGroup(u,V,M),u+=V,d+=N}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Hc(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}class Uh extends pn{constructor(e=1,t=1,i=1,a=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:i,heightSegments:a};const s=e/2,o=t/2,r=Math.floor(i),l=Math.floor(a),c=r+1,p=l+1,h=e/r,d=t/l,u=[],f=[],v=[],g=[];for(let m=0;m<p;m++){const x=m*d-o;for(let _=0;_<c;_++){const w=_*h-s;f.push(w,-x,0),v.push(0,0,1),g.push(_/r),g.push(1-m/l)}}for(let m=0;m<l;m++)for(let x=0;x<r;x++){const _=x+c*m,w=x+c*(m+1),S=x+1+c*(m+1),A=x+1+c*m;u.push(_,w,A),u.push(w,S,A)}this.setIndex(u),this.setAttribute("position",new Ui(f,3)),this.setAttribute("normal",new Ui(v,3)),this.setAttribute("uv",new Ui(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Uh(e.width,e.height,e.widthSegments,e.heightSegments)}}function Hr(n){const e={};for(const t in n){e[t]={};for(const i in n[t]){const a=n[t][i];if(uk(a))a.isRenderTargetTexture?(rt("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][i]=null):e[t][i]=a.clone();else if(Array.isArray(a))if(uk(a[0])){const s=[];for(let o=0,r=a.length;o<r;o++)s[o]=a[o].clone();e[t][i]=s}else e[t][i]=a.slice();else e[t][i]=a}}return e}function Xn(n){const e={};for(let t=0;t<n.length;t++){const i=Hr(n[t]);for(const a in i)e[a]=i[a]}return e}function uk(n){return n&&(n.isColor||n.isMatrix3||n.isMatrix4||n.isVector2||n.isVector3||n.isVector4||n.isTexture||n.isQuaternion)}function S5(n){const e=[];for(let t=0;t<n.length;t++)e.push(n[t].clone());return e}function fk(n){const e=n.getRenderTarget();return e===null?n.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:St.workingColorSpace}const M5={clone:Hr,merge:Xn};var A5=`void main() {
4285
+ </div>`,nR(e),Qp()}function nR(n){const e=U("#axQ"),t=U("#axQx"),i=()=>{t.hidden=!e.value,U("#axQWrap").classList.toggle("has",!!e.value)};i();const a=ol(()=>{ue.q=e.value.trim(),As=Ss,qn(!1)},140);e.oninput=()=>{i(),a()},e.onkeydown=p=>{p.key==="Escape"&&e.value&&(p.stopPropagation(),e.value="",i(),ue.q="",qn(!1))},t.onclick=()=>{e.value="",i(),ue.q="",qn(!1),e.focus()},U("#axFilt").onclick=()=>J3({scoped:Tc,agents:()=>t2(Tc()),changed:p=>{As=Ss,p==="time"?(Yp=Mg,Es()):qn(!1)}}),U("#axViews").onclick=p=>{const h=p.target.closest("[data-view]");h&&Cg(h.dataset.view)},U("#axChips").onclick=p=>{const h=p.target;if(h.closest("[data-open]"))return U("#axFilt").click();if(h.closest("[data-clear]")){const u=ue.time!=="7d";Om(),ue.q="",e.value="",i(),As=Ss,u?Es():qn(!1);return}const d=h.closest("[data-rm]");d&&iR(d.dataset.rm)},U("#axSum").onclick=p=>{p.target.closest("#axCompact")&&(jp=!jp,qn(!1))};const s=U("#axBody");ar(s,p=>ea.find(h=>h.id===p),r2),s.addEventListener("click",p=>{const h=p.target,d=f=>h.closest(f);let u;if(d("[data-more]"))As+=Ss,qn(!0);else if(d("[data-older]"))Yp+=Mg,Es(!0);else if(u=d("a[data-go]")){const f=p;if(f.metaKey||f.ctrlKey||f.shiftKey||f.button!==0)return;p.preventDefault(),Q4(u.dataset.go)}else if(u=d("[data-only]"))r2(u.dataset.only);else if(u=d("[data-f]")){const[f,...v]=u.dataset.f.split(":"),g=v.join(":");f==="cats"?ue.cats=new Set([g]):f==="actions"?ue.actions=new Set([g]):f==="agents"?ue.agents=new Set([g]):f==="srcs"&&(ue.srcs=new Set([g])),Cg("day")}else(u=d("[data-time]"))?(ue.time="all",ue.from=ue.to="",Es()):d("[data-clear]")&&(Om(!0),ue.q="",e.value="",i(),qn(!1))}),U("#axReload").onclick=()=>{_r=[],Es()},U("#lgLive").onclick=()=>{Pi=!Pi,Pi&&(c2(),Rg()),Qp()},U("#axExport").onclick=p=>so(p.currentTarget,[{label:"Export shown as JSON",icon:pe.download,run:()=>Np(Tc().filter(h=>Ra(h)),"json")},{label:"Export shown as CSV",icon:pe.download,run:()=>Np(Tc().filter(h=>Ra(h)),"csv")}]);const o=U("#axBar"),r=n.querySelector(".ax"),l=()=>{const p=parseFloat(getComputedStyle(n).paddingTop)||0;r.style.setProperty("--ax-pt",p+"px"),r.style.setProperty("--ax-stick",o.offsetHeight-p+"px")};l(),new ResizeObserver(l).observe(o);const c=()=>{if(ta!=="list")return;const h=n.scrollTop>0&&o.getBoundingClientRect().top<=n.getBoundingClientRect().top+1;o.classList.toggle("stuck",h)};n.addEventListener("scroll",c,{passive:!0})}function Cg(n){$a=n,z3(n),As=Ss,o2(),qn(!1);const e=Ts(),t=U("#axBar"),i=e.querySelector(".ax-sub");i&&e.scrollTop>i.offsetTop&&(e.scrollTop=Math.max(0,t.offsetTop))}function o2(){document.querySelectorAll("#axViews [data-view]").forEach(n=>n.setAttribute("aria-pressed",String(n.dataset.view===$a)))}function iR(n){const[e,...t]=n.split(":"),i=t.join(":");if(As=Ss,e==="time"){ue.time="7d",ue.from=ue.to="",Es();return}e==="cats"?ue.cats.delete(i):e==="actions"?ue.actions.delete(i):e==="srcs"?ue.srcs.delete(i):e==="agents"?ue.agents.delete(i):e==="status"&&ue.status.delete(i),qn(!1)}function r2(n){ue.agents=new Set([n]),Cg("day")}function aR(n){Dl(n,()=>zf(e=>{if(nC(e,ta==="agent"),!Pi){Ms.push(e),Qp();return}l2(e)}))}function l2(n){Kp.add(n.id),Fd(ea,n),!Eg&&(Eg=!0,setTimeout(()=>{Eg=!1,qn(!0)},150))}function c2(){const n=Ms;Ms=[],n.forEach(l2)}function Qp(){const n=document.getElementById("lgLive");if(!n)return;n.setAttribute("aria-pressed",String(Pi)),n.innerHTML=Pi?'<span class="cc-dot ok"></span>Live':`<span class="cc-dot idle"></span>Paused${Ms.length?` · ${Ms.length} new`:""}`,n.title=Pi?"Pause the live stream":"Resume the live stream";const e=U("#axNew");e.hidden=Pi||!Ms.length,e.textContent=`${Ms.length} new`,e.setAttribute("aria-label",`Show ${bn(Ms.length,"new event")}`),e.onclick=()=>{Pi=!0,c2(),Rg(),Qp(),Ts().scrollTo({top:0})}}const Rg=ol(()=>{Es(!0)},900);async function Es(n=!1){const e=++Tg;n||(Zp=!0,qn(!1));try{const t=_r.length?Promise.resolve(_r):tt("/api/keys").then(r=>Array.isArray(r)?r:r.keys||[]).catch(()=>[]),[i,a]=await Promise.all([Ud(R3(),Yp),t]);if(e!==Tg)return;_r=a;const s=i.length?i[0].ts:0,o=ea.filter(r=>r.live&&r.ts>s-15&&!i.some(l=>l.actor===r.actor&&l.action===r.action&&Math.abs(l.ts-r.ts)<15));for(const r of i){if(r.ok!==void 0&&!r.running)continue;const l=ea.find(c=>c.live&&c.actor===r.actor&&c.action===r.action&&Math.abs(c.ts-r.ts)<5);l&&!l.running&&(r.running=!1,r.ok=l.ok,r.ms=l.ms)}if(n&&ea.length){const r=new Set(ea.map(l=>l.actor+l.action+Math.round(l.ts)));i.forEach(l=>{r.has(l.actor+l.action+Math.round(l.ts))||Kp.add(l.id)})}e2=ue.time!=="1h"&&ue.time!=="today"&&i.filter(r=>r.source!=="auth").length>=Yp*.9,ea=[...o,...i]}catch(t){if(e!==Tg)return;Be("Could not load activity: "+t.message,"err")}Zp=!1,qn(n)}function sR(){const n=[`<button type="button" class="ax-chip time" data-open aria-label="${O(`Time: ${U1()}. Change filters`)}">${H1}<span class="t">${b(U1())}</span></button>`];ue.status.forEach(i=>n.push(gs("status:"+i,Ep.find(a=>a.id===i).label,"","Status "))),ue.cats.forEach(i=>n.push(gs("cats:"+i,rc.find(a=>a.id===i).label,`<i class="sw" style="--c:${ms[i]}"></i>`))),ue.actions.forEach(i=>n.push(gs("actions:"+i,cn(i),"","Action "))),ue.srcs.forEach(i=>n.push(gs("srcs:"+i,Nm.find(a=>a.id===i).label,"","Source "))),ue.agents.forEach(i=>n.push(gs("agents:"+i,i,qt(i,22)))),(n2()||ue.time!=="7d")&&n.push('<button type="button" class="ax-clear" data-clear>Clear all</button>'),U("#axChips").innerHTML=n.join("");const e=P3(),t=U("#axBadge");t.hidden=!e,t.textContent=String(e),U("#axFilt").setAttribute("aria-label",e?`Filters, ${e} active`:"Filters")}function oR(n){const e=n.filter(i=>lc(i)==="fail").length,t=new Set(n.map(i=>i.actor)).size;U("#axSum").innerHTML=Zp?"<span>Loading…</span>":`<span><b>${n.length}</b> ${n.length===1?"event":"events"}</span><span><b>${t}</b> ${t===1?"actor":"actors"}</span>${e?`<span class="bad"><b>${e}</b> failed</span>`:""}${$a==="day"?`<button type="button" class="ax-tgl" id="axCompact" aria-pressed="${jp}" title="Collapse repeated calls by the same agent"><i></i>Group repeats</button>`:""}`}function rR(){const n=Ts(),e=n.querySelector("#axBar")?.offsetHeight||0,t=n.getBoundingClientRect().top+e,i=n.querySelectorAll("#axBody [data-act],#axBody .ax-ag");let a=null;for(const l of i)if(l.getBoundingClientRect().bottom>t+40){a=l;break}if(!a||n.scrollTop<40)return()=>{};const s=a.dataset.act?`[data-act="${window.CSS.escape(a.dataset.act)}"]`:null,o=a.querySelector("[data-agent]")?.dataset.agent,r=a.getBoundingClientRect().top;return()=>{const l=s?n.querySelector(`#axBody ${s}`):o&&n.querySelector(`#axBody [data-agent="${window.CSS.escape(o)}"]`)?.closest(".ax-ag")||null;l&&(n.scrollTop+=l.getBoundingClientRect().top-r)}}function qn(n=!0){const e=document.getElementById("axBody");if(!e)return;sR();const t=Tc(),i=t.filter(o=>Ra(o));if(oR(i),Z3(),Zp){e.setAttribute("aria-busy","true"),e.innerHTML=Um($a);return}e.removeAttribute("aria-busy");const a={rows:i,agents:t2(t),fresh:Kp,limit:As,compact:jp,older:e2,narrowed:n2(),none:!t.length},s=n?rR():()=>{};e.innerHTML=$a==="agent"?X3(a):$a==="board"?K3(a):q1(a),s(),Kp.clear(),lR(e)}function lR(n){Jp?.disconnect();const e=n.querySelector("[data-more]");!e||typeof IntersectionObserver>"u"||(Jp=new IntersectionObserver(t=>{t.some(i=>i.isIntersecting)&&(Jp?.disconnect(),As+=Ss,qn(!0))},{root:Ts(),rootMargin:"0px 0px 300px 0px"}),Jp.observe(e))}const d2=["#5eead4","#7dd3fc","#a78bfa","#f472b6","#fbbf24","#86efac","#fb923c","#93c5fd","#e879f9","#facc15","#67e8f9","#fca5a5","#c4b5fd","#bef264"];function cR(n,e){return e&&/^#[0-9a-f]{6}$/i.test(e)?e:d2[n%d2.length]}function p2(n){const e=/^#?([0-9a-f]{6})$/i.exec(n.trim());if(!e)return[.6,.8,.9];const t=parseInt(e[1],16);return[(t>>16&255)/255,(t>>8&255)/255,(t&255)/255]}const Lg="186",Sr={ROTATE:0,DOLLY:1,PAN:2},Mr={ROTATE:0,PAN:1,DOLLY_PAN:2,DOLLY_ROTATE:3},dR=0,h2=1,pR=2,eh=1,hR=2,Ec=3,wo=0,ei=1,Na=2,Da=0,Ar=1,za=2,u2=3,f2=4,uR=5,Tr=100,fR=101,mR=102,gR=103,vR=104,xR=200,bR=201,yR=202,wR=203,m2=204,g2=205,kR=206,_R=207,SR=208,MR=209,AR=210,TR=211,ER=212,CR=213,RR=214,Pg=0,Ig=1,$g=2,Cc=3,Ng=4,Dg=5,zg=6,Og=7,v2=0,LR=1,PR=2,na=0,x2=1,b2=2,y2=3,w2=4,k2=5,_2=6,S2=7,M2=300,ko=301,Er=302,Ug=303,Fg=304,th=306,Bg=1e3,Oa=1001,Hg=1002,Sn=1003,IR=1004,nh=1005,Cn=1006,Gg=1007,_o=1008,xi=1009,A2=1010,T2=1011,Rc=1012,qg=1013,ia=1014,aa=1015,sa=1016,Vg=1017,Wg=1018,Lc=1020,E2=35902,C2=35899,R2=1021,L2=1022,Ii=1023,Ua=1026,So=1027,P2=1028,Xg=1029,Mo=1030,Kg=1031,Yg=1033,ih=33776,ah=33777,sh=33778,oh=33779,jg=35840,Zg=35841,Jg=35842,Qg=35843,ev=36196,tv=37492,nv=37496,iv=37488,av=37489,rh=37490,sv=37491,ov=37808,rv=37809,lv=37810,cv=37811,dv=37812,pv=37813,hv=37814,uv=37815,fv=37816,mv=37817,gv=37818,vv=37819,xv=37820,bv=37821,yv=36492,wv=36494,kv=36495,_v=36283,Sv=36284,lh=36285,Mv=36286,$R=3200,I2=0,NR=1,Cs="",bi="srgb",ch="srgb-linear",dh="linear",Bt="srgb",Av=7680,DR=519,zR=512,OR=513,UR=514,Tv=515,FR=516,BR=517,Ev=518,HR=519,GR=35044,qR=35048,$2="300 es",oa=2e3,ph=2001;function VR(n){for(let e=n.length-1;e>=0;--e)if(n[e]>=65535)return!0;return!1}function hh(n){return document.createElementNS("http://www.w3.org/1999/xhtml",n)}function WR(){const n=hh("canvas");return n.style.display="block",n}const N2={};function D2(...n){const e="THREE."+n.shift();console.log(e,...n)}function z2(n){const e=n[0];if(typeof e=="string"&&e.startsWith("TSL:")){const t=n[1];t&&t.isStackTrace?n[0]+=" "+t.getLocation():n[1]='Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'}return n}function rt(...n){n=z2(n);const e="THREE."+n.shift();{const t=n[0];t&&t.isStackTrace?console.warn(t.getError(e)):console.warn(e,...n)}}function Pt(...n){n=z2(n);const e="THREE."+n.shift();{const t=n[0];t&&t.isStackTrace?console.error(t.getError(e)):console.error(e,...n)}}function Cr(...n){const e=n.join(" ");e in N2||(N2[e]=!0,rt(...n))}function XR(n,e,t){return new Promise(function(i,a){function s(){switch(n.clientWaitSync(e,n.SYNC_FLUSH_COMMANDS_BIT,0)){case n.WAIT_FAILED:a();break;case n.TIMEOUT_EXPIRED:setTimeout(s,t);break;default:i()}}setTimeout(s,t)})}const KR={[Pg]:Ig,[$g]:zg,[Ng]:Og,[Cc]:Dg,[Ig]:Pg,[zg]:$g,[Og]:Ng,[Dg]:Cc};class Rs{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});const i=this._listeners;i[e]===void 0&&(i[e]=[]),i[e].indexOf(t)===-1&&i[e].push(t)}hasEventListener(e,t){const i=this._listeners;return i===void 0?!1:i[e]!==void 0&&i[e].indexOf(t)!==-1}removeEventListener(e,t){const i=this._listeners;if(i===void 0)return;const a=i[e];if(a!==void 0){const s=a.indexOf(t);s!==-1&&a.splice(s,1)}}dispatchEvent(e){const t=this._listeners;if(t===void 0)return;const i=t[e.type];if(i!==void 0){e.target=this;const a=i.slice(0);for(let s=0,o=a.length;s<o;s++)a[s].call(this,e);e.target=null}}}const Rn=["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"],uh=Math.PI/180,Cv=180/Math.PI;function Pc(){const n=Math.random()*4294967295|0,e=Math.random()*4294967295|0,t=Math.random()*4294967295|0,i=Math.random()*4294967295|0;return(Rn[n&255]+Rn[n>>8&255]+Rn[n>>16&255]+Rn[n>>24&255]+"-"+Rn[e&255]+Rn[e>>8&255]+"-"+Rn[e>>16&15|64]+Rn[e>>24&255]+"-"+Rn[t&63|128]+Rn[t>>8&255]+"-"+Rn[t>>16&255]+Rn[t>>24&255]+Rn[i&255]+Rn[i>>8&255]+Rn[i>>16&255]+Rn[i>>24&255]).toLowerCase()}function yt(n,e,t){return Math.max(e,Math.min(t,n))}function YR(n,e){return(n%e+e)%e}function Rv(n,e,t){return(1-t)*n+t*e}function Ic(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return n/4294967295;case Uint16Array:return n/65535;case Uint8Array:case Uint8ClampedArray:return n/255;case Int32Array:return Math.max(n/2147483647,-1);case Int16Array:return Math.max(n/32767,-1);case Int8Array:return Math.max(n/127,-1);default:throw new Error("THREE.MathUtils: Invalid component type.")}}function ti(n,e){switch(e.constructor){case Float32Array:return n;case Uint32Array:return Math.round(n*4294967295);case Uint16Array:return Math.round(n*65535);case Uint8Array:case Uint8ClampedArray:return Math.round(n*255);case Int32Array:return Math.round(n*2147483647);case Int16Array:return Math.round(n*32767);case Int8Array:return Math.round(n*127);default:throw new Error("THREE.MathUtils: Invalid component type.")}}const jR={DEG2RAD:uh},ab=class ab{constructor(e=0,t=0){this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("THREE.Vector2: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("THREE.Vector2: index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,i=this.y,a=e.elements;return this.x=a[0]*t+a[3]*i+a[6],this.y=a[1]*t+a[4]*i+a[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=yt(this.x,e.x,t.x),this.y=yt(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=yt(this.x,e,t),this.y=yt(this.y,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(yt(i,e,t))}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(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.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(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(yt(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y;return t*t+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const i=Math.cos(t),a=Math.sin(t),s=this.x-e.x,o=this.y-e.y;return this.x=s*i-o*a+e.x,this.y=s*a+o*i+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}};ab.prototype.isVector2=!0;let ut=ab;class Ls{constructor(e=0,t=0,i=0,a=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=i,this._w=a}static slerpFlat(e,t,i,a,s,o,r){let l=i[a+0],c=i[a+1],p=i[a+2],h=i[a+3],d=s[o+0],u=s[o+1],f=s[o+2],v=s[o+3];if(h!==v||l!==d||c!==u||p!==f){let g=l*d+c*u+p*f+h*v;g<0&&(d=-d,u=-u,f=-f,v=-v,g=-g);let m=1-r;if(g<.9995){const x=Math.acos(g),_=Math.sin(x);m=Math.sin(m*x)/_,r=Math.sin(r*x)/_,l=l*m+d*r,c=c*m+u*r,p=p*m+f*r,h=h*m+v*r}else{l=l*m+d*r,c=c*m+u*r,p=p*m+f*r,h=h*m+v*r;const x=1/Math.sqrt(l*l+c*c+p*p+h*h);l*=x,c*=x,p*=x,h*=x}}e[t]=l,e[t+1]=c,e[t+2]=p,e[t+3]=h}static multiplyQuaternionsFlat(e,t,i,a,s,o){const r=i[a],l=i[a+1],c=i[a+2],p=i[a+3],h=s[o],d=s[o+1],u=s[o+2],f=s[o+3];return e[t]=r*f+p*h+l*u-c*d,e[t+1]=l*f+p*d+c*h-r*u,e[t+2]=c*f+p*u+r*d-l*h,e[t+3]=p*f-r*h-l*d-c*u,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,i,a){return this._x=e,this._y=t,this._z=i,this._w=a,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){const i=e._x,a=e._y,s=e._z,o=e._order,r=Math.cos,l=Math.sin,c=r(i/2),p=r(a/2),h=r(s/2),d=l(i/2),u=l(a/2),f=l(s/2);switch(o){case"XYZ":this._x=d*p*h+c*u*f,this._y=c*u*h-d*p*f,this._z=c*p*f+d*u*h,this._w=c*p*h-d*u*f;break;case"YXZ":this._x=d*p*h+c*u*f,this._y=c*u*h-d*p*f,this._z=c*p*f-d*u*h,this._w=c*p*h+d*u*f;break;case"ZXY":this._x=d*p*h-c*u*f,this._y=c*u*h+d*p*f,this._z=c*p*f+d*u*h,this._w=c*p*h-d*u*f;break;case"ZYX":this._x=d*p*h-c*u*f,this._y=c*u*h+d*p*f,this._z=c*p*f-d*u*h,this._w=c*p*h+d*u*f;break;case"YZX":this._x=d*p*h+c*u*f,this._y=c*u*h+d*p*f,this._z=c*p*f-d*u*h,this._w=c*p*h-d*u*f;break;case"XZY":this._x=d*p*h-c*u*f,this._y=c*u*h-d*p*f,this._z=c*p*f+d*u*h,this._w=c*p*h+d*u*f;break;default:rt("Quaternion: .setFromEuler() encountered an unknown order: "+o)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const i=t/2,a=Math.sin(i);return this._x=e.x*a,this._y=e.y*a,this._z=e.z*a,this._w=Math.cos(i),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,i=t[0],a=t[4],s=t[8],o=t[1],r=t[5],l=t[9],c=t[2],p=t[6],h=t[10],d=i+r+h;if(d>0){const u=.5/Math.sqrt(d+1);this._w=.25/u,this._x=(p-l)*u,this._y=(s-c)*u,this._z=(o-a)*u}else if(i>r&&i>h){const u=2*Math.sqrt(1+i-r-h);this._w=(p-l)/u,this._x=.25*u,this._y=(a+o)/u,this._z=(s+c)/u}else if(r>h){const u=2*Math.sqrt(1+r-i-h);this._w=(s-c)/u,this._x=(a+o)/u,this._y=.25*u,this._z=(l+p)/u}else{const u=2*Math.sqrt(1+h-i-r);this._w=(o-a)/u,this._x=(s+c)/u,this._y=(l+p)/u,this._z=.25*u}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let i=e.dot(t)+1;return i<1e-8?(i=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=i):(this._x=0,this._y=-e.z,this._z=e.y,this._w=i)):(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=i),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(yt(this.dot(e),-1,1)))}rotateTowards(e,t){const i=this.angleTo(e);if(i===0)return this;const a=Math.min(1,t/i);return this.slerp(e,a),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){const i=e._x,a=e._y,s=e._z,o=e._w,r=t._x,l=t._y,c=t._z,p=t._w;return this._x=i*p+o*r+a*c-s*l,this._y=a*p+o*l+s*r-i*c,this._z=s*p+o*c+i*l-a*r,this._w=o*p-i*r-a*l-s*c,this._onChangeCallback(),this}slerp(e,t){let i=e._x,a=e._y,s=e._z,o=e._w,r=this.dot(e);r<0&&(i=-i,a=-a,s=-s,o=-o,r=-r);let l=1-t;if(r<.9995){const c=Math.acos(r),p=Math.sin(c);l=Math.sin(l*c)/p,t=Math.sin(t*c)/p,this._x=this._x*l+i*t,this._y=this._y*l+a*t,this._z=this._z*l+s*t,this._w=this._w*l+o*t,this._onChangeCallback()}else this._x=this._x*l+i*t,this._y=this._y*l+a*t,this._z=this._z*l+s*t,this._w=this._w*l+o*t,this.normalize();return this}slerpQuaternions(e,t,i){return this.copy(e).slerp(t,i)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),i=Math.random(),a=Math.sqrt(1-i),s=Math.sqrt(i);return this.set(a*Math.sin(e),a*Math.cos(e),s*Math.sin(t),s*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}}const sb=class sb{constructor(e=0,t=0,i=0){this.x=e,this.y=t,this.z=i}set(e,t,i){return i===void 0&&(i=this.z),this.x=e,this.y=t,this.z=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("THREE.Vector3: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("THREE.Vector3: index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(O2.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(O2.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,i=this.y,a=this.z,s=e.elements;return this.x=s[0]*t+s[3]*i+s[6]*a,this.y=s[1]*t+s[4]*i+s[7]*a,this.z=s[2]*t+s[5]*i+s[8]*a,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,i=this.y,a=this.z,s=e.elements,o=1/(s[3]*t+s[7]*i+s[11]*a+s[15]);return this.x=(s[0]*t+s[4]*i+s[8]*a+s[12])*o,this.y=(s[1]*t+s[5]*i+s[9]*a+s[13])*o,this.z=(s[2]*t+s[6]*i+s[10]*a+s[14])*o,this}applyQuaternion(e){const t=this.x,i=this.y,a=this.z,s=e.x,o=e.y,r=e.z,l=e.w,c=2*(o*a-r*i),p=2*(r*t-s*a),h=2*(s*i-o*t);return this.x=t+l*c+o*h-r*p,this.y=i+l*p+r*c-s*h,this.z=a+l*h+s*p-o*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,i=this.y,a=this.z,s=e.elements;return this.x=s[0]*t+s[4]*i+s[8]*a,this.y=s[1]*t+s[5]*i+s[9]*a,this.z=s[2]*t+s[6]*i+s[10]*a,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=yt(this.x,e.x,t.x),this.y=yt(this.y,e.y,t.y),this.z=yt(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=yt(this.x,e,t),this.y=yt(this.y,e,t),this.z=yt(this.z,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(yt(i,e,t))}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(e){return this.x*e.x+this.y*e.y+this.z*e.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(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const i=e.x,a=e.y,s=e.z,o=t.x,r=t.y,l=t.z;return this.x=a*l-s*r,this.y=s*o-i*l,this.z=i*r-a*o,this}projectOnVector(e){const t=e.lengthSq();if(t===0)return this.set(0,0,0);const i=e.dot(this)/t;return this.copy(e).multiplyScalar(i)}projectOnPlane(e){return Lv.copy(this).projectOnVector(e),this.sub(Lv)}reflect(e){return this.sub(Lv.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;const i=this.dot(e)/t;return Math.acos(yt(i,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,i=this.y-e.y,a=this.z-e.z;return t*t+i*i+a*a}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,i){const a=Math.sin(t)*e;return this.x=a*Math.sin(i),this.y=Math.cos(t)*e,this.z=a*Math.cos(i),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,i){return this.x=e*Math.sin(t),this.y=i,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),i=this.setFromMatrixColumn(e,1).length(),a=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=i,this.z=a,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=Math.random()*2-1,i=Math.sqrt(1-t*t);return this.x=i*Math.cos(e),this.y=t,this.z=i*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}};sb.prototype.isVector3=!0;let X=sb;const Lv=new X,O2=new Ls,ob=class ob{constructor(e,t,i,a,s,o,r,l,c){this.elements=[1,0,0,0,1,0,0,0,1],e!==void 0&&this.set(e,t,i,a,s,o,r,l,c)}set(e,t,i,a,s,o,r,l,c){const p=this.elements;return p[0]=e,p[1]=a,p[2]=r,p[3]=t,p[4]=s,p[5]=l,p[6]=i,p[7]=o,p[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],this}extractBasis(e,t,i){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),i.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,a=t.elements,s=this.elements,o=i[0],r=i[3],l=i[6],c=i[1],p=i[4],h=i[7],d=i[2],u=i[5],f=i[8],v=a[0],g=a[3],m=a[6],x=a[1],_=a[4],w=a[7],S=a[2],A=a[5],C=a[8];return s[0]=o*v+r*x+l*S,s[3]=o*g+r*_+l*A,s[6]=o*m+r*w+l*C,s[1]=c*v+p*x+h*S,s[4]=c*g+p*_+h*A,s[7]=c*m+p*w+h*C,s[2]=d*v+u*x+f*S,s[5]=d*g+u*_+f*A,s[8]=d*m+u*w+f*C,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[1],a=e[2],s=e[3],o=e[4],r=e[5],l=e[6],c=e[7],p=e[8];return t*o*p-t*r*c-i*s*p+i*r*l+a*s*c-a*o*l}invert(){const e=this.elements,t=e[0],i=e[1],a=e[2],s=e[3],o=e[4],r=e[5],l=e[6],c=e[7],p=e[8],h=p*o-r*c,d=r*l-p*s,u=c*s-o*l,f=t*h+i*d+a*u;if(f===0)return this.set(0,0,0,0,0,0,0,0,0);const v=1/f;return e[0]=h*v,e[1]=(a*c-p*i)*v,e[2]=(r*i-a*o)*v,e[3]=d*v,e[4]=(p*t-a*l)*v,e[5]=(a*s-r*t)*v,e[6]=u*v,e[7]=(i*l-c*t)*v,e[8]=(o*t-i*s)*v,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,i,a,s,o,r){const l=Math.cos(s),c=Math.sin(s);return this.set(i*l,i*c,-i*(l*o+c*r)+o+e,-a*c,a*l,-a*(-c*o+l*r)+r+t,0,0,1),this}scale(e,t){return Cr("Matrix3: .scale() is deprecated. Use .makeScale() instead."),this.premultiply(Pv.makeScale(e,t)),this}rotate(e){return Cr("Matrix3: .rotate() is deprecated. Use .makeRotation() instead."),this.premultiply(Pv.makeRotation(-e)),this}translate(e,t){return Cr("Matrix3: .translate() is deprecated. Use .makeTranslation() instead."),this.premultiply(Pv.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,i,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,i=e.elements;for(let a=0;a<9;a++)if(t[a]!==i[a])return!1;return!0}fromArray(e,t=0){for(let i=0;i<9;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e}clone(){return new this.constructor().fromArray(this.elements)}};ob.prototype.isMatrix3=!0;let pt=ob;const Pv=new pt,U2=new pt().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),F2=new pt().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function ZR(){const n={enabled:!0,workingColorSpace:ch,spaces:{},convert:function(a,s,o){return this.enabled===!1||s===o||!s||!o||(this.spaces[s].transfer===Bt&&(a.r=Fa(a.r),a.g=Fa(a.g),a.b=Fa(a.b)),this.spaces[s].primaries!==this.spaces[o].primaries&&(a.applyMatrix3(this.spaces[s].toXYZ),a.applyMatrix3(this.spaces[o].fromXYZ)),this.spaces[o].transfer===Bt&&(a.r=Rr(a.r),a.g=Rr(a.g),a.b=Rr(a.b))),a},workingToColorSpace:function(a,s){return this.convert(a,this.workingColorSpace,s)},colorSpaceToWorking:function(a,s){return this.convert(a,s,this.workingColorSpace)},getPrimaries:function(a){return this.spaces[a].primaries},getTransfer:function(a){return a===Cs?dh:this.spaces[a].transfer},getToneMappingMode:function(a){return this.spaces[a].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(a,s=this.workingColorSpace){return a.fromArray(this.spaces[s].luminanceCoefficients)},define:function(a){Object.assign(this.spaces,a)},_getMatrix:function(a,s,o){return a.copy(this.spaces[s].toXYZ).multiply(this.spaces[o].fromXYZ)},_getDrawingBufferColorSpace:function(a){return this.spaces[a].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(a=this.workingColorSpace){return this.spaces[a].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(a,s){return Cr("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),n.workingToColorSpace(a,s)},toWorkingColorSpace:function(a,s){return Cr("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),n.colorSpaceToWorking(a,s)}},e=[.64,.33,.3,.6,.15,.06],t=[.2126,.7152,.0722],i=[.3127,.329];return n.define({[ch]:{primaries:e,whitePoint:i,transfer:dh,toXYZ:U2,fromXYZ:F2,luminanceCoefficients:t,workingColorSpaceConfig:{unpackColorSpace:bi},outputColorSpaceConfig:{drawingBufferColorSpace:bi}},[bi]:{primaries:e,whitePoint:i,transfer:Bt,toXYZ:U2,fromXYZ:F2,luminanceCoefficients:t,outputColorSpaceConfig:{drawingBufferColorSpace:bi}}}),n}const St=ZR();function Fa(n){return n<.04045?n*.0773993808:Math.pow(n*.9478672986+.0521327014,2.4)}function Rr(n){return n<.0031308?n*12.92:1.055*Math.pow(n,.41666)-.055}let Lr;class JR{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>"u")return e.src;let i;if(e instanceof HTMLCanvasElement)i=e;else{Lr===void 0&&(Lr=hh("canvas")),Lr.width=e.width,Lr.height=e.height;const a=Lr.getContext("2d");e instanceof ImageData?a.putImageData(e,0,0):a.drawImage(e,0,0,e.width,e.height),i=Lr}return i.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap){const t=hh("canvas");t.width=e.width,t.height=e.height;const i=t.getContext("2d");i.drawImage(e,0,0,e.width,e.height);const a=i.getImageData(0,0,e.width,e.height),s=a.data;for(let o=0;o<s.length;o++)s[o]=Fa(s[o]/255)*255;return i.putImageData(a,0,0),t}else if(e.data){const t=e.data.slice(0);for(let i=0;i<t.length;i++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[i]=Math.floor(Fa(t[i]/255)*255):t[i]=Fa(t[i]);return{data:t,width:e.width,height:e.height}}else return rt("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let QR=0;class Iv{constructor(e=null){this.isTextureSource=!0,Object.defineProperty(this,"id",{value:QR++}),this.uuid=Pc(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){const t=this.data;return typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):typeof VideoFrame<"u"&&t instanceof VideoFrame?e.set(t.displayWidth,t.displayHeight,0):t!==null?e.set(t.width,t.height,t.depth||0):e.set(0,0,0),e}set needsUpdate(e){e===!0&&this.version++}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.images[this.uuid]!==void 0)return e.images[this.uuid];const i={uuid:this.uuid,url:""},a=this.data;if(a!==null){let s;if(Array.isArray(a)){s=[];for(let o=0,r=a.length;o<r;o++)a[o].isDataTexture?s.push($v(a[o].image)):s.push($v(a[o]))}else s=$v(a);i.url=s}return t||(e.images[this.uuid]=i),i}}function $v(n){return typeof HTMLImageElement<"u"&&n instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&n instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&n instanceof ImageBitmap?JR.getDataURL(n):n.data?{data:Array.from(n.data),width:n.width,height:n.height,type:n.data.constructor.name}:(rt("Texture: Unable to serialize Texture."),{})}let e5=0;const Nv=new X;class Vn extends Rs{constructor(e=Vn.DEFAULT_IMAGE,t=Vn.DEFAULT_MAPPING,i=Oa,a=Oa,s=Cn,o=_o,r=Ii,l=xi,c=Vn.DEFAULT_ANISOTROPY,p=Cs){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:e5++}),this.uuid=Pc(),this.name="",this.source=new Iv(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=i,this.wrapT=a,this.magFilter=s,this.minFilter=o,this.anisotropy=c,this.format=r,this.internalFormat=null,this.type=l,this.offset=new ut(0,0),this.repeat=new ut(1,1),this.center=new ut(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new pt,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=p,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0,this.normalized=!1}get width(){return this.source.getSize(Nv).x}get height(){return this.source.getSize(Nv).y}get depth(){return this.source.getSize(Nv).z}get image(){return this.source.data}set image(e){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.normalized=e.normalized,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const i=e[t];if(i===void 0){rt(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const a=this[t];if(a===void 0){rt(`Texture.setValues(): property '${t}' does not exist.`);continue}a&&i&&a.isVector2&&i.isVector2||a&&i&&a.isVector3&&i.isVector3||a&&i&&a.isMatrix3&&i.isMatrix3?a.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];const i={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).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,normalized:this.normalized,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),t||(e.textures[this.uuid]=i),i}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(this.mapping!==M2)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case Bg:e.x=e.x-Math.floor(e.x);break;case Oa:e.x=e.x<0?0:1;break;case Hg:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case Bg:e.y=e.y-Math.floor(e.y);break;case Oa:e.y=e.y<0?0:1;break;case Hg:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}}Vn.DEFAULT_IMAGE=null,Vn.DEFAULT_MAPPING=M2,Vn.DEFAULT_ANISOTROPY=1;const rb=class rb{constructor(e=0,t=0,i=0,a=1){this.x=e,this.y=t,this.z=i,this.w=a}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,i,a){return this.x=e,this.y=t,this.z=i,this.w=a,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("THREE.Vector4: index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("THREE.Vector4: index is out of range: "+e)}}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!==void 0?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,i=this.y,a=this.z,s=this.w,o=e.elements;return this.x=o[0]*t+o[4]*i+o[8]*a+o[12]*s,this.y=o[1]*t+o[5]*i+o[9]*a+o[13]*s,this.z=o[2]*t+o[6]*i+o[10]*a+o[14]*s,this.w=o[3]*t+o[7]*i+o[11]*a+o[15]*s,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,i,a,s;const l=e.elements,c=l[0],p=l[4],h=l[8],d=l[1],u=l[5],f=l[9],v=l[2],g=l[6],m=l[10];if(Math.abs(p-d)<.01&&Math.abs(h-v)<.01&&Math.abs(f-g)<.01){if(Math.abs(p+d)<.1&&Math.abs(h+v)<.1&&Math.abs(f+g)<.1&&Math.abs(c+u+m-3)<.1)return this.set(1,0,0,0),this;t=Math.PI;const _=(c+1)/2,w=(u+1)/2,S=(m+1)/2,A=(p+d)/4,C=(h+v)/4,y=(f+g)/4;return _>w&&_>S?_<.01?(i=0,a=.707106781,s=.707106781):(i=Math.sqrt(_),a=A/i,s=C/i):w>S?w<.01?(i=.707106781,a=0,s=.707106781):(a=Math.sqrt(w),i=A/a,s=y/a):S<.01?(i=.707106781,a=.707106781,s=0):(s=Math.sqrt(S),i=C/s,a=y/s),this.set(i,a,s,t),this}let x=Math.sqrt((g-f)*(g-f)+(h-v)*(h-v)+(d-p)*(d-p));return Math.abs(x)<.001&&(x=1),this.x=(g-f)/x,this.y=(h-v)/x,this.z=(d-p)/x,this.w=Math.acos((c+u+m-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=yt(this.x,e.x,t.x),this.y=yt(this.y,e.y,t.y),this.z=yt(this.z,e.z,t.z),this.w=yt(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=yt(this.x,e,t),this.y=yt(this.y,e,t),this.z=yt(this.z,e,t),this.w=yt(this.w,e,t),this}clampLength(e,t){const i=this.length();return this.divideScalar(i||1).multiplyScalar(yt(i,e,t))}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(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)}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(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,i){return this.x=e.x+(t.x-e.x)*i,this.y=e.y+(t.y-e.y)*i,this.z=e.z+(t.z-e.z)*i,this.w=e.w+(t.w-e.w)*i,this}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}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}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}};rb.prototype.isVector4=!0;let nn=rb;class t5 extends Rs{constructor(e=1,t=1,i={}){super(),i=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:Cn,depthBuffer:!0,stencilBuffer:!1,resolveColorBuffer:!0,resolveDepthBuffer:!0,resolveStencilBuffer:!0,storeMultisampledColorBuffer:!0,storeMultisampledDepthBuffer:!0,storeMultisampledStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1,useArrayDepthTexture:!1},i),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=i.depth,this.scissor=new nn(0,0,e,t),this.scissorTest=!1,this.viewport=new nn(0,0,e,t),this.textures=[];const a={width:e,height:t,depth:i.depth},s=new Vn(a),o=i.count;for(let r=0;r<o;r++)this.textures[r]=s.clone(),this.textures[r].isRenderTargetTexture=!0,this.textures[r].renderTarget=this;this._setTextureOptions(i),this.depthBuffer=i.depthBuffer,this.stencilBuffer=i.stencilBuffer,this.resolveColorBuffer=i.resolveColorBuffer,this.resolveDepthBuffer=i.resolveDepthBuffer,this.resolveStencilBuffer=i.resolveStencilBuffer,this.storeMultisampledColorBuffer=i.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=i.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=i.storeMultisampledStencilBuffer,this._depthTexture=null,this.depthTexture=i.depthTexture,this.samples=i.samples,this.multiview=i.multiview,this.useArrayDepthTexture=i.useArrayDepthTexture}_setTextureOptions(e={}){const t={minFilter:Cn,generateMipmaps:!1,flipY:!1,internalFormat:null};e.mapping!==void 0&&(t.mapping=e.mapping),e.wrapS!==void 0&&(t.wrapS=e.wrapS),e.wrapT!==void 0&&(t.wrapT=e.wrapT),e.wrapR!==void 0&&(t.wrapR=e.wrapR),e.magFilter!==void 0&&(t.magFilter=e.magFilter),e.minFilter!==void 0&&(t.minFilter=e.minFilter),e.format!==void 0&&(t.format=e.format),e.type!==void 0&&(t.type=e.type),e.anisotropy!==void 0&&(t.anisotropy=e.anisotropy),e.colorSpace!==void 0&&(t.colorSpace=e.colorSpace),e.flipY!==void 0&&(t.flipY=e.flipY),e.generateMipmaps!==void 0&&(t.generateMipmaps=e.generateMipmaps),e.internalFormat!==void 0&&(t.internalFormat=e.internalFormat);for(let i=0;i<this.textures.length;i++)this.textures[i].setValues(t)}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){this._depthTexture!==null&&this._depthTexture.renderTarget===this&&(this._depthTexture.renderTarget=null),e!==null&&e.renderTarget===null&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,i=1){if(this.width!==e||this.height!==t||this.depth!==i){this.width=e,this.height=t,this.depth=i;for(let a=0,s=this.textures.length;a<s;a++)this.textures[a].image.width=e,this.textures[a].image.height=t,this.textures[a].image.depth=i,this.textures[a].isData3DTexture!==!0&&(this.textures[a].isArrayTexture=this.textures[a].image.depth>1);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 t=0,i=e.textures.length;t<i;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;const a=Object.assign({},e.textures[t].image);this.textures[t].source=new Iv(a)}if(this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveColorBuffer=e.resolveColorBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,this.storeMultisampledColorBuffer=e.storeMultisampledColorBuffer,this.storeMultisampledDepthBuffer=e.storeMultisampledDepthBuffer,this.storeMultisampledStencilBuffer=e.storeMultisampledStencilBuffer,e.depthTexture!==null)if(e.depthTexture.renderTarget===e){const t=e.depthTexture.clone();t.renderTarget=null,this.depthTexture=t}else this.depthTexture=e.depthTexture;return this.samples=e.samples,this.multiview=e.multiview,this.useArrayDepthTexture=e.useArrayDepthTexture,this}dispose(){this.dispatchEvent({type:"dispose"})}}class $i extends t5{constructor(e=1,t=1,i={}){super(e,t,i),this.isWebGLRenderTarget=!0}}class B2 extends Vn{constructor(e=null,t=1,i=1,a=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:i,depth:a},this.magFilter=Sn,this.minFilter=Sn,this.wrapR=Oa,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class n5 extends Vn{constructor(e=null,t=1,i=1,a=1){super(null),this.isData3DTexture=!0,this.image={data:e,width:t,height:i,depth:a},this.magFilter=Sn,this.minFilter=Sn,this.wrapR=Oa,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}copy(e){return super.copy(e),this.wrapR=e.wrapR,this}}const xu=class xu{constructor(e,t,i,a,s,o,r,l,c,p,h,d,u,f,v,g){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],e!==void 0&&this.set(e,t,i,a,s,o,r,l,c,p,h,d,u,f,v,g)}set(e,t,i,a,s,o,r,l,c,p,h,d,u,f,v,g){const m=this.elements;return m[0]=e,m[4]=t,m[8]=i,m[12]=a,m[1]=s,m[5]=o,m[9]=r,m[13]=l,m[2]=c,m[6]=p,m[10]=h,m[14]=d,m[3]=u,m[7]=f,m[11]=v,m[15]=g,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return new xu().fromArray(this.elements)}copy(e){const t=this.elements,i=e.elements;return t[0]=i[0],t[1]=i[1],t[2]=i[2],t[3]=i[3],t[4]=i[4],t[5]=i[5],t[6]=i[6],t[7]=i[7],t[8]=i[8],t[9]=i[9],t[10]=i[10],t[11]=i[11],t[12]=i[12],t[13]=i[13],t[14]=i[14],t[15]=i[15],this}copyPosition(e){const t=this.elements,i=e.elements;return t[12]=i[12],t[13]=i[13],t[14]=i[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,i){return this.determinantAffine()===0?(e.set(1,0,0),t.set(0,1,0),i.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),i.setFromMatrixColumn(this,2),this)}makeBasis(e,t,i){return this.set(e.x,t.x,i.x,0,e.y,t.y,i.y,0,e.z,t.z,i.z,0,0,0,0,1),this}extractRotation(e){if(e.determinantAffine()===0)return this.identity();const t=this.elements,i=e.elements,a=1/Pr.setFromMatrixColumn(e,0).length(),s=1/Pr.setFromMatrixColumn(e,1).length(),o=1/Pr.setFromMatrixColumn(e,2).length();return t[0]=i[0]*a,t[1]=i[1]*a,t[2]=i[2]*a,t[3]=0,t[4]=i[4]*s,t[5]=i[5]*s,t[6]=i[6]*s,t[7]=0,t[8]=i[8]*o,t[9]=i[9]*o,t[10]=i[10]*o,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,i=e.x,a=e.y,s=e.z,o=Math.cos(i),r=Math.sin(i),l=Math.cos(a),c=Math.sin(a),p=Math.cos(s),h=Math.sin(s);if(e.order==="XYZ"){const d=o*p,u=o*h,f=r*p,v=r*h;t[0]=l*p,t[4]=-l*h,t[8]=c,t[1]=u+f*c,t[5]=d-v*c,t[9]=-r*l,t[2]=v-d*c,t[6]=f+u*c,t[10]=o*l}else if(e.order==="YXZ"){const d=l*p,u=l*h,f=c*p,v=c*h;t[0]=d+v*r,t[4]=f*r-u,t[8]=o*c,t[1]=o*h,t[5]=o*p,t[9]=-r,t[2]=u*r-f,t[6]=v+d*r,t[10]=o*l}else if(e.order==="ZXY"){const d=l*p,u=l*h,f=c*p,v=c*h;t[0]=d-v*r,t[4]=-o*h,t[8]=f+u*r,t[1]=u+f*r,t[5]=o*p,t[9]=v-d*r,t[2]=-o*c,t[6]=r,t[10]=o*l}else if(e.order==="ZYX"){const d=o*p,u=o*h,f=r*p,v=r*h;t[0]=l*p,t[4]=f*c-u,t[8]=d*c+v,t[1]=l*h,t[5]=v*c+d,t[9]=u*c-f,t[2]=-c,t[6]=r*l,t[10]=o*l}else if(e.order==="YZX"){const d=o*l,u=o*c,f=r*l,v=r*c;t[0]=l*p,t[4]=v-d*h,t[8]=f*h+u,t[1]=h,t[5]=o*p,t[9]=-r*p,t[2]=-c*p,t[6]=u*h+f,t[10]=d-v*h}else if(e.order==="XZY"){const d=o*l,u=o*c,f=r*l,v=r*c;t[0]=l*p,t[4]=-h,t[8]=c*p,t[1]=d*h+v,t[5]=o*p,t[9]=u*h-f,t[2]=f*h-u,t[6]=r*p,t[10]=v*h+d}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(i5,e,a5)}lookAt(e,t,i){const a=this.elements;return ui.subVectors(e,t),ui.lengthSq()===0&&(ui.z=1),ui.normalize(),Ps.crossVectors(i,ui),Ps.lengthSq()===0&&(Math.abs(i.z)===1?ui.x+=1e-4:ui.z+=1e-4,ui.normalize(),Ps.crossVectors(i,ui)),Ps.normalize(),fh.crossVectors(ui,Ps),a[0]=Ps.x,a[4]=fh.x,a[8]=ui.x,a[1]=Ps.y,a[5]=fh.y,a[9]=ui.y,a[2]=Ps.z,a[6]=fh.z,a[10]=ui.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const i=e.elements,a=t.elements,s=this.elements,o=i[0],r=i[4],l=i[8],c=i[12],p=i[1],h=i[5],d=i[9],u=i[13],f=i[2],v=i[6],g=i[10],m=i[14],x=i[3],_=i[7],w=i[11],S=i[15],A=a[0],C=a[4],y=a[8],M=a[12],T=a[1],L=a[5],P=a[9],z=a[13],R=a[2],B=a[6],K=a[10],N=a[14],V=a[3],Z=a[7],te=a[11],ce=a[15];return s[0]=o*A+r*T+l*R+c*V,s[4]=o*C+r*L+l*B+c*Z,s[8]=o*y+r*P+l*K+c*te,s[12]=o*M+r*z+l*N+c*ce,s[1]=p*A+h*T+d*R+u*V,s[5]=p*C+h*L+d*B+u*Z,s[9]=p*y+h*P+d*K+u*te,s[13]=p*M+h*z+d*N+u*ce,s[2]=f*A+v*T+g*R+m*V,s[6]=f*C+v*L+g*B+m*Z,s[10]=f*y+v*P+g*K+m*te,s[14]=f*M+v*z+g*N+m*ce,s[3]=x*A+_*T+w*R+S*V,s[7]=x*C+_*L+w*B+S*Z,s[11]=x*y+_*P+w*K+S*te,s[15]=x*M+_*z+w*N+S*ce,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],i=e[4],a=e[8],s=e[12],o=e[1],r=e[5],l=e[9],c=e[13],p=e[2],h=e[6],d=e[10],u=e[14],f=e[3],v=e[7],g=e[11],m=e[15],x=l*u-c*d,_=r*u-c*h,w=r*d-l*h,S=o*u-c*p,A=o*d-l*p,C=o*h-r*p;return t*(v*x-g*_+m*w)-i*(f*x-g*S+m*A)+a*(f*_-v*S+m*C)-s*(f*w-v*A+g*C)}determinantAffine(){const e=this.elements,t=e[0],i=e[4],a=e[8],s=e[1],o=e[5],r=e[9],l=e[2],c=e[6],p=e[10];return t*(o*p-r*c)-i*(s*p-r*l)+a*(s*c-o*l)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,i){const a=this.elements;return e.isVector3?(a[12]=e.x,a[13]=e.y,a[14]=e.z):(a[12]=e,a[13]=t,a[14]=i),this}invert(){const e=this.elements,t=e[0],i=e[1],a=e[2],s=e[3],o=e[4],r=e[5],l=e[6],c=e[7],p=e[8],h=e[9],d=e[10],u=e[11],f=e[12],v=e[13],g=e[14],m=e[15],x=t*r-i*o,_=t*l-a*o,w=t*c-s*o,S=i*l-a*r,A=i*c-s*r,C=a*c-s*l,y=p*v-h*f,M=p*g-d*f,T=p*m-u*f,L=h*g-d*v,P=h*m-u*v,z=d*m-u*g,R=x*z-_*P+w*L+S*T-A*M+C*y;if(R===0)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const B=1/R;return e[0]=(r*z-l*P+c*L)*B,e[1]=(a*P-i*z-s*L)*B,e[2]=(v*C-g*A+m*S)*B,e[3]=(d*A-h*C-u*S)*B,e[4]=(l*T-o*z-c*M)*B,e[5]=(t*z-a*T+s*M)*B,e[6]=(g*w-f*C-m*_)*B,e[7]=(p*C-d*w+u*_)*B,e[8]=(o*P-r*T+c*y)*B,e[9]=(i*T-t*P-s*y)*B,e[10]=(f*A-v*w+m*x)*B,e[11]=(h*w-p*A-u*x)*B,e[12]=(r*M-o*L-l*y)*B,e[13]=(t*L-i*M+a*y)*B,e[14]=(v*_-f*S-g*x)*B,e[15]=(p*S-h*_+d*x)*B,this}scale(e){const t=this.elements,i=e.x,a=e.y,s=e.z;return t[0]*=i,t[4]*=a,t[8]*=s,t[1]*=i,t[5]*=a,t[9]*=s,t[2]*=i,t[6]*=a,t[10]*=s,t[3]*=i,t[7]*=a,t[11]*=s,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],i=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],a=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,i,a))}makeTranslation(e,t,i){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,i,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),i=Math.sin(e);return this.set(1,0,0,0,0,t,-i,0,0,i,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,0,i,0,0,1,0,0,-i,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),i=Math.sin(e);return this.set(t,-i,0,0,i,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const i=Math.cos(t),a=Math.sin(t),s=1-i,o=e.x,r=e.y,l=e.z,c=s*o,p=s*r;return this.set(c*o+i,c*r-a*l,c*l+a*r,0,c*r+a*l,p*r+i,p*l-a*o,0,c*l-a*r,p*l+a*o,s*l*l+i,0,0,0,0,1),this}makeScale(e,t,i){return this.set(e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1),this}makeShear(e,t,i,a,s,o){return this.set(1,i,s,0,e,1,o,0,t,a,1,0,0,0,0,1),this}compose(e,t,i){const a=this.elements,s=t._x,o=t._y,r=t._z,l=t._w,c=s+s,p=o+o,h=r+r,d=s*c,u=s*p,f=s*h,v=o*p,g=o*h,m=r*h,x=l*c,_=l*p,w=l*h,S=i.x,A=i.y,C=i.z;return a[0]=(1-(v+m))*S,a[1]=(u+w)*S,a[2]=(f-_)*S,a[3]=0,a[4]=(u-w)*A,a[5]=(1-(d+m))*A,a[6]=(g+x)*A,a[7]=0,a[8]=(f+_)*C,a[9]=(g-x)*C,a[10]=(1-(d+v))*C,a[11]=0,a[12]=e.x,a[13]=e.y,a[14]=e.z,a[15]=1,this}decompose(e,t,i){const a=this.elements;e.x=a[12],e.y=a[13],e.z=a[14];const s=this.determinantAffine();if(s===0)return i.set(1,1,1),t.identity(),this;let o=Pr.set(a[0],a[1],a[2]).length();const r=Pr.set(a[4],a[5],a[6]).length(),l=Pr.set(a[8],a[9],a[10]).length();s<0&&(o=-o),Ni.copy(this);const c=1/o,p=1/r,h=1/l;return Ni.elements[0]*=c,Ni.elements[1]*=c,Ni.elements[2]*=c,Ni.elements[4]*=p,Ni.elements[5]*=p,Ni.elements[6]*=p,Ni.elements[8]*=h,Ni.elements[9]*=h,Ni.elements[10]*=h,t.setFromRotationMatrix(Ni),i.x=o,i.y=r,i.z=l,this}makePerspective(e,t,i,a,s,o,r=oa,l=!1){const c=this.elements,p=2*s/(t-e),h=2*s/(i-a),d=(t+e)/(t-e),u=(i+a)/(i-a);let f,v;if(l)f=s/(o-s),v=o*s/(o-s);else if(r===oa)f=-(o+s)/(o-s),v=-2*o*s/(o-s);else if(r===ph)f=-o/(o-s),v=-o*s/(o-s);else throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+r);return c[0]=p,c[4]=0,c[8]=d,c[12]=0,c[1]=0,c[5]=h,c[9]=u,c[13]=0,c[2]=0,c[6]=0,c[10]=f,c[14]=v,c[3]=0,c[7]=0,c[11]=-1,c[15]=0,this}makeOrthographic(e,t,i,a,s,o,r=oa,l=!1){const c=this.elements,p=2/(t-e),h=2/(i-a),d=-(t+e)/(t-e),u=-(i+a)/(i-a);let f,v;if(l)f=1/(o-s),v=o/(o-s);else if(r===oa)f=-2/(o-s),v=-(o+s)/(o-s);else if(r===ph)f=-1/(o-s),v=-s/(o-s);else throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+r);return c[0]=p,c[4]=0,c[8]=0,c[12]=d,c[1]=0,c[5]=h,c[9]=0,c[13]=u,c[2]=0,c[6]=0,c[10]=f,c[14]=v,c[3]=0,c[7]=0,c[11]=0,c[15]=1,this}equals(e){const t=this.elements,i=e.elements;for(let a=0;a<16;a++)if(t[a]!==i[a])return!1;return!0}fromArray(e,t=0){for(let i=0;i<16;i++)this.elements[i]=e[i+t];return this}toArray(e=[],t=0){const i=this.elements;return e[t]=i[0],e[t+1]=i[1],e[t+2]=i[2],e[t+3]=i[3],e[t+4]=i[4],e[t+5]=i[5],e[t+6]=i[6],e[t+7]=i[7],e[t+8]=i[8],e[t+9]=i[9],e[t+10]=i[10],e[t+11]=i[11],e[t+12]=i[12],e[t+13]=i[13],e[t+14]=i[14],e[t+15]=i[15],e}};xu.prototype.isMatrix4=!0;let en=xu;const Pr=new X,Ni=new en,i5=new X(0,0,0),a5=new X(1,1,1),Ps=new X,fh=new X,ui=new X,H2=new en,G2=new Ls;class Ao{constructor(e=0,t=0,i=0,a=Ao.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=i,this._order=a}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 order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,i,a=this._order){return this._x=e,this._y=t,this._z=i,this._order=a,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,i=!0){const a=e.elements,s=a[0],o=a[4],r=a[8],l=a[1],c=a[5],p=a[9],h=a[2],d=a[6],u=a[10];switch(t){case"XYZ":this._y=Math.asin(yt(r,-1,1)),Math.abs(r)<.9999999?(this._x=Math.atan2(-p,u),this._z=Math.atan2(-o,s)):(this._x=Math.atan2(d,c),this._z=0);break;case"YXZ":this._x=Math.asin(-yt(p,-1,1)),Math.abs(p)<.9999999?(this._y=Math.atan2(r,u),this._z=Math.atan2(l,c)):(this._y=Math.atan2(-h,s),this._z=0);break;case"ZXY":this._x=Math.asin(yt(d,-1,1)),Math.abs(d)<.9999999?(this._y=Math.atan2(-h,u),this._z=Math.atan2(-o,c)):(this._y=0,this._z=Math.atan2(l,s));break;case"ZYX":this._y=Math.asin(-yt(h,-1,1)),Math.abs(h)<.9999999?(this._x=Math.atan2(d,u),this._z=Math.atan2(l,s)):(this._x=0,this._z=Math.atan2(-o,c));break;case"YZX":this._z=Math.asin(yt(l,-1,1)),Math.abs(l)<.9999999?(this._x=Math.atan2(-p,c),this._y=Math.atan2(-h,s)):(this._x=0,this._y=Math.atan2(r,u));break;case"XZY":this._z=Math.asin(-yt(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(d,c),this._y=Math.atan2(r,s)):(this._x=Math.atan2(-p,u),this._y=0);break;default:rt("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,i===!0&&this._onChangeCallback(),this}setFromQuaternion(e,t,i){return H2.makeRotationFromQuaternion(e),this.setFromRotationMatrix(H2,t,i)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return G2.setFromEuler(this),this.setFromQuaternion(G2,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],e[3]!==void 0&&(this._order=e[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._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}Ao.DEFAULT_ORDER="XYZ";class q2{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}}let s5=0;const V2=new X,Ir=new Ls,Ba=new en,mh=new X,$c=new X,o5=new X,r5=new Ls,W2=new X(1,0,0),X2=new X(0,1,0),K2=new X(0,0,1),Y2={type:"added"},l5={type:"removed"},$r={type:"childadded",child:null},Dv={type:"childremoved",child:null};class Wn extends Rs{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:s5++}),this.uuid=Pc(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Wn.DEFAULT_UP.clone();const e=new X,t=new Ao,i=new Ls,a=new X(1,1,1);function s(){i.setFromEuler(t,!1)}function o(){t.setFromQuaternion(i,void 0,!1)}t._onChange(s),i._onChange(o),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:i},scale:{configurable:!0,enumerable:!0,value:a},modelViewMatrix:{value:new en},normalMatrix:{value:new pt}}),this.matrix=new en,this.matrixWorld=new en,this.matrixAutoUpdate=Wn.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Wn.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new q2,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.static=!1,this.userData={},this.pivot=null}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return Ir.setFromAxisAngle(e,t),this.quaternion.multiply(Ir),this}rotateOnWorldAxis(e,t){return Ir.setFromAxisAngle(e,t),this.quaternion.premultiply(Ir),this}rotateX(e){return this.rotateOnAxis(W2,e)}rotateY(e){return this.rotateOnAxis(X2,e)}rotateZ(e){return this.rotateOnAxis(K2,e)}translateOnAxis(e,t){return V2.copy(e).applyQuaternion(this.quaternion),this.position.add(V2.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(W2,e)}translateY(e){return this.translateOnAxis(X2,e)}translateZ(e){return this.translateOnAxis(K2,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Ba.copy(this.matrixWorld).invert())}lookAt(e,t,i){e.isVector3?mh.copy(e):mh.set(e,t,i);const a=this.parent;this.updateWorldMatrix(!0,!1),$c.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Ba.lookAt($c,mh,this.up):Ba.lookAt(mh,$c,this.up),this.quaternion.setFromRotationMatrix(Ba),a&&(Ba.extractRotation(a.matrixWorld),Ir.setFromRotationMatrix(Ba),this.quaternion.premultiply(Ir.invert()))}add(e){if(arguments.length>1){for(let t=0;t<arguments.length;t++)this.add(arguments[t]);return this}return e===this?(Pt("Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(Y2),$r.child=e,this.dispatchEvent($r),$r.child=null):Pt("Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let i=0;i<arguments.length;i++)this.remove(arguments[i]);return this}const t=this.children.indexOf(e);return t!==-1&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(l5),Dv.child=e,this.dispatchEvent(Dv),Dv.child=null),this}removeFromParent(){const e=this.parent;return e!==null&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),Ba.copy(this.matrixWorld).invert(),e.parent!==null&&(e.parent.updateWorldMatrix(!0,!1),Ba.multiply(e.parent.matrixWorld)),e.applyMatrix4(Ba),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Y2),$r.child=e,this.dispatchEvent($r),$r.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let i=0,a=this.children.length;i<a;i++){const o=this.children[i].getObjectByProperty(e,t);if(o!==void 0)return o}}getObjectsByProperty(e,t,i=[]){this[e]===t&&i.push(this);const a=this.children;for(let s=0,o=a.length;s<o;s++)a[s].getObjectsByProperty(e,t,i);return i}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose($c,e,o5),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose($c,r5,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}intersectsFrustum(){}traverse(e){e(this);const t=this.children;for(let i=0,a=t.length;i<a;i++)t[i].traverse(e)}traverseVisible(e){if(this.visible===!1)return;e(this);const t=this.children;for(let i=0,a=t.length;i<a;i++)t[i].traverseVisible(e)}traverseAncestors(e){const t=this.parent;t!==null&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale);const e=this.pivot;if(e!==null){const t=e.x,i=e.y,a=e.z,s=this.matrix.elements;s[12]+=t-s[0]*t-s[4]*i-s[8]*a,s[13]+=i-s[1]*t-s[5]*i-s[9]*a,s[14]+=a-s[2]*t-s[6]*i-s[10]*a}this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let i=0,a=t.length;i<a;i++)t[i].updateMatrixWorld(e)}updateWorldMatrix(e,t,i=!1){const a=this.parent;if(e===!0&&a!==null&&a.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||i)&&(this.matrixWorldAutoUpdate===!0&&(this.parent===null?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,i=!0),t===!0){const s=this.children;for(let o=0,r=s.length;o<r;o++)s[o].updateWorldMatrix(!1,!0,i)}}toJSON(e){const t=e===void 0||typeof e=="string",i={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},i.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const a={};a.uuid=this.uuid,a.type=this.type,a.name=this.name,a.castShadow=this.castShadow,a.receiveShadow=this.receiveShadow,a.visible=this.visible,a.frustumCulled=this.frustumCulled,a.renderOrder=this.renderOrder,a.static=this.static,a.matrixAutoUpdate=this.matrixAutoUpdate,Object.keys(this.userData).length>0&&(a.userData=this.userData),a.layers=this.layers.mask,a.matrix=this.matrix.toArray(),a.up=this.up.toArray(),this.pivot!==null&&(a.pivot=this.pivot.toArray()),this.morphTargetDictionary!==void 0&&(a.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(a.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(a.type="InstancedMesh",a.count=this.count,a.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(a.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(a.type="BatchedMesh",a.perObjectFrustumCulled=this.perObjectFrustumCulled,a.sortObjects=this.sortObjects,a.drawRanges=this._drawRanges,a.reservedRanges=this._reservedRanges,a.geometryInfo=this._geometryInfo.map(r=>({...r,boundingBox:r.boundingBox?r.boundingBox.toJSON():void 0,boundingSphere:r.boundingSphere?r.boundingSphere.toJSON():void 0})),a.instanceInfo=this._instanceInfo.map(r=>({...r})),a.availableInstanceIds=this._availableInstanceIds.slice(),a.availableGeometryIds=this._availableGeometryIds.slice(),a.nextIndexStart=this._nextIndexStart,a.nextVertexStart=this._nextVertexStart,a.geometryCount=this._geometryCount,a.maxInstanceCount=this._maxInstanceCount,a.maxVertexCount=this._maxVertexCount,a.maxIndexCount=this._maxIndexCount,a.geometryInitialized=this._geometryInitialized,a.matricesTexture=this._matricesTexture.toJSON(e),a.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(a.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(a.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(a.boundingBox=this.boundingBox.toJSON()));function s(r,l){return r[l.uuid]===void 0&&(r[l.uuid]=l.toJSON(e)),l.uuid}if(this.isScene)this.background&&(this.background.isColor?a.background=this.background.toJSON():this.background.isTexture&&(a.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(a.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){a.geometry=s(e.geometries,this.geometry);const r=this.geometry.parameters;if(r!==void 0&&r.shapes!==void 0){const l=r.shapes;if(Array.isArray(l))for(let c=0,p=l.length;c<p;c++){const h=l[c];s(e.shapes,h)}else s(e.shapes,l)}}if(this.isSkinnedMesh&&(a.bindMode=this.bindMode,a.bindMatrix=this.bindMatrix.toArray(),this.skeleton!==void 0&&(s(e.skeletons,this.skeleton),a.skeleton=this.skeleton.uuid)),this.material!==void 0)if(Array.isArray(this.material)){const r=[];for(let l=0,c=this.material.length;l<c;l++)r.push(s(e.materials,this.material[l]));a.material=r}else a.material=s(e.materials,this.material);if(this.children.length>0){a.children=[];for(let r=0;r<this.children.length;r++)a.children.push(this.children[r].toJSON(e).object)}if(this.animations.length>0){a.animations=[];for(let r=0;r<this.animations.length;r++){const l=this.animations[r];a.animations.push(s(e.animations,l))}}if(t){const r=o(e.geometries),l=o(e.materials),c=o(e.textures),p=o(e.images),h=o(e.shapes),d=o(e.skeletons),u=o(e.animations),f=o(e.nodes);r.length>0&&(i.geometries=r),l.length>0&&(i.materials=l),c.length>0&&(i.textures=c),p.length>0&&(i.images=p),h.length>0&&(i.shapes=h),d.length>0&&(i.skeletons=d),u.length>0&&(i.animations=u),f.length>0&&(i.nodes=f)}return i.object=a,i;function o(r){const l=[];for(const c in r){const p=r[c];delete p.metadata,l.push(p)}return l}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.pivot=e.pivot!==null?e.pivot.clone():null,this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let i=0;i<e.children.length;i++){const a=e.children[i];this.add(a.clone())}return this}dispose(){this.dispatchEvent({type:"dispose"})}}Wn.DEFAULT_UP=new X(0,1,0),Wn.DEFAULT_MATRIX_AUTO_UPDATE=!0,Wn.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;class gh extends Wn{constructor(){super(),this.isGroup=!0,this.type="Group"}}const c5={type:"move"};class zv{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return this._hand===null&&(this._hand=new gh,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 gh,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new X,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new X),this._targetRay}getGripSpace(){return this._grip===null&&(this._grip=new gh,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new X,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new X,this._grip.eventsEnabled=!1),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){const t=this._hand;if(t)for(const i of e.hand.values())this._getHandJoint(t,i)}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,i){let a=null,s=null,o=null;const r=this._targetRay,l=this._grip,c=this._hand;if(e&&t.session.visibilityState!=="visible-blurred"){if(c&&e.hand){o=!0;for(const v of e.hand.values()){const g=t.getJointPose(v,i),m=this._getHandJoint(c,v);g!==null&&(m.matrix.fromArray(g.transform.matrix),m.matrix.decompose(m.position,m.rotation,m.scale),m.matrixWorldNeedsUpdate=!0,m.jointRadius=g.radius),m.visible=g!==null}const p=c.joints["index-finger-tip"],h=c.joints["thumb-tip"],d=p.position.distanceTo(h.position),u=.02,f=.005;c.inputState.pinching&&d>u+f?(c.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!c.inputState.pinching&&d<=u-f&&(c.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else l!==null&&e.gripSpace&&(s=t.getPose(e.gripSpace,i),s!==null&&(l.matrix.fromArray(s.transform.matrix),l.matrix.decompose(l.position,l.rotation,l.scale),l.matrixWorldNeedsUpdate=!0,s.linearVelocity?(l.hasLinearVelocity=!0,l.linearVelocity.copy(s.linearVelocity)):l.hasLinearVelocity=!1,s.angularVelocity?(l.hasAngularVelocity=!0,l.angularVelocity.copy(s.angularVelocity)):l.hasAngularVelocity=!1,l.eventsEnabled&&l.dispatchEvent({type:"gripUpdated",data:e,target:this})));r!==null&&(a=t.getPose(e.targetRaySpace,i),a===null&&s!==null&&(a=s),a!==null&&(r.matrix.fromArray(a.transform.matrix),r.matrix.decompose(r.position,r.rotation,r.scale),r.matrixWorldNeedsUpdate=!0,a.linearVelocity?(r.hasLinearVelocity=!0,r.linearVelocity.copy(a.linearVelocity)):r.hasLinearVelocity=!1,a.angularVelocity?(r.hasAngularVelocity=!0,r.angularVelocity.copy(a.angularVelocity)):r.hasAngularVelocity=!1,this.dispatchEvent(c5)))}return r!==null&&(r.visible=a!==null),l!==null&&(l.visible=s!==null),c!==null&&(c.visible=o!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){const i=new gh;i.matrixAutoUpdate=!1,i.visible=!1,e.joints[t.jointName]=i,e.add(i)}return e.joints[t.jointName]}}const j2={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},Is={h:0,s:0,l:0},vh={h:0,s:0,l:0};function Ov(n,e,t){return t<0&&(t+=1),t>1&&(t-=1),t<1/6?n+(e-n)*6*t:t<1/2?e:t<2/3?n+(e-n)*6*(2/3-t):n}class It{constructor(e,t,i){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,i)}set(e,t,i){if(t===void 0&&i===void 0){const a=e;a&&a.isColor?this.copy(a):typeof a=="number"?this.setHex(a):typeof a=="string"&&this.setStyle(a)}else this.setRGB(e,t,i);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=bi){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,St.colorSpaceToWorking(this,t),this}setRGB(e,t,i,a=St.workingColorSpace){return this.r=e,this.g=t,this.b=i,St.colorSpaceToWorking(this,a),this}setHSL(e,t,i,a=St.workingColorSpace){if(e=YR(e,1),t=yt(t,0,1),i=yt(i,0,1),t===0)this.r=this.g=this.b=i;else{const s=i<=.5?i*(1+t):i+t-i*t,o=2*i-s;this.r=Ov(o,s,e+1/3),this.g=Ov(o,s,e),this.b=Ov(o,s,e-1/3)}return St.colorSpaceToWorking(this,a),this}setStyle(e,t=bi){function i(s){s!==void 0&&parseFloat(s)<1&&rt("Color: Alpha component of "+e+" will be ignored.")}let a;if(a=/^(\w+)\(([^\)]*)\)/.exec(e)){let s;const o=a[1],r=a[2];switch(o){case"rgb":case"rgba":if(s=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(r))return i(s[4]),this.setRGB(Math.min(255,parseInt(s[1],10))/255,Math.min(255,parseInt(s[2],10))/255,Math.min(255,parseInt(s[3],10))/255,t);if(s=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(r))return i(s[4]),this.setRGB(Math.min(100,parseInt(s[1],10))/100,Math.min(100,parseInt(s[2],10))/100,Math.min(100,parseInt(s[3],10))/100,t);break;case"hsl":case"hsla":if(s=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(r))return i(s[4]),this.setHSL(parseFloat(s[1])/360,parseFloat(s[2])/100,parseFloat(s[3])/100,t);break;default:rt("Color: Unknown color model "+e)}}else if(a=/^\#([A-Fa-f\d]+)$/.exec(e)){const s=a[1],o=s.length;if(o===3)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,t);if(o===6)return this.setHex(parseInt(s,16),t);rt("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=bi){const i=j2[e.toLowerCase()];return i!==void 0?this.setHex(i,t):rt("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=Fa(e.r),this.g=Fa(e.g),this.b=Fa(e.b),this}copyLinearToSRGB(e){return this.r=Rr(e.r),this.g=Rr(e.g),this.b=Rr(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=bi){return St.workingToColorSpace(Ln.copy(this),e),Math.round(yt(Ln.r*255,0,255))*65536+Math.round(yt(Ln.g*255,0,255))*256+Math.round(yt(Ln.b*255,0,255))}getHexString(e=bi){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=St.workingColorSpace){St.workingToColorSpace(Ln.copy(this),t);const i=Ln.r,a=Ln.g,s=Ln.b,o=Math.max(i,a,s),r=Math.min(i,a,s);let l,c;const p=(r+o)/2;if(r===o)l=0,c=0;else{const h=o-r;switch(c=p<=.5?h/(o+r):h/(2-o-r),o){case i:l=(a-s)/h+(a<s?6:0);break;case a:l=(s-i)/h+2;break;case s:l=(i-a)/h+4;break}l/=6}return e.h=l,e.s=c,e.l=p,e}getRGB(e,t=St.workingColorSpace){return St.workingToColorSpace(Ln.copy(this),t),e.r=Ln.r,e.g=Ln.g,e.b=Ln.b,e}getStyle(e=bi){St.workingToColorSpace(Ln.copy(this),e);const t=Ln.r,i=Ln.g,a=Ln.b;return e!==bi?`color(${e} ${t.toFixed(3)} ${i.toFixed(3)} ${a.toFixed(3)})`:`rgb(${Math.round(t*255)},${Math.round(i*255)},${Math.round(a*255)})`}offsetHSL(e,t,i){return this.getHSL(Is),this.setHSL(Is.h+e,Is.s+t,Is.l+i)}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,i){return this.r=e.r+(t.r-e.r)*i,this.g=e.g+(t.g-e.g)*i,this.b=e.b+(t.b-e.b)*i,this}lerpHSL(e,t){this.getHSL(Is),e.getHSL(vh);const i=Rv(Is.h,vh.h,t),a=Rv(Is.s,vh.s,t),s=Rv(Is.l,vh.l,t);return this.setHSL(i,a,s),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,i=this.g,a=this.b,s=e.elements;return this.r=s[0]*t+s[3]*i+s[6]*a,this.g=s[1]*t+s[4]*i+s[7]*a,this.b=s[2]*t+s[5]*i+s[8]*a,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}}const Ln=new It;It.NAMES=j2;class d5 extends Wn{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 Ao,this.environmentIntensity=1,this.environmentRotation=new Ao,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){const t=super.toJSON(e);return this.fog!==null&&(t.object.fog=this.fog.toJSON()),t.object.backgroundBlurriness=this.backgroundBlurriness,t.object.backgroundIntensity=this.backgroundIntensity,t.object.backgroundRotation=this.backgroundRotation.toArray(),t.object.environmentIntensity=this.environmentIntensity,t.object.environmentRotation=this.environmentRotation.toArray(),t}}const Di=new X,Ha=new X,Uv=new X,Ga=new X,Nr=new X,Dr=new X,Z2=new X,Fv=new X,Bv=new X,Hv=new X,Gv=new nn,qv=new nn,Vv=new nn;class zi{constructor(e=new X,t=new X,i=new X){this.a=e,this.b=t,this.c=i}static getNormal(e,t,i,a){a.subVectors(i,t),Di.subVectors(e,t),a.cross(Di);const s=a.lengthSq();return s>0?a.multiplyScalar(1/Math.sqrt(s)):a.set(0,0,0)}static getBarycoord(e,t,i,a,s){Di.subVectors(a,t),Ha.subVectors(i,t),Uv.subVectors(e,t);const o=Di.dot(Di),r=Di.dot(Ha),l=Di.dot(Uv),c=Ha.dot(Ha),p=Ha.dot(Uv),h=o*c-r*r;if(h===0)return s.set(0,0,0),null;const d=1/h,u=(c*l-r*p)*d,f=(o*p-r*l)*d;return s.set(1-u-f,f,u)}static containsPoint(e,t,i,a){return this.getBarycoord(e,t,i,a,Ga)===null?!1:Ga.x>=0&&Ga.y>=0&&Ga.x+Ga.y<=1}static getInterpolation(e,t,i,a,s,o,r,l){return this.getBarycoord(e,t,i,a,Ga)===null?(l.x=0,l.y=0,"z"in l&&(l.z=0),"w"in l&&(l.w=0),null):(l.setScalar(0),l.addScaledVector(s,Ga.x),l.addScaledVector(o,Ga.y),l.addScaledVector(r,Ga.z),l)}static getInterpolatedAttribute(e,t,i,a,s,o){return Gv.setScalar(0),qv.setScalar(0),Vv.setScalar(0),Gv.fromBufferAttribute(e,t),qv.fromBufferAttribute(e,i),Vv.fromBufferAttribute(e,a),o.setScalar(0),o.addScaledVector(Gv,s.x),o.addScaledVector(qv,s.y),o.addScaledVector(Vv,s.z),o}static isFrontFacing(e,t,i,a){return Di.subVectors(i,t),Ha.subVectors(e,t),Di.cross(Ha).dot(a)<0}set(e,t,i){return this.a.copy(e),this.b.copy(t),this.c.copy(i),this}setFromPointsAndIndices(e,t,i,a){return this.a.copy(e[t]),this.b.copy(e[i]),this.c.copy(e[a]),this}setFromAttributeAndIndices(e,t,i,a){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,i),this.c.fromBufferAttribute(e,a),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Di.subVectors(this.c,this.b),Ha.subVectors(this.a,this.b),Di.cross(Ha).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return zi.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return zi.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,i,a,s){return zi.getInterpolation(e,this.a,this.b,this.c,t,i,a,s)}containsPoint(e){return zi.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return zi.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const i=this.a,a=this.b,s=this.c;let o,r;Nr.subVectors(a,i),Dr.subVectors(s,i),Fv.subVectors(e,i);const l=Nr.dot(Fv),c=Dr.dot(Fv);if(l<=0&&c<=0)return t.copy(i);Bv.subVectors(e,a);const p=Nr.dot(Bv),h=Dr.dot(Bv);if(p>=0&&h<=p)return t.copy(a);const d=l*h-p*c;if(d<=0&&l>=0&&p<=0)return o=l/(l-p),t.copy(i).addScaledVector(Nr,o);Hv.subVectors(e,s);const u=Nr.dot(Hv),f=Dr.dot(Hv);if(f>=0&&u<=f)return t.copy(s);const v=u*c-l*f;if(v<=0&&c>=0&&f<=0)return r=c/(c-f),t.copy(i).addScaledVector(Dr,r);const g=p*f-u*h;if(g<=0&&h-p>=0&&u-f>=0)return Z2.subVectors(s,a),r=(h-p)/(h-p+(u-f)),t.copy(a).addScaledVector(Z2,r);const m=1/(g+v+d);return o=v*m,r=d*m,t.copy(i).addScaledVector(Nr,o).addScaledVector(Dr,r)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}class Nc{constructor(e=new X(1/0,1/0,1/0),t=new X(-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,i=e.length;t<i;t+=3)this.expandByPoint(Oi.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,i=e.count;t<i;t++)this.expandByPoint(Oi.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,i=e.length;t<i;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const i=Oi.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(i),this.max.copy(e).add(i),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);const i=e.geometry;if(i!==void 0){const s=i.getAttribute("position");if(t===!0&&s!==void 0&&e.isInstancedMesh!==!0)for(let o=0,r=s.count;o<r;o++)e.isMesh===!0?e.getVertexPosition(o,Oi):Oi.fromBufferAttribute(s,o),Oi.applyMatrix4(e.matrixWorld),this.expandByPoint(Oi);else e.boundingBox!==void 0?(e.boundingBox===null&&e.computeBoundingBox(),xh.copy(e.boundingBox)):(i.boundingBox===null&&i.computeBoundingBox(),xh.copy(i.boundingBox)),xh.applyMatrix4(e.matrixWorld),this.union(xh)}const a=e.children;for(let s=0,o=a.length;s<o;s++)this.expandByObject(a[s],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,Oi),Oi.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,i;return e.normal.x>0?(t=e.normal.x*this.min.x,i=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,i=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,i+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,i+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,i+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,i+=e.normal.z*this.min.z),t<=-e.constant&&i>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Dc),bh.subVectors(this.max,Dc),zr.subVectors(e.a,Dc),Or.subVectors(e.b,Dc),Ur.subVectors(e.c,Dc),$s.subVectors(Or,zr),Ns.subVectors(Ur,Or),To.subVectors(zr,Ur);let t=[0,-$s.z,$s.y,0,-Ns.z,Ns.y,0,-To.z,To.y,$s.z,0,-$s.x,Ns.z,0,-Ns.x,To.z,0,-To.x,-$s.y,$s.x,0,-Ns.y,Ns.x,0,-To.y,To.x,0];return!Wv(t,zr,Or,Ur,bh)||(t=[1,0,0,0,1,0,0,0,1],!Wv(t,zr,Or,Ur,bh))?!1:(yh.crossVectors($s,Ns),t=[yh.x,yh.y,yh.z],Wv(t,zr,Or,Ur,bh))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Oi).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Oi).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:(qa[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),qa[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),qa[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),qa[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),qa[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),qa[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),qa[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),qa[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(qa),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)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}}const qa=[new X,new X,new X,new X,new X,new X,new X,new X],Oi=new X,xh=new Nc,zr=new X,Or=new X,Ur=new X,$s=new X,Ns=new X,To=new X,Dc=new X,bh=new X,yh=new X,Eo=new X;function Wv(n,e,t,i,a){for(let s=0,o=n.length-3;s<=o;s+=3){Eo.fromArray(n,s);const r=a.x*Math.abs(Eo.x)+a.y*Math.abs(Eo.y)+a.z*Math.abs(Eo.z),l=e.dot(Eo),c=t.dot(Eo),p=i.dot(Eo);if(Math.max(-Math.max(l,c,p),Math.min(l,c,p))>r)return!1}return!0}const dn=new X,wh=new ut;let p5=0;class ra extends Rs{constructor(e,t,i=!1){if(super(),Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:p5++}),this.name="",this.array=e,this.itemSize=t,this.count=e!==void 0?e.length/t:0,this.normalized=i,this.usage=GR,this.updateRanges=[],this.gpuType=aa,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,i){e*=this.itemSize,i*=t.itemSize;for(let a=0,s=this.itemSize;a<s;a++)this.array[e+a]=t.array[i+a];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(this.itemSize===2)for(let t=0,i=this.count;t<i;t++)wh.fromBufferAttribute(this,t),wh.applyMatrix3(e),this.setXY(t,wh.x,wh.y);else if(this.itemSize===3)for(let t=0,i=this.count;t<i;t++)dn.fromBufferAttribute(this,t),dn.applyMatrix3(e),this.setXYZ(t,dn.x,dn.y,dn.z);return this}applyMatrix4(e){for(let t=0,i=this.count;t<i;t++)dn.fromBufferAttribute(this,t),dn.applyMatrix4(e),this.setXYZ(t,dn.x,dn.y,dn.z);return this}applyNormalMatrix(e){for(let t=0,i=this.count;t<i;t++)dn.fromBufferAttribute(this,t),dn.applyNormalMatrix(e),this.setXYZ(t,dn.x,dn.y,dn.z);return this}transformDirection(e){for(let t=0,i=this.count;t<i;t++)dn.fromBufferAttribute(this,t),dn.transformDirection(e),this.setXYZ(t,dn.x,dn.y,dn.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let i=this.array[e*this.itemSize+t];return this.normalized&&(i=Ic(i,this.array)),i}setComponent(e,t,i){return this.normalized&&(i=ti(i,this.array)),this.array[e*this.itemSize+t]=i,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Ic(t,this.array)),t}setX(e,t){return this.normalized&&(t=ti(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Ic(t,this.array)),t}setY(e,t){return this.normalized&&(t=ti(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=Ic(t,this.array)),t}setZ(e,t){return this.normalized&&(t=ti(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=Ic(t,this.array)),t}setW(e,t){return this.normalized&&(t=ti(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,i){return e*=this.itemSize,this.normalized&&(t=ti(t,this.array),i=ti(i,this.array)),this.array[e+0]=t,this.array[e+1]=i,this}setXYZ(e,t,i,a){return e*=this.itemSize,this.normalized&&(t=ti(t,this.array),i=ti(i,this.array),a=ti(a,this.array)),this.array[e+0]=t,this.array[e+1]=i,this.array[e+2]=a,this}setXYZW(e,t,i,a,s){return e*=this.itemSize,this.normalized&&(t=ti(t,this.array),i=ti(i,this.array),a=ti(a,this.array),s=ti(s,this.array)),this.array[e+0]=t,this.array[e+1]=i,this.array[e+2]=a,this.array[e+3]=s,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return e.name=this.name,e.usage=this.usage,e.gpuType=this.gpuType,e}dispose(){this.dispatchEvent({type:"dispose"})}}class J2 extends ra{constructor(e,t,i){super(new Uint16Array(e),t,i)}}class Q2 extends ra{constructor(e,t,i){super(new Uint32Array(e),t,i)}}class Ui extends ra{constructor(e,t,i){super(new Float32Array(e),t,i)}}const h5=new Nc,zc=new X,Xv=new X;class Oc{constructor(e=new X,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){const i=this.center;t!==void 0?i.copy(t):h5.setFromPoints(e).getCenter(i);let a=0;for(let s=0,o=e.length;s<o;s++)a=Math.max(a,i.distanceToSquared(e[s]));return this.radius=Math.sqrt(a),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){const 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){const i=this.center.distanceToSquared(e);return t.copy(e),i>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;zc.subVectors(e,this.center);const t=zc.lengthSq();if(t>this.radius*this.radius){const i=Math.sqrt(t),a=(i-this.radius)*.5;this.center.addScaledVector(zc,a/i),this.radius+=a}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):(Xv.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(zc.copy(e.center).add(Xv)),this.expandByPoint(zc.copy(e.center).sub(Xv))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}let u5=0;const yi=new en,Kv=new Wn,Fr=new X,fi=new Nc,Uc=new Nc,yn=new X;class pn extends Rs{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:u5++}),this.uuid=Pc(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={},this._transformed=!1}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(VR(e)?Q2:J2)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,i=0){this.groups.push({start:e,count:t,materialIndex:i})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);const i=this.attributes.normal;if(i!==void 0){const s=new pt().getNormalMatrix(e);i.applyNormalMatrix(s),i.needsUpdate=!0}const a=this.attributes.tangent;return a!==void 0&&(a.transformDirection(e),a.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this._transformed=!0,this}applyQuaternion(e){return yi.makeRotationFromQuaternion(e),this.applyMatrix4(yi),this}rotateX(e){return yi.makeRotationX(e),this.applyMatrix4(yi),this}rotateY(e){return yi.makeRotationY(e),this.applyMatrix4(yi),this}rotateZ(e){return yi.makeRotationZ(e),this.applyMatrix4(yi),this}translate(e,t,i){return yi.makeTranslation(e,t,i),this.applyMatrix4(yi),this}scale(e,t,i){return yi.makeScale(e,t,i),this.applyMatrix4(yi),this}lookAt(e){return Kv.lookAt(e),Kv.updateMatrix(),this.applyMatrix4(Kv.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(Fr).negate(),this.translate(Fr.x,Fr.y,Fr.z),this}setFromPoints(e){const t=this.getAttribute("position");if(t===void 0){const i=[];for(let a=0,s=e.length;a<s;a++){const o=e[a];i.push(o.x,o.y,o.z||0)}this.setAttribute("position",new Ui(i,3))}else{const i=Math.min(e.length,t.count);for(let a=0;a<i;a++){const s=e[a];t.setXYZ(a,s.x,s.y,s.z||0)}e.length>t.count&&rt("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Nc);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Pt("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),this.boundingBox.set(new X(-1/0,-1/0,-1/0),new X(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let i=0,a=t.length;i<a;i++){const s=t[i];fi.setFromBufferAttribute(s),this.morphTargetsRelative?(yn.addVectors(this.boundingBox.min,fi.min),this.boundingBox.expandByPoint(yn),yn.addVectors(this.boundingBox.max,fi.max),this.boundingBox.expandByPoint(yn)):(this.boundingBox.expandByPoint(fi.min),this.boundingBox.expandByPoint(fi.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&Pt('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 Oc);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){Pt("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),this.boundingSphere.set(new X,1/0);return}if(e){const i=this.boundingSphere.center;if(fi.setFromBufferAttribute(e),t)for(let s=0,o=t.length;s<o;s++){const r=t[s];Uc.setFromBufferAttribute(r),this.morphTargetsRelative?(yn.addVectors(fi.min,Uc.min),fi.expandByPoint(yn),yn.addVectors(fi.max,Uc.max),fi.expandByPoint(yn)):(fi.expandByPoint(Uc.min),fi.expandByPoint(Uc.max))}fi.getCenter(i);let a=0;for(let s=0,o=e.count;s<o;s++)yn.fromBufferAttribute(e,s),a=Math.max(a,i.distanceToSquared(yn));if(t)for(let s=0,o=t.length;s<o;s++){const r=t[s],l=this.morphTargetsRelative;for(let c=0,p=r.count;c<p;c++)yn.fromBufferAttribute(r,c),l&&(Fr.fromBufferAttribute(e,c),yn.add(Fr)),a=Math.max(a,i.distanceToSquared(yn))}this.boundingSphere.radius=Math.sqrt(a),isNaN(this.boundingSphere.radius)&&Pt('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(e===null||t.position===void 0||t.normal===void 0||t.uv===void 0){Pt("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");return}const i=t.position,a=t.normal,s=t.uv;let o=this.getAttribute("tangent");(o===void 0||o.count!==i.count)&&(o=new ra(new Float32Array(4*i.count),4),this.setAttribute("tangent",o));const r=[],l=[];for(let y=0;y<i.count;y++)r[y]=new X,l[y]=new X;const c=new X,p=new X,h=new X,d=new ut,u=new ut,f=new ut,v=new X,g=new X;function m(y,M,T){c.fromBufferAttribute(i,y),p.fromBufferAttribute(i,M),h.fromBufferAttribute(i,T),d.fromBufferAttribute(s,y),u.fromBufferAttribute(s,M),f.fromBufferAttribute(s,T),p.sub(c),h.sub(c),u.sub(d),f.sub(d);const L=1/(u.x*f.y-f.x*u.y);isFinite(L)&&(v.copy(p).multiplyScalar(f.y).addScaledVector(h,-u.y).multiplyScalar(L),g.copy(h).multiplyScalar(u.x).addScaledVector(p,-f.x).multiplyScalar(L),r[y].add(v),r[M].add(v),r[T].add(v),l[y].add(g),l[M].add(g),l[T].add(g))}let x=this.groups;x.length===0&&(x=[{start:0,count:e.count}]);for(let y=0,M=x.length;y<M;++y){const T=x[y],L=T.start,P=T.count;for(let z=L,R=L+P;z<R;z+=3)m(e.getX(z+0),e.getX(z+1),e.getX(z+2))}const _=new X,w=new X,S=new X,A=new X;function C(y){S.fromBufferAttribute(a,y),A.copy(S);const M=r[y];_.copy(M),_.sub(S.multiplyScalar(S.dot(M))).normalize(),w.crossVectors(A,M);const L=w.dot(l[y])<0?-1:1;o.setXYZW(y,_.x,_.y,_.z,L)}for(let y=0,M=x.length;y<M;++y){const T=x[y],L=T.start,P=T.count;for(let z=L,R=L+P;z<R;z+=3)C(e.getX(z+0)),C(e.getX(z+1)),C(e.getX(z+2))}this._transformed=!0}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(t!==void 0){let i=this.getAttribute("normal");if(i===void 0||i.count!==t.count)i=new ra(new Float32Array(t.count*3),3),this.setAttribute("normal",i);else for(let d=0,u=i.count;d<u;d++)i.setXYZ(d,0,0,0);const a=new X,s=new X,o=new X,r=new X,l=new X,c=new X,p=new X,h=new X;if(e)for(let d=0,u=e.count;d<u;d+=3){const f=e.getX(d+0),v=e.getX(d+1),g=e.getX(d+2);a.fromBufferAttribute(t,f),s.fromBufferAttribute(t,v),o.fromBufferAttribute(t,g),p.subVectors(o,s),h.subVectors(a,s),p.cross(h),r.fromBufferAttribute(i,f),l.fromBufferAttribute(i,v),c.fromBufferAttribute(i,g),r.add(p),l.add(p),c.add(p),i.setXYZ(f,r.x,r.y,r.z),i.setXYZ(v,l.x,l.y,l.z),i.setXYZ(g,c.x,c.y,c.z)}else for(let d=0,u=t.count;d<u;d+=3)a.fromBufferAttribute(t,d+0),s.fromBufferAttribute(t,d+1),o.fromBufferAttribute(t,d+2),p.subVectors(o,s),h.subVectors(a,s),p.cross(h),i.setXYZ(d+0,p.x,p.y,p.z),i.setXYZ(d+1,p.x,p.y,p.z),i.setXYZ(d+2,p.x,p.y,p.z);this.normalizeNormals(),i.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,i=e.count;t<i;t++)yn.fromBufferAttribute(e,t),yn.normalize(),e.setXYZ(t,yn.x,yn.y,yn.z)}toNonIndexed(){function e(r,l){const c=r.array,p=r.itemSize,h=r.normalized,d=new c.constructor(l.length*p);let u=0,f=0;for(let v=0,g=l.length;v<g;v++){r.isInterleavedBufferAttribute?u=l[v]*r.data.stride+r.offset:u=l[v]*p;for(let m=0;m<p;m++)d[f++]=c[u++]}return new ra(d,p,h)}if(this.index===null)return rt("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new pn,i=this.index.array,a=this.attributes;for(const r in a){const l=a[r],c=e(l,i);t.setAttribute(r,c)}const s=this.morphAttributes;for(const r in s){const l=[],c=s[r];for(let p=0,h=c.length;p<h;p++){const d=c[p],u=e(d,i);l.push(u)}t.morphAttributes[r]=l}t.morphTargetsRelative=this.morphTargetsRelative;const o=this.groups;for(let r=0,l=o.length;r<l;r++){const c=o[r];t.addGroup(c.start,c.count,c.materialIndex)}return t}toJSON(){const e={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.parameters!==void 0&&this._transformed===!0?"BufferGeometry":this.type,e.name=this.name,Object.keys(this.userData).length>0&&(e.userData=this.userData),this.parameters!==void 0&&this._transformed!==!0){const l=this.parameters;for(const c in l)l[c]!==void 0&&(e[c]=l[c]);return e}e.data={attributes:{}};const t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const i=this.attributes;for(const l in i){const c=i[l];e.data.attributes[l]=c.toJSON(e.data)}const a={};let s=!1;for(const l in this.morphAttributes){const c=this.morphAttributes[l],p=[];for(let h=0,d=c.length;h<d;h++){const u=c[h];p.push(u.toJSON(e.data))}p.length>0&&(a[l]=p,s=!0)}s&&(e.data.morphAttributes=a,e.data.morphTargetsRelative=this.morphTargetsRelative);const o=this.groups;o.length>0&&(e.data.groups=JSON.parse(JSON.stringify(o)));const r=this.boundingSphere;return r!==null&&(e.data.boundingSphere=r.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const i=e.index;i!==null&&this.setIndex(i.clone());const a=e.attributes;for(const c in a){const p=a[c];this.setAttribute(c,p.clone(t))}const s=e.morphAttributes;for(const c in s){const p=[],h=s[c];for(let d=0,u=h.length;d<u;d++)p.push(h[d].clone(t));this.morphAttributes[c]=p}this.morphTargetsRelative=e.morphTargetsRelative;const o=e.groups;for(let c=0,p=o.length;c<p;c++){const h=o[c];this.addGroup(h.start,h.count,h.materialIndex)}const r=e.boundingBox;r!==null&&(this.boundingBox=r.clone());const l=e.boundingSphere;return l!==null&&(this.boundingSphere=l.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this._transformed=e._transformed,this}dispose(){this.dispatchEvent({type:"dispose"})}}const Yv=new X,f5=new X,m5=new pt;class Va{constructor(e=new X(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,i,a){return this.normal.set(e,t,i),this.constant=a,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,i){const a=Yv.subVectors(i,t).cross(f5.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(a,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const 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,i=!0){const a=e.delta(Yv),s=this.normal.dot(a);if(s===0)return this.distanceToPoint(e.start)===0?t.copy(e.start):null;const o=-(e.start.dot(this.normal)+this.constant)/s;return i===!0&&(o<0||o>1)?null:t.copy(e.start).addScaledVector(a,o)}intersectsLine(e){const t=this.distanceToPoint(e.start),i=this.distanceToPoint(e.end);return t<0&&i>0||i<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){const i=t||m5.getNormalMatrix(e),a=this.coplanarPoint(Yv).applyMatrix4(e),s=this.normal.applyMatrix3(i).normalize();return this.constant=-a.dot(s),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)}toJSON(){return{normal:this.normal.toArray(),constant:this.constant}}fromJSON(e){return this.normal.fromArray(e.normal),this.constant=e.constant,this}}let g5=0;class Br extends Rs{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:g5++}),this.uuid=Pc(),this.name="",this.type="Material",this.blending=Ar,this.side=wo,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=m2,this.blendDst=g2,this.blendEquation=Tr,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new It(0,0,0),this.blendAlpha=0,this.depthFunc=Cc,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=DR,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Av,this.stencilZFail=Av,this.stencilZPass=Av,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.allowOverride=!0,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(const t in e){const i=e[t];if(i===void 0){rt(`Material: parameter '${t}' has value of undefined.`);continue}const a=this[t];if(a===void 0){rt(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}a&&a.isColor?a.set(i):a&&a.isVector2&&i&&i.isVector2||a&&a.isEuler&&i&&i.isEuler||a&&a.isVector3&&i&&i.isVector3?a.copy(i):this[t]=i}}toJSON(e){const t=e===void 0||typeof e=="string";t&&(e={textures:{},images:{}});const i={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};i.uuid=this.uuid,i.type=this.type,i.blending=this.blending,i.side=this.side,i.shadowSide=this.shadowSide,i.vertexColors=this.vertexColors,i.opacity=this.opacity,i.transparent=this.transparent,i.blendSrc=this.blendSrc,i.blendDst=this.blendDst,i.blendEquation=this.blendEquation,i.blendSrcAlpha=this.blendSrcAlpha,i.blendDstAlpha=this.blendDstAlpha,i.blendEquationAlpha=this.blendEquationAlpha,i.blendColor=this.blendColor.getHex(),i.blendAlpha=this.blendAlpha,i.depthFunc=this.depthFunc,i.depthTest=this.depthTest,i.depthWrite=this.depthWrite,i.colorWrite=this.colorWrite,i.clipIntersection=this.clipIntersection,i.clipShadows=this.clipShadows,i.stencilWriteMask=this.stencilWriteMask,i.stencilFunc=this.stencilFunc,i.stencilRef=this.stencilRef,i.stencilFuncMask=this.stencilFuncMask,i.stencilFail=this.stencilFail,i.stencilZFail=this.stencilZFail,i.stencilZPass=this.stencilZPass,i.stencilWrite=this.stencilWrite,i.polygonOffset=this.polygonOffset,i.polygonOffsetFactor=this.polygonOffsetFactor,i.polygonOffsetUnits=this.polygonOffsetUnits,i.dithering=this.dithering,i.alphaTest=this.alphaTest,i.alphaHash=this.alphaHash,i.alphaToCoverage=this.alphaToCoverage,i.premultipliedAlpha=this.premultipliedAlpha,i.forceSinglePass=this.forceSinglePass,i.allowOverride=this.allowOverride,i.visible=this.visible,i.toneMapped=this.toneMapped,i.name=this.name,this.color&&this.color.isColor&&(i.color=this.color.getHex()),this.roughness!==void 0&&(i.roughness=this.roughness),this.metalness!==void 0&&(i.metalness=this.metalness),this.sheen!==void 0&&(i.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(i.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(i.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(i.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&(i.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(i.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(i.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(i.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(i.shininess=this.shininess),this.clearcoat!==void 0&&(i.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(i.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(i.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(i.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(i.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,i.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(i.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(i.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(i.dispersion=this.dispersion),this.retroreflectivity!==void 0&&(i.retroreflectivity=this.retroreflectivity),this.iridescence!==void 0&&(i.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(i.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(i.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(i.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(i.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(i.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(i.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(i.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(i.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(i.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(i.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(i.lightMap=this.lightMap.toJSON(e).uuid,i.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(i.aoMap=this.aoMap.toJSON(e).uuid,i.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(i.bumpMap=this.bumpMap.toJSON(e).uuid,i.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(i.normalMap=this.normalMap.toJSON(e).uuid,i.normalMapType=this.normalMapType,i.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(i.displacementMap=this.displacementMap.toJSON(e).uuid,i.displacementScale=this.displacementScale,i.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(i.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(i.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(i.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(i.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(i.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(i.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(i.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(i.combine=this.combine)),this.envMapRotation!==void 0&&(i.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(i.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(i.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(i.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(i.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(i.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(i.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(i.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(i.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&(i.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(i.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(i.size=this.size),this.sizeAttenuation!==void 0&&(i.sizeAttenuation=this.sizeAttenuation),Array.isArray(this.clippingPlanes)&&this.clippingPlanes.length>0&&(i.clippingPlanes=this.clippingPlanes.map(s=>s.toJSON())),this.rotation!==void 0&&(i.rotation=this.rotation),this.depthPacking!==void 0&&(i.depthPacking=this.depthPacking),this.linewidth!==void 0&&(i.linewidth=this.linewidth),this.linecap!==void 0&&(i.linecap=this.linecap),this.linejoin!==void 0&&(i.linejoin=this.linejoin),this.dashSize!==void 0&&(i.dashSize=this.dashSize),this.gapSize!==void 0&&(i.gapSize=this.gapSize),this.scale!==void 0&&(i.scale=this.scale),this.wireframe!==void 0&&(i.wireframe=this.wireframe),this.wireframeLinewidth!==void 0&&(i.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!==void 0&&(i.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!==void 0&&(i.wireframeLinejoin=this.wireframeLinejoin),this.flatShading!==void 0&&(i.flatShading=this.flatShading),this.fog!==void 0&&(i.fog=this.fog),Object.keys(this.userData).length>0&&(i.userData=this.userData);function a(s){const o=[];for(const r in s){const l=s[r];delete l.metadata,o.push(l)}return o}if(t){const s=a(e.textures),o=a(e.images);s.length>0&&(i.textures=s),o.length>0&&(i.images=o)}return i}fromJSON(e,t){if(e.uuid!==void 0&&(this.uuid=e.uuid),e.name!==void 0&&(this.name=e.name),e.color!==void 0&&this.color!==void 0&&this.color.setHex(e.color),e.roughness!==void 0&&(this.roughness=e.roughness),e.metalness!==void 0&&(this.metalness=e.metalness),e.sheen!==void 0&&(this.sheen=e.sheen),e.sheenColor!==void 0&&(this.sheenColor=new It().setHex(e.sheenColor)),e.sheenRoughness!==void 0&&(this.sheenRoughness=e.sheenRoughness),e.emissive!==void 0&&this.emissive!==void 0&&this.emissive.setHex(e.emissive),e.specular!==void 0&&this.specular!==void 0&&this.specular.setHex(e.specular),e.specularIntensity!==void 0&&(this.specularIntensity=e.specularIntensity),e.specularColor!==void 0&&this.specularColor!==void 0&&this.specularColor.setHex(e.specularColor),e.shininess!==void 0&&(this.shininess=e.shininess),e.clearcoat!==void 0&&(this.clearcoat=e.clearcoat),e.clearcoatRoughness!==void 0&&(this.clearcoatRoughness=e.clearcoatRoughness),e.dispersion!==void 0&&(this.dispersion=e.dispersion),e.retroreflectivity!==void 0&&(this.retroreflectivity=e.retroreflectivity),e.iridescence!==void 0&&(this.iridescence=e.iridescence),e.iridescenceIOR!==void 0&&(this.iridescenceIOR=e.iridescenceIOR),e.iridescenceThicknessRange!==void 0&&(this.iridescenceThicknessRange=e.iridescenceThicknessRange),e.transmission!==void 0&&(this.transmission=e.transmission),e.thickness!==void 0&&(this.thickness=e.thickness),e.attenuationDistance!==void 0&&(this.attenuationDistance=e.attenuationDistance),e.attenuationColor!==void 0&&this.attenuationColor!==void 0&&this.attenuationColor.setHex(e.attenuationColor),e.anisotropy!==void 0&&(this.anisotropy=e.anisotropy),e.anisotropyRotation!==void 0&&(this.anisotropyRotation=e.anisotropyRotation),e.fog!==void 0&&(this.fog=e.fog),e.flatShading!==void 0&&(this.flatShading=e.flatShading),e.blending!==void 0&&(this.blending=e.blending),e.combine!==void 0&&(this.combine=e.combine),e.side!==void 0&&(this.side=e.side),e.shadowSide!==void 0&&(this.shadowSide=e.shadowSide),e.opacity!==void 0&&(this.opacity=e.opacity),e.transparent!==void 0&&(this.transparent=e.transparent),e.alphaTest!==void 0&&(this.alphaTest=e.alphaTest),e.alphaHash!==void 0&&(this.alphaHash=e.alphaHash),e.depthFunc!==void 0&&(this.depthFunc=e.depthFunc),e.depthTest!==void 0&&(this.depthTest=e.depthTest),e.depthWrite!==void 0&&(this.depthWrite=e.depthWrite),e.colorWrite!==void 0&&(this.colorWrite=e.colorWrite),e.clippingPlanes!==void 0&&(this.clippingPlanes=e.clippingPlanes.map(i=>new Va().fromJSON(i))),e.clipIntersection!==void 0&&(this.clipIntersection=e.clipIntersection),e.clipShadows!==void 0&&(this.clipShadows=e.clipShadows),e.depthPacking!==void 0&&(this.depthPacking=e.depthPacking),e.blendSrc!==void 0&&(this.blendSrc=e.blendSrc),e.blendDst!==void 0&&(this.blendDst=e.blendDst),e.blendEquation!==void 0&&(this.blendEquation=e.blendEquation),e.blendSrcAlpha!==void 0&&(this.blendSrcAlpha=e.blendSrcAlpha),e.blendDstAlpha!==void 0&&(this.blendDstAlpha=e.blendDstAlpha),e.blendEquationAlpha!==void 0&&(this.blendEquationAlpha=e.blendEquationAlpha),e.blendColor!==void 0&&this.blendColor!==void 0&&this.blendColor.setHex(e.blendColor),e.blendAlpha!==void 0&&(this.blendAlpha=e.blendAlpha),e.stencilWriteMask!==void 0&&(this.stencilWriteMask=e.stencilWriteMask),e.stencilFunc!==void 0&&(this.stencilFunc=e.stencilFunc),e.stencilRef!==void 0&&(this.stencilRef=e.stencilRef),e.stencilFuncMask!==void 0&&(this.stencilFuncMask=e.stencilFuncMask),e.stencilFail!==void 0&&(this.stencilFail=e.stencilFail),e.stencilZFail!==void 0&&(this.stencilZFail=e.stencilZFail),e.stencilZPass!==void 0&&(this.stencilZPass=e.stencilZPass),e.stencilWrite!==void 0&&(this.stencilWrite=e.stencilWrite),e.wireframe!==void 0&&(this.wireframe=e.wireframe),e.wireframeLinewidth!==void 0&&(this.wireframeLinewidth=e.wireframeLinewidth),e.wireframeLinecap!==void 0&&(this.wireframeLinecap=e.wireframeLinecap),e.wireframeLinejoin!==void 0&&(this.wireframeLinejoin=e.wireframeLinejoin),e.rotation!==void 0&&(this.rotation=e.rotation),e.linewidth!==void 0&&(this.linewidth=e.linewidth),e.linecap!==void 0&&(this.linecap=e.linecap),e.linejoin!==void 0&&(this.linejoin=e.linejoin),e.dashSize!==void 0&&(this.dashSize=e.dashSize),e.gapSize!==void 0&&(this.gapSize=e.gapSize),e.scale!==void 0&&(this.scale=e.scale),e.polygonOffset!==void 0&&(this.polygonOffset=e.polygonOffset),e.polygonOffsetFactor!==void 0&&(this.polygonOffsetFactor=e.polygonOffsetFactor),e.polygonOffsetUnits!==void 0&&(this.polygonOffsetUnits=e.polygonOffsetUnits),e.dithering!==void 0&&(this.dithering=e.dithering),e.alphaToCoverage!==void 0&&(this.alphaToCoverage=e.alphaToCoverage),e.premultipliedAlpha!==void 0&&(this.premultipliedAlpha=e.premultipliedAlpha),e.forceSinglePass!==void 0&&(this.forceSinglePass=e.forceSinglePass),e.allowOverride!==void 0&&(this.allowOverride=e.allowOverride),e.visible!==void 0&&(this.visible=e.visible),e.toneMapped!==void 0&&(this.toneMapped=e.toneMapped),e.userData!==void 0&&(this.userData=e.userData),e.vertexColors!==void 0&&(typeof e.vertexColors=="number"?this.vertexColors=e.vertexColors>0:this.vertexColors=e.vertexColors),e.size!==void 0&&(this.size=e.size),e.sizeAttenuation!==void 0&&(this.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(this.map=t[e.map]||null),e.matcap!==void 0&&(this.matcap=t[e.matcap]||null),e.alphaMap!==void 0&&(this.alphaMap=t[e.alphaMap]||null),e.bumpMap!==void 0&&(this.bumpMap=t[e.bumpMap]||null),e.bumpScale!==void 0&&(this.bumpScale=e.bumpScale),e.normalMap!==void 0&&(this.normalMap=t[e.normalMap]||null),e.normalMapType!==void 0&&(this.normalMapType=e.normalMapType),e.normalScale!==void 0){let i=e.normalScale;Array.isArray(i)===!1&&(i=[i,i]),this.normalScale=new ut().fromArray(i)}return e.displacementMap!==void 0&&(this.displacementMap=t[e.displacementMap]||null),e.displacementScale!==void 0&&(this.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(this.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(this.roughnessMap=t[e.roughnessMap]||null),e.metalnessMap!==void 0&&(this.metalnessMap=t[e.metalnessMap]||null),e.emissiveMap!==void 0&&(this.emissiveMap=t[e.emissiveMap]||null),e.emissiveIntensity!==void 0&&(this.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(this.specularMap=t[e.specularMap]||null),e.specularIntensityMap!==void 0&&(this.specularIntensityMap=t[e.specularIntensityMap]||null),e.specularColorMap!==void 0&&(this.specularColorMap=t[e.specularColorMap]||null),e.envMap!==void 0&&(this.envMap=t[e.envMap]||null),e.envMapRotation!==void 0&&this.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(this.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(this.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(this.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(this.lightMap=t[e.lightMap]||null),e.lightMapIntensity!==void 0&&(this.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(this.aoMap=t[e.aoMap]||null),e.aoMapIntensity!==void 0&&(this.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(this.gradientMap=t[e.gradientMap]||null),e.clearcoatMap!==void 0&&(this.clearcoatMap=t[e.clearcoatMap]||null),e.clearcoatRoughnessMap!==void 0&&(this.clearcoatRoughnessMap=t[e.clearcoatRoughnessMap]||null),e.clearcoatNormalMap!==void 0&&(this.clearcoatNormalMap=t[e.clearcoatNormalMap]||null),e.clearcoatNormalScale!==void 0&&(this.clearcoatNormalScale=new ut().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(this.iridescenceMap=t[e.iridescenceMap]||null),e.iridescenceThicknessMap!==void 0&&(this.iridescenceThicknessMap=t[e.iridescenceThicknessMap]||null),e.transmissionMap!==void 0&&(this.transmissionMap=t[e.transmissionMap]||null),e.thicknessMap!==void 0&&(this.thicknessMap=t[e.thicknessMap]||null),e.anisotropyMap!==void 0&&(this.anisotropyMap=t[e.anisotropyMap]||null),e.sheenColorMap!==void 0&&(this.sheenColorMap=t[e.sheenColorMap]||null),e.sheenRoughnessMap!==void 0&&(this.sheenRoughnessMap=t[e.sheenRoughnessMap]||null),this}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;const t=e.clippingPlanes;let i=null;if(t!==null){const a=t.length;i=new Array(a);for(let s=0;s!==a;++s)i[s]=t[s].clone()}return this.clippingPlanes=i,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.allowOverride=e.allowOverride,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++}}const Wa=new X,jv=new X,kh=new X,_h=new X;class Sh{constructor(e=new X,t=new X(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,Wa)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const i=t.dot(this.direction);return i<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,i)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=Wa.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Wa.copy(this.origin).addScaledVector(this.direction,t),Wa.distanceToSquared(e))}distanceSqToSegment(e,t,i,a){jv.copy(e).add(t).multiplyScalar(.5),kh.copy(t).sub(e).normalize(),_h.copy(this.origin).sub(jv);const s=e.distanceTo(t)*.5,o=-this.direction.dot(kh),r=_h.dot(this.direction),l=-_h.dot(kh),c=_h.lengthSq(),p=Math.abs(1-o*o);let h,d,u,f;if(p>0)if(h=o*l-r,d=o*r-l,f=s*p,h>=0)if(d>=-f)if(d<=f){const v=1/p;h*=v,d*=v,u=h*(h+o*d+2*r)+d*(o*h+d+2*l)+c}else d=s,h=Math.max(0,-(o*d+r)),u=-h*h+d*(d+2*l)+c;else d=-s,h=Math.max(0,-(o*d+r)),u=-h*h+d*(d+2*l)+c;else d<=-f?(h=Math.max(0,-(-o*s+r)),d=h>0?-s:Math.min(Math.max(-s,-l),s),u=-h*h+d*(d+2*l)+c):d<=f?(h=0,d=Math.min(Math.max(-s,-l),s),u=d*(d+2*l)+c):(h=Math.max(0,-(o*s+r)),d=h>0?s:Math.min(Math.max(-s,-l),s),u=-h*h+d*(d+2*l)+c);else d=o>0?-s:s,h=Math.max(0,-(o*d+r)),u=-h*h+d*(d+2*l)+c;return i&&i.copy(this.origin).addScaledVector(this.direction,h),a&&a.copy(jv).addScaledVector(kh,d),u}intersectSphere(e,t){if(e.radius<0)return null;Wa.subVectors(e.center,this.origin);const i=Wa.dot(this.direction),a=Wa.dot(Wa)-i*i,s=e.radius*e.radius;if(a>s)return null;const o=Math.sqrt(s-a),r=i-o,l=i+o;return l<0?null:r<0?this.at(l,t):this.at(r,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;const i=-(this.origin.dot(e.normal)+e.constant)/t;return i>=0?i:null}intersectPlane(e,t){const i=this.distanceToPlane(e);return i===null?null:this.at(i,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let i,a,s,o,r,l;const c=1/this.direction.x,p=1/this.direction.y,h=1/this.direction.z,d=this.origin;return c>=0?(i=(e.min.x-d.x)*c,a=(e.max.x-d.x)*c):(i=(e.max.x-d.x)*c,a=(e.min.x-d.x)*c),p>=0?(s=(e.min.y-d.y)*p,o=(e.max.y-d.y)*p):(s=(e.max.y-d.y)*p,o=(e.min.y-d.y)*p),i>o||s>a||((s>i||isNaN(i))&&(i=s),(o<a||isNaN(a))&&(a=o),h>=0?(r=(e.min.z-d.z)*h,l=(e.max.z-d.z)*h):(r=(e.max.z-d.z)*h,l=(e.min.z-d.z)*h),i>l||r>a)||((r>i||i!==i)&&(i=r),(l<a||a!==a)&&(a=l),a<0)?null:this.at(i>=0?i:a,t)}intersectsBox(e){return this.intersectBox(e,Wa)!==null}intersectTriangle(e,t,i,a,s){const o=this.origin,r=this.direction,l=r.x,c=r.y,p=r.z,h=e.x-o.x,d=e.y-o.y,u=e.z-o.z,f=t.x-o.x,v=t.y-o.y,g=t.z-o.z,m=i.x-o.x,x=i.y-o.y,_=i.z-o.z,w=Math.abs(l),S=Math.abs(c),A=Math.abs(p);let C,y,M,T,L,P,z,R,B,K,N,V;if(w>=S&&w>=A?(M=l,P=h,B=f,V=m,l>=0?(C=c,y=p,T=d,L=u,z=v,R=g,K=x,N=_):(C=p,y=c,T=u,L=d,z=g,R=v,K=_,N=x)):S>=A?(M=c,P=d,B=v,V=x,c>=0?(C=p,y=l,T=u,L=h,z=g,R=f,K=_,N=m):(C=l,y=p,T=h,L=u,z=f,R=g,K=m,N=_)):(M=p,P=u,B=g,V=_,p>=0?(C=l,y=c,T=h,L=d,z=f,R=v,K=m,N=x):(C=c,y=l,T=d,L=h,z=v,R=f,K=x,N=m)),M===0)return null;const Z=C/M,te=y/M,ce=1/M,Ne=T-Z*P,He=L-te*P,ct=z-Z*B,ot=R-te*B,ft=K-Z*V,ne=N-te*V,oe=ft*ot-ne*ct,Te=Ne*ne-He*ft,We=ct*He-ot*Ne;if(a){if(oe<0||Te<0||We<0)return null}else if((oe<0||Te<0||We<0)&&(oe>0||Te>0||We>0))return null;const Re=oe+Te+We;if(Re===0)return null;const $=ce*(oe*P+Te*B+We*V);return(Re>0?$<0:$>0)?null:this.at($/Re,s)}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)}}class ek extends Br{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new It(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 Ao,this.combine=v2,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}}const tk=new en,Co=new Sh,Mh=new Oc,nk=new X,Ah=new X,Th=new X,Eh=new X,Zv=new X,Ch=new X,ik=new X,Rh=new X;class Xa extends Wn{constructor(e=new pn,t=new ek){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,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(){const t=this.geometry.morphAttributes,i=Object.keys(t);if(i.length>0){const a=t[i[0]];if(a!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=a.length;s<o;s++){const r=a[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[r]=s}}}}getVertexPosition(e,t){const i=this.geometry,a=i.attributes.position,s=i.morphAttributes.position,o=i.morphTargetsRelative;t.fromBufferAttribute(a,e);const r=this.morphTargetInfluences;if(s&&r){Ch.set(0,0,0);for(let l=0,c=s.length;l<c;l++){const p=r[l],h=s[l];p!==0&&(Zv.fromBufferAttribute(h,e),o?Ch.addScaledVector(Zv,p):Ch.addScaledVector(Zv.sub(t),p))}t.add(Ch)}return t}intersectsFrustum(e){return e.intersectsObject(this)}raycast(e,t){const i=this.geometry,a=this.material,s=this.matrixWorld;a!==void 0&&(i.boundingSphere===null&&i.computeBoundingSphere(),Mh.copy(i.boundingSphere),Mh.applyMatrix4(s),Co.copy(e.ray).recast(e.near),!(Mh.containsPoint(Co.origin)===!1&&(Co.intersectSphere(Mh,nk)===null||Co.origin.distanceToSquared(nk)>(e.far-e.near)**2))&&(tk.copy(s).invert(),Co.copy(e.ray).applyMatrix4(tk),!(i.boundingBox!==null&&Co.intersectsBox(i.boundingBox)===!1)&&this._computeIntersections(e,t,Co)))}_computeIntersections(e,t,i){let a;const s=this.geometry,o=this.material,r=s.index,l=s.attributes.position,c=s.attributes.uv,p=s.attributes.uv1,h=s.attributes.normal,d=s.groups,u=s.drawRange;if(r!==null)if(Array.isArray(o))for(let f=0,v=d.length;f<v;f++){const g=d[f],m=o[g.materialIndex],x=Math.max(g.start,u.start),_=Math.min(r.count,Math.min(g.start+g.count,u.start+u.count));for(let w=x,S=_;w<S;w+=3){const A=r.getX(w),C=r.getX(w+1),y=r.getX(w+2);a=Lh(this,m,e,i,c,p,h,A,C,y),a&&(a.faceIndex=Math.floor(w/3),a.face.materialIndex=g.materialIndex,t.push(a))}}else{const f=Math.max(0,u.start),v=Math.min(r.count,u.start+u.count);for(let g=f,m=v;g<m;g+=3){const x=r.getX(g),_=r.getX(g+1),w=r.getX(g+2);a=Lh(this,o,e,i,c,p,h,x,_,w),a&&(a.faceIndex=Math.floor(g/3),t.push(a))}}else if(l!==void 0)if(Array.isArray(o))for(let f=0,v=d.length;f<v;f++){const g=d[f],m=o[g.materialIndex],x=Math.max(g.start,u.start),_=Math.min(l.count,Math.min(g.start+g.count,u.start+u.count));for(let w=x,S=_;w<S;w+=3){const A=w,C=w+1,y=w+2;a=Lh(this,m,e,i,c,p,h,A,C,y),a&&(a.faceIndex=Math.floor(w/3),a.face.materialIndex=g.materialIndex,t.push(a))}}else{const f=Math.max(0,u.start),v=Math.min(l.count,u.start+u.count);for(let g=f,m=v;g<m;g+=3){const x=g,_=g+1,w=g+2;a=Lh(this,o,e,i,c,p,h,x,_,w),a&&(a.faceIndex=Math.floor(g/3),t.push(a))}}}}function v5(n,e,t,i,a,s,o,r){let l;if(e.side===ei?l=i.intersectTriangle(o,s,a,!0,r):l=i.intersectTriangle(a,s,o,e.side===wo,r),l===null)return null;Rh.copy(r),Rh.applyMatrix4(n.matrixWorld);const c=t.ray.origin.distanceTo(Rh);return c<t.near||c>t.far?null:{distance:c,point:Rh.clone(),object:n}}function Lh(n,e,t,i,a,s,o,r,l,c){n.getVertexPosition(r,Ah),n.getVertexPosition(l,Th),n.getVertexPosition(c,Eh);const p=v5(n,e,t,i,Ah,Th,Eh,ik);if(p){const h=new X;zi.getBarycoord(ik,Ah,Th,Eh,h),a&&(p.uv=zi.getInterpolatedAttribute(a,r,l,c,h,new ut)),s&&(p.uv1=zi.getInterpolatedAttribute(s,r,l,c,h,new ut)),o&&(p.normal=zi.getInterpolatedAttribute(o,r,l,c,h,new X),p.normal.dot(i.direction)>0&&p.normal.multiplyScalar(-1));const d={a:r,b:l,c,normal:new X,materialIndex:0};zi.getNormal(Ah,Th,Eh,d.normal),p.face=d,p.barycoord=h}return p}class x5 extends Vn{constructor(e=null,t=1,i=1,a,s,o,r,l,c=Sn,p=Sn,h,d){super(null,o,r,l,c,p,a,s,h,d),this.isDataTexture=!0,this.image={data:e,width:t,height:i},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}const Ro=new Oc,b5=new ut(.5,.5),Ph=new X;class ak{constructor(e=new Va,t=new Va,i=new Va,a=new Va,s=new Va,o=new Va){this.planes=[e,t,i,a,s,o]}set(e,t,i,a,s,o){const r=this.planes;return r[0].copy(e),r[1].copy(t),r[2].copy(i),r[3].copy(a),r[4].copy(s),r[5].copy(o),this}copy(e){const t=this.planes;for(let i=0;i<6;i++)t[i].copy(e.planes[i]);return this}setFromProjectionMatrix(e,t=oa,i=!1){const a=this.planes,s=e.elements,o=s[0],r=s[1],l=s[2],c=s[3],p=s[4],h=s[5],d=s[6],u=s[7],f=s[8],v=s[9],g=s[10],m=s[11],x=s[12],_=s[13],w=s[14],S=s[15];if(a[0].setComponents(c-o,u-p,m-f,S-x).normalize(),a[1].setComponents(c+o,u+p,m+f,S+x).normalize(),a[2].setComponents(c+r,u+h,m+v,S+_).normalize(),a[3].setComponents(c-r,u-h,m-v,S-_).normalize(),i)a[4].setComponents(l,d,g,w).normalize(),a[5].setComponents(c-l,u-d,m-g,S-w).normalize();else if(a[4].setComponents(c-l,u-d,m-g,S-w).normalize(),t===oa)a[5].setComponents(c+l,u+d,m+g,S+w).normalize();else if(t===ph)a[5].setComponents(l,d,g,w).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(),Ro.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Ro.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Ro)}intersectsSprite(e){Ro.center.set(0,0,0);const t=b5.distanceTo(e.center);return Ro.radius=.7071067811865476+t,Ro.applyMatrix4(e.matrixWorld),this.intersectsSphere(Ro)}intersectsSphere(e){const t=this.planes,i=e.center,a=-e.radius;for(let s=0;s<6;s++)if(t[s].distanceToPoint(i)<a)return!1;return!0}intersectsBox(e){const t=this.planes;for(let i=0;i<6;i++){const a=t[i];if(Ph.x=a.normal.x>0?e.max.x:e.min.x,Ph.y=a.normal.y>0?e.max.y:e.min.y,Ph.z=a.normal.z>0?e.max.z:e.min.z,a.distanceToPoint(Ph)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let i=0;i<6;i++)if(t[i].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}}class y5 extends Br{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new It(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}}const Ih=new X,$h=new X,sk=new en,Fc=new Sh,Nh=new Oc,Jv=new X,ok=new X;class w5 extends Wn{constructor(e=new pn,t=new y5){super(),this.isLine=!0,this.type="Line",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,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(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,i=[0];for(let a=1,s=t.count;a<s;a++)Ih.fromBufferAttribute(t,a-1),$h.fromBufferAttribute(t,a),i[a]=i[a-1],i[a]+=Ih.distanceTo($h);e.setAttribute("lineDistance",new Ui(i,1))}else rt("Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}intersectsFrustum(e){return e.intersectsObject(this)}raycast(e,t){const i=this.geometry,a=this.matrixWorld,s=e.params.Line.threshold,o=i.drawRange;if(i.boundingSphere===null&&i.computeBoundingSphere(),Nh.copy(i.boundingSphere),Nh.applyMatrix4(a),Nh.radius+=s,e.ray.intersectsSphere(Nh)===!1)return;sk.copy(a).invert(),Fc.copy(e.ray).applyMatrix4(sk);const r=s/((this.scale.x+this.scale.y+this.scale.z)/3),l=r*r,c=this.isLineSegments?2:1,p=i.index,d=i.attributes.position;if(p!==null){const u=Math.max(0,o.start),f=Math.min(p.count,o.start+o.count);for(let v=u,g=f-1;v<g;v+=c){const m=p.getX(v),x=p.getX(v+1),_=Dh(this,e,Fc,l,m,x,v);_&&t.push(_)}if(this.isLineLoop){const v=p.getX(f-1),g=p.getX(u),m=Dh(this,e,Fc,l,v,g,f-1);m&&t.push(m)}}else{const u=Math.max(0,o.start),f=Math.min(d.count,o.start+o.count);for(let v=u,g=f-1;v<g;v+=c){const m=Dh(this,e,Fc,l,v,v+1,v);m&&t.push(m)}if(this.isLineLoop){const v=Dh(this,e,Fc,l,f-1,u,f-1);v&&t.push(v)}}}updateMorphTargets(){const t=this.geometry.morphAttributes,i=Object.keys(t);if(i.length>0){const a=t[i[0]];if(a!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=a.length;s<o;s++){const r=a[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[r]=s}}}}}function Dh(n,e,t,i,a,s,o){const r=n.geometry.attributes.position;if(Ih.fromBufferAttribute(r,a),$h.fromBufferAttribute(r,s),t.distanceSqToSegment(Ih,$h,Jv,ok)>i)return;Jv.applyMatrix4(n.matrixWorld);const c=e.ray.origin.distanceTo(Jv);if(!(c<e.near||c>e.far))return{distance:c,point:ok.clone().applyMatrix4(n.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:n}}const rk=new X,lk=new X;class Qv extends w5{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type="LineSegments"}computeLineDistances(){const e=this.geometry;if(e.index===null){const t=e.attributes.position,i=[];for(let a=0,s=t.count;a<s;a+=2)rk.fromBufferAttribute(t,a),lk.fromBufferAttribute(t,a+1),i[a]=a===0?0:i[a-1],i[a+1]=i[a]+rk.distanceTo(lk);e.setAttribute("lineDistance",new Ui(i,1))}else rt("LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.");return this}}class k5 extends Br{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new It(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}}const ck=new en,ex=new Sh,zh=new Oc,Oh=new X;class tx extends Wn{constructor(e=new pn,t=new k5){super(),this.isPoints=!0,this.type="Points",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,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}intersectsFrustum(e){return e.intersectsObject(this)}raycast(e,t){const i=this.geometry,a=this.matrixWorld,s=e.params.Points.threshold,o=i.drawRange;if(i.boundingSphere===null&&i.computeBoundingSphere(),zh.copy(i.boundingSphere),zh.applyMatrix4(a),zh.radius+=s,e.ray.intersectsSphere(zh)===!1)return;ck.copy(a).invert(),ex.copy(e.ray).applyMatrix4(ck);const r=s/((this.scale.x+this.scale.y+this.scale.z)/3),l=r*r,c=i.index,h=i.attributes.position;if(c!==null){const d=Math.max(0,o.start),u=Math.min(c.count,o.start+o.count);for(let f=d,v=u;f<v;f++){const g=c.getX(f);Oh.fromBufferAttribute(h,g),dk(Oh,g,l,a,e,t,this)}}else{const d=Math.max(0,o.start),u=Math.min(h.count,o.start+o.count);for(let f=d,v=u;f<v;f++)Oh.fromBufferAttribute(h,f),dk(Oh,f,l,a,e,t,this)}}updateMorphTargets(){const t=this.geometry.morphAttributes,i=Object.keys(t);if(i.length>0){const a=t[i[0]];if(a!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let s=0,o=a.length;s<o;s++){const r=a[s].name||String(s);this.morphTargetInfluences.push(0),this.morphTargetDictionary[r]=s}}}}}function dk(n,e,t,i,a,s,o){const r=ex.distanceSqToPoint(n);if(r<t){const l=new X;ex.closestPointToPoint(n,l),l.applyMatrix4(i);const c=a.ray.origin.distanceTo(l);if(c<a.near||c>a.far)return;s.push({distance:c,distanceToRay:Math.sqrt(r),point:l,index:e,face:null,faceIndex:null,barycoord:null,object:o})}}class pk extends Vn{constructor(e=[],t=ko,i,a,s,o,r,l,c,p){super(e,t,i,a,s,o,r,l,c,p),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Bc extends Vn{constructor(e,t,i=ia,a,s,o,r=Sn,l=Sn,c,p=Ua,h=1){if(p!==Ua&&p!==So)throw new Error("THREE.DepthTexture: format must be either THREE.DepthFormat or THREE.DepthStencilFormat");const d={width:e,height:t,depth:h};super(d,a,s,o,r,l,p,i,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Iv(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return t.compareFunction=this.compareFunction,t}}class _5 extends Bc{constructor(e,t=ia,i=ko,a,s,o=Sn,r=Sn,l,c=Ua){const p={width:e,height:e,depth:1},h=[p,p,p,p,p,p];super(e,e,t,i,a,s,o,r,l,c),this.image=h,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class hk extends Vn{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}}class Hc extends pn{constructor(e=1,t=1,i=1,a=1,s=1,o=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:i,widthSegments:a,heightSegments:s,depthSegments:o};const r=this;a=Math.floor(a),s=Math.floor(s),o=Math.floor(o);const l=[],c=[],p=[],h=[];let d=0,u=0;f("z","y","x",-1,-1,i,t,e,o,s,0),f("z","y","x",1,-1,i,t,-e,o,s,1),f("x","z","y",1,1,e,i,t,a,o,2),f("x","z","y",1,-1,e,i,-t,a,o,3),f("x","y","z",1,-1,e,t,i,a,s,4),f("x","y","z",-1,-1,e,t,-i,a,s,5),this.setIndex(l),this.setAttribute("position",new Ui(c,3)),this.setAttribute("normal",new Ui(p,3)),this.setAttribute("uv",new Ui(h,2));function f(v,g,m,x,_,w,S,A,C,y,M){const T=w/C,L=S/y,P=w/2,z=S/2,R=A/2,B=C+1,K=y+1;let N=0,V=0;const Z=new X;for(let te=0;te<K;te++){const ce=te*L-z;for(let Ne=0;Ne<B;Ne++){const He=Ne*T-P;Z[v]=He*x,Z[g]=ce*_,Z[m]=R,c.push(Z.x,Z.y,Z.z),Z[v]=0,Z[g]=0,Z[m]=A>0?1:-1,p.push(Z.x,Z.y,Z.z),h.push(Ne/C),h.push(1-te/y),N+=1}}for(let te=0;te<y;te++)for(let ce=0;ce<C;ce++){const Ne=d+ce+B*te,He=d+ce+B*(te+1),ct=d+(ce+1)+B*(te+1),ot=d+(ce+1)+B*te;l.push(Ne,He,ot),l.push(He,ct,ot),V+=6}r.addGroup(u,V,M),u+=V,d+=N}}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Hc(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}class Uh extends pn{constructor(e=1,t=1,i=1,a=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:i,heightSegments:a};const s=e/2,o=t/2,r=Math.floor(i),l=Math.floor(a),c=r+1,p=l+1,h=e/r,d=t/l,u=[],f=[],v=[],g=[];for(let m=0;m<p;m++){const x=m*d-o;for(let _=0;_<c;_++){const w=_*h-s;f.push(w,-x,0),v.push(0,0,1),g.push(_/r),g.push(1-m/l)}}for(let m=0;m<l;m++)for(let x=0;x<r;x++){const _=x+c*m,w=x+c*(m+1),S=x+1+c*(m+1),A=x+1+c*m;u.push(_,w,A),u.push(w,S,A)}this.setIndex(u),this.setAttribute("position",new Ui(f,3)),this.setAttribute("normal",new Ui(v,3)),this.setAttribute("uv",new Ui(g,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Uh(e.width,e.height,e.widthSegments,e.heightSegments)}}function Hr(n){const e={};for(const t in n){e[t]={};for(const i in n[t]){const a=n[t][i];if(uk(a))a.isRenderTargetTexture?(rt("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),e[t][i]=null):e[t][i]=a.clone();else if(Array.isArray(a))if(uk(a[0])){const s=[];for(let o=0,r=a.length;o<r;o++)s[o]=a[o].clone();e[t][i]=s}else e[t][i]=a.slice();else e[t][i]=a}}return e}function Xn(n){const e={};for(let t=0;t<n.length;t++){const i=Hr(n[t]);for(const a in i)e[a]=i[a]}return e}function uk(n){return n&&(n.isColor||n.isMatrix3||n.isMatrix4||n.isVector2||n.isVector3||n.isVector4||n.isTexture||n.isQuaternion)}function S5(n){const e=[];for(let t=0;t<n.length;t++)e.push(n[t].clone());return e}function fk(n){const e=n.getRenderTarget();return e===null?n.outputColorSpace:e.isXRRenderTarget===!0?e.texture.colorSpace:St.workingColorSpace}const M5={clone:Hr,merge:Xn};var A5=`void main() {
4286
4286
  gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
4287
4287
  }`,T5=`void main() {
4288
4288
  gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
4289
- }`;class Pn extends Br{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=A5,this.fragmentShader=T5,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=Hr(e.uniforms),this.uniformsGroups=S5(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.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const a in this.uniforms){const o=this.uniforms[a].value;o&&o.isTexture?t.uniforms[a]={type:"t",value:o.toJSON(e).uuid}:o&&o.isColor?t.uniforms[a]={type:"c",value:o.getHex()}:o&&o.isVector2?t.uniforms[a]={type:"v2",value:o.toArray()}:o&&o.isVector3?t.uniforms[a]={type:"v3",value:o.toArray()}:o&&o.isVector4?t.uniforms[a]={type:"v4",value:o.toArray()}:o&&o.isMatrix3?t.uniforms[a]={type:"m3",value:o.toArray()}:o&&o.isMatrix4?t.uniforms[a]={type:"m4",value:o.toArray()}:t.uniforms[a]={value:o}}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;const i={};for(const a in this.extensions)this.extensions[a]===!0&&(i[a]=!0);return Object.keys(i).length>0&&(t.extensions=i),t}fromJSON(e,t){if(super.fromJSON(e,t),e.uniforms!==void 0)for(const i in e.uniforms){const a=e.uniforms[i];switch(this.uniforms[i]={},a.type){case"t":this.uniforms[i].value=t[a.value]||null;break;case"c":this.uniforms[i].value=new It().setHex(a.value);break;case"v2":this.uniforms[i].value=new ut().fromArray(a.value);break;case"v3":this.uniforms[i].value=new X().fromArray(a.value);break;case"v4":this.uniforms[i].value=new nn().fromArray(a.value);break;case"m3":this.uniforms[i].value=new pt().fromArray(a.value);break;case"m4":this.uniforms[i].value=new en().fromArray(a.value);break;default:this.uniforms[i].value=a.value}}if(e.defines!==void 0&&(this.defines=e.defines),e.vertexShader!==void 0&&(this.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(this.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(this.glslVersion=e.glslVersion),e.extensions!==void 0)for(const i in e.extensions)this.extensions[i]=e.extensions[i];return e.lights!==void 0&&(this.lights=e.lights),e.clipping!==void 0&&(this.clipping=e.clipping),this}}class E5 extends Pn{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class C5 extends Br{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=$4,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}}class R5 extends Br{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}}const Fh=new X,Bh=new Ls,la=new X;class mk extends Wn{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new en,this.projectionMatrix=new en,this.projectionMatrixInverse=new en,this.coordinateSystem=oa,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}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.matrixWorld.decompose(Fh,Bh,la),la.x===1&&la.y===1&&la.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(Fh,Bh,la.set(1,1,1)).invert()}updateWorldMatrix(e,t,i=!1){super.updateWorldMatrix(e,t,i),this.matrixWorld.decompose(Fh,Bh,la),la.x===1&&la.y===1&&la.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(Fh,Bh,la.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}}const Ds=new X,gk=new ut,vk=new ut;class wi extends mk{constructor(e=50,t=1,i=.1,a=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=i,this.far=a,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){const t=.5*this.getFilmHeight()/e;this.fov=Cv*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(uh*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Cv*2*Math.atan(Math.tan(uh*.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,i){Ds.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Ds.x,Ds.y).multiplyScalar(-e/Ds.z),Ds.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),i.set(Ds.x,Ds.y).multiplyScalar(-e/Ds.z)}getViewSize(e,t){return this.getViewBounds(e,gk,vk),t.subVectors(vk,gk)}setViewOffset(e,t,i,a,s,o){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=i,this.view.offsetY=a,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(uh*.5*this.fov)/this.zoom,i=2*t,a=this.aspect*i,s=-.5*a;const o=this.view;if(this.view!==null&&this.view.enabled){const l=o.fullWidth,c=o.fullHeight;s+=o.offsetX*a/l,t-=o.offsetY*i/c,a*=o.width/l,i*=o.height/c}const r=this.filmOffset;r!==0&&(s+=e*r/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+a,t,t-i,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const 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}}class xk extends mk{constructor(e=-1,t=1,i=1,a=-1,s=.1,o=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=i,this.bottom=a,this.near=s,this.far=o,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,i,a,s,o){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=i,this.view.offsetY=a,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),i=(this.right+this.left)/2,a=(this.top+this.bottom)/2;let s=i-e,o=i+e,r=a+t,l=a-t;if(this.view!==null&&this.view.enabled){const c=(this.right-this.left)/this.view.fullWidth/this.zoom,p=(this.top-this.bottom)/this.view.fullHeight/this.zoom;s+=c*this.view.offsetX,o=s+c*this.view.width,r-=p*this.view.offsetY,l=r-p*this.view.height}this.projectionMatrix.makeOrthographic(s,o,r,l,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const 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}}const Gr=-90,qr=1;class L5 extends Wn{constructor(e,t,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const a=new wi(Gr,qr,e,t);a.layers=this.layers,this.add(a);const s=new wi(Gr,qr,e,t);s.layers=this.layers,this.add(s);const o=new wi(Gr,qr,e,t);o.layers=this.layers,this.add(o);const r=new wi(Gr,qr,e,t);r.layers=this.layers,this.add(r);const l=new wi(Gr,qr,e,t);l.layers=this.layers,this.add(l);const c=new wi(Gr,qr,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[i,a,s,o,r,l]=t;for(const c of t)this.remove(c);if(e===oa)i.up.set(0,1,0),i.lookAt(1,0,0),a.up.set(0,1,0),a.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),o.up.set(0,0,1),o.lookAt(0,-1,0),r.up.set(0,1,0),r.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(e===ph)i.up.set(0,-1,0),i.lookAt(-1,0,0),a.up.set(0,-1,0),a.lookAt(1,0,0),s.up.set(0,0,1),s.lookAt(0,1,0),o.up.set(0,0,-1),o.lookAt(0,-1,0),r.up.set(0,-1,0),r.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const c of t)this.add(c),c.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:i,activeMipmapLevel:a}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[s,o,r,l,c,p]=this.children,h=e.getRenderTarget(),d=e.getActiveCubeFace(),u=e.getActiveMipmapLevel(),f=e.xr.enabled;e.xr.enabled=!1;const v=i.texture.generateMipmaps;i.texture.generateMipmaps=!1;let g=!1;e.isWebGLRenderer===!0?g=e.state.buffers.depth.getReversed():g=e.reversedDepthBuffer,e.setRenderTarget(i,0,a),g&&e.autoClear===!1&&e.clearDepth(),e.render(t,s),e.setRenderTarget(i,1,a),g&&e.autoClear===!1&&e.clearDepth(),e.render(t,o),e.setRenderTarget(i,2,a),g&&e.autoClear===!1&&e.clearDepth(),e.render(t,r),e.setRenderTarget(i,3,a),g&&e.autoClear===!1&&e.clearDepth(),e.render(t,l),e.setRenderTarget(i,4,a),g&&e.autoClear===!1&&e.clearDepth(),e.render(t,c),i.texture.generateMipmaps=v,e.setRenderTarget(i,5,a),g&&e.autoClear===!1&&e.clearDepth(),e.render(t,p),e.setRenderTarget(h,d,u),e.xr.enabled=f,i.texture.needsPMREMUpdate=!0}}class P5 extends wi{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class bk{constructor(e=1,t=0,i=0){this.radius=e,this.phi=t,this.theta=i}set(e,t,i){return this.radius=e,this.phi=t,this.theta=i,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){return this.phi=yt(this.phi,1e-6,Math.PI-1e-6),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,i){return this.radius=Math.sqrt(e*e+t*t+i*i),this.radius===0?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,i),this.phi=Math.acos(yt(t/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}}const lb=class lb{constructor(e,t,i,a){this.elements=[1,0,0,1],e!==void 0&&this.set(e,t,i,a)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let i=0;i<4;i++)this.elements[i]=e[i+t];return this}set(e,t,i,a){const s=this.elements;return s[0]=e,s[2]=t,s[1]=i,s[3]=a,this}};lb.prototype.isMatrix2=!0;let yk=lb;class I5 extends Rs{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(e){this.domElement!==null&&this.disconnect(),this.domElement=e}disconnect(){}dispose(){}update(){}}function wk(n,e,t,i){const a=$5(i);switch(t){case R2:return n*e;case P2:return n*e/a.components*a.byteLength;case Xg:return n*e/a.components*a.byteLength;case Mo:return n*e*2/a.components*a.byteLength;case Kg:return n*e*2/a.components*a.byteLength;case L2:return n*e*3/a.components*a.byteLength;case Ii:return n*e*4/a.components*a.byteLength;case Yg:return n*e*4/a.components*a.byteLength;case ih:case ah:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*8;case sh:case oh:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case Zg:case Qg:return Math.max(n,16)*Math.max(e,8)/4;case jg:case Jg:return Math.max(n,8)*Math.max(e,8)/2;case ev:case tv:case iv:case av:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*8;case nv:case rh:case sv:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case ov:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case rv:return Math.floor((n+4)/5)*Math.floor((e+3)/4)*16;case lv:return Math.floor((n+4)/5)*Math.floor((e+4)/5)*16;case cv:return Math.floor((n+5)/6)*Math.floor((e+4)/5)*16;case dv:return Math.floor((n+5)/6)*Math.floor((e+5)/6)*16;case pv:return Math.floor((n+7)/8)*Math.floor((e+4)/5)*16;case hv:return Math.floor((n+7)/8)*Math.floor((e+5)/6)*16;case uv:return Math.floor((n+7)/8)*Math.floor((e+7)/8)*16;case fv:return Math.floor((n+9)/10)*Math.floor((e+4)/5)*16;case mv:return Math.floor((n+9)/10)*Math.floor((e+5)/6)*16;case gv:return Math.floor((n+9)/10)*Math.floor((e+7)/8)*16;case vv:return Math.floor((n+9)/10)*Math.floor((e+9)/10)*16;case xv:return Math.floor((n+11)/12)*Math.floor((e+9)/10)*16;case bv:return Math.floor((n+11)/12)*Math.floor((e+11)/12)*16;case yv:case wv:case kv:return Math.ceil(n/4)*Math.ceil(e/4)*16;case _v:case Sv:return Math.ceil(n/4)*Math.ceil(e/4)*8;case lh:case Mv:return Math.ceil(n/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function $5(n){switch(n){case xi:case A2:return{byteLength:1,components:1};case Rc:case T2:case sa:return{byteLength:2,components:1};case Vg:case Wg:return{byteLength:2,components:4};case ia:case qg:case aa:return{byteLength:4,components:1};case E2:case C2:return{byteLength:4,components:3}}throw new Error(`THREE.TextureUtils: Unknown texture type ${n}.`)}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:Lg}})),typeof window<"u"&&(window.__THREE__?rt("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=Lg);function kk(){let n=null,e=!1,t=null,i=null;function a(s,o){i=n.requestAnimationFrame(a),t(s,o)}return{start:function(){e!==!0&&t!==null&&n!==null&&(i=n.requestAnimationFrame(a),e=!0)},stop:function(){n!==null&&n.cancelAnimationFrame(i),e=!1},setAnimationLoop:function(s){t=s},setContext:function(s){n=s}}}function N5(n){const e=new WeakMap;function t(r,l){const c=r.array,p=r.usage,h=c.byteLength,d=n.createBuffer();n.bindBuffer(l,d),n.bufferData(l,c,p),r.onUploadCallback();let u;if(c instanceof Float32Array)u=n.FLOAT;else if(typeof Float16Array<"u"&&c instanceof Float16Array)u=n.HALF_FLOAT;else if(c instanceof Uint16Array)r.isFloat16BufferAttribute?u=n.HALF_FLOAT:u=n.UNSIGNED_SHORT;else if(c instanceof Int16Array)u=n.SHORT;else if(c instanceof Uint32Array)u=n.UNSIGNED_INT;else if(c instanceof Int32Array)u=n.INT;else if(c instanceof Int8Array)u=n.BYTE;else if(c instanceof Uint8Array)u=n.UNSIGNED_BYTE;else if(c instanceof Uint8ClampedArray)u=n.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+c);return{buffer:d,type:u,bytesPerElement:c.BYTES_PER_ELEMENT,version:r.version,size:h}}function i(r,l,c){const p=l.array,h=l.updateRanges;if(n.bindBuffer(c,r),h.length===0)n.bufferSubData(c,0,p);else{h.sort((u,f)=>u.start-f.start);let d=0;for(let u=1;u<h.length;u++){const f=h[d],v=h[u];v.start<=f.start+f.count+1?f.count=Math.max(f.count,v.start+v.count-f.start):(++d,h[d]=v)}h.length=d+1;for(let u=0,f=h.length;u<f;u++){const v=h[u];n.bufferSubData(c,v.start*p.BYTES_PER_ELEMENT,p,v.start,v.count)}l.clearUpdateRanges()}l.onUploadCallback()}function a(r){return r.isInterleavedBufferAttribute&&(r=r.data),e.get(r)}function s(r){r.isInterleavedBufferAttribute&&(r=r.data);const l=e.get(r);l&&(n.deleteBuffer(l.buffer),e.delete(r))}function o(r,l){if(r.isInterleavedBufferAttribute&&(r=r.data),r.isGLBufferAttribute){const p=e.get(r);(!p||p.version<r.version)&&e.set(r,{buffer:r.buffer,type:r.type,bytesPerElement:r.elementSize,version:r.version});return}const c=e.get(r);if(c===void 0)e.set(r,t(r,l));else if(c.version<r.version){if(c.size!==r.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,r,l),c.version=r.version}}return{get:a,remove:s,update:o}}var D5=`#ifdef USE_ALPHAHASH
4289
+ }`;class Pn extends Br{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader=A5,this.fragmentShader=T5,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=Hr(e.uniforms),this.uniformsGroups=S5(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.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const a in this.uniforms){const o=this.uniforms[a].value;o&&o.isTexture?t.uniforms[a]={type:"t",value:o.toJSON(e).uuid}:o&&o.isColor?t.uniforms[a]={type:"c",value:o.getHex()}:o&&o.isVector2?t.uniforms[a]={type:"v2",value:o.toArray()}:o&&o.isVector3?t.uniforms[a]={type:"v3",value:o.toArray()}:o&&o.isVector4?t.uniforms[a]={type:"v4",value:o.toArray()}:o&&o.isMatrix3?t.uniforms[a]={type:"m3",value:o.toArray()}:o&&o.isMatrix4?t.uniforms[a]={type:"m4",value:o.toArray()}:t.uniforms[a]={value:o}}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;const i={};for(const a in this.extensions)this.extensions[a]===!0&&(i[a]=!0);return Object.keys(i).length>0&&(t.extensions=i),t}fromJSON(e,t){if(super.fromJSON(e,t),e.uniforms!==void 0)for(const i in e.uniforms){const a=e.uniforms[i];switch(this.uniforms[i]={},a.type){case"t":this.uniforms[i].value=t[a.value]||null;break;case"c":this.uniforms[i].value=new It().setHex(a.value);break;case"v2":this.uniforms[i].value=new ut().fromArray(a.value);break;case"v3":this.uniforms[i].value=new X().fromArray(a.value);break;case"v4":this.uniforms[i].value=new nn().fromArray(a.value);break;case"m3":this.uniforms[i].value=new pt().fromArray(a.value);break;case"m4":this.uniforms[i].value=new en().fromArray(a.value);break;default:this.uniforms[i].value=a.value}}if(e.defines!==void 0&&(this.defines=e.defines),e.vertexShader!==void 0&&(this.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(this.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(this.glslVersion=e.glslVersion),e.extensions!==void 0)for(const i in e.extensions)this.extensions[i]=e.extensions[i];return e.lights!==void 0&&(this.lights=e.lights),e.clipping!==void 0&&(this.clipping=e.clipping),this}}class E5 extends Pn{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type="RawShaderMaterial"}}class C5 extends Br{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type="MeshDepthMaterial",this.depthPacking=$R,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}}class R5 extends Br{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}}const Fh=new X,Bh=new Ls,la=new X;class mk extends Wn{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new en,this.projectionMatrix=new en,this.projectionMatrixInverse=new en,this.coordinateSystem=oa,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}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.matrixWorld.decompose(Fh,Bh,la),la.x===1&&la.y===1&&la.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(Fh,Bh,la.set(1,1,1)).invert()}updateWorldMatrix(e,t,i=!1){super.updateWorldMatrix(e,t,i),this.matrixWorld.decompose(Fh,Bh,la),la.x===1&&la.y===1&&la.z===1?this.matrixWorldInverse.copy(this.matrixWorld).invert():this.matrixWorldInverse.compose(Fh,Bh,la.set(1,1,1)).invert()}clone(){return new this.constructor().copy(this)}}const Ds=new X,gk=new ut,vk=new ut;class wi extends mk{constructor(e=50,t=1,i=.1,a=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=i,this.far=a,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){const t=.5*this.getFilmHeight()/e;this.fov=Cv*2*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(uh*.5*this.fov);return .5*this.getFilmHeight()/e}getEffectiveFOV(){return Cv*2*Math.atan(Math.tan(uh*.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,i){Ds.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Ds.x,Ds.y).multiplyScalar(-e/Ds.z),Ds.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),i.set(Ds.x,Ds.y).multiplyScalar(-e/Ds.z)}getViewSize(e,t){return this.getViewBounds(e,gk,vk),t.subVectors(vk,gk)}setViewOffset(e,t,i,a,s,o){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=i,this.view.offsetY=a,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(uh*.5*this.fov)/this.zoom,i=2*t,a=this.aspect*i,s=-.5*a;const o=this.view;if(this.view!==null&&this.view.enabled){const l=o.fullWidth,c=o.fullHeight;s+=o.offsetX*a/l,t-=o.offsetY*i/c,a*=o.width/l,i*=o.height/c}const r=this.filmOffset;r!==0&&(s+=e*r/this.getFilmWidth()),this.projectionMatrix.makePerspective(s,s+a,t,t-i,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const 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}}class xk extends mk{constructor(e=-1,t=1,i=1,a=-1,s=.1,o=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=i,this.bottom=a,this.near=s,this.far=o,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,i,a,s,o){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=i,this.view.offsetY=a,this.view.width=s,this.view.height=o,this.updateProjectionMatrix()}clearViewOffset(){this.view!==null&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),i=(this.right+this.left)/2,a=(this.top+this.bottom)/2;let s=i-e,o=i+e,r=a+t,l=a-t;if(this.view!==null&&this.view.enabled){const c=(this.right-this.left)/this.view.fullWidth/this.zoom,p=(this.top-this.bottom)/this.view.fullHeight/this.zoom;s+=c*this.view.offsetX,o=s+c*this.view.width,r-=p*this.view.offsetY,l=r-p*this.view.height}this.projectionMatrix.makeOrthographic(s,o,r,l,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const 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}}const Gr=-90,qr=1;class L5 extends Wn{constructor(e,t,i){super(),this.type="CubeCamera",this.renderTarget=i,this.coordinateSystem=null,this.activeMipmapLevel=0;const a=new wi(Gr,qr,e,t);a.layers=this.layers,this.add(a);const s=new wi(Gr,qr,e,t);s.layers=this.layers,this.add(s);const o=new wi(Gr,qr,e,t);o.layers=this.layers,this.add(o);const r=new wi(Gr,qr,e,t);r.layers=this.layers,this.add(r);const l=new wi(Gr,qr,e,t);l.layers=this.layers,this.add(l);const c=new wi(Gr,qr,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[i,a,s,o,r,l]=t;for(const c of t)this.remove(c);if(e===oa)i.up.set(0,1,0),i.lookAt(1,0,0),a.up.set(0,1,0),a.lookAt(-1,0,0),s.up.set(0,0,-1),s.lookAt(0,1,0),o.up.set(0,0,1),o.lookAt(0,-1,0),r.up.set(0,1,0),r.lookAt(0,0,1),l.up.set(0,1,0),l.lookAt(0,0,-1);else if(e===ph)i.up.set(0,-1,0),i.lookAt(-1,0,0),a.up.set(0,-1,0),a.lookAt(1,0,0),s.up.set(0,0,1),s.lookAt(0,1,0),o.up.set(0,0,-1),o.lookAt(0,-1,0),r.up.set(0,-1,0),r.lookAt(0,0,1),l.up.set(0,-1,0),l.lookAt(0,0,-1);else throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);for(const c of t)this.add(c),c.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();const{renderTarget:i,activeMipmapLevel:a}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[s,o,r,l,c,p]=this.children,h=e.getRenderTarget(),d=e.getActiveCubeFace(),u=e.getActiveMipmapLevel(),f=e.xr.enabled;e.xr.enabled=!1;const v=i.texture.generateMipmaps;i.texture.generateMipmaps=!1;let g=!1;e.isWebGLRenderer===!0?g=e.state.buffers.depth.getReversed():g=e.reversedDepthBuffer,e.setRenderTarget(i,0,a),g&&e.autoClear===!1&&e.clearDepth(),e.render(t,s),e.setRenderTarget(i,1,a),g&&e.autoClear===!1&&e.clearDepth(),e.render(t,o),e.setRenderTarget(i,2,a),g&&e.autoClear===!1&&e.clearDepth(),e.render(t,r),e.setRenderTarget(i,3,a),g&&e.autoClear===!1&&e.clearDepth(),e.render(t,l),e.setRenderTarget(i,4,a),g&&e.autoClear===!1&&e.clearDepth(),e.render(t,c),i.texture.generateMipmaps=v,e.setRenderTarget(i,5,a),g&&e.autoClear===!1&&e.clearDepth(),e.render(t,p),e.setRenderTarget(h,d,u),e.xr.enabled=f,i.texture.needsPMREMUpdate=!0}}class P5 extends wi{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class bk{constructor(e=1,t=0,i=0){this.radius=e,this.phi=t,this.theta=i}set(e,t,i){return this.radius=e,this.phi=t,this.theta=i,this}copy(e){return this.radius=e.radius,this.phi=e.phi,this.theta=e.theta,this}makeSafe(){return this.phi=yt(this.phi,1e-6,Math.PI-1e-6),this}setFromVector3(e){return this.setFromCartesianCoords(e.x,e.y,e.z)}setFromCartesianCoords(e,t,i){return this.radius=Math.sqrt(e*e+t*t+i*i),this.radius===0?(this.theta=0,this.phi=0):(this.theta=Math.atan2(e,i),this.phi=Math.acos(yt(t/this.radius,-1,1))),this}clone(){return new this.constructor().copy(this)}}const lb=class lb{constructor(e,t,i,a){this.elements=[1,0,0,1],e!==void 0&&this.set(e,t,i,a)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let i=0;i<4;i++)this.elements[i]=e[i+t];return this}set(e,t,i,a){const s=this.elements;return s[0]=e,s[2]=t,s[1]=i,s[3]=a,this}};lb.prototype.isMatrix2=!0;let yk=lb;class I5 extends Rs{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(e){this.domElement!==null&&this.disconnect(),this.domElement=e}disconnect(){}dispose(){}update(){}}function wk(n,e,t,i){const a=$5(i);switch(t){case R2:return n*e;case P2:return n*e/a.components*a.byteLength;case Xg:return n*e/a.components*a.byteLength;case Mo:return n*e*2/a.components*a.byteLength;case Kg:return n*e*2/a.components*a.byteLength;case L2:return n*e*3/a.components*a.byteLength;case Ii:return n*e*4/a.components*a.byteLength;case Yg:return n*e*4/a.components*a.byteLength;case ih:case ah:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*8;case sh:case oh:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case Zg:case Qg:return Math.max(n,16)*Math.max(e,8)/4;case jg:case Jg:return Math.max(n,8)*Math.max(e,8)/2;case ev:case tv:case iv:case av:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*8;case nv:case rh:case sv:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case ov:return Math.floor((n+3)/4)*Math.floor((e+3)/4)*16;case rv:return Math.floor((n+4)/5)*Math.floor((e+3)/4)*16;case lv:return Math.floor((n+4)/5)*Math.floor((e+4)/5)*16;case cv:return Math.floor((n+5)/6)*Math.floor((e+4)/5)*16;case dv:return Math.floor((n+5)/6)*Math.floor((e+5)/6)*16;case pv:return Math.floor((n+7)/8)*Math.floor((e+4)/5)*16;case hv:return Math.floor((n+7)/8)*Math.floor((e+5)/6)*16;case uv:return Math.floor((n+7)/8)*Math.floor((e+7)/8)*16;case fv:return Math.floor((n+9)/10)*Math.floor((e+4)/5)*16;case mv:return Math.floor((n+9)/10)*Math.floor((e+5)/6)*16;case gv:return Math.floor((n+9)/10)*Math.floor((e+7)/8)*16;case vv:return Math.floor((n+9)/10)*Math.floor((e+9)/10)*16;case xv:return Math.floor((n+11)/12)*Math.floor((e+9)/10)*16;case bv:return Math.floor((n+11)/12)*Math.floor((e+11)/12)*16;case yv:case wv:case kv:return Math.ceil(n/4)*Math.ceil(e/4)*16;case _v:case Sv:return Math.ceil(n/4)*Math.ceil(e/4)*8;case lh:case Mv:return Math.ceil(n/4)*Math.ceil(e/4)*16}throw new Error(`Unable to determine texture byte length for ${t} format.`)}function $5(n){switch(n){case xi:case A2:return{byteLength:1,components:1};case Rc:case T2:case sa:return{byteLength:2,components:1};case Vg:case Wg:return{byteLength:2,components:4};case ia:case qg:case aa:return{byteLength:4,components:1};case E2:case C2:return{byteLength:4,components:3}}throw new Error(`THREE.TextureUtils: Unknown texture type ${n}.`)}typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:Lg}})),typeof window<"u"&&(window.__THREE__?rt("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=Lg);function kk(){let n=null,e=!1,t=null,i=null;function a(s,o){i=n.requestAnimationFrame(a),t(s,o)}return{start:function(){e!==!0&&t!==null&&n!==null&&(i=n.requestAnimationFrame(a),e=!0)},stop:function(){n!==null&&n.cancelAnimationFrame(i),e=!1},setAnimationLoop:function(s){t=s},setContext:function(s){n=s}}}function N5(n){const e=new WeakMap;function t(r,l){const c=r.array,p=r.usage,h=c.byteLength,d=n.createBuffer();n.bindBuffer(l,d),n.bufferData(l,c,p),r.onUploadCallback();let u;if(c instanceof Float32Array)u=n.FLOAT;else if(typeof Float16Array<"u"&&c instanceof Float16Array)u=n.HALF_FLOAT;else if(c instanceof Uint16Array)r.isFloat16BufferAttribute?u=n.HALF_FLOAT:u=n.UNSIGNED_SHORT;else if(c instanceof Int16Array)u=n.SHORT;else if(c instanceof Uint32Array)u=n.UNSIGNED_INT;else if(c instanceof Int32Array)u=n.INT;else if(c instanceof Int8Array)u=n.BYTE;else if(c instanceof Uint8Array)u=n.UNSIGNED_BYTE;else if(c instanceof Uint8ClampedArray)u=n.UNSIGNED_BYTE;else throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: "+c);return{buffer:d,type:u,bytesPerElement:c.BYTES_PER_ELEMENT,version:r.version,size:h}}function i(r,l,c){const p=l.array,h=l.updateRanges;if(n.bindBuffer(c,r),h.length===0)n.bufferSubData(c,0,p);else{h.sort((u,f)=>u.start-f.start);let d=0;for(let u=1;u<h.length;u++){const f=h[d],v=h[u];v.start<=f.start+f.count+1?f.count=Math.max(f.count,v.start+v.count-f.start):(++d,h[d]=v)}h.length=d+1;for(let u=0,f=h.length;u<f;u++){const v=h[u];n.bufferSubData(c,v.start*p.BYTES_PER_ELEMENT,p,v.start,v.count)}l.clearUpdateRanges()}l.onUploadCallback()}function a(r){return r.isInterleavedBufferAttribute&&(r=r.data),e.get(r)}function s(r){r.isInterleavedBufferAttribute&&(r=r.data);const l=e.get(r);l&&(n.deleteBuffer(l.buffer),e.delete(r))}function o(r,l){if(r.isInterleavedBufferAttribute&&(r=r.data),r.isGLBufferAttribute){const p=e.get(r);(!p||p.version<r.version)&&e.set(r,{buffer:r.buffer,type:r.type,bytesPerElement:r.elementSize,version:r.version});return}const c=e.get(r);if(c===void 0)e.set(r,t(r,l));else if(c.version<r.version){if(c.size!==r.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,r,l),c.version=r.version}}return{get:a,remove:s,update:o}}var D5=`#ifdef USE_ALPHAHASH
4290
4290
  if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;
4291
4291
  #endif`,z5=`#ifdef USE_ALPHAHASH
4292
4292
  const float ALPHA_HASH_SCALE = 0.05;
@@ -8429,7 +8429,7 @@ void main() {
8429
8429
  `;return n.precision==="highp"?e+=`
8430
8430
  #define HIGH_PRECISION`:n.precision==="mediump"?e+=`
8431
8431
  #define MEDIUM_PRECISION`:n.precision==="lowp"&&(e+=`
8432
- #define LOW_PRECISION`),e}const dI={[eh]:"SHADOWMAP_TYPE_PCF",[Ec]:"SHADOWMAP_TYPE_VSM"};function pI(n){return dI[n.shadowMapType]||"SHADOWMAP_TYPE_BASIC"}const hI={[ko]:"ENVMAP_TYPE_CUBE",[Er]:"ENVMAP_TYPE_CUBE",[th]:"ENVMAP_TYPE_CUBE_UV"};function uI(n){return n.envMap===!1?"ENVMAP_TYPE_CUBE":hI[n.envMapMode]||"ENVMAP_TYPE_CUBE"}const fI={[Er]:"ENVMAP_MODE_REFRACTION"};function mI(n){return n.envMap===!1?"ENVMAP_MODE_REFLECTION":fI[n.envMapMode]||"ENVMAP_MODE_REFLECTION"}const gI={[v2]:"ENVMAP_BLENDING_MULTIPLY",[L4]:"ENVMAP_BLENDING_MIX",[P4]:"ENVMAP_BLENDING_ADD"};function vI(n){return n.envMap===!1?"ENVMAP_BLENDING_NONE":gI[n.combine]||"ENVMAP_BLENDING_NONE"}function xI(n){const e=n.envMapCubeUVHeight;if(e===null)return null;const t=Math.log2(e)-2,i=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:i,maxMip:t}}function bI(n,e,t,i){const a=n.getContext(),s=t.defines;let o=t.vertexShader,r=t.fragmentShader;const l=pI(t),c=uI(t),p=mI(t),h=vI(t),d=xI(t),u=nI(t),f=iI(s),v=a.createProgram();let g,m,x=t.glslVersion?"#version "+t.glslVersion+`
8432
+ #define LOW_PRECISION`),e}const dI={[eh]:"SHADOWMAP_TYPE_PCF",[Ec]:"SHADOWMAP_TYPE_VSM"};function pI(n){return dI[n.shadowMapType]||"SHADOWMAP_TYPE_BASIC"}const hI={[ko]:"ENVMAP_TYPE_CUBE",[Er]:"ENVMAP_TYPE_CUBE",[th]:"ENVMAP_TYPE_CUBE_UV"};function uI(n){return n.envMap===!1?"ENVMAP_TYPE_CUBE":hI[n.envMapMode]||"ENVMAP_TYPE_CUBE"}const fI={[Er]:"ENVMAP_MODE_REFRACTION"};function mI(n){return n.envMap===!1?"ENVMAP_MODE_REFLECTION":fI[n.envMapMode]||"ENVMAP_MODE_REFLECTION"}const gI={[v2]:"ENVMAP_BLENDING_MULTIPLY",[LR]:"ENVMAP_BLENDING_MIX",[PR]:"ENVMAP_BLENDING_ADD"};function vI(n){return n.envMap===!1?"ENVMAP_BLENDING_NONE":gI[n.combine]||"ENVMAP_BLENDING_NONE"}function xI(n){const e=n.envMapCubeUVHeight;if(e===null)return null;const t=Math.log2(e)-2,i=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:i,maxMip:t}}function bI(n,e,t,i){const a=n.getContext(),s=t.defines;let o=t.vertexShader,r=t.fragmentShader;const l=pI(t),c=uI(t),p=mI(t),h=vI(t),d=xI(t),u=nI(t),f=iI(s),v=a.createProgram();let g,m,x=t.glslVersion?"#version "+t.glslVersion+`
8433
8433
  `:"";t.isRawShaderMaterial?(g=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,f].filter(qc).join(`
8434
8434
  `),g.length>0&&(g+=`
8435
8435
  `),m=["#define SHADER_TYPE "+t.shaderType,"#define SHADER_NAME "+t.shaderName,f].filter(qc).join(`
@@ -8450,7 +8450,7 @@ Material Type: `+L.type+`
8450
8450
 
8451
8451
  Program Info Log: `+B+`
8452
8452
  `+te+`
8453
- `+ce)}else B!==""?rt("WebGLProgram: Program Info Log:",B):(K===""||N==="")&&(Z=!1);Z&&(L.diagnostics={runnable:V,programLog:B,vertexShader:{log:K,prefix:g},fragmentShader:{log:N,prefix:m}})}a.deleteShader(S),a.deleteShader(A),y=new Vh(a,v),M=aI(a,v)}let y;this.getUniforms=function(){return y===void 0&&C(this),y};let M;this.getAttributes=function(){return M===void 0&&C(this),M};let T=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return T===!1&&(T=a.getProgramParameter(v,K6)),T},this.destroy=function(){i.releaseStatesOfProgram(this),a.deleteProgram(v),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=Y6++,this.cacheKey=e,this.usedTimes=1,this.program=v,this.vertexShader=S,this.fragmentShader=A,this}let yI=0;class wI{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e,t,i){const a=this._getShaderCacheForMaterial(e);return a.has(t)===!1&&(a.add(t),t.usedTimes++),a.has(i)===!1&&(a.add(i),i.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const i of t)i.usedTimes--,i.usedTimes===0&&this.shaderCache.delete(i.code);return this.materialCache.delete(e),this}getVertexShaderStage(e){return this._getShaderStage(e.vertexShader)}getFragmentShaderStage(e){return this._getShaderStage(e.fragmentShader)}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let i=t.get(e);return i===void 0&&(i=new Set,t.set(e,i)),i}_getShaderStage(e){const t=this.shaderCache;let i=t.get(e);return i===void 0&&(i=new kI(e),t.set(e,i)),i}}class kI{constructor(e){this.id=yI++,this.code=e,this.usedTimes=0}}function _I(n){return n===Mo||n===rh||n===lh}function SI(n,e,t,i,a,s){const o=new q2,r=new wI,l=new Set,c=[],p=new Map,h=i.logarithmicDepthBuffer;let d=i.precision;const u={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",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 f(y){return l.add(y),y===0?"uv":`uv${y}`}function v(y,M,T,L,P,z){const R=L.fog,B=P.geometry,K=y.isMeshStandardMaterial||y.isMeshLambertMaterial||y.isMeshPhongMaterial?L.environment:null,N=y.isMeshStandardMaterial||y.isMeshLambertMaterial&&!y.envMap||y.isMeshPhongMaterial&&!y.envMap,V=e.get(y.envMap||K,N),Z=V&&V.mapping===th?V.image.height:null,te=u[y.type];y.precision!==null&&(d=i.getMaxPrecision(y.precision),d!==y.precision&&rt("WebGLProgram.getParameters:",y.precision,"not supported, using",d,"instead."));const ce=B.morphAttributes.position||B.morphAttributes.normal||B.morphAttributes.color,Ne=ce!==void 0?ce.length:0;let He=0;B.morphAttributes.position!==void 0&&(He=1),B.morphAttributes.normal!==void 0&&(He=2),B.morphAttributes.color!==void 0&&(He=3);let ct,ot,ft,ne;if(te){const Kt=ca[te];ct=Kt.vertexShader,ot=Kt.fragmentShader}else{ct=y.vertexShader,ot=y.fragmentShader;const Kt=r.getVertexShaderStage(y),zt=r.getFragmentShaderStage(y);r.update(y,Kt,zt),ft=Kt.id,ne=zt.id}const oe=n.getRenderTarget(),Te=n.state.buffers.depth.getReversed(),We=P.isInstancedMesh===!0,Re=P.isBatchedMesh===!0,$=!!y.map,H=!!y.matcap,Y=!!V,j=!!y.aoMap,de=!!y.lightMap,fe=!!y.bumpMap&&y.wireframe===!1,Ve=!!y.normalMap,st=!!y.displacementMap,kt=!!y.emissiveMap,Ue=!!y.metalnessMap,Ze=!!y.roughnessMap,F=y.anisotropy>0,lt=y.clearcoat>0,Je=y.dispersion>0,I=y.retroreflectivity>0,k=y.iridescence>0,W=y.sheen>0,J=y.transmission>0,ae=F&&!!y.anisotropyMap,ve=lt&&!!y.clearcoatMap,be=lt&&!!y.clearcoatNormalMap,se=lt&&!!y.clearcoatRoughnessMap,re=k&&!!y.iridescenceMap,ke=k&&!!y.iridescenceThicknessMap,Fe=W&&!!y.sheenColorMap,Me=W&&!!y.sheenRoughnessMap,_e=!!y.specularMap,Xe=!!y.specularColorMap,nt=!!y.specularIntensityMap,ht=J&&!!y.transmissionMap,q=J&&!!y.thicknessMap,Se=!!y.gradientMap,le=!!y.alphaMap,Ae=y.alphaTest>0,$e=!!y.alphaHash,me=!!y.extensions;let et=na;y.toneMapped&&(oe===null||oe.isXRRenderTarget===!0)&&(et=n.toneMapping);const Ke={shaderID:te,shaderType:y.type,shaderName:y.name,vertexShader:ct,fragmentShader:ot,defines:y.defines,customVertexShaderID:ft,customFragmentShaderID:ne,isRawShaderMaterial:y.isRawShaderMaterial===!0,glslVersion:y.glslVersion,precision:d,batching:Re,batchingColor:Re&&P._colorsTexture!==null,instancing:We,instancingColor:We&&P.instanceColor!==null,instancingMorph:We&&P.morphTexture!==null,outputColorSpace:oe===null?n.outputColorSpace:oe.isXRRenderTarget===!0?oe.texture.colorSpace:St.workingColorSpace,alphaToCoverage:!!y.alphaToCoverage,map:$,matcap:H,envMap:Y,envMapMode:Y&&V.mapping,envMapCubeUVHeight:Z,aoMap:j,lightMap:de,bumpMap:fe,normalMap:Ve,displacementMap:st,emissiveMap:kt,normalMapObjectSpace:Ve&&y.normalMapType===N4,normalMapTangentSpace:Ve&&y.normalMapType===I2,packedNormalMap:Ve&&y.normalMapType===I2&&_I(y.normalMap.format),metalnessMap:Ue,roughnessMap:Ze,anisotropy:F,anisotropyMap:ae,clearcoat:lt,clearcoatMap:ve,clearcoatNormalMap:be,clearcoatRoughnessMap:se,dispersion:Je,retroreflection:I,iridescence:k,iridescenceMap:re,iridescenceThicknessMap:ke,sheen:W,sheenColorMap:Fe,sheenRoughnessMap:Me,specularMap:_e,specularColorMap:Xe,specularIntensityMap:nt,transmission:J,transmissionMap:ht,thicknessMap:q,gradientMap:Se,opaque:y.transparent===!1&&y.blending===Ar&&y.alphaToCoverage===!1,alphaMap:le,alphaTest:Ae,alphaHash:$e,combine:y.combine,mapUv:$&&f(y.map.channel),aoMapUv:j&&f(y.aoMap.channel),lightMapUv:de&&f(y.lightMap.channel),bumpMapUv:fe&&f(y.bumpMap.channel),normalMapUv:Ve&&f(y.normalMap.channel),displacementMapUv:st&&f(y.displacementMap.channel),emissiveMapUv:kt&&f(y.emissiveMap.channel),metalnessMapUv:Ue&&f(y.metalnessMap.channel),roughnessMapUv:Ze&&f(y.roughnessMap.channel),anisotropyMapUv:ae&&f(y.anisotropyMap.channel),clearcoatMapUv:ve&&f(y.clearcoatMap.channel),clearcoatNormalMapUv:be&&f(y.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:se&&f(y.clearcoatRoughnessMap.channel),iridescenceMapUv:re&&f(y.iridescenceMap.channel),iridescenceThicknessMapUv:ke&&f(y.iridescenceThicknessMap.channel),sheenColorMapUv:Fe&&f(y.sheenColorMap.channel),sheenRoughnessMapUv:Me&&f(y.sheenRoughnessMap.channel),specularMapUv:_e&&f(y.specularMap.channel),specularColorMapUv:Xe&&f(y.specularColorMap.channel),specularIntensityMapUv:nt&&f(y.specularIntensityMap.channel),transmissionMapUv:ht&&f(y.transmissionMap.channel),thicknessMapUv:q&&f(y.thicknessMap.channel),alphaMapUv:le&&f(y.alphaMap.channel),vertexTangents:!!B.attributes.tangent&&(Ve||F),vertexNormals:!!B.attributes.normal,vertexColors:y.vertexColors,vertexAlphas:y.vertexColors===!0&&!!B.attributes.color&&B.attributes.color.itemSize===4,pointsUvs:P.isPoints===!0&&!!B.attributes.uv&&($||le),fog:!!R,useFog:y.fog===!0,fogExp2:!!R&&R.isFogExp2,flatShading:y.wireframe===!1&&(y.flatShading===!0||B.attributes.normal===void 0&&Ve===!1&&(y.isMeshLambertMaterial||y.isMeshPhongMaterial||y.isMeshStandardMaterial||y.isMeshPhysicalMaterial)),sizeAttenuation:y.sizeAttenuation===!0,logarithmicDepthBuffer:h,reversedDepthBuffer:Te,skinning:P.isSkinnedMesh===!0,hasPositionAttribute:B.attributes.position!==void 0,morphTargets:B.morphAttributes.position!==void 0,morphNormals:B.morphAttributes.normal!==void 0,morphColors:B.morphAttributes.color!==void 0,morphTargetsCount:Ne,morphTextureStride:He,numSunLights:M.sun.length,numDirLights:M.directional.length,numPointLights:M.point.length,numSpotLights:M.spot.length,numSpotLightMaps:M.spotLightMap.length,numRectAreaLights:M.rectArea.length,numHemiLights:M.hemi.length,numSunLightShadows:M.sunShadowMap.length,numDirLightShadows:M.directionalShadowMap.length,numPointLightShadows:M.pointShadowMap.length,numSpotLightShadows:M.spotShadowMap.length,numSpotLightShadowsWithMaps:M.numSpotLightShadowsWithMaps,numLightProbes:M.numLightProbes,numLightProbeGrids:z.length,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:y.dithering,shadowMapEnabled:n.shadowMap.enabled&&T.length>0,shadowMapType:n.shadowMap.type,toneMapping:et,decodeVideoTexture:$&&y.map.isVideoTexture===!0&&St.getTransfer(y.map.colorSpace)===Bt,decodeVideoTextureEmissive:kt&&y.emissiveMap.isVideoTexture===!0&&St.getTransfer(y.emissiveMap.colorSpace)===Bt,premultipliedAlpha:y.premultipliedAlpha,doubleSided:y.side===Na,flipSided:y.side===ei,useDepthPacking:y.depthPacking>=0,depthPacking:y.depthPacking||0,index0AttributeName:y.index0AttributeName,extensionClipCullDistance:me&&y.extensions.clipCullDistance===!0&&t.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(me&&y.extensions.multiDraw===!0||Re)&&t.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:t.has("KHR_parallel_shader_compile"),customProgramCacheKey:y.customProgramCacheKey()};return Ke.vertexUv1s=l.has(1),Ke.vertexUv2s=l.has(2),Ke.vertexUv3s=l.has(3),l.clear(),Ke}function g(y){const M=[];if(y.shaderID?M.push(y.shaderID):(M.push(y.customVertexShaderID),M.push(y.customFragmentShaderID)),y.defines!==void 0)for(const T in y.defines)M.push(T),M.push(y.defines[T]);return y.isRawShaderMaterial===!1&&(m(M,y),x(M,y),M.push(n.outputColorSpace)),M.push(y.customProgramCacheKey),M.join()}function m(y,M){y.push(M.precision),y.push(M.outputColorSpace),y.push(M.envMapMode),y.push(M.envMapCubeUVHeight),y.push(M.mapUv),y.push(M.alphaMapUv),y.push(M.lightMapUv),y.push(M.aoMapUv),y.push(M.bumpMapUv),y.push(M.normalMapUv),y.push(M.displacementMapUv),y.push(M.emissiveMapUv),y.push(M.metalnessMapUv),y.push(M.roughnessMapUv),y.push(M.anisotropyMapUv),y.push(M.clearcoatMapUv),y.push(M.clearcoatNormalMapUv),y.push(M.clearcoatRoughnessMapUv),y.push(M.iridescenceMapUv),y.push(M.iridescenceThicknessMapUv),y.push(M.sheenColorMapUv),y.push(M.sheenRoughnessMapUv),y.push(M.specularMapUv),y.push(M.specularColorMapUv),y.push(M.specularIntensityMapUv),y.push(M.transmissionMapUv),y.push(M.thicknessMapUv),y.push(M.combine),y.push(M.fogExp2),y.push(M.sizeAttenuation),y.push(M.morphTargetsCount),y.push(M.morphAttributeCount),y.push(M.numSunLights),y.push(M.numDirLights),y.push(M.numPointLights),y.push(M.numSpotLights),y.push(M.numSpotLightMaps),y.push(M.numHemiLights),y.push(M.numRectAreaLights),y.push(M.numSunLightShadows),y.push(M.numDirLightShadows),y.push(M.numPointLightShadows),y.push(M.numSpotLightShadows),y.push(M.numSpotLightShadowsWithMaps),y.push(M.numLightProbes),y.push(M.shadowMapType),y.push(M.toneMapping),y.push(M.numClippingPlanes),y.push(M.numClipIntersection),y.push(M.depthPacking)}function x(y,M){o.disableAll(),M.instancing&&o.enable(0),M.instancingColor&&o.enable(1),M.instancingMorph&&o.enable(2),M.matcap&&o.enable(3),M.envMap&&o.enable(4),M.normalMapObjectSpace&&o.enable(5),M.normalMapTangentSpace&&o.enable(6),M.clearcoat&&o.enable(7),M.iridescence&&o.enable(8),M.alphaTest&&o.enable(9),M.vertexColors&&o.enable(10),M.vertexAlphas&&o.enable(11),M.vertexUv1s&&o.enable(12),M.vertexUv2s&&o.enable(13),M.vertexUv3s&&o.enable(14),M.vertexTangents&&o.enable(15),M.anisotropy&&o.enable(16),M.alphaHash&&o.enable(17),M.batching&&o.enable(18),M.dispersion&&o.enable(19),M.retroreflection&&o.enable(24),M.batchingColor&&o.enable(20),M.gradientMap&&o.enable(21),M.packedNormalMap&&o.enable(22),M.vertexNormals&&o.enable(23),y.push(o.mask),o.disableAll(),M.fog&&o.enable(0),M.useFog&&o.enable(1),M.flatShading&&o.enable(2),M.logarithmicDepthBuffer&&o.enable(3),M.reversedDepthBuffer&&o.enable(4),M.skinning&&o.enable(5),M.morphTargets&&o.enable(6),M.morphNormals&&o.enable(7),M.morphColors&&o.enable(8),M.premultipliedAlpha&&o.enable(9),M.shadowMapEnabled&&o.enable(10),M.doubleSided&&o.enable(11),M.flipSided&&o.enable(12),M.useDepthPacking&&o.enable(13),M.dithering&&o.enable(14),M.transmission&&o.enable(15),M.sheen&&o.enable(16),M.opaque&&o.enable(17),M.pointsUvs&&o.enable(18),M.decodeVideoTexture&&o.enable(19),M.decodeVideoTextureEmissive&&o.enable(20),M.alphaToCoverage&&o.enable(21),M.numLightProbeGrids>0&&o.enable(22),M.hasPositionAttribute&&o.enable(23),y.push(o.mask)}function _(y){const M=u[y.type];let T;if(M){const L=ca[M];T=M5.clone(L.uniforms)}else T=y.uniforms;return T}function w(y,M){let T=p.get(M);return T!==void 0?++T.usedTimes:(T=new bI(n,M,y,a),c.push(T),p.set(M,T)),T}function S(y){if(--y.usedTimes===0){const M=c.indexOf(y);c[M]=c[c.length-1],c.pop(),p.delete(y.cacheKey),y.destroy()}}function A(y){r.remove(y)}function C(){r.dispose()}return{getParameters:v,getProgramCacheKey:g,getUniforms:_,acquireProgram:w,releaseProgram:S,releaseShaderCache:A,programs:c,dispose:C}}function MI(){let n=new WeakMap;function e(o){return n.has(o)}function t(o){let r=n.get(o);return r===void 0&&(r={},n.set(o,r)),r}function i(o){n.delete(o)}function a(o,r,l){n.get(o)[r]=l}function s(){n=new WeakMap}return{has:e,get:t,remove:i,update:a,dispose:s}}function AI(n,e){return n.groupOrder!==e.groupOrder?n.groupOrder-e.groupOrder:n.renderOrder!==e.renderOrder?n.renderOrder-e.renderOrder:n.material.id!==e.material.id?n.material.id-e.material.id:n.materialVariant!==e.materialVariant?n.materialVariant-e.materialVariant:n.z!==e.z?n.z-e.z:n.id-e.id}function Xk(n,e){return n.groupOrder!==e.groupOrder?n.groupOrder-e.groupOrder:n.renderOrder!==e.renderOrder?n.renderOrder-e.renderOrder:n.z!==e.z?e.z-n.z:n.id-e.id}function Kk(){const n=[];let e=0;const t=[],i=[],a=[];function s(){e=0,t.length=0,i.length=0,a.length=0}function o(d){let u=0;return d.isInstancedMesh&&(u+=2),d.isSkinnedMesh&&(u+=1),u}function r(d,u,f,v,g,m){let x=n[e];return x===void 0?(x={id:d.id,object:d,geometry:u,material:f,materialVariant:o(d),groupOrder:v,renderOrder:d.renderOrder,z:g,group:m},n[e]=x):(x.id=d.id,x.object=d,x.geometry=u,x.material=f,x.materialVariant=o(d),x.groupOrder=v,x.renderOrder=d.renderOrder,x.z=g,x.group=m),e++,x}function l(d,u,f,v,g,m,x){x.reversedDepth===!0&&(g=-g);const _=r(d,u,f,v,g,m);f.transmission>0?i.push(_):f.transparent===!0?a.push(_):t.push(_)}function c(d,u,f,v,g,m){const x=r(d,u,f,v,g,m);f.transmission>0?i.unshift(x):f.transparent===!0?a.unshift(x):t.unshift(x)}function p(d,u){t.length>1&&t.sort(d||AI),i.length>1&&i.sort(u||Xk),a.length>1&&a.sort(u||Xk)}function h(){for(let d=e,u=n.length;d<u;d++){const f=n[d];if(f.id===null)break;f.id=null,f.object=null,f.geometry=null,f.material=null,f.group=null}}return{opaque:t,transmissive:i,transparent:a,init:s,push:l,unshift:c,finish:h,sort:p}}function TI(){let n=new WeakMap;function e(i,a){const s=n.get(i);let o;return s===void 0?(o=new Kk,n.set(i,[o])):a>=s.length?(o=new Kk,s.push(o)):o=s[a],o}function t(){n=new WeakMap}return{get:e,dispose:t}}function EI(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"SunLight":case"DirectionalLight":t={direction:new X,color:new It};break;case"SpotLight":t={position:new X,direction:new X,color:new It,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new X,color:new It,distance:0,decay:0};break;case"HemisphereLight":t={direction:new X,skyColor:new It,groundColor:new It};break;case"RectAreaLight":t={color:new It,position:new X,halfWidth:new X,halfHeight:new X};break}return n[e.id]=t,t}}}function CI(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"SunLight":case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ut};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ut};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ut,shadowCameraNear:1,shadowCameraFar:1e3};break}return n[e.id]=t,t}}}let RI=0;function LI(n,e){return(e.castShadow?2:0)-(n.castShadow?2:0)+(e.map?1:0)-(n.map?1:0)}function PI(n){const e=new EI,t=CI(),i={version:0,hash:{sunLength:-1,directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numSunShadows:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],sun:[],sunShadow:[],sunShadowMap:[],sunShadowMatrix:[],sunShadowCascade:[],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 X);const a=new X,s=new en,o=new en;function r(c){let p=0,h=0,d=0;for(let P=0;P<9;P++)i.probe[P].set(0,0,0);let u=0,f=0,v=0,g=0,m=0,x=0,_=0,w=0,S=0,A=0,C=0,y=0,M=0,T=0;c.sort(LI);for(let P=0,z=c.length;P<z;P++){const R=c[P],B=R.color,K=R.intensity,N=R.distance;let V=null;if(R.shadow&&R.shadow.map&&(R.shadow.map.texture.format===Mo?V=R.shadow.map.texture:V=R.shadow.map.depthTexture||R.shadow.map.texture),R.isAmbientLight)p+=B.r*K,h+=B.g*K,d+=B.b*K;else if(R.isLightProbe){for(let Z=0;Z<9;Z++)i.probe[Z].addScaledVector(R.sh.coefficients[Z],K);T++}else if(R.isSunLight){const Z=e.get(R);if(Z.color.copy(R.color).multiplyScalar(R.intensity),R.castShadow){const te=R.shadow,ce=t.get(R);ce.shadowIntensity=te.intensity,ce.shadowBias=te.bias,ce.shadowNormalBias=te.normalBias,ce.shadowRadius=te.radius,ce.shadowMapSize.copy(te.mapSize).multiply(te.getFrameExtents()),i.sunShadow[f]=ce,i.sunShadowMap[f]=V;const Ne=te.getViewportCount();for(let He=0;He<Ne;He++)i.sunShadowMatrix[v+He]=te.getMatrix(He),i.sunShadowCascade[v+He]=te._cascadeData[He];v+=Ne,f++}i.sun[u]=Z,u++}else if(R.isDirectionalLight){const Z=e.get(R);if(Z.color.copy(R.color).multiplyScalar(R.intensity),R.castShadow){const te=R.shadow,ce=t.get(R);ce.shadowIntensity=te.intensity,ce.shadowBias=te.bias,ce.shadowNormalBias=te.normalBias,ce.shadowRadius=te.radius,ce.shadowMapSize=te.mapSize,i.directionalShadow[g]=ce,i.directionalShadowMap[g]=V,i.directionalShadowMatrix[g]=R.shadow.matrix,S++}i.directional[g]=Z,g++}else if(R.isSpotLight){const Z=e.get(R);Z.position.setFromMatrixPosition(R.matrixWorld),Z.color.copy(B).multiplyScalar(K),Z.distance=N,Z.coneCos=Math.cos(R.angle),Z.penumbraCos=Math.cos(R.angle*(1-R.penumbra)),Z.decay=R.decay,i.spot[x]=Z;const te=R.shadow;if(R.map&&(i.spotLightMap[y]=R.map,y++,te.updateMatrices(R),R.castShadow&&M++),i.spotLightMatrix[x]=te.matrix,R.castShadow){const ce=t.get(R);ce.shadowIntensity=te.intensity,ce.shadowBias=te.bias,ce.shadowNormalBias=te.normalBias,ce.shadowRadius=te.radius,ce.shadowMapSize=te.mapSize,i.spotShadow[x]=ce,i.spotShadowMap[x]=V,C++}x++}else if(R.isRectAreaLight){const Z=e.get(R);Z.color.copy(B).multiplyScalar(K),Z.halfWidth.set(R.width*.5,0,0),Z.halfHeight.set(0,R.height*.5,0),i.rectArea[_]=Z,_++}else if(R.isPointLight){const Z=e.get(R);if(Z.color.copy(R.color).multiplyScalar(R.intensity),Z.distance=R.distance,Z.decay=R.decay,R.castShadow){const te=R.shadow,ce=t.get(R);ce.shadowIntensity=te.intensity,ce.shadowBias=te.bias,ce.shadowNormalBias=te.normalBias,ce.shadowRadius=te.radius,ce.shadowMapSize=te.mapSize,ce.shadowCameraNear=te.camera.near,ce.shadowCameraFar=te.camera.far,i.pointShadow[m]=ce,i.pointShadowMap[m]=V,i.pointShadowMatrix[m]=R.shadow.matrix,A++}i.point[m]=Z,m++}else if(R.isHemisphereLight){const Z=e.get(R);Z.skyColor.copy(R.color).multiplyScalar(K),Z.groundColor.copy(R.groundColor).multiplyScalar(K),i.hemi[w]=Z,w++}}_>0&&(n.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=Ee.LTC_FLOAT_1,i.rectAreaLTC2=Ee.LTC_FLOAT_2):(i.rectAreaLTC1=Ee.LTC_HALF_1,i.rectAreaLTC2=Ee.LTC_HALF_2)),i.ambient[0]=p,i.ambient[1]=h,i.ambient[2]=d;const L=i.hash;(L.sunLength!==u||L.directionalLength!==g||L.pointLength!==m||L.spotLength!==x||L.rectAreaLength!==_||L.hemiLength!==w||L.numSunShadows!==f||L.numDirectionalShadows!==S||L.numPointShadows!==A||L.numSpotShadows!==C||L.numSpotMaps!==y||L.numLightProbes!==T)&&(i.sun.length=u,i.directional.length=g,i.spot.length=x,i.rectArea.length=_,i.point.length=m,i.hemi.length=w,i.sunShadow.length=f,i.sunShadowMap.length=f,i.sunShadowMatrix.length=v,i.sunShadowCascade.length=v,i.directionalShadow.length=S,i.directionalShadowMap.length=S,i.directionalShadowMatrix.length=S,i.pointShadow.length=A,i.pointShadowMap.length=A,i.pointShadowMatrix.length=A,i.spotShadow.length=C,i.spotShadowMap.length=C,i.spotLightMatrix.length=C+y-M,i.spotLightMap.length=y,i.numSpotLightShadowsWithMaps=M,i.numLightProbes=T,L.sunLength=u,L.directionalLength=g,L.pointLength=m,L.spotLength=x,L.rectAreaLength=_,L.hemiLength=w,L.numSunShadows=f,L.numDirectionalShadows=S,L.numPointShadows=A,L.numSpotShadows=C,L.numSpotMaps=y,L.numLightProbes=T,i.version=RI++)}function l(c,p){let h=0,d=0,u=0,f=0,v=0,g=0;const m=p.matrixWorldInverse;for(let x=0,_=c.length;x<_;x++){const w=c[x];if(w.isSunLight){const S=i.sun[h];S.direction.setFromMatrixPosition(w.matrixWorld),S.direction.transformDirection(m),h++}else if(w.isDirectionalLight){const S=i.directional[d];S.direction.setFromMatrixPosition(w.matrixWorld),a.setFromMatrixPosition(w.target.matrixWorld),S.direction.sub(a),S.direction.transformDirection(m),d++}else if(w.isSpotLight){const S=i.spot[f];S.position.setFromMatrixPosition(w.matrixWorld),S.position.applyMatrix4(m),S.direction.setFromMatrixPosition(w.matrixWorld),a.setFromMatrixPosition(w.target.matrixWorld),S.direction.sub(a),S.direction.transformDirection(m),f++}else if(w.isRectAreaLight){const S=i.rectArea[v];S.position.setFromMatrixPosition(w.matrixWorld),S.position.applyMatrix4(m),o.identity(),s.copy(w.matrixWorld),s.premultiply(m),o.extractRotation(s),S.halfWidth.set(w.width*.5,0,0),S.halfHeight.set(0,w.height*.5,0),S.halfWidth.applyMatrix4(o),S.halfHeight.applyMatrix4(o),v++}else if(w.isPointLight){const S=i.point[u];S.position.setFromMatrixPosition(w.matrixWorld),S.position.applyMatrix4(m),u++}else if(w.isHemisphereLight){const S=i.hemi[g];S.direction.setFromMatrixPosition(w.matrixWorld),S.direction.transformDirection(m),g++}}}return{setup:r,setupView:l,state:i}}function Yk(n){const e=new PI(n),t=[],i=[],a=[];function s(d){h.camera=d,t.length=0,i.length=0,a.length=0}function o(d){t.push(d)}function r(d){i.push(d)}function l(d){a.push(d)}function c(){e.setup(t)}function p(d){e.setupView(t,d)}const h={lightsArray:t,shadowsArray:i,lightProbeGridArray:a,camera:null,lights:e,transmissionRenderTarget:{},textureUnits:0};return{init:s,state:h,setupLights:c,setupLightsView:p,pushLight:o,pushShadow:r,pushLightProbeGrid:l}}function II(n){let e=new WeakMap;function t(a,s=0){const o=e.get(a);let r;return o===void 0?(r=new Yk(n),e.set(a,[r])):s>=o.length?(r=new Yk(n),o.push(r)):r=o[s],r}function i(){e=new WeakMap}return{get:t,dispose:i}}const $I=`void main() {
8453
+ `+ce)}else B!==""?rt("WebGLProgram: Program Info Log:",B):(K===""||N==="")&&(Z=!1);Z&&(L.diagnostics={runnable:V,programLog:B,vertexShader:{log:K,prefix:g},fragmentShader:{log:N,prefix:m}})}a.deleteShader(S),a.deleteShader(A),y=new Vh(a,v),M=aI(a,v)}let y;this.getUniforms=function(){return y===void 0&&C(this),y};let M;this.getAttributes=function(){return M===void 0&&C(this),M};let T=t.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return T===!1&&(T=a.getProgramParameter(v,K6)),T},this.destroy=function(){i.releaseStatesOfProgram(this),a.deleteProgram(v),this.program=void 0},this.type=t.shaderType,this.name=t.shaderName,this.id=Y6++,this.cacheKey=e,this.usedTimes=1,this.program=v,this.vertexShader=S,this.fragmentShader=A,this}let yI=0;class wI{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e,t,i){const a=this._getShaderCacheForMaterial(e);return a.has(t)===!1&&(a.add(t),t.usedTimes++),a.has(i)===!1&&(a.add(i),i.usedTimes++),this}remove(e){const t=this.materialCache.get(e);for(const i of t)i.usedTimes--,i.usedTimes===0&&this.shaderCache.delete(i.code);return this.materialCache.delete(e),this}getVertexShaderStage(e){return this._getShaderStage(e.vertexShader)}getFragmentShaderStage(e){return this._getShaderStage(e.fragmentShader)}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){const t=this.materialCache;let i=t.get(e);return i===void 0&&(i=new Set,t.set(e,i)),i}_getShaderStage(e){const t=this.shaderCache;let i=t.get(e);return i===void 0&&(i=new kI(e),t.set(e,i)),i}}class kI{constructor(e){this.id=yI++,this.code=e,this.usedTimes=0}}function _I(n){return n===Mo||n===rh||n===lh}function SI(n,e,t,i,a,s){const o=new q2,r=new wI,l=new Set,c=[],p=new Map,h=i.logarithmicDepthBuffer;let d=i.precision;const u={MeshDepthMaterial:"depth",MeshDistanceMaterial:"distance",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 f(y){return l.add(y),y===0?"uv":`uv${y}`}function v(y,M,T,L,P,z){const R=L.fog,B=P.geometry,K=y.isMeshStandardMaterial||y.isMeshLambertMaterial||y.isMeshPhongMaterial?L.environment:null,N=y.isMeshStandardMaterial||y.isMeshLambertMaterial&&!y.envMap||y.isMeshPhongMaterial&&!y.envMap,V=e.get(y.envMap||K,N),Z=V&&V.mapping===th?V.image.height:null,te=u[y.type];y.precision!==null&&(d=i.getMaxPrecision(y.precision),d!==y.precision&&rt("WebGLProgram.getParameters:",y.precision,"not supported, using",d,"instead."));const ce=B.morphAttributes.position||B.morphAttributes.normal||B.morphAttributes.color,Ne=ce!==void 0?ce.length:0;let He=0;B.morphAttributes.position!==void 0&&(He=1),B.morphAttributes.normal!==void 0&&(He=2),B.morphAttributes.color!==void 0&&(He=3);let ct,ot,ft,ne;if(te){const Kt=ca[te];ct=Kt.vertexShader,ot=Kt.fragmentShader}else{ct=y.vertexShader,ot=y.fragmentShader;const Kt=r.getVertexShaderStage(y),zt=r.getFragmentShaderStage(y);r.update(y,Kt,zt),ft=Kt.id,ne=zt.id}const oe=n.getRenderTarget(),Te=n.state.buffers.depth.getReversed(),We=P.isInstancedMesh===!0,Re=P.isBatchedMesh===!0,$=!!y.map,H=!!y.matcap,Y=!!V,j=!!y.aoMap,de=!!y.lightMap,fe=!!y.bumpMap&&y.wireframe===!1,Ve=!!y.normalMap,st=!!y.displacementMap,kt=!!y.emissiveMap,Ue=!!y.metalnessMap,Ze=!!y.roughnessMap,F=y.anisotropy>0,lt=y.clearcoat>0,Je=y.dispersion>0,I=y.retroreflectivity>0,k=y.iridescence>0,W=y.sheen>0,J=y.transmission>0,ae=F&&!!y.anisotropyMap,ve=lt&&!!y.clearcoatMap,be=lt&&!!y.clearcoatNormalMap,se=lt&&!!y.clearcoatRoughnessMap,re=k&&!!y.iridescenceMap,ke=k&&!!y.iridescenceThicknessMap,Fe=W&&!!y.sheenColorMap,Me=W&&!!y.sheenRoughnessMap,_e=!!y.specularMap,Xe=!!y.specularColorMap,nt=!!y.specularIntensityMap,ht=J&&!!y.transmissionMap,q=J&&!!y.thicknessMap,Se=!!y.gradientMap,le=!!y.alphaMap,Ae=y.alphaTest>0,$e=!!y.alphaHash,me=!!y.extensions;let et=na;y.toneMapped&&(oe===null||oe.isXRRenderTarget===!0)&&(et=n.toneMapping);const Ke={shaderID:te,shaderType:y.type,shaderName:y.name,vertexShader:ct,fragmentShader:ot,defines:y.defines,customVertexShaderID:ft,customFragmentShaderID:ne,isRawShaderMaterial:y.isRawShaderMaterial===!0,glslVersion:y.glslVersion,precision:d,batching:Re,batchingColor:Re&&P._colorsTexture!==null,instancing:We,instancingColor:We&&P.instanceColor!==null,instancingMorph:We&&P.morphTexture!==null,outputColorSpace:oe===null?n.outputColorSpace:oe.isXRRenderTarget===!0?oe.texture.colorSpace:St.workingColorSpace,alphaToCoverage:!!y.alphaToCoverage,map:$,matcap:H,envMap:Y,envMapMode:Y&&V.mapping,envMapCubeUVHeight:Z,aoMap:j,lightMap:de,bumpMap:fe,normalMap:Ve,displacementMap:st,emissiveMap:kt,normalMapObjectSpace:Ve&&y.normalMapType===NR,normalMapTangentSpace:Ve&&y.normalMapType===I2,packedNormalMap:Ve&&y.normalMapType===I2&&_I(y.normalMap.format),metalnessMap:Ue,roughnessMap:Ze,anisotropy:F,anisotropyMap:ae,clearcoat:lt,clearcoatMap:ve,clearcoatNormalMap:be,clearcoatRoughnessMap:se,dispersion:Je,retroreflection:I,iridescence:k,iridescenceMap:re,iridescenceThicknessMap:ke,sheen:W,sheenColorMap:Fe,sheenRoughnessMap:Me,specularMap:_e,specularColorMap:Xe,specularIntensityMap:nt,transmission:J,transmissionMap:ht,thicknessMap:q,gradientMap:Se,opaque:y.transparent===!1&&y.blending===Ar&&y.alphaToCoverage===!1,alphaMap:le,alphaTest:Ae,alphaHash:$e,combine:y.combine,mapUv:$&&f(y.map.channel),aoMapUv:j&&f(y.aoMap.channel),lightMapUv:de&&f(y.lightMap.channel),bumpMapUv:fe&&f(y.bumpMap.channel),normalMapUv:Ve&&f(y.normalMap.channel),displacementMapUv:st&&f(y.displacementMap.channel),emissiveMapUv:kt&&f(y.emissiveMap.channel),metalnessMapUv:Ue&&f(y.metalnessMap.channel),roughnessMapUv:Ze&&f(y.roughnessMap.channel),anisotropyMapUv:ae&&f(y.anisotropyMap.channel),clearcoatMapUv:ve&&f(y.clearcoatMap.channel),clearcoatNormalMapUv:be&&f(y.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:se&&f(y.clearcoatRoughnessMap.channel),iridescenceMapUv:re&&f(y.iridescenceMap.channel),iridescenceThicknessMapUv:ke&&f(y.iridescenceThicknessMap.channel),sheenColorMapUv:Fe&&f(y.sheenColorMap.channel),sheenRoughnessMapUv:Me&&f(y.sheenRoughnessMap.channel),specularMapUv:_e&&f(y.specularMap.channel),specularColorMapUv:Xe&&f(y.specularColorMap.channel),specularIntensityMapUv:nt&&f(y.specularIntensityMap.channel),transmissionMapUv:ht&&f(y.transmissionMap.channel),thicknessMapUv:q&&f(y.thicknessMap.channel),alphaMapUv:le&&f(y.alphaMap.channel),vertexTangents:!!B.attributes.tangent&&(Ve||F),vertexNormals:!!B.attributes.normal,vertexColors:y.vertexColors,vertexAlphas:y.vertexColors===!0&&!!B.attributes.color&&B.attributes.color.itemSize===4,pointsUvs:P.isPoints===!0&&!!B.attributes.uv&&($||le),fog:!!R,useFog:y.fog===!0,fogExp2:!!R&&R.isFogExp2,flatShading:y.wireframe===!1&&(y.flatShading===!0||B.attributes.normal===void 0&&Ve===!1&&(y.isMeshLambertMaterial||y.isMeshPhongMaterial||y.isMeshStandardMaterial||y.isMeshPhysicalMaterial)),sizeAttenuation:y.sizeAttenuation===!0,logarithmicDepthBuffer:h,reversedDepthBuffer:Te,skinning:P.isSkinnedMesh===!0,hasPositionAttribute:B.attributes.position!==void 0,morphTargets:B.morphAttributes.position!==void 0,morphNormals:B.morphAttributes.normal!==void 0,morphColors:B.morphAttributes.color!==void 0,morphTargetsCount:Ne,morphTextureStride:He,numSunLights:M.sun.length,numDirLights:M.directional.length,numPointLights:M.point.length,numSpotLights:M.spot.length,numSpotLightMaps:M.spotLightMap.length,numRectAreaLights:M.rectArea.length,numHemiLights:M.hemi.length,numSunLightShadows:M.sunShadowMap.length,numDirLightShadows:M.directionalShadowMap.length,numPointLightShadows:M.pointShadowMap.length,numSpotLightShadows:M.spotShadowMap.length,numSpotLightShadowsWithMaps:M.numSpotLightShadowsWithMaps,numLightProbes:M.numLightProbes,numLightProbeGrids:z.length,numClippingPlanes:s.numPlanes,numClipIntersection:s.numIntersection,dithering:y.dithering,shadowMapEnabled:n.shadowMap.enabled&&T.length>0,shadowMapType:n.shadowMap.type,toneMapping:et,decodeVideoTexture:$&&y.map.isVideoTexture===!0&&St.getTransfer(y.map.colorSpace)===Bt,decodeVideoTextureEmissive:kt&&y.emissiveMap.isVideoTexture===!0&&St.getTransfer(y.emissiveMap.colorSpace)===Bt,premultipliedAlpha:y.premultipliedAlpha,doubleSided:y.side===Na,flipSided:y.side===ei,useDepthPacking:y.depthPacking>=0,depthPacking:y.depthPacking||0,index0AttributeName:y.index0AttributeName,extensionClipCullDistance:me&&y.extensions.clipCullDistance===!0&&t.has("WEBGL_clip_cull_distance"),extensionMultiDraw:(me&&y.extensions.multiDraw===!0||Re)&&t.has("WEBGL_multi_draw"),rendererExtensionParallelShaderCompile:t.has("KHR_parallel_shader_compile"),customProgramCacheKey:y.customProgramCacheKey()};return Ke.vertexUv1s=l.has(1),Ke.vertexUv2s=l.has(2),Ke.vertexUv3s=l.has(3),l.clear(),Ke}function g(y){const M=[];if(y.shaderID?M.push(y.shaderID):(M.push(y.customVertexShaderID),M.push(y.customFragmentShaderID)),y.defines!==void 0)for(const T in y.defines)M.push(T),M.push(y.defines[T]);return y.isRawShaderMaterial===!1&&(m(M,y),x(M,y),M.push(n.outputColorSpace)),M.push(y.customProgramCacheKey),M.join()}function m(y,M){y.push(M.precision),y.push(M.outputColorSpace),y.push(M.envMapMode),y.push(M.envMapCubeUVHeight),y.push(M.mapUv),y.push(M.alphaMapUv),y.push(M.lightMapUv),y.push(M.aoMapUv),y.push(M.bumpMapUv),y.push(M.normalMapUv),y.push(M.displacementMapUv),y.push(M.emissiveMapUv),y.push(M.metalnessMapUv),y.push(M.roughnessMapUv),y.push(M.anisotropyMapUv),y.push(M.clearcoatMapUv),y.push(M.clearcoatNormalMapUv),y.push(M.clearcoatRoughnessMapUv),y.push(M.iridescenceMapUv),y.push(M.iridescenceThicknessMapUv),y.push(M.sheenColorMapUv),y.push(M.sheenRoughnessMapUv),y.push(M.specularMapUv),y.push(M.specularColorMapUv),y.push(M.specularIntensityMapUv),y.push(M.transmissionMapUv),y.push(M.thicknessMapUv),y.push(M.combine),y.push(M.fogExp2),y.push(M.sizeAttenuation),y.push(M.morphTargetsCount),y.push(M.morphAttributeCount),y.push(M.numSunLights),y.push(M.numDirLights),y.push(M.numPointLights),y.push(M.numSpotLights),y.push(M.numSpotLightMaps),y.push(M.numHemiLights),y.push(M.numRectAreaLights),y.push(M.numSunLightShadows),y.push(M.numDirLightShadows),y.push(M.numPointLightShadows),y.push(M.numSpotLightShadows),y.push(M.numSpotLightShadowsWithMaps),y.push(M.numLightProbes),y.push(M.shadowMapType),y.push(M.toneMapping),y.push(M.numClippingPlanes),y.push(M.numClipIntersection),y.push(M.depthPacking)}function x(y,M){o.disableAll(),M.instancing&&o.enable(0),M.instancingColor&&o.enable(1),M.instancingMorph&&o.enable(2),M.matcap&&o.enable(3),M.envMap&&o.enable(4),M.normalMapObjectSpace&&o.enable(5),M.normalMapTangentSpace&&o.enable(6),M.clearcoat&&o.enable(7),M.iridescence&&o.enable(8),M.alphaTest&&o.enable(9),M.vertexColors&&o.enable(10),M.vertexAlphas&&o.enable(11),M.vertexUv1s&&o.enable(12),M.vertexUv2s&&o.enable(13),M.vertexUv3s&&o.enable(14),M.vertexTangents&&o.enable(15),M.anisotropy&&o.enable(16),M.alphaHash&&o.enable(17),M.batching&&o.enable(18),M.dispersion&&o.enable(19),M.retroreflection&&o.enable(24),M.batchingColor&&o.enable(20),M.gradientMap&&o.enable(21),M.packedNormalMap&&o.enable(22),M.vertexNormals&&o.enable(23),y.push(o.mask),o.disableAll(),M.fog&&o.enable(0),M.useFog&&o.enable(1),M.flatShading&&o.enable(2),M.logarithmicDepthBuffer&&o.enable(3),M.reversedDepthBuffer&&o.enable(4),M.skinning&&o.enable(5),M.morphTargets&&o.enable(6),M.morphNormals&&o.enable(7),M.morphColors&&o.enable(8),M.premultipliedAlpha&&o.enable(9),M.shadowMapEnabled&&o.enable(10),M.doubleSided&&o.enable(11),M.flipSided&&o.enable(12),M.useDepthPacking&&o.enable(13),M.dithering&&o.enable(14),M.transmission&&o.enable(15),M.sheen&&o.enable(16),M.opaque&&o.enable(17),M.pointsUvs&&o.enable(18),M.decodeVideoTexture&&o.enable(19),M.decodeVideoTextureEmissive&&o.enable(20),M.alphaToCoverage&&o.enable(21),M.numLightProbeGrids>0&&o.enable(22),M.hasPositionAttribute&&o.enable(23),y.push(o.mask)}function _(y){const M=u[y.type];let T;if(M){const L=ca[M];T=M5.clone(L.uniforms)}else T=y.uniforms;return T}function w(y,M){let T=p.get(M);return T!==void 0?++T.usedTimes:(T=new bI(n,M,y,a),c.push(T),p.set(M,T)),T}function S(y){if(--y.usedTimes===0){const M=c.indexOf(y);c[M]=c[c.length-1],c.pop(),p.delete(y.cacheKey),y.destroy()}}function A(y){r.remove(y)}function C(){r.dispose()}return{getParameters:v,getProgramCacheKey:g,getUniforms:_,acquireProgram:w,releaseProgram:S,releaseShaderCache:A,programs:c,dispose:C}}function MI(){let n=new WeakMap;function e(o){return n.has(o)}function t(o){let r=n.get(o);return r===void 0&&(r={},n.set(o,r)),r}function i(o){n.delete(o)}function a(o,r,l){n.get(o)[r]=l}function s(){n=new WeakMap}return{has:e,get:t,remove:i,update:a,dispose:s}}function AI(n,e){return n.groupOrder!==e.groupOrder?n.groupOrder-e.groupOrder:n.renderOrder!==e.renderOrder?n.renderOrder-e.renderOrder:n.material.id!==e.material.id?n.material.id-e.material.id:n.materialVariant!==e.materialVariant?n.materialVariant-e.materialVariant:n.z!==e.z?n.z-e.z:n.id-e.id}function Xk(n,e){return n.groupOrder!==e.groupOrder?n.groupOrder-e.groupOrder:n.renderOrder!==e.renderOrder?n.renderOrder-e.renderOrder:n.z!==e.z?e.z-n.z:n.id-e.id}function Kk(){const n=[];let e=0;const t=[],i=[],a=[];function s(){e=0,t.length=0,i.length=0,a.length=0}function o(d){let u=0;return d.isInstancedMesh&&(u+=2),d.isSkinnedMesh&&(u+=1),u}function r(d,u,f,v,g,m){let x=n[e];return x===void 0?(x={id:d.id,object:d,geometry:u,material:f,materialVariant:o(d),groupOrder:v,renderOrder:d.renderOrder,z:g,group:m},n[e]=x):(x.id=d.id,x.object=d,x.geometry=u,x.material=f,x.materialVariant=o(d),x.groupOrder=v,x.renderOrder=d.renderOrder,x.z=g,x.group=m),e++,x}function l(d,u,f,v,g,m,x){x.reversedDepth===!0&&(g=-g);const _=r(d,u,f,v,g,m);f.transmission>0?i.push(_):f.transparent===!0?a.push(_):t.push(_)}function c(d,u,f,v,g,m){const x=r(d,u,f,v,g,m);f.transmission>0?i.unshift(x):f.transparent===!0?a.unshift(x):t.unshift(x)}function p(d,u){t.length>1&&t.sort(d||AI),i.length>1&&i.sort(u||Xk),a.length>1&&a.sort(u||Xk)}function h(){for(let d=e,u=n.length;d<u;d++){const f=n[d];if(f.id===null)break;f.id=null,f.object=null,f.geometry=null,f.material=null,f.group=null}}return{opaque:t,transmissive:i,transparent:a,init:s,push:l,unshift:c,finish:h,sort:p}}function TI(){let n=new WeakMap;function e(i,a){const s=n.get(i);let o;return s===void 0?(o=new Kk,n.set(i,[o])):a>=s.length?(o=new Kk,s.push(o)):o=s[a],o}function t(){n=new WeakMap}return{get:e,dispose:t}}function EI(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"SunLight":case"DirectionalLight":t={direction:new X,color:new It};break;case"SpotLight":t={position:new X,direction:new X,color:new It,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case"PointLight":t={position:new X,color:new It,distance:0,decay:0};break;case"HemisphereLight":t={direction:new X,skyColor:new It,groundColor:new It};break;case"RectAreaLight":t={color:new It,position:new X,halfWidth:new X,halfHeight:new X};break}return n[e.id]=t,t}}}function CI(){const n={};return{get:function(e){if(n[e.id]!==void 0)return n[e.id];let t;switch(e.type){case"SunLight":case"DirectionalLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ut};break;case"SpotLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ut};break;case"PointLight":t={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new ut,shadowCameraNear:1,shadowCameraFar:1e3};break}return n[e.id]=t,t}}}let RI=0;function LI(n,e){return(e.castShadow?2:0)-(n.castShadow?2:0)+(e.map?1:0)-(n.map?1:0)}function PI(n){const e=new EI,t=CI(),i={version:0,hash:{sunLength:-1,directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numSunShadows:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],sun:[],sunShadow:[],sunShadowMap:[],sunShadowMatrix:[],sunShadowCascade:[],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 X);const a=new X,s=new en,o=new en;function r(c){let p=0,h=0,d=0;for(let P=0;P<9;P++)i.probe[P].set(0,0,0);let u=0,f=0,v=0,g=0,m=0,x=0,_=0,w=0,S=0,A=0,C=0,y=0,M=0,T=0;c.sort(LI);for(let P=0,z=c.length;P<z;P++){const R=c[P],B=R.color,K=R.intensity,N=R.distance;let V=null;if(R.shadow&&R.shadow.map&&(R.shadow.map.texture.format===Mo?V=R.shadow.map.texture:V=R.shadow.map.depthTexture||R.shadow.map.texture),R.isAmbientLight)p+=B.r*K,h+=B.g*K,d+=B.b*K;else if(R.isLightProbe){for(let Z=0;Z<9;Z++)i.probe[Z].addScaledVector(R.sh.coefficients[Z],K);T++}else if(R.isSunLight){const Z=e.get(R);if(Z.color.copy(R.color).multiplyScalar(R.intensity),R.castShadow){const te=R.shadow,ce=t.get(R);ce.shadowIntensity=te.intensity,ce.shadowBias=te.bias,ce.shadowNormalBias=te.normalBias,ce.shadowRadius=te.radius,ce.shadowMapSize.copy(te.mapSize).multiply(te.getFrameExtents()),i.sunShadow[f]=ce,i.sunShadowMap[f]=V;const Ne=te.getViewportCount();for(let He=0;He<Ne;He++)i.sunShadowMatrix[v+He]=te.getMatrix(He),i.sunShadowCascade[v+He]=te._cascadeData[He];v+=Ne,f++}i.sun[u]=Z,u++}else if(R.isDirectionalLight){const Z=e.get(R);if(Z.color.copy(R.color).multiplyScalar(R.intensity),R.castShadow){const te=R.shadow,ce=t.get(R);ce.shadowIntensity=te.intensity,ce.shadowBias=te.bias,ce.shadowNormalBias=te.normalBias,ce.shadowRadius=te.radius,ce.shadowMapSize=te.mapSize,i.directionalShadow[g]=ce,i.directionalShadowMap[g]=V,i.directionalShadowMatrix[g]=R.shadow.matrix,S++}i.directional[g]=Z,g++}else if(R.isSpotLight){const Z=e.get(R);Z.position.setFromMatrixPosition(R.matrixWorld),Z.color.copy(B).multiplyScalar(K),Z.distance=N,Z.coneCos=Math.cos(R.angle),Z.penumbraCos=Math.cos(R.angle*(1-R.penumbra)),Z.decay=R.decay,i.spot[x]=Z;const te=R.shadow;if(R.map&&(i.spotLightMap[y]=R.map,y++,te.updateMatrices(R),R.castShadow&&M++),i.spotLightMatrix[x]=te.matrix,R.castShadow){const ce=t.get(R);ce.shadowIntensity=te.intensity,ce.shadowBias=te.bias,ce.shadowNormalBias=te.normalBias,ce.shadowRadius=te.radius,ce.shadowMapSize=te.mapSize,i.spotShadow[x]=ce,i.spotShadowMap[x]=V,C++}x++}else if(R.isRectAreaLight){const Z=e.get(R);Z.color.copy(B).multiplyScalar(K),Z.halfWidth.set(R.width*.5,0,0),Z.halfHeight.set(0,R.height*.5,0),i.rectArea[_]=Z,_++}else if(R.isPointLight){const Z=e.get(R);if(Z.color.copy(R.color).multiplyScalar(R.intensity),Z.distance=R.distance,Z.decay=R.decay,R.castShadow){const te=R.shadow,ce=t.get(R);ce.shadowIntensity=te.intensity,ce.shadowBias=te.bias,ce.shadowNormalBias=te.normalBias,ce.shadowRadius=te.radius,ce.shadowMapSize=te.mapSize,ce.shadowCameraNear=te.camera.near,ce.shadowCameraFar=te.camera.far,i.pointShadow[m]=ce,i.pointShadowMap[m]=V,i.pointShadowMatrix[m]=R.shadow.matrix,A++}i.point[m]=Z,m++}else if(R.isHemisphereLight){const Z=e.get(R);Z.skyColor.copy(R.color).multiplyScalar(K),Z.groundColor.copy(R.groundColor).multiplyScalar(K),i.hemi[w]=Z,w++}}_>0&&(n.has("OES_texture_float_linear")===!0?(i.rectAreaLTC1=Ee.LTC_FLOAT_1,i.rectAreaLTC2=Ee.LTC_FLOAT_2):(i.rectAreaLTC1=Ee.LTC_HALF_1,i.rectAreaLTC2=Ee.LTC_HALF_2)),i.ambient[0]=p,i.ambient[1]=h,i.ambient[2]=d;const L=i.hash;(L.sunLength!==u||L.directionalLength!==g||L.pointLength!==m||L.spotLength!==x||L.rectAreaLength!==_||L.hemiLength!==w||L.numSunShadows!==f||L.numDirectionalShadows!==S||L.numPointShadows!==A||L.numSpotShadows!==C||L.numSpotMaps!==y||L.numLightProbes!==T)&&(i.sun.length=u,i.directional.length=g,i.spot.length=x,i.rectArea.length=_,i.point.length=m,i.hemi.length=w,i.sunShadow.length=f,i.sunShadowMap.length=f,i.sunShadowMatrix.length=v,i.sunShadowCascade.length=v,i.directionalShadow.length=S,i.directionalShadowMap.length=S,i.directionalShadowMatrix.length=S,i.pointShadow.length=A,i.pointShadowMap.length=A,i.pointShadowMatrix.length=A,i.spotShadow.length=C,i.spotShadowMap.length=C,i.spotLightMatrix.length=C+y-M,i.spotLightMap.length=y,i.numSpotLightShadowsWithMaps=M,i.numLightProbes=T,L.sunLength=u,L.directionalLength=g,L.pointLength=m,L.spotLength=x,L.rectAreaLength=_,L.hemiLength=w,L.numSunShadows=f,L.numDirectionalShadows=S,L.numPointShadows=A,L.numSpotShadows=C,L.numSpotMaps=y,L.numLightProbes=T,i.version=RI++)}function l(c,p){let h=0,d=0,u=0,f=0,v=0,g=0;const m=p.matrixWorldInverse;for(let x=0,_=c.length;x<_;x++){const w=c[x];if(w.isSunLight){const S=i.sun[h];S.direction.setFromMatrixPosition(w.matrixWorld),S.direction.transformDirection(m),h++}else if(w.isDirectionalLight){const S=i.directional[d];S.direction.setFromMatrixPosition(w.matrixWorld),a.setFromMatrixPosition(w.target.matrixWorld),S.direction.sub(a),S.direction.transformDirection(m),d++}else if(w.isSpotLight){const S=i.spot[f];S.position.setFromMatrixPosition(w.matrixWorld),S.position.applyMatrix4(m),S.direction.setFromMatrixPosition(w.matrixWorld),a.setFromMatrixPosition(w.target.matrixWorld),S.direction.sub(a),S.direction.transformDirection(m),f++}else if(w.isRectAreaLight){const S=i.rectArea[v];S.position.setFromMatrixPosition(w.matrixWorld),S.position.applyMatrix4(m),o.identity(),s.copy(w.matrixWorld),s.premultiply(m),o.extractRotation(s),S.halfWidth.set(w.width*.5,0,0),S.halfHeight.set(0,w.height*.5,0),S.halfWidth.applyMatrix4(o),S.halfHeight.applyMatrix4(o),v++}else if(w.isPointLight){const S=i.point[u];S.position.setFromMatrixPosition(w.matrixWorld),S.position.applyMatrix4(m),u++}else if(w.isHemisphereLight){const S=i.hemi[g];S.direction.setFromMatrixPosition(w.matrixWorld),S.direction.transformDirection(m),g++}}}return{setup:r,setupView:l,state:i}}function Yk(n){const e=new PI(n),t=[],i=[],a=[];function s(d){h.camera=d,t.length=0,i.length=0,a.length=0}function o(d){t.push(d)}function r(d){i.push(d)}function l(d){a.push(d)}function c(){e.setup(t)}function p(d){e.setupView(t,d)}const h={lightsArray:t,shadowsArray:i,lightProbeGridArray:a,camera:null,lights:e,transmissionRenderTarget:{},textureUnits:0};return{init:s,state:h,setupLights:c,setupLightsView:p,pushLight:o,pushShadow:r,pushLightProbeGrid:l}}function II(n){let e=new WeakMap;function t(a,s=0){const o=e.get(a);let r;return o===void 0?(r=new Yk(n),e.set(a,[r])):s>=o.length?(r=new Yk(n),o.push(r)):r=o[s],r}function i(){e=new WeakMap}return{get:t,dispose:i}}const $I=`void main() {
8454
8454
  gl_Position = vec4( position, 1.0 );
8455
8455
  }`,NI=`uniform sampler2D shadow_pass;
8456
8456
  uniform vec2 resolution;
@@ -8477,7 +8477,7 @@ void main() {
8477
8477
  squared_mean = squared_mean / samples;
8478
8478
  float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) );
8479
8479
  gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );
8480
- }`,DI=[new X(1,0,0),new X(-1,0,0),new X(0,1,0),new X(0,-1,0),new X(0,0,1),new X(0,0,-1)],zI=[new X(0,-1,0),new X(0,-1,0),new X(0,0,1),new X(0,0,-1),new X(0,-1,0),new X(0,-1,0)],jk=new en,Vc=new X,cx=new X;function OI(n,e,t){let i=new ak;const a=new ut,s=new ut,o=new nn,r=new C5,l=new R5,c={},p=t.maxTextureSize,h={[wo]:ei,[ei]:wo,[Na]:Na},d=new Pn({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new ut},radius:{value:4}},vertexShader:$I,fragmentShader:NI}),u=d.clone();u.defines.HORIZONTAL_PASS=1;const f=new pn;f.setAttribute("position",new ra(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new Xa(f,d),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=eh;let m=this.type;this.render=function(A,C,y){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||A.length===0)return;this.type===h4&&(rt("WebGLShadowMap: PCFSoftShadowMap has been removed. Using PCFShadowMap instead."),this.type=eh);const M=n.getRenderTarget(),T=n.getActiveCubeFace(),L=n.getActiveMipmapLevel(),P=n.state;P.setBlending(Da),P.buffers.depth.getReversed()===!0?P.buffers.color.setClear(0,0,0,0):P.buffers.color.setClear(1,1,1,1),P.buffers.depth.setTest(!0),P.setScissorTest(!1);const z=m!==this.type;z&&C.traverse(function(R){R.material&&(Array.isArray(R.material)?R.material.forEach(B=>B.needsUpdate=!0):R.material.needsUpdate=!0)});for(let R=0,B=A.length;R<B;R++){const K=A[R],N=K.shadow;if(N===void 0){rt("WebGLShadowMap:",K,"has no shadow.");continue}if(N.autoUpdate===!1&&N.needsUpdate===!1)continue;a.copy(N.mapSize);const V=N.getFrameExtents();a.multiply(V),s.copy(N.mapSize),(a.x>p||a.y>p)&&(a.x>p&&(s.x=Math.floor(p/V.x),a.x=s.x*V.x,N.mapSize.x=s.x),a.y>p&&(s.y=Math.floor(p/V.y),a.y=s.y*V.y,N.mapSize.y=s.y));const Z=n.state.buffers.depth.getReversed();if(N.camera._reversedDepth=Z,N.map===null||z===!0){if(N.map!==null&&(N.map.depthTexture!==null&&(N.map.depthTexture.dispose(),N.map.depthTexture=null),N.map.dispose()),this.type===Ec){if(K.isPointLight){rt("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}N.map=new $i(a.x,a.y,{format:Mo,type:sa,minFilter:Cn,magFilter:Cn,generateMipmaps:!1}),N.map.texture.name=K.name+".shadowMap",N.map.depthTexture=new Bc(a.x,a.y,aa),N.map.depthTexture.name=K.name+".shadowMapDepth",N.map.depthTexture.format=Ua,N.map.depthTexture.compareFunction=null,N.map.depthTexture.minFilter=Sn,N.map.depthTexture.magFilter=Sn}else K.isPointLight?(N.map=new Ck(a.x),N.map.depthTexture=new _5(a.x,ia)):(N.map=new $i(a.x,a.y),N.map.depthTexture=new Bc(a.x,a.y,ia)),N.map.depthTexture.name=K.name+".shadowMap",N.map.depthTexture.format=Ua,this.type===eh?(N.map.depthTexture.compareFunction=Z?Ev:Tv,N.map.depthTexture.minFilter=Cn,N.map.depthTexture.magFilter=Cn):(N.map.depthTexture.compareFunction=null,N.map.depthTexture.minFilter=Sn,N.map.depthTexture.magFilter=Sn);N.camera.updateProjectionMatrix()}N.map.isWebGLCubeRenderTarget!==!0&&(N.map.width!==a.x||N.map.height!==a.y)&&N.map.setSize(a.x,a.y);const te=N.map.isWebGLCubeRenderTarget?6:N.getViewportCount();K.isPointLight!==!0&&N.updateMatrices(K,y);for(let ce=0;ce<te;ce++){const Ne=N.getCamera(ce);if(K.isPointLight){const He=N.camera,ct=N.matrix,ot=K.distance||He.far;ot!==He.far&&(He.far=ot,He.updateProjectionMatrix()),Vc.setFromMatrixPosition(K.matrixWorld),He.position.copy(Vc),cx.copy(He.position),cx.add(DI[ce]),He.up.copy(zI[ce]),He.lookAt(cx),He.updateMatrixWorld(),ct.makeTranslation(-Vc.x,-Vc.y,-Vc.z),jk.multiplyMatrices(He.projectionMatrix,He.matrixWorldInverse),N._frustum.setFromProjectionMatrix(jk,He.coordinateSystem,He.reversedDepth)}if(N.map.isWebGLCubeRenderTarget)n.setRenderTarget(N.map,ce),n.clear();else{ce===0&&(n.setRenderTarget(N.map),n.clear());const He=N.getViewport(ce);o.set(s.x*He.x,s.y*He.y,s.x*He.z,s.y*He.w),P.viewport(o)}i=N.getFrustum(ce),w(C,y,Ne,K,this.type)}N.isPointLightShadow!==!0&&this.type===Ec&&x(N,y),N.needsUpdate=!1}m=this.type,g.needsUpdate=!1,n.setRenderTarget(M,T,L)};function x(A,C){const y=e.update(v);d.defines.VSM_SAMPLES!==A.blurSamples&&(d.defines.VSM_SAMPLES=A.blurSamples,u.defines.VSM_SAMPLES=A.blurSamples,d.needsUpdate=!0,u.needsUpdate=!0),A.mapPass===null?A.mapPass=new $i(a.x,a.y,{format:Mo,type:sa}):(A.mapPass.width!==A.map.width||A.mapPass.height!==A.map.height)&&A.mapPass.setSize(A.map.width,A.map.height),d.uniforms.shadow_pass.value=A.map.depthTexture,d.uniforms.resolution.value.set(A.map.width,A.map.height),d.uniforms.radius.value=A.radius,n.setRenderTarget(A.mapPass),n.clear(),n.renderBufferDirect(C,null,y,d,v,null),u.uniforms.shadow_pass.value=A.mapPass.texture,u.uniforms.resolution.value.set(A.map.width,A.map.height),u.uniforms.radius.value=A.radius,n.setRenderTarget(A.map),n.clear(),n.renderBufferDirect(C,null,y,u,v,null)}function _(A,C,y,M){let T=null;const L=y.isPointLight===!0?A.customDistanceMaterial:A.customDepthMaterial;if(L!==void 0)T=L;else if(T=y.isPointLight===!0?l:r,n.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||C.alphaToCoverage===!0){const P=T.uuid,z=C.uuid;let R=c[P];R===void 0&&(R={},c[P]=R);let B=R[z];B===void 0&&(B=T.clone(),R[z]=B,C.addEventListener("dispose",S)),T=B}if(T.visible=C.visible,T.wireframe=C.wireframe,M===Ec?T.side=C.shadowSide!==null?C.shadowSide:C.side:T.side=C.shadowSide!==null?C.shadowSide:h[C.side],T.alphaMap=C.alphaMap,T.alphaTest=C.alphaToCoverage===!0?.5:C.alphaTest,T.map=C.map,T.clipShadows=C.clipShadows,T.clippingPlanes=C.clippingPlanes,T.clipIntersection=C.clipIntersection,T.displacementMap=C.displacementMap,T.displacementScale=C.displacementScale,T.displacementBias=C.displacementBias,T.wireframeLinewidth=C.wireframeLinewidth,T.linewidth=C.linewidth,y.isPointLight===!0&&T.isMeshDistanceMaterial===!0){const P=n.properties.get(T);P.light=y}return T}function w(A,C,y,M,T){if(A.visible===!1)return;if(A.layers.test(C.layers)&&(A.isMesh||A.isLine||A.isPoints)&&(A.castShadow||A.receiveShadow&&T===Ec)&&(!A.frustumCulled||A.intersectsFrustum(i))){A.modelViewMatrix.multiplyMatrices(y.matrixWorldInverse,A.matrixWorld);const z=e.update(A),R=A.material;if(Array.isArray(R)){const B=z.groups;for(let K=0,N=B.length;K<N;K++){const V=B[K],Z=R[V.materialIndex];if(Z&&Z.visible){const te=_(A,Z,M,T);A.onBeforeShadow(n,A,C,y,z,te,V),n.renderBufferDirect(y,null,z,te,A,V),A.onAfterShadow(n,A,C,y,z,te,V)}}}else if(R.visible){const B=_(A,R,M,T);A.onBeforeShadow(n,A,C,y,z,B,null),n.renderBufferDirect(y,null,z,B,A,null),A.onAfterShadow(n,A,C,y,z,B,null)}}const P=A.children;for(let z=0,R=P.length;z<R;z++)w(P[z],C,y,M,T)}function S(A){A.target.removeEventListener("dispose",S);for(const y in c){const M=c[y],T=A.target.uuid;T in M&&(M[T].dispose(),delete M[T])}}}function UI(n,e){function t(){let q=!1;const Se=new nn;let le=null;const Ae=new nn(0,0,0,0);return{setMask:function($e){le!==$e&&!q&&(n.colorMask($e,$e,$e,$e),le=$e)},setLocked:function($e){q=$e},setClear:function($e,me,et,Ke,Kt){Kt===!0&&($e*=Ke,me*=Ke,et*=Ke),Se.set($e,me,et,Ke),Ae.equals(Se)===!1&&(n.clearColor($e,me,et,Ke),Ae.copy(Se))},reset:function(){q=!1,le=null,Ae.set(-1,0,0,0)}}}function i(){let q=!1,Se=!1,le=null,Ae=null,$e=null;return{setReversed:function(me){if(Se!==me){const et=e.get("EXT_clip_control");me?et.clipControlEXT(et.LOWER_LEFT_EXT,et.ZERO_TO_ONE_EXT):et.clipControlEXT(et.LOWER_LEFT_EXT,et.NEGATIVE_ONE_TO_ONE_EXT),Se=me;const Ke=$e;$e=null,this.setClear(Ke)}},getReversed:function(){return Se},setTest:function(me){me?oe(n.DEPTH_TEST):Te(n.DEPTH_TEST)},setMask:function(me){le!==me&&!q&&(n.depthMask(me),le=me)},setFunc:function(me){if(Se&&(me=K4[me]),Ae!==me){switch(me){case Pg:n.depthFunc(n.NEVER);break;case Ig:n.depthFunc(n.ALWAYS);break;case $g:n.depthFunc(n.LESS);break;case Cc:n.depthFunc(n.LEQUAL);break;case Ng:n.depthFunc(n.EQUAL);break;case Dg:n.depthFunc(n.GEQUAL);break;case zg:n.depthFunc(n.GREATER);break;case Og:n.depthFunc(n.NOTEQUAL);break;default:n.depthFunc(n.LEQUAL)}Ae=me}},setLocked:function(me){q=me},setClear:function(me){$e!==me&&($e=me,Se&&(me=1-me),n.clearDepth(me))},reset:function(){q=!1,le=null,Ae=null,$e=null,Se=!1}}}function a(){let q=!1,Se=null,le=null,Ae=null,$e=null,me=null,et=null,Ke=null,Kt=null;return{setTest:function(zt){q||(zt?oe(n.STENCIL_TEST):Te(n.STENCIL_TEST))},setMask:function(zt){Se!==zt&&!q&&(n.stencilMask(zt),Se=zt)},setFunc:function(zt,Hi,fa){(le!==zt||Ae!==Hi||$e!==fa)&&(n.stencilFunc(zt,Hi,fa),le=zt,Ae=Hi,$e=fa)},setOp:function(zt,Hi,fa){(me!==zt||et!==Hi||Ke!==fa)&&(n.stencilOp(zt,Hi,fa),me=zt,et=Hi,Ke=fa)},setLocked:function(zt){q=zt},setClear:function(zt){Kt!==zt&&(n.clearStencil(zt),Kt=zt)},reset:function(){q=!1,Se=null,le=null,Ae=null,$e=null,me=null,et=null,Ke=null,Kt=null}}}const s=new t,o=new i,r=new a,l=new WeakMap,c=new WeakMap;let p={},h={},d={},u=new WeakMap,f=[],v=null,g=!1,m=null,x=null,_=null,w=null,S=null,A=null,C=null,y=new It(0,0,0),M=0,T=!1,L=null,P=null,z=null,R=null,B=null;const K=n.getParameter(n.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let N=!1,V=0;const Z=n.getParameter(n.VERSION);Z.indexOf("WebGL")!==-1?(V=parseFloat(/^WebGL (\d)/.exec(Z)[1]),N=V>=1):Z.indexOf("OpenGL ES")!==-1&&(V=parseFloat(/^OpenGL ES (\d)/.exec(Z)[1]),N=V>=2);let te=null,ce={};const Ne=n.getParameter(n.SCISSOR_BOX),He=n.getParameter(n.VIEWPORT),ct=new nn().fromArray(Ne),ot=new nn().fromArray(He);function ft(q,Se,le,Ae){const $e=new Uint8Array(4),me=n.createTexture();n.bindTexture(q,me),n.texParameteri(q,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(q,n.TEXTURE_MAG_FILTER,n.NEAREST);for(let et=0;et<le;et++)q===n.TEXTURE_3D||q===n.TEXTURE_2D_ARRAY?n.texImage3D(Se,0,n.RGBA,1,1,Ae,0,n.RGBA,n.UNSIGNED_BYTE,$e):n.texImage2D(Se+et,0,n.RGBA,1,1,0,n.RGBA,n.UNSIGNED_BYTE,$e);return me}const ne={};ne[n.TEXTURE_2D]=ft(n.TEXTURE_2D,n.TEXTURE_2D,1),ne[n.TEXTURE_CUBE_MAP]=ft(n.TEXTURE_CUBE_MAP,n.TEXTURE_CUBE_MAP_POSITIVE_X,6),ne[n.TEXTURE_2D_ARRAY]=ft(n.TEXTURE_2D_ARRAY,n.TEXTURE_2D_ARRAY,1,1),ne[n.TEXTURE_3D]=ft(n.TEXTURE_3D,n.TEXTURE_3D,1,1),s.setClear(0,0,0,1),o.setClear(1),r.setClear(0),oe(n.DEPTH_TEST),o.setFunc(Cc),fe(!1),Ve(h2),oe(n.CULL_FACE),j(Da);function oe(q){p[q]!==!0&&(n.enable(q),p[q]=!0)}function Te(q){p[q]!==!1&&(n.disable(q),p[q]=!1)}function We(q,Se){return d[q]!==Se?(n.bindFramebuffer(q,Se),d[q]=Se,q===n.DRAW_FRAMEBUFFER&&(d[n.FRAMEBUFFER]=Se),q===n.FRAMEBUFFER&&(d[n.DRAW_FRAMEBUFFER]=Se),!0):!1}function Re(q,Se){let le=f,Ae=!1;if(q){le=u.get(Se),le===void 0&&(le=[],u.set(Se,le));const $e=q.textures;if(le.length!==$e.length||le[0]!==n.COLOR_ATTACHMENT0){for(let me=0,et=$e.length;me<et;me++)le[me]=n.COLOR_ATTACHMENT0+me;le.length=$e.length,Ae=!0}}else le[0]!==n.BACK&&(le[0]=n.BACK,Ae=!0);Ae&&n.drawBuffers(le)}function $(q){return v!==q?(n.useProgram(q),v=q,!0):!1}const H={[Tr]:n.FUNC_ADD,[f4]:n.FUNC_SUBTRACT,[m4]:n.FUNC_REVERSE_SUBTRACT};H[g4]=n.MIN,H[v4]=n.MAX;const Y={[x4]:n.ZERO,[b4]:n.ONE,[y4]:n.SRC_COLOR,[m2]:n.SRC_ALPHA,[A4]:n.SRC_ALPHA_SATURATE,[S4]:n.DST_COLOR,[k4]:n.DST_ALPHA,[w4]:n.ONE_MINUS_SRC_COLOR,[g2]:n.ONE_MINUS_SRC_ALPHA,[M4]:n.ONE_MINUS_DST_COLOR,[_4]:n.ONE_MINUS_DST_ALPHA,[T4]:n.CONSTANT_COLOR,[E4]:n.ONE_MINUS_CONSTANT_COLOR,[C4]:n.CONSTANT_ALPHA,[R4]:n.ONE_MINUS_CONSTANT_ALPHA};function j(q,Se,le,Ae,$e,me,et,Ke,Kt,zt){if(q===Da){g===!0&&(Te(n.BLEND),g=!1);return}if(g===!1&&(oe(n.BLEND),g=!0),q!==u4){if(q!==m||zt!==T){if((x!==Tr||S!==Tr)&&(n.blendEquation(n.FUNC_ADD),x=Tr,S=Tr),zt)switch(q){case Ar:n.blendFuncSeparate(n.ONE,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break;case za:n.blendFunc(n.ONE,n.ONE);break;case u2:n.blendFuncSeparate(n.ZERO,n.ONE_MINUS_SRC_COLOR,n.ZERO,n.ONE);break;case f2:n.blendFuncSeparate(n.DST_COLOR,n.ONE_MINUS_SRC_ALPHA,n.ZERO,n.ONE);break;default:Pt("WebGLState: Invalid blending: ",q);break}else switch(q){case Ar:n.blendFuncSeparate(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break;case za:n.blendFuncSeparate(n.SRC_ALPHA,n.ONE,n.ONE,n.ONE);break;case u2:Pt("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case f2:Pt("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:Pt("WebGLState: Invalid blending: ",q);break}_=null,w=null,A=null,C=null,y.set(0,0,0),M=0,m=q,T=zt}return}$e=$e||Se,me=me||le,et=et||Ae,(Se!==x||$e!==S)&&(n.blendEquationSeparate(H[Se],H[$e]),x=Se,S=$e),(le!==_||Ae!==w||me!==A||et!==C)&&(n.blendFuncSeparate(Y[le],Y[Ae],Y[me],Y[et]),_=le,w=Ae,A=me,C=et),(Ke.equals(y)===!1||Kt!==M)&&(n.blendColor(Ke.r,Ke.g,Ke.b,Kt),y.copy(Ke),M=Kt),m=q,T=!1}function de(q,Se){q.side===Na?Te(n.CULL_FACE):oe(n.CULL_FACE);let le=q.side===ei;Se&&(le=!le),fe(le),q.blending===Ar&&q.transparent===!1?j(Da):j(q.blending,q.blendEquation,q.blendSrc,q.blendDst,q.blendEquationAlpha,q.blendSrcAlpha,q.blendDstAlpha,q.blendColor,q.blendAlpha,q.premultipliedAlpha),o.setFunc(q.depthFunc),o.setTest(q.depthTest),o.setMask(q.depthWrite),s.setMask(q.colorWrite);const Ae=q.stencilWrite;r.setTest(Ae),Ae&&(r.setMask(q.stencilWriteMask),r.setFunc(q.stencilFunc,q.stencilRef,q.stencilFuncMask),r.setOp(q.stencilFail,q.stencilZFail,q.stencilZPass)),kt(q.polygonOffset,q.polygonOffsetFactor,q.polygonOffsetUnits),q.alphaToCoverage===!0?oe(n.SAMPLE_ALPHA_TO_COVERAGE):Te(n.SAMPLE_ALPHA_TO_COVERAGE)}function fe(q){L!==q&&(q?n.frontFace(n.CW):n.frontFace(n.CCW),L=q)}function Ve(q){q!==d4?(oe(n.CULL_FACE),q!==P&&(q===h2?n.cullFace(n.BACK):q===p4?n.cullFace(n.FRONT):n.cullFace(n.FRONT_AND_BACK))):Te(n.CULL_FACE),P=q}function st(q){q!==z&&(N&&n.lineWidth(q),z=q)}function kt(q,Se,le){q?(oe(n.POLYGON_OFFSET_FILL),(R!==Se||B!==le)&&(R=Se,B=le,o.getReversed()&&(Se=-Se),n.polygonOffset(Se,le))):Te(n.POLYGON_OFFSET_FILL)}function Ue(q){q?oe(n.SCISSOR_TEST):Te(n.SCISSOR_TEST)}function Ze(q){q===void 0&&(q=n.TEXTURE0+K-1),te!==q&&(n.activeTexture(q),te=q)}function F(q,Se,le){le===void 0&&(te===null?le=n.TEXTURE0+K-1:le=te);let Ae=ce[le];Ae===void 0&&(Ae={type:void 0,texture:void 0},ce[le]=Ae),(Ae.type!==q||Ae.texture!==Se)&&(te!==le&&(n.activeTexture(le),te=le),n.bindTexture(q,Se||ne[q]),Ae.type=q,Ae.texture=Se)}function lt(){const q=ce[te];q!==void 0&&q.type!==void 0&&(n.bindTexture(q.type,null),q.type=void 0,q.texture=void 0)}function Je(){try{n.compressedTexImage2D(...arguments)}catch(q){Pt("WebGLState:",q)}}function I(){try{n.compressedTexImage3D(...arguments)}catch(q){Pt("WebGLState:",q)}}function k(){try{n.texSubImage2D(...arguments)}catch(q){Pt("WebGLState:",q)}}function W(){try{n.texSubImage3D(...arguments)}catch(q){Pt("WebGLState:",q)}}function J(){try{n.compressedTexSubImage2D(...arguments)}catch(q){Pt("WebGLState:",q)}}function ae(){try{n.compressedTexSubImage3D(...arguments)}catch(q){Pt("WebGLState:",q)}}function ve(){try{n.texStorage2D(...arguments)}catch(q){Pt("WebGLState:",q)}}function be(){try{n.texStorage3D(...arguments)}catch(q){Pt("WebGLState:",q)}}function se(){try{n.texImage2D(...arguments)}catch(q){Pt("WebGLState:",q)}}function re(){try{n.texImage3D(...arguments)}catch(q){Pt("WebGLState:",q)}}function ke(q){return h[q]!==void 0?h[q]:n.getParameter(q)}function Fe(q,Se){h[q]!==Se&&(n.pixelStorei(q,Se),h[q]=Se)}function Me(q){ct.equals(q)===!1&&(n.scissor(q.x,q.y,q.z,q.w),ct.copy(q))}function _e(q){ot.equals(q)===!1&&(n.viewport(q.x,q.y,q.z,q.w),ot.copy(q))}function Xe(q,Se){let le=c.get(Se);le===void 0&&(le=new WeakMap,c.set(Se,le));let Ae=le.get(q);Ae===void 0&&(Ae=n.getUniformBlockIndex(Se,q.name),le.set(q,Ae))}function nt(q,Se){const Ae=c.get(Se).get(q);l.get(Se)!==Ae&&(n.uniformBlockBinding(Se,Ae,q.__bindingPointIndex),l.set(Se,Ae))}function ht(){n.disable(n.BLEND),n.disable(n.CULL_FACE),n.disable(n.DEPTH_TEST),n.disable(n.POLYGON_OFFSET_FILL),n.disable(n.SCISSOR_TEST),n.disable(n.STENCIL_TEST),n.disable(n.SAMPLE_ALPHA_TO_COVERAGE),n.blendEquation(n.FUNC_ADD),n.blendFunc(n.ONE,n.ZERO),n.blendFuncSeparate(n.ONE,n.ZERO,n.ONE,n.ZERO),n.blendColor(0,0,0,0),n.colorMask(!0,!0,!0,!0),n.clearColor(0,0,0,0),n.depthMask(!0),n.depthFunc(n.LESS),o.setReversed(!1),n.clearDepth(1),n.stencilMask(4294967295),n.stencilFunc(n.ALWAYS,0,4294967295),n.stencilOp(n.KEEP,n.KEEP,n.KEEP),n.clearStencil(0),n.cullFace(n.BACK),n.frontFace(n.CCW),n.polygonOffset(0,0),n.activeTexture(n.TEXTURE0),n.bindFramebuffer(n.FRAMEBUFFER,null),n.bindFramebuffer(n.DRAW_FRAMEBUFFER,null),n.bindFramebuffer(n.READ_FRAMEBUFFER,null),n.useProgram(null),n.lineWidth(1),n.scissor(0,0,n.canvas.width,n.canvas.height),n.viewport(0,0,n.canvas.width,n.canvas.height),n.pixelStorei(n.PACK_ALIGNMENT,4),n.pixelStorei(n.UNPACK_ALIGNMENT,4),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),n.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,n.BROWSER_DEFAULT_WEBGL),n.pixelStorei(n.PACK_ROW_LENGTH,0),n.pixelStorei(n.PACK_SKIP_PIXELS,0),n.pixelStorei(n.PACK_SKIP_ROWS,0),n.pixelStorei(n.UNPACK_ROW_LENGTH,0),n.pixelStorei(n.UNPACK_IMAGE_HEIGHT,0),n.pixelStorei(n.UNPACK_SKIP_PIXELS,0),n.pixelStorei(n.UNPACK_SKIP_ROWS,0),n.pixelStorei(n.UNPACK_SKIP_IMAGES,0),p={},h={},te=null,ce={},d={},u=new WeakMap,f=[],v=null,g=!1,m=null,x=null,_=null,w=null,S=null,A=null,C=null,y=new It(0,0,0),M=0,T=!1,L=null,P=null,z=null,R=null,B=null,ct.set(0,0,n.canvas.width,n.canvas.height),ot.set(0,0,n.canvas.width,n.canvas.height),s.reset(),o.reset(),r.reset()}return{buffers:{color:s,depth:o,stencil:r},enable:oe,disable:Te,bindFramebuffer:We,drawBuffers:Re,useProgram:$,setBlending:j,setMaterial:de,setFlipSided:fe,setCullFace:Ve,setLineWidth:st,setPolygonOffset:kt,setScissorTest:Ue,activeTexture:Ze,bindTexture:F,unbindTexture:lt,compressedTexImage2D:Je,compressedTexImage3D:I,texImage2D:se,texImage3D:re,pixelStorei:Fe,getParameter:ke,updateUBOMapping:Xe,uniformBlockBinding:nt,texStorage2D:ve,texStorage3D:be,texSubImage2D:k,texSubImage3D:W,compressedTexSubImage2D:J,compressedTexSubImage3D:ae,scissor:Me,viewport:_e,reset:ht}}function FI(n,e,t,i,a,s,o){const r=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,l=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new ut,p=new WeakMap,h=new Set;let d;const u=new WeakMap;let f=!1;try{f=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function v(I,k){return f?new OffscreenCanvas(I,k):hh("canvas")}function g(I,k,W){let J=1;const ae=Je(I);if((ae.width>W||ae.height>W)&&(J=W/Math.max(ae.width,ae.height)),J<1)if(typeof HTMLImageElement<"u"&&I instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&I instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&I instanceof ImageBitmap||typeof VideoFrame<"u"&&I instanceof VideoFrame){const ve=Math.floor(J*ae.width),be=Math.floor(J*ae.height);d===void 0&&(d=v(ve,be));const se=k?v(ve,be):d;return se.width=ve,se.height=be,se.getContext("2d").drawImage(I,0,0,ve,be),rt("WebGLRenderer: Texture has been resized from ("+ae.width+"x"+ae.height+") to ("+ve+"x"+be+")."),se}else return"data"in I&&rt("WebGLRenderer: Image in DataTexture is too big ("+ae.width+"x"+ae.height+")."),I;return I}function m(I){return I.generateMipmaps}function x(I){n.generateMipmap(I)}function _(I){return I.isWebGLCubeRenderTarget?n.TEXTURE_CUBE_MAP:I.isWebGL3DRenderTarget?n.TEXTURE_3D:I.isWebGLArrayRenderTarget||I.isCompressedArrayTexture?n.TEXTURE_2D_ARRAY:n.TEXTURE_2D}function w(I,k,W,J,ae,ve=!1){if(I!==null){if(n[I]!==void 0)return n[I];rt("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+I+"'")}let be;J&&(be=e.get("EXT_texture_norm16"),be||rt("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let se=k;if(k===n.RED&&(W===n.FLOAT&&(se=n.R32F),W===n.HALF_FLOAT&&(se=n.R16F),W===n.UNSIGNED_BYTE&&(se=n.R8),W===n.UNSIGNED_SHORT&&be&&(se=be.R16_EXT),W===n.SHORT&&be&&(se=be.R16_SNORM_EXT)),k===n.RED_INTEGER&&(W===n.UNSIGNED_BYTE&&(se=n.R8UI),W===n.UNSIGNED_SHORT&&(se=n.R16UI),W===n.UNSIGNED_INT&&(se=n.R32UI),W===n.BYTE&&(se=n.R8I),W===n.SHORT&&(se=n.R16I),W===n.INT&&(se=n.R32I)),k===n.RG&&(W===n.FLOAT&&(se=n.RG32F),W===n.HALF_FLOAT&&(se=n.RG16F),W===n.UNSIGNED_BYTE&&(se=n.RG8),W===n.UNSIGNED_SHORT&&be&&(se=be.RG16_EXT),W===n.SHORT&&be&&(se=be.RG16_SNORM_EXT)),k===n.RG_INTEGER&&(W===n.UNSIGNED_BYTE&&(se=n.RG8UI),W===n.UNSIGNED_SHORT&&(se=n.RG16UI),W===n.UNSIGNED_INT&&(se=n.RG32UI),W===n.BYTE&&(se=n.RG8I),W===n.SHORT&&(se=n.RG16I),W===n.INT&&(se=n.RG32I)),k===n.RGB_INTEGER&&(W===n.UNSIGNED_BYTE&&(se=n.RGB8UI),W===n.UNSIGNED_SHORT&&(se=n.RGB16UI),W===n.UNSIGNED_INT&&(se=n.RGB32UI),W===n.BYTE&&(se=n.RGB8I),W===n.SHORT&&(se=n.RGB16I),W===n.INT&&(se=n.RGB32I)),k===n.RGBA_INTEGER&&(W===n.UNSIGNED_BYTE&&(se=n.RGBA8UI),W===n.UNSIGNED_SHORT&&(se=n.RGBA16UI),W===n.UNSIGNED_INT&&(se=n.RGBA32UI),W===n.BYTE&&(se=n.RGBA8I),W===n.SHORT&&(se=n.RGBA16I),W===n.INT&&(se=n.RGBA32I)),k===n.RGB&&(W===n.UNSIGNED_SHORT&&be&&(se=be.RGB16_EXT),W===n.SHORT&&be&&(se=be.RGB16_SNORM_EXT),W===n.UNSIGNED_INT_5_9_9_9_REV&&(se=n.RGB9_E5),W===n.UNSIGNED_INT_10F_11F_11F_REV&&(se=n.R11F_G11F_B10F)),k===n.RGBA){const re=ve?dh:St.getTransfer(ae);W===n.FLOAT&&(se=n.RGBA32F),W===n.HALF_FLOAT&&(se=n.RGBA16F),W===n.UNSIGNED_BYTE&&(se=re===Bt?n.SRGB8_ALPHA8:n.RGBA8),W===n.UNSIGNED_SHORT&&be&&(se=be.RGBA16_EXT),W===n.SHORT&&be&&(se=be.RGBA16_SNORM_EXT),W===n.UNSIGNED_SHORT_4_4_4_4&&(se=n.RGBA4),W===n.UNSIGNED_SHORT_5_5_5_1&&(se=n.RGB5_A1)}return(se===n.R16F||se===n.R32F||se===n.RG16F||se===n.RG32F||se===n.RGBA16F||se===n.RGBA32F)&&e.get("EXT_color_buffer_float"),se}function S(I,k){let W;return I?k===null||k===ia||k===Lc?W=n.DEPTH24_STENCIL8:k===aa?W=n.DEPTH32F_STENCIL8:k===Rc&&(W=n.DEPTH24_STENCIL8,rt("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):k===null||k===ia||k===Lc?W=n.DEPTH_COMPONENT24:k===aa?W=n.DEPTH_COMPONENT32F:k===Rc&&(W=n.DEPTH_COMPONENT16),W}function A(I,k){return m(I)===!0||I.isFramebufferTexture&&I.minFilter!==Sn&&I.minFilter!==Cn?Math.log2(Math.max(k.width,k.height))+1:I.mipmaps!==void 0&&I.mipmaps.length>0?I.mipmaps.length:I.isCompressedTexture&&Array.isArray(I.image)?k.mipmaps.length:1}function C(I){const k=I.target;k.removeEventListener("dispose",C),M(k),k.isVideoTexture&&p.delete(k),k.isHTMLTexture&&h.delete(k)}function y(I){const k=I.target;k.removeEventListener("dispose",y),L(k)}function M(I){const k=i.get(I);if(k.__webglInit===void 0)return;const W=I.source,J=u.get(W);if(J){const ae=J[k.__cacheKey];ae.usedTimes--,ae.usedTimes===0&&T(I),Object.keys(J).length===0&&u.delete(W)}i.remove(I)}function T(I){const k=i.get(I);n.deleteTexture(k.__webglTexture);const W=I.source,J=u.get(W);delete J[k.__cacheKey],o.memory.textures--}function L(I){const k=i.get(I);if(I.depthTexture&&(I.depthTexture.dispose(),i.remove(I.depthTexture)),I.isWebGLCubeRenderTarget)for(let J=0;J<6;J++){if(Array.isArray(k.__webglFramebuffer[J]))for(let ae=0;ae<k.__webglFramebuffer[J].length;ae++)n.deleteFramebuffer(k.__webglFramebuffer[J][ae]);else n.deleteFramebuffer(k.__webglFramebuffer[J]);k.__webglDepthbuffer&&n.deleteRenderbuffer(k.__webglDepthbuffer[J])}else{if(Array.isArray(k.__webglFramebuffer))for(let J=0;J<k.__webglFramebuffer.length;J++)n.deleteFramebuffer(k.__webglFramebuffer[J]);else n.deleteFramebuffer(k.__webglFramebuffer);if(k.__webglDepthbuffer&&n.deleteRenderbuffer(k.__webglDepthbuffer),k.__webglMultisampledFramebuffer&&n.deleteFramebuffer(k.__webglMultisampledFramebuffer),k.__webglColorRenderbuffer)for(let J=0;J<k.__webglColorRenderbuffer.length;J++)k.__webglColorRenderbuffer[J]&&n.deleteRenderbuffer(k.__webglColorRenderbuffer[J]);k.__webglDepthRenderbuffer&&n.deleteRenderbuffer(k.__webglDepthRenderbuffer)}const W=I.textures;for(let J=0,ae=W.length;J<ae;J++){const ve=i.get(W[J]);ve.__webglTexture&&(n.deleteTexture(ve.__webglTexture),o.memory.textures--),i.remove(W[J])}i.remove(I)}let P=0;function z(){P=0}function R(){return P}function B(I){P=I}function K(){const I=P;return I>=a.maxTextures&&rt("WebGLTextures: Trying to use "+(I+1)+" texture units while this GPU supports only "+a.maxTextures),P+=1,I}function N(I){const k=[];return k.push(I.wrapS),k.push(I.wrapT),k.push(I.wrapR||0),k.push(I.magFilter),k.push(I.minFilter),k.push(I.anisotropy),k.push(I.internalFormat),k.push(I.format),k.push(I.type),k.push(I.generateMipmaps),k.push(I.premultiplyAlpha),k.push(I.flipY),k.push(I.unpackAlignment),k.push(I.colorSpace),k.join()}function V(I,k){const W=i.get(I);if(I.isVideoTexture&&F(I),I.isRenderTargetTexture===!1&&I.isExternalTexture!==!0&&I.version>0&&W.__version!==I.version){const J=I.image;if(J===null)rt("WebGLRenderer: Texture marked for update but no image data found.");else if(J.complete===!1)rt("WebGLRenderer: Texture marked for update but image is incomplete");else{Te(W,I,k);return}}else I.isExternalTexture&&(W.__webglTexture=I.sourceTexture?I.sourceTexture:null);t.bindTexture(n.TEXTURE_2D,W.__webglTexture,n.TEXTURE0+k)}function Z(I,k){const W=i.get(I);if(I.isRenderTargetTexture===!1&&I.version>0&&W.__version!==I.version){Te(W,I,k);return}else I.isExternalTexture&&(W.__webglTexture=I.sourceTexture?I.sourceTexture:null);t.bindTexture(n.TEXTURE_2D_ARRAY,W.__webglTexture,n.TEXTURE0+k)}function te(I,k){const W=i.get(I);if(I.isRenderTargetTexture===!1&&I.version>0&&W.__version!==I.version){Te(W,I,k);return}t.bindTexture(n.TEXTURE_3D,W.__webglTexture,n.TEXTURE0+k)}function ce(I,k){const W=i.get(I);if(I.isCubeDepthTexture!==!0&&I.version>0&&W.__version!==I.version){We(W,I,k);return}t.bindTexture(n.TEXTURE_CUBE_MAP,W.__webglTexture,n.TEXTURE0+k)}const Ne={[Bg]:n.REPEAT,[Oa]:n.CLAMP_TO_EDGE,[Hg]:n.MIRRORED_REPEAT},He={[Sn]:n.NEAREST,[I4]:n.NEAREST_MIPMAP_NEAREST,[nh]:n.NEAREST_MIPMAP_LINEAR,[Cn]:n.LINEAR,[Gg]:n.LINEAR_MIPMAP_NEAREST,[_o]:n.LINEAR_MIPMAP_LINEAR},ct={[z4]:n.NEVER,[H4]:n.ALWAYS,[O4]:n.LESS,[Tv]:n.LEQUAL,[U4]:n.EQUAL,[Ev]:n.GEQUAL,[F4]:n.GREATER,[B4]:n.NOTEQUAL};function ot(I,k){if(k.type===aa&&e.has("OES_texture_float_linear")===!1&&(k.magFilter===Cn||k.magFilter===Gg||k.magFilter===nh||k.magFilter===_o||k.minFilter===Cn||k.minFilter===Gg||k.minFilter===nh||k.minFilter===_o)&&rt("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),n.texParameteri(I,n.TEXTURE_WRAP_S,Ne[k.wrapS]),n.texParameteri(I,n.TEXTURE_WRAP_T,Ne[k.wrapT]),(I===n.TEXTURE_3D||I===n.TEXTURE_2D_ARRAY)&&n.texParameteri(I,n.TEXTURE_WRAP_R,Ne[k.wrapR]),n.texParameteri(I,n.TEXTURE_MAG_FILTER,He[k.magFilter]),n.texParameteri(I,n.TEXTURE_MIN_FILTER,He[k.minFilter]),k.compareFunction&&(n.texParameteri(I,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(I,n.TEXTURE_COMPARE_FUNC,ct[k.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(k.magFilter===Sn||k.minFilter!==nh&&k.minFilter!==_o||k.type===aa&&e.has("OES_texture_float_linear")===!1)return;if(k.anisotropy>1||i.get(k).__currentAnisotropy){const W=e.get("EXT_texture_filter_anisotropic");n.texParameterf(I,W.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(k.anisotropy,a.getMaxAnisotropy())),i.get(k).__currentAnisotropy=k.anisotropy}}}function ft(I,k){let W=!1;I.__webglInit===void 0&&(I.__webglInit=!0,k.addEventListener("dispose",C));const J=k.source;let ae=u.get(J);ae===void 0&&(ae={},u.set(J,ae));const ve=N(k);if(ve!==I.__cacheKey){ae[ve]===void 0&&(ae[ve]={texture:n.createTexture(),usedTimes:0},o.memory.textures++,W=!0),ae[ve].usedTimes++;const be=ae[I.__cacheKey];be!==void 0&&(ae[I.__cacheKey].usedTimes--,be.usedTimes===0&&T(k)),I.__cacheKey=ve,I.__webglTexture=ae[ve].texture}return W}function ne(I,k,W){return Math.floor(Math.floor(I/W)/k)}function oe(I,k,W,J){const ve=I.updateRanges;if(ve.length===0)t.texSubImage2D(n.TEXTURE_2D,0,0,0,k.width,k.height,W,J,k.data);else{ve.sort((Fe,Me)=>Fe.start-Me.start);let be=0;for(let Fe=1;Fe<ve.length;Fe++){const Me=ve[be],_e=ve[Fe],Xe=Me.start+Me.count,nt=ne(_e.start,k.width,4),ht=ne(Me.start,k.width,4);_e.start<=Xe+1&&nt===ht&&ne(_e.start+_e.count-1,k.width,4)===nt?Me.count=Math.max(Me.count,_e.start+_e.count-Me.start):(++be,ve[be]=_e)}ve.length=be+1;const se=t.getParameter(n.UNPACK_ROW_LENGTH),re=t.getParameter(n.UNPACK_SKIP_PIXELS),ke=t.getParameter(n.UNPACK_SKIP_ROWS);t.pixelStorei(n.UNPACK_ROW_LENGTH,k.width);for(let Fe=0,Me=ve.length;Fe<Me;Fe++){const _e=ve[Fe],Xe=Math.floor(_e.start/4),nt=Math.ceil(_e.count/4),ht=Xe%k.width,q=Math.floor(Xe/k.width),Se=nt,le=1;t.pixelStorei(n.UNPACK_SKIP_PIXELS,ht),t.pixelStorei(n.UNPACK_SKIP_ROWS,q),t.texSubImage2D(n.TEXTURE_2D,0,ht,q,Se,le,W,J,k.data)}I.clearUpdateRanges(),t.pixelStorei(n.UNPACK_ROW_LENGTH,se),t.pixelStorei(n.UNPACK_SKIP_PIXELS,re),t.pixelStorei(n.UNPACK_SKIP_ROWS,ke)}}function Te(I,k,W){let J=n.TEXTURE_2D;(k.isDataArrayTexture||k.isCompressedArrayTexture)&&(J=n.TEXTURE_2D_ARRAY),k.isData3DTexture&&(J=n.TEXTURE_3D);const ae=ft(I,k),ve=k.source;t.bindTexture(J,I.__webglTexture,n.TEXTURE0+W);const be=i.get(ve);if(ve.version!==be.__version||ae===!0){if(t.activeTexture(n.TEXTURE0+W),(typeof ImageBitmap<"u"&&k.image instanceof ImageBitmap)===!1){const le=St.getPrimaries(St.workingColorSpace),Ae=k.colorSpace===Cs?null:St.getPrimaries(k.colorSpace),$e=k.colorSpace===Cs||le===Ae?n.NONE:n.BROWSER_DEFAULT_WEBGL;t.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,k.flipY),t.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,k.premultiplyAlpha),t.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,$e)}t.pixelStorei(n.UNPACK_ALIGNMENT,k.unpackAlignment);let re=g(k.image,!1,a.maxTextureSize);re=lt(k,re);const ke=s.convert(k.format,k.colorSpace),Fe=s.convert(k.type);let Me=w(k.internalFormat,ke,Fe,k.normalized,k.colorSpace,k.isVideoTexture);ot(J,k);let _e;const Xe=k.mipmaps,nt=k.isVideoTexture!==!0,ht=be.__version===void 0||ae===!0,q=ve.dataReady,Se=A(k,re);if(k.isDepthTexture)Me=S(k.format===So,k.type),ht&&(nt?t.texStorage2D(n.TEXTURE_2D,1,Me,re.width,re.height):t.texImage2D(n.TEXTURE_2D,0,Me,re.width,re.height,0,ke,Fe,null));else if(k.isDataTexture)if(Xe.length>0){nt&&ht&&t.texStorage2D(n.TEXTURE_2D,Se,Me,Xe[0].width,Xe[0].height);for(let le=0,Ae=Xe.length;le<Ae;le++)_e=Xe[le],nt?q&&t.texSubImage2D(n.TEXTURE_2D,le,0,0,_e.width,_e.height,ke,Fe,_e.data):t.texImage2D(n.TEXTURE_2D,le,Me,_e.width,_e.height,0,ke,Fe,_e.data);k.generateMipmaps=!1}else nt?(ht&&t.texStorage2D(n.TEXTURE_2D,Se,Me,re.width,re.height),q&&oe(k,re,ke,Fe)):t.texImage2D(n.TEXTURE_2D,0,Me,re.width,re.height,0,ke,Fe,re.data);else if(k.isCompressedTexture)if(k.isCompressedArrayTexture){nt&&ht&&t.texStorage3D(n.TEXTURE_2D_ARRAY,Se,Me,Xe[0].width,Xe[0].height,re.depth);for(let le=0,Ae=Xe.length;le<Ae;le++)if(_e=Xe[le],k.format!==Ii)if(ke!==null)if(nt){if(q)if(k.layerUpdates.size>0){const $e=wk(_e.width,_e.height,k.format,k.type);for(const me of k.layerUpdates){const et=_e.data.subarray(me*$e/_e.data.BYTES_PER_ELEMENT,(me+1)*$e/_e.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,le,0,0,me,_e.width,_e.height,1,ke,et)}}else t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,le,0,0,0,_e.width,_e.height,re.depth,ke,_e.data)}else t.compressedTexImage3D(n.TEXTURE_2D_ARRAY,le,Me,_e.width,_e.height,re.depth,0,_e.data,0,0);else rt("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else nt?q&&t.texSubImage3D(n.TEXTURE_2D_ARRAY,le,0,0,0,_e.width,_e.height,re.depth,ke,Fe,_e.data):t.texImage3D(n.TEXTURE_2D_ARRAY,le,Me,_e.width,_e.height,re.depth,0,ke,Fe,_e.data);k.layerUpdates.size>0&&k.clearLayerUpdates()}else{nt&&ht&&t.texStorage2D(n.TEXTURE_2D,Se,Me,Xe[0].width,Xe[0].height);for(let le=0,Ae=Xe.length;le<Ae;le++)_e=Xe[le],k.format!==Ii?ke!==null?nt?q&&t.compressedTexSubImage2D(n.TEXTURE_2D,le,0,0,_e.width,_e.height,ke,_e.data):t.compressedTexImage2D(n.TEXTURE_2D,le,Me,_e.width,_e.height,0,_e.data):rt("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):nt?q&&t.texSubImage2D(n.TEXTURE_2D,le,0,0,_e.width,_e.height,ke,Fe,_e.data):t.texImage2D(n.TEXTURE_2D,le,Me,_e.width,_e.height,0,ke,Fe,_e.data)}else if(k.isDataArrayTexture)if(nt){if(ht&&t.texStorage3D(n.TEXTURE_2D_ARRAY,Se,Me,re.width,re.height,re.depth),q)if(k.layerUpdates.size>0){const le=wk(re.width,re.height,k.format,k.type);for(const Ae of k.layerUpdates){const $e=re.data.subarray(Ae*le/re.data.BYTES_PER_ELEMENT,(Ae+1)*le/re.data.BYTES_PER_ELEMENT);t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,Ae,re.width,re.height,1,ke,Fe,$e)}k.clearLayerUpdates()}else t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,re.width,re.height,re.depth,ke,Fe,re.data)}else t.texImage3D(n.TEXTURE_2D_ARRAY,0,Me,re.width,re.height,re.depth,0,ke,Fe,re.data);else if(k.isData3DTexture)nt?(ht&&t.texStorage3D(n.TEXTURE_3D,Se,Me,re.width,re.height,re.depth),q&&t.texSubImage3D(n.TEXTURE_3D,0,0,0,0,re.width,re.height,re.depth,ke,Fe,re.data)):t.texImage3D(n.TEXTURE_3D,0,Me,re.width,re.height,re.depth,0,ke,Fe,re.data);else if(k.isFramebufferTexture){if(ht)if(nt)t.texStorage2D(n.TEXTURE_2D,Se,Me,re.width,re.height);else{let le=re.width,Ae=re.height;for(let $e=0;$e<Se;$e++)t.texImage2D(n.TEXTURE_2D,$e,Me,le,Ae,0,ke,Fe,null),le>>=1,Ae>>=1}}else if(k.isHTMLTexture){if("texElementImage2D"in n){const le=n.canvas;if(le.hasAttribute("layoutsubtree")||le.setAttribute("layoutsubtree","true"),re.parentNode!==le){le.appendChild(re),h.add(k),le.onpaint=Ae=>{const $e=Ae.changedElements;for(const me of h)$e.includes(me.image)&&(me.needsUpdate=!0)},le.requestPaint();return}if(n.texElementImage2D.length===3)n.texElementImage2D(n.TEXTURE_2D,n.RGBA8,re);else{const $e=n.RGBA,me=n.RGBA,et=n.UNSIGNED_BYTE;n.texElementImage2D(n.TEXTURE_2D,0,$e,me,et,re)}n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE)}}else if(Xe.length>0){if(nt&&ht){const le=Je(Xe[0]);t.texStorage2D(n.TEXTURE_2D,Se,Me,le.width,le.height)}for(let le=0,Ae=Xe.length;le<Ae;le++)_e=Xe[le],nt?q&&t.texSubImage2D(n.TEXTURE_2D,le,0,0,ke,Fe,_e):t.texImage2D(n.TEXTURE_2D,le,Me,ke,Fe,_e);k.generateMipmaps=!1}else if(nt){if(ht){const le=Je(re);t.texStorage2D(n.TEXTURE_2D,Se,Me,le.width,le.height)}q&&t.texSubImage2D(n.TEXTURE_2D,0,0,0,ke,Fe,re)}else t.texImage2D(n.TEXTURE_2D,0,Me,ke,Fe,re);m(k)&&x(J),be.__version=ve.version,k.onUpdate&&k.onUpdate(k)}I.__version=k.version}function We(I,k,W){if(k.image.length!==6)return;const J=ft(I,k),ae=k.source;t.bindTexture(n.TEXTURE_CUBE_MAP,I.__webglTexture,n.TEXTURE0+W);const ve=i.get(ae);if(ae.version!==ve.__version||J===!0){t.activeTexture(n.TEXTURE0+W);const be=St.getPrimaries(St.workingColorSpace),se=k.colorSpace===Cs?null:St.getPrimaries(k.colorSpace),re=k.colorSpace===Cs||be===se?n.NONE:n.BROWSER_DEFAULT_WEBGL;t.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,k.flipY),t.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,k.premultiplyAlpha),t.pixelStorei(n.UNPACK_ALIGNMENT,k.unpackAlignment),t.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,re);const ke=k.isCompressedTexture||k.image[0].isCompressedTexture,Fe=k.image[0]&&k.image[0].isDataTexture,Me=[];for(let me=0;me<6;me++)!ke&&!Fe?Me[me]=g(k.image[me],!0,a.maxCubemapSize):Me[me]=Fe?k.image[me].image:k.image[me],Me[me]=lt(k,Me[me]);const _e=Me[0],Xe=s.convert(k.format,k.colorSpace),nt=s.convert(k.type),ht=w(k.internalFormat,Xe,nt,k.normalized,k.colorSpace),q=k.isVideoTexture!==!0,Se=ve.__version===void 0||J===!0,le=ae.dataReady;let Ae=A(k,_e);ot(n.TEXTURE_CUBE_MAP,k);let $e;if(ke){q&&Se&&t.texStorage2D(n.TEXTURE_CUBE_MAP,Ae,ht,_e.width,_e.height);for(let me=0;me<6;me++){$e=Me[me].mipmaps;for(let et=0;et<$e.length;et++){const Ke=$e[et];k.format!==Ii?Xe!==null?q?le&&t.compressedTexSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+me,et,0,0,Ke.width,Ke.height,Xe,Ke.data):t.compressedTexImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+me,et,ht,Ke.width,Ke.height,0,Ke.data):rt("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):q?le&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+me,et,0,0,Ke.width,Ke.height,Xe,nt,Ke.data):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+me,et,ht,Ke.width,Ke.height,0,Xe,nt,Ke.data)}}}else{if($e=k.mipmaps,q&&Se){$e.length>0&&Ae++;const me=Je(Me[0]);t.texStorage2D(n.TEXTURE_CUBE_MAP,Ae,ht,me.width,me.height)}for(let me=0;me<6;me++)if(Fe){q?le&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+me,0,0,0,Me[me].width,Me[me].height,Xe,nt,Me[me].data):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+me,0,ht,Me[me].width,Me[me].height,0,Xe,nt,Me[me].data);for(let et=0;et<$e.length;et++){const Kt=$e[et].image[me].image;q?le&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+me,et+1,0,0,Kt.width,Kt.height,Xe,nt,Kt.data):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+me,et+1,ht,Kt.width,Kt.height,0,Xe,nt,Kt.data)}}else{q?le&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+me,0,0,0,Xe,nt,Me[me]):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+me,0,ht,Xe,nt,Me[me]);for(let et=0;et<$e.length;et++){const Ke=$e[et];q?le&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+me,et+1,0,0,Xe,nt,Ke.image[me]):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+me,et+1,ht,Xe,nt,Ke.image[me])}}}m(k)&&x(n.TEXTURE_CUBE_MAP),ve.__version=ae.version,k.onUpdate&&k.onUpdate(k)}I.__version=k.version}function Re(I,k,W,J,ae,ve){const be=s.convert(W.format,W.colorSpace),se=s.convert(W.type),re=w(W.internalFormat,be,se,W.normalized,W.colorSpace),ke=i.get(k),Fe=i.get(W);if(Fe.__renderTarget=k,!ke.__hasExternalTextures){const Me=Math.max(1,k.width>>ve),_e=Math.max(1,k.height>>ve);ae===n.TEXTURE_3D||ae===n.TEXTURE_2D_ARRAY?t.texImage3D(ae,ve,re,Me,_e,k.depth,0,be,se,null):t.texImage2D(ae,ve,re,Me,_e,0,be,se,null)}t.bindFramebuffer(n.FRAMEBUFFER,I),Ze(k)?r.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER,J,ae,Fe.__webglTexture,0,Ue(k)):(ae===n.TEXTURE_2D||ae>=n.TEXTURE_CUBE_MAP_POSITIVE_X&&ae<=n.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&n.framebufferTexture2D(n.FRAMEBUFFER,J,ae,Fe.__webglTexture,ve),t.bindFramebuffer(n.FRAMEBUFFER,null)}function $(I,k,W){if(n.bindRenderbuffer(n.RENDERBUFFER,I),k.depthBuffer){const J=k.depthTexture,ae=J&&J.isDepthTexture?J.type:null,ve=S(k.stencilBuffer,ae),be=k.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT;Ze(k)?r.renderbufferStorageMultisampleEXT(n.RENDERBUFFER,Ue(k),ve,k.width,k.height):W?n.renderbufferStorageMultisample(n.RENDERBUFFER,Ue(k),ve,k.width,k.height):n.renderbufferStorage(n.RENDERBUFFER,ve,k.width,k.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,be,n.RENDERBUFFER,I)}else{const J=k.textures;for(let ae=0;ae<J.length;ae++){const ve=J[ae],be=s.convert(ve.format,ve.colorSpace),se=s.convert(ve.type),re=w(ve.internalFormat,be,se,ve.normalized,ve.colorSpace);Ze(k)?r.renderbufferStorageMultisampleEXT(n.RENDERBUFFER,Ue(k),re,k.width,k.height):W?n.renderbufferStorageMultisample(n.RENDERBUFFER,Ue(k),re,k.width,k.height):n.renderbufferStorage(n.RENDERBUFFER,re,k.width,k.height)}}n.bindRenderbuffer(n.RENDERBUFFER,null)}function H(I,k,W){const J=k.isWebGLCubeRenderTarget===!0;if(t.bindFramebuffer(n.FRAMEBUFFER,I),!(k.depthTexture&&k.depthTexture.isDepthTexture))throw new Error("THREE.WebGLTextures: renderTarget.depthTexture must be an instance of THREE.DepthTexture.");const ae=i.get(k.depthTexture);if(ae.__renderTarget=k,(!ae.__webglTexture||k.depthTexture.image.width!==k.width||k.depthTexture.image.height!==k.height)&&(k.depthTexture.image.width=k.width,k.depthTexture.image.height=k.height,k.depthTexture.needsUpdate=!0),J){if(ae.__webglInit===void 0&&(ae.__webglInit=!0,k.depthTexture.addEventListener("dispose",C)),ae.__webglTexture===void 0){ae.__webglTexture=n.createTexture(),t.bindTexture(n.TEXTURE_CUBE_MAP,ae.__webglTexture),ot(n.TEXTURE_CUBE_MAP,k.depthTexture);const ke=s.convert(k.depthTexture.format),Fe=s.convert(k.depthTexture.type);let Me;k.depthTexture.format===Ua?Me=n.DEPTH_COMPONENT24:k.depthTexture.format===So&&(Me=n.DEPTH24_STENCIL8);for(let _e=0;_e<6;_e++)n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+_e,0,Me,k.width,k.height,0,ke,Fe,null)}}else V(k.depthTexture,0);const ve=ae.__webglTexture,be=Ue(k),se=J?n.TEXTURE_CUBE_MAP_POSITIVE_X+W:n.TEXTURE_2D,re=k.depthTexture.format===So?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT;if(k.depthTexture.format===Ua)Ze(k)?r.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER,re,se,ve,0,be):n.framebufferTexture2D(n.FRAMEBUFFER,re,se,ve,0);else if(k.depthTexture.format===So)Ze(k)?r.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER,re,se,ve,0,be):n.framebufferTexture2D(n.FRAMEBUFFER,re,se,ve,0);else throw new Error("THREE.WebGLTextures: Unknown depthTexture format.")}function Y(I){const k=i.get(I),W=I.isWebGLCubeRenderTarget===!0;if(k.__boundDepthTexture!==I.depthTexture){const J=I.depthTexture;if(k.__depthDisposeCallback&&k.__depthDisposeCallback(),J){const ae=()=>{delete k.__boundDepthTexture,delete k.__depthDisposeCallback,J.removeEventListener("dispose",ae)};J.addEventListener("dispose",ae),k.__depthDisposeCallback=ae}k.__boundDepthTexture=J}if(I.depthTexture&&!k.__autoAllocateDepthBuffer)if(W)for(let J=0;J<6;J++)H(k.__webglFramebuffer[J],I,J);else{const J=I.texture.mipmaps;J&&J.length>0?H(k.__webglFramebuffer[0],I,0):H(k.__webglFramebuffer,I,0)}else if(W){k.__webglDepthbuffer=[];for(let J=0;J<6;J++)if(t.bindFramebuffer(n.FRAMEBUFFER,k.__webglFramebuffer[J]),k.__webglDepthbuffer[J]===void 0)k.__webglDepthbuffer[J]=n.createRenderbuffer(),$(k.__webglDepthbuffer[J],I,!1);else{const ae=I.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ve=k.__webglDepthbuffer[J];n.bindRenderbuffer(n.RENDERBUFFER,ve),n.framebufferRenderbuffer(n.FRAMEBUFFER,ae,n.RENDERBUFFER,ve)}}else{const J=I.texture.mipmaps;if(J&&J.length>0?t.bindFramebuffer(n.FRAMEBUFFER,k.__webglFramebuffer[0]):t.bindFramebuffer(n.FRAMEBUFFER,k.__webglFramebuffer),k.__webglDepthbuffer===void 0)k.__webglDepthbuffer=n.createRenderbuffer(),$(k.__webglDepthbuffer,I,!1);else{const ae=I.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ve=k.__webglDepthbuffer;n.bindRenderbuffer(n.RENDERBUFFER,ve),n.framebufferRenderbuffer(n.FRAMEBUFFER,ae,n.RENDERBUFFER,ve)}}t.bindFramebuffer(n.FRAMEBUFFER,null)}function j(I,k,W){const J=i.get(I);k!==void 0&&Re(J.__webglFramebuffer,I,I.texture,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,0),W!==void 0&&Y(I)}function de(I){const k=I.texture,W=i.get(I),J=i.get(k);I.addEventListener("dispose",y);const ae=I.textures,ve=I.isWebGLCubeRenderTarget===!0,be=ae.length>1;if(be||(J.__webglTexture===void 0&&(J.__webglTexture=n.createTexture()),J.__version=k.version,o.memory.textures++),ve){W.__webglFramebuffer=[];for(let se=0;se<6;se++)if(k.mipmaps&&k.mipmaps.length>0){W.__webglFramebuffer[se]=[];for(let re=0;re<k.mipmaps.length;re++)W.__webglFramebuffer[se][re]=n.createFramebuffer()}else W.__webglFramebuffer[se]=n.createFramebuffer()}else{if(k.mipmaps&&k.mipmaps.length>0){W.__webglFramebuffer=[];for(let se=0;se<k.mipmaps.length;se++)W.__webglFramebuffer[se]=n.createFramebuffer()}else W.__webglFramebuffer=n.createFramebuffer();if(be)for(let se=0,re=ae.length;se<re;se++){const ke=i.get(ae[se]);ke.__webglTexture===void 0&&(ke.__webglTexture=n.createTexture(),o.memory.textures++)}if(I.samples>0&&Ze(I)===!1){W.__webglMultisampledFramebuffer=n.createFramebuffer(),W.__webglColorRenderbuffer=[],t.bindFramebuffer(n.FRAMEBUFFER,W.__webglMultisampledFramebuffer);for(let se=0;se<ae.length;se++){const re=ae[se];W.__webglColorRenderbuffer[se]=n.createRenderbuffer(),n.bindRenderbuffer(n.RENDERBUFFER,W.__webglColorRenderbuffer[se]);const ke=s.convert(re.format,re.colorSpace),Fe=s.convert(re.type),Me=w(re.internalFormat,ke,Fe,re.normalized,re.colorSpace,I.isXRRenderTarget===!0),_e=Ue(I);n.renderbufferStorageMultisample(n.RENDERBUFFER,_e,Me,I.width,I.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0+se,n.RENDERBUFFER,W.__webglColorRenderbuffer[se])}n.bindRenderbuffer(n.RENDERBUFFER,null),I.depthBuffer&&(W.__webglDepthRenderbuffer=n.createRenderbuffer(),$(W.__webglDepthRenderbuffer,I,!0)),t.bindFramebuffer(n.FRAMEBUFFER,null)}}if(ve){t.bindTexture(n.TEXTURE_CUBE_MAP,J.__webglTexture),ot(n.TEXTURE_CUBE_MAP,k);for(let se=0;se<6;se++)if(k.mipmaps&&k.mipmaps.length>0)for(let re=0;re<k.mipmaps.length;re++)Re(W.__webglFramebuffer[se][re],I,k,n.COLOR_ATTACHMENT0,n.TEXTURE_CUBE_MAP_POSITIVE_X+se,re);else Re(W.__webglFramebuffer[se],I,k,n.COLOR_ATTACHMENT0,n.TEXTURE_CUBE_MAP_POSITIVE_X+se,0);m(k)&&x(n.TEXTURE_CUBE_MAP),t.unbindTexture()}else if(be){for(let se=0,re=ae.length;se<re;se++){const ke=ae[se],Fe=i.get(ke);let Me=n.TEXTURE_2D;(I.isWebGL3DRenderTarget||I.isWebGLArrayRenderTarget)&&(Me=I.isWebGL3DRenderTarget?n.TEXTURE_3D:n.TEXTURE_2D_ARRAY),t.bindTexture(Me,Fe.__webglTexture),ot(Me,ke),Re(W.__webglFramebuffer,I,ke,n.COLOR_ATTACHMENT0+se,Me,0),m(ke)&&x(Me)}t.unbindTexture()}else{let se=n.TEXTURE_2D;if((I.isWebGL3DRenderTarget||I.isWebGLArrayRenderTarget)&&(se=I.isWebGL3DRenderTarget?n.TEXTURE_3D:n.TEXTURE_2D_ARRAY),t.bindTexture(se,J.__webglTexture),ot(se,k),k.mipmaps&&k.mipmaps.length>0)for(let re=0;re<k.mipmaps.length;re++)Re(W.__webglFramebuffer[re],I,k,n.COLOR_ATTACHMENT0,se,re);else Re(W.__webglFramebuffer,I,k,n.COLOR_ATTACHMENT0,se,0);m(k)&&x(se),t.unbindTexture()}I.depthBuffer&&Y(I)}function fe(I){const k=I.textures;for(let W=0,J=k.length;W<J;W++){const ae=k[W];if(m(ae)){const ve=_(I),be=i.get(ae).__webglTexture;t.bindTexture(ve,be),x(ve),t.unbindTexture()}}}const Ve=[],st=[];function kt(I){if(I.samples>0){if(Ze(I)===!1){const k=I.textures,W=I.width,J=I.height;let ae=n.COLOR_BUFFER_BIT;const ve=I.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,be=i.get(I),se=k.length>1;if(se)for(let ke=0;ke<k.length;ke++)t.bindFramebuffer(n.FRAMEBUFFER,be.__webglMultisampledFramebuffer),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0+ke,n.RENDERBUFFER,null),t.bindFramebuffer(n.FRAMEBUFFER,be.__webglFramebuffer),n.framebufferTexture2D(n.DRAW_FRAMEBUFFER,n.COLOR_ATTACHMENT0+ke,n.TEXTURE_2D,null,0);t.bindFramebuffer(n.READ_FRAMEBUFFER,be.__webglMultisampledFramebuffer);const re=I.texture.mipmaps;re&&re.length>0?t.bindFramebuffer(n.DRAW_FRAMEBUFFER,be.__webglFramebuffer[0]):t.bindFramebuffer(n.DRAW_FRAMEBUFFER,be.__webglFramebuffer);for(let ke=0;ke<k.length;ke++){if(I.resolveDepthBuffer&&(I.depthBuffer&&(ae|=n.DEPTH_BUFFER_BIT),I.stencilBuffer&&I.resolveStencilBuffer&&(ae|=n.STENCIL_BUFFER_BIT)),se){n.framebufferRenderbuffer(n.READ_FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.RENDERBUFFER,be.__webglColorRenderbuffer[ke]);const Fe=i.get(k[ke]).__webglTexture;n.framebufferTexture2D(n.DRAW_FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,Fe,0)}n.blitFramebuffer(0,0,W,J,0,0,W,J,ae,n.NEAREST),l===!0&&(Ve.length=0,st.length=0,Ve.push(n.COLOR_ATTACHMENT0+ke),I.depthBuffer&&I.storeMultisampledDepthBuffer===!1&&(Ve.push(ve),st.push(ve),n.invalidateFramebuffer(n.DRAW_FRAMEBUFFER,st)),n.invalidateFramebuffer(n.READ_FRAMEBUFFER,Ve))}if(t.bindFramebuffer(n.READ_FRAMEBUFFER,null),t.bindFramebuffer(n.DRAW_FRAMEBUFFER,null),se)for(let ke=0;ke<k.length;ke++){t.bindFramebuffer(n.FRAMEBUFFER,be.__webglMultisampledFramebuffer),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0+ke,n.RENDERBUFFER,be.__webglColorRenderbuffer[ke]);const Fe=i.get(k[ke]).__webglTexture;t.bindFramebuffer(n.FRAMEBUFFER,be.__webglFramebuffer),n.framebufferTexture2D(n.DRAW_FRAMEBUFFER,n.COLOR_ATTACHMENT0+ke,n.TEXTURE_2D,Fe,0)}t.bindFramebuffer(n.DRAW_FRAMEBUFFER,be.__webglMultisampledFramebuffer)}else if(I.depthBuffer&&I.storeMultisampledDepthBuffer===!1&&l){const k=I.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT;n.invalidateFramebuffer(n.DRAW_FRAMEBUFFER,[k])}}}function Ue(I){return Math.min(a.maxSamples,I.samples)}function Ze(I){const k=i.get(I);return I.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&k.__useRenderToTexture!==!1}function F(I){const k=o.render.frame;p.get(I)!==k&&(p.set(I,k),I.update())}function lt(I,k){const W=I.colorSpace,J=I.format,ae=I.type;return I.isCompressedTexture===!0||I.isVideoTexture===!0||W!==ch&&W!==Cs&&(St.getTransfer(W)===Bt?(J!==Ii||ae!==xi)&&rt("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):Pt("WebGLTextures: Unsupported texture color space:",W)),k}function Je(I){return typeof HTMLImageElement<"u"&&I instanceof HTMLImageElement?(c.width=I.naturalWidth||I.width,c.height=I.naturalHeight||I.height):typeof VideoFrame<"u"&&I instanceof VideoFrame?(c.width=I.displayWidth,c.height=I.displayHeight):(c.width=I.width,c.height=I.height),c}this.allocateTextureUnit=K,this.resetTextureUnits=z,this.getTextureUnits=R,this.setTextureUnits=B,this.setTexture2D=V,this.setTexture2DArray=Z,this.setTexture3D=te,this.setTextureCube=ce,this.rebindTextures=j,this.setupRenderTarget=de,this.updateRenderTargetMipmap=fe,this.updateMultisampleRenderTarget=kt,this.setupDepthRenderbuffer=Y,this.setupFrameBufferTexture=Re,this.useMultisampledRTT=Ze,this.isReversedDepthBuffer=function(){return t.buffers.depth.getReversed()}}function BI(n,e){function t(i,a=Cs){let s;const o=St.getTransfer(a);if(i===xi)return n.UNSIGNED_BYTE;if(i===Vg)return n.UNSIGNED_SHORT_4_4_4_4;if(i===Wg)return n.UNSIGNED_SHORT_5_5_5_1;if(i===E2)return n.UNSIGNED_INT_5_9_9_9_REV;if(i===C2)return n.UNSIGNED_INT_10F_11F_11F_REV;if(i===A2)return n.BYTE;if(i===T2)return n.SHORT;if(i===Rc)return n.UNSIGNED_SHORT;if(i===qg)return n.INT;if(i===ia)return n.UNSIGNED_INT;if(i===aa)return n.FLOAT;if(i===sa)return n.HALF_FLOAT;if(i===R2)return n.ALPHA;if(i===L2)return n.RGB;if(i===Ii)return n.RGBA;if(i===Ua)return n.DEPTH_COMPONENT;if(i===So)return n.DEPTH_STENCIL;if(i===P2)return n.RED;if(i===Xg)return n.RED_INTEGER;if(i===Mo)return n.RG;if(i===Kg)return n.RG_INTEGER;if(i===Yg)return n.RGBA_INTEGER;if(i===ih||i===ah||i===sh||i===oh)if(o===Bt)if(s=e.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(i===ih)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===ah)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===sh)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===oh)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=e.get("WEBGL_compressed_texture_s3tc"),s!==null){if(i===ih)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===ah)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===sh)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===oh)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===jg||i===Zg||i===Jg||i===Qg)if(s=e.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(i===jg)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===Zg)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===Jg)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===Qg)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===ev||i===tv||i===nv||i===iv||i===av||i===rh||i===sv)if(s=e.get("WEBGL_compressed_texture_etc"),s!==null){if(i===ev||i===tv)return o===Bt?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(i===nv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC;if(i===iv)return s.COMPRESSED_R11_EAC;if(i===av)return s.COMPRESSED_SIGNED_R11_EAC;if(i===rh)return s.COMPRESSED_RG11_EAC;if(i===sv)return s.COMPRESSED_SIGNED_RG11_EAC}else return null;if(i===ov||i===rv||i===lv||i===cv||i===dv||i===pv||i===hv||i===uv||i===fv||i===mv||i===gv||i===vv||i===xv||i===bv)if(s=e.get("WEBGL_compressed_texture_astc"),s!==null){if(i===ov)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===rv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===lv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===cv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===dv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===pv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===hv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===uv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===fv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===mv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===gv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===vv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===xv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===bv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===yv||i===wv||i===kv)if(s=e.get("EXT_texture_compression_bptc"),s!==null){if(i===yv)return o===Bt?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===wv)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===kv)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===_v||i===Sv||i===lh||i===Mv)if(s=e.get("EXT_texture_compression_rgtc"),s!==null){if(i===_v)return s.COMPRESSED_RED_RGTC1_EXT;if(i===Sv)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===lh)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===Mv)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===Lc?n.UNSIGNED_INT_24_8:n[i]!==void 0?n[i]:null}return{convert:t}}const HI=`
8480
+ }`,DI=[new X(1,0,0),new X(-1,0,0),new X(0,1,0),new X(0,-1,0),new X(0,0,1),new X(0,0,-1)],zI=[new X(0,-1,0),new X(0,-1,0),new X(0,0,1),new X(0,0,-1),new X(0,-1,0),new X(0,-1,0)],jk=new en,Vc=new X,cx=new X;function OI(n,e,t){let i=new ak;const a=new ut,s=new ut,o=new nn,r=new C5,l=new R5,c={},p=t.maxTextureSize,h={[wo]:ei,[ei]:wo,[Na]:Na},d=new Pn({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new ut},radius:{value:4}},vertexShader:$I,fragmentShader:NI}),u=d.clone();u.defines.HORIZONTAL_PASS=1;const f=new pn;f.setAttribute("position",new ra(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));const v=new Xa(f,d),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=eh;let m=this.type;this.render=function(A,C,y){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||A.length===0)return;this.type===hR&&(rt("WebGLShadowMap: PCFSoftShadowMap has been removed. Using PCFShadowMap instead."),this.type=eh);const M=n.getRenderTarget(),T=n.getActiveCubeFace(),L=n.getActiveMipmapLevel(),P=n.state;P.setBlending(Da),P.buffers.depth.getReversed()===!0?P.buffers.color.setClear(0,0,0,0):P.buffers.color.setClear(1,1,1,1),P.buffers.depth.setTest(!0),P.setScissorTest(!1);const z=m!==this.type;z&&C.traverse(function(R){R.material&&(Array.isArray(R.material)?R.material.forEach(B=>B.needsUpdate=!0):R.material.needsUpdate=!0)});for(let R=0,B=A.length;R<B;R++){const K=A[R],N=K.shadow;if(N===void 0){rt("WebGLShadowMap:",K,"has no shadow.");continue}if(N.autoUpdate===!1&&N.needsUpdate===!1)continue;a.copy(N.mapSize);const V=N.getFrameExtents();a.multiply(V),s.copy(N.mapSize),(a.x>p||a.y>p)&&(a.x>p&&(s.x=Math.floor(p/V.x),a.x=s.x*V.x,N.mapSize.x=s.x),a.y>p&&(s.y=Math.floor(p/V.y),a.y=s.y*V.y,N.mapSize.y=s.y));const Z=n.state.buffers.depth.getReversed();if(N.camera._reversedDepth=Z,N.map===null||z===!0){if(N.map!==null&&(N.map.depthTexture!==null&&(N.map.depthTexture.dispose(),N.map.depthTexture=null),N.map.dispose()),this.type===Ec){if(K.isPointLight){rt("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.");continue}N.map=new $i(a.x,a.y,{format:Mo,type:sa,minFilter:Cn,magFilter:Cn,generateMipmaps:!1}),N.map.texture.name=K.name+".shadowMap",N.map.depthTexture=new Bc(a.x,a.y,aa),N.map.depthTexture.name=K.name+".shadowMapDepth",N.map.depthTexture.format=Ua,N.map.depthTexture.compareFunction=null,N.map.depthTexture.minFilter=Sn,N.map.depthTexture.magFilter=Sn}else K.isPointLight?(N.map=new Ck(a.x),N.map.depthTexture=new _5(a.x,ia)):(N.map=new $i(a.x,a.y),N.map.depthTexture=new Bc(a.x,a.y,ia)),N.map.depthTexture.name=K.name+".shadowMap",N.map.depthTexture.format=Ua,this.type===eh?(N.map.depthTexture.compareFunction=Z?Ev:Tv,N.map.depthTexture.minFilter=Cn,N.map.depthTexture.magFilter=Cn):(N.map.depthTexture.compareFunction=null,N.map.depthTexture.minFilter=Sn,N.map.depthTexture.magFilter=Sn);N.camera.updateProjectionMatrix()}N.map.isWebGLCubeRenderTarget!==!0&&(N.map.width!==a.x||N.map.height!==a.y)&&N.map.setSize(a.x,a.y);const te=N.map.isWebGLCubeRenderTarget?6:N.getViewportCount();K.isPointLight!==!0&&N.updateMatrices(K,y);for(let ce=0;ce<te;ce++){const Ne=N.getCamera(ce);if(K.isPointLight){const He=N.camera,ct=N.matrix,ot=K.distance||He.far;ot!==He.far&&(He.far=ot,He.updateProjectionMatrix()),Vc.setFromMatrixPosition(K.matrixWorld),He.position.copy(Vc),cx.copy(He.position),cx.add(DI[ce]),He.up.copy(zI[ce]),He.lookAt(cx),He.updateMatrixWorld(),ct.makeTranslation(-Vc.x,-Vc.y,-Vc.z),jk.multiplyMatrices(He.projectionMatrix,He.matrixWorldInverse),N._frustum.setFromProjectionMatrix(jk,He.coordinateSystem,He.reversedDepth)}if(N.map.isWebGLCubeRenderTarget)n.setRenderTarget(N.map,ce),n.clear();else{ce===0&&(n.setRenderTarget(N.map),n.clear());const He=N.getViewport(ce);o.set(s.x*He.x,s.y*He.y,s.x*He.z,s.y*He.w),P.viewport(o)}i=N.getFrustum(ce),w(C,y,Ne,K,this.type)}N.isPointLightShadow!==!0&&this.type===Ec&&x(N,y),N.needsUpdate=!1}m=this.type,g.needsUpdate=!1,n.setRenderTarget(M,T,L)};function x(A,C){const y=e.update(v);d.defines.VSM_SAMPLES!==A.blurSamples&&(d.defines.VSM_SAMPLES=A.blurSamples,u.defines.VSM_SAMPLES=A.blurSamples,d.needsUpdate=!0,u.needsUpdate=!0),A.mapPass===null?A.mapPass=new $i(a.x,a.y,{format:Mo,type:sa}):(A.mapPass.width!==A.map.width||A.mapPass.height!==A.map.height)&&A.mapPass.setSize(A.map.width,A.map.height),d.uniforms.shadow_pass.value=A.map.depthTexture,d.uniforms.resolution.value.set(A.map.width,A.map.height),d.uniforms.radius.value=A.radius,n.setRenderTarget(A.mapPass),n.clear(),n.renderBufferDirect(C,null,y,d,v,null),u.uniforms.shadow_pass.value=A.mapPass.texture,u.uniforms.resolution.value.set(A.map.width,A.map.height),u.uniforms.radius.value=A.radius,n.setRenderTarget(A.map),n.clear(),n.renderBufferDirect(C,null,y,u,v,null)}function _(A,C,y,M){let T=null;const L=y.isPointLight===!0?A.customDistanceMaterial:A.customDepthMaterial;if(L!==void 0)T=L;else if(T=y.isPointLight===!0?l:r,n.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||C.alphaToCoverage===!0){const P=T.uuid,z=C.uuid;let R=c[P];R===void 0&&(R={},c[P]=R);let B=R[z];B===void 0&&(B=T.clone(),R[z]=B,C.addEventListener("dispose",S)),T=B}if(T.visible=C.visible,T.wireframe=C.wireframe,M===Ec?T.side=C.shadowSide!==null?C.shadowSide:C.side:T.side=C.shadowSide!==null?C.shadowSide:h[C.side],T.alphaMap=C.alphaMap,T.alphaTest=C.alphaToCoverage===!0?.5:C.alphaTest,T.map=C.map,T.clipShadows=C.clipShadows,T.clippingPlanes=C.clippingPlanes,T.clipIntersection=C.clipIntersection,T.displacementMap=C.displacementMap,T.displacementScale=C.displacementScale,T.displacementBias=C.displacementBias,T.wireframeLinewidth=C.wireframeLinewidth,T.linewidth=C.linewidth,y.isPointLight===!0&&T.isMeshDistanceMaterial===!0){const P=n.properties.get(T);P.light=y}return T}function w(A,C,y,M,T){if(A.visible===!1)return;if(A.layers.test(C.layers)&&(A.isMesh||A.isLine||A.isPoints)&&(A.castShadow||A.receiveShadow&&T===Ec)&&(!A.frustumCulled||A.intersectsFrustum(i))){A.modelViewMatrix.multiplyMatrices(y.matrixWorldInverse,A.matrixWorld);const z=e.update(A),R=A.material;if(Array.isArray(R)){const B=z.groups;for(let K=0,N=B.length;K<N;K++){const V=B[K],Z=R[V.materialIndex];if(Z&&Z.visible){const te=_(A,Z,M,T);A.onBeforeShadow(n,A,C,y,z,te,V),n.renderBufferDirect(y,null,z,te,A,V),A.onAfterShadow(n,A,C,y,z,te,V)}}}else if(R.visible){const B=_(A,R,M,T);A.onBeforeShadow(n,A,C,y,z,B,null),n.renderBufferDirect(y,null,z,B,A,null),A.onAfterShadow(n,A,C,y,z,B,null)}}const P=A.children;for(let z=0,R=P.length;z<R;z++)w(P[z],C,y,M,T)}function S(A){A.target.removeEventListener("dispose",S);for(const y in c){const M=c[y],T=A.target.uuid;T in M&&(M[T].dispose(),delete M[T])}}}function UI(n,e){function t(){let q=!1;const Se=new nn;let le=null;const Ae=new nn(0,0,0,0);return{setMask:function($e){le!==$e&&!q&&(n.colorMask($e,$e,$e,$e),le=$e)},setLocked:function($e){q=$e},setClear:function($e,me,et,Ke,Kt){Kt===!0&&($e*=Ke,me*=Ke,et*=Ke),Se.set($e,me,et,Ke),Ae.equals(Se)===!1&&(n.clearColor($e,me,et,Ke),Ae.copy(Se))},reset:function(){q=!1,le=null,Ae.set(-1,0,0,0)}}}function i(){let q=!1,Se=!1,le=null,Ae=null,$e=null;return{setReversed:function(me){if(Se!==me){const et=e.get("EXT_clip_control");me?et.clipControlEXT(et.LOWER_LEFT_EXT,et.ZERO_TO_ONE_EXT):et.clipControlEXT(et.LOWER_LEFT_EXT,et.NEGATIVE_ONE_TO_ONE_EXT),Se=me;const Ke=$e;$e=null,this.setClear(Ke)}},getReversed:function(){return Se},setTest:function(me){me?oe(n.DEPTH_TEST):Te(n.DEPTH_TEST)},setMask:function(me){le!==me&&!q&&(n.depthMask(me),le=me)},setFunc:function(me){if(Se&&(me=KR[me]),Ae!==me){switch(me){case Pg:n.depthFunc(n.NEVER);break;case Ig:n.depthFunc(n.ALWAYS);break;case $g:n.depthFunc(n.LESS);break;case Cc:n.depthFunc(n.LEQUAL);break;case Ng:n.depthFunc(n.EQUAL);break;case Dg:n.depthFunc(n.GEQUAL);break;case zg:n.depthFunc(n.GREATER);break;case Og:n.depthFunc(n.NOTEQUAL);break;default:n.depthFunc(n.LEQUAL)}Ae=me}},setLocked:function(me){q=me},setClear:function(me){$e!==me&&($e=me,Se&&(me=1-me),n.clearDepth(me))},reset:function(){q=!1,le=null,Ae=null,$e=null,Se=!1}}}function a(){let q=!1,Se=null,le=null,Ae=null,$e=null,me=null,et=null,Ke=null,Kt=null;return{setTest:function(zt){q||(zt?oe(n.STENCIL_TEST):Te(n.STENCIL_TEST))},setMask:function(zt){Se!==zt&&!q&&(n.stencilMask(zt),Se=zt)},setFunc:function(zt,Hi,fa){(le!==zt||Ae!==Hi||$e!==fa)&&(n.stencilFunc(zt,Hi,fa),le=zt,Ae=Hi,$e=fa)},setOp:function(zt,Hi,fa){(me!==zt||et!==Hi||Ke!==fa)&&(n.stencilOp(zt,Hi,fa),me=zt,et=Hi,Ke=fa)},setLocked:function(zt){q=zt},setClear:function(zt){Kt!==zt&&(n.clearStencil(zt),Kt=zt)},reset:function(){q=!1,Se=null,le=null,Ae=null,$e=null,me=null,et=null,Ke=null,Kt=null}}}const s=new t,o=new i,r=new a,l=new WeakMap,c=new WeakMap;let p={},h={},d={},u=new WeakMap,f=[],v=null,g=!1,m=null,x=null,_=null,w=null,S=null,A=null,C=null,y=new It(0,0,0),M=0,T=!1,L=null,P=null,z=null,R=null,B=null;const K=n.getParameter(n.MAX_COMBINED_TEXTURE_IMAGE_UNITS);let N=!1,V=0;const Z=n.getParameter(n.VERSION);Z.indexOf("WebGL")!==-1?(V=parseFloat(/^WebGL (\d)/.exec(Z)[1]),N=V>=1):Z.indexOf("OpenGL ES")!==-1&&(V=parseFloat(/^OpenGL ES (\d)/.exec(Z)[1]),N=V>=2);let te=null,ce={};const Ne=n.getParameter(n.SCISSOR_BOX),He=n.getParameter(n.VIEWPORT),ct=new nn().fromArray(Ne),ot=new nn().fromArray(He);function ft(q,Se,le,Ae){const $e=new Uint8Array(4),me=n.createTexture();n.bindTexture(q,me),n.texParameteri(q,n.TEXTURE_MIN_FILTER,n.NEAREST),n.texParameteri(q,n.TEXTURE_MAG_FILTER,n.NEAREST);for(let et=0;et<le;et++)q===n.TEXTURE_3D||q===n.TEXTURE_2D_ARRAY?n.texImage3D(Se,0,n.RGBA,1,1,Ae,0,n.RGBA,n.UNSIGNED_BYTE,$e):n.texImage2D(Se+et,0,n.RGBA,1,1,0,n.RGBA,n.UNSIGNED_BYTE,$e);return me}const ne={};ne[n.TEXTURE_2D]=ft(n.TEXTURE_2D,n.TEXTURE_2D,1),ne[n.TEXTURE_CUBE_MAP]=ft(n.TEXTURE_CUBE_MAP,n.TEXTURE_CUBE_MAP_POSITIVE_X,6),ne[n.TEXTURE_2D_ARRAY]=ft(n.TEXTURE_2D_ARRAY,n.TEXTURE_2D_ARRAY,1,1),ne[n.TEXTURE_3D]=ft(n.TEXTURE_3D,n.TEXTURE_3D,1,1),s.setClear(0,0,0,1),o.setClear(1),r.setClear(0),oe(n.DEPTH_TEST),o.setFunc(Cc),fe(!1),Ve(h2),oe(n.CULL_FACE),j(Da);function oe(q){p[q]!==!0&&(n.enable(q),p[q]=!0)}function Te(q){p[q]!==!1&&(n.disable(q),p[q]=!1)}function We(q,Se){return d[q]!==Se?(n.bindFramebuffer(q,Se),d[q]=Se,q===n.DRAW_FRAMEBUFFER&&(d[n.FRAMEBUFFER]=Se),q===n.FRAMEBUFFER&&(d[n.DRAW_FRAMEBUFFER]=Se),!0):!1}function Re(q,Se){let le=f,Ae=!1;if(q){le=u.get(Se),le===void 0&&(le=[],u.set(Se,le));const $e=q.textures;if(le.length!==$e.length||le[0]!==n.COLOR_ATTACHMENT0){for(let me=0,et=$e.length;me<et;me++)le[me]=n.COLOR_ATTACHMENT0+me;le.length=$e.length,Ae=!0}}else le[0]!==n.BACK&&(le[0]=n.BACK,Ae=!0);Ae&&n.drawBuffers(le)}function $(q){return v!==q?(n.useProgram(q),v=q,!0):!1}const H={[Tr]:n.FUNC_ADD,[fR]:n.FUNC_SUBTRACT,[mR]:n.FUNC_REVERSE_SUBTRACT};H[gR]=n.MIN,H[vR]=n.MAX;const Y={[xR]:n.ZERO,[bR]:n.ONE,[yR]:n.SRC_COLOR,[m2]:n.SRC_ALPHA,[AR]:n.SRC_ALPHA_SATURATE,[SR]:n.DST_COLOR,[kR]:n.DST_ALPHA,[wR]:n.ONE_MINUS_SRC_COLOR,[g2]:n.ONE_MINUS_SRC_ALPHA,[MR]:n.ONE_MINUS_DST_COLOR,[_R]:n.ONE_MINUS_DST_ALPHA,[TR]:n.CONSTANT_COLOR,[ER]:n.ONE_MINUS_CONSTANT_COLOR,[CR]:n.CONSTANT_ALPHA,[RR]:n.ONE_MINUS_CONSTANT_ALPHA};function j(q,Se,le,Ae,$e,me,et,Ke,Kt,zt){if(q===Da){g===!0&&(Te(n.BLEND),g=!1);return}if(g===!1&&(oe(n.BLEND),g=!0),q!==uR){if(q!==m||zt!==T){if((x!==Tr||S!==Tr)&&(n.blendEquation(n.FUNC_ADD),x=Tr,S=Tr),zt)switch(q){case Ar:n.blendFuncSeparate(n.ONE,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break;case za:n.blendFunc(n.ONE,n.ONE);break;case u2:n.blendFuncSeparate(n.ZERO,n.ONE_MINUS_SRC_COLOR,n.ZERO,n.ONE);break;case f2:n.blendFuncSeparate(n.DST_COLOR,n.ONE_MINUS_SRC_ALPHA,n.ZERO,n.ONE);break;default:Pt("WebGLState: Invalid blending: ",q);break}else switch(q){case Ar:n.blendFuncSeparate(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA,n.ONE,n.ONE_MINUS_SRC_ALPHA);break;case za:n.blendFuncSeparate(n.SRC_ALPHA,n.ONE,n.ONE,n.ONE);break;case u2:Pt("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case f2:Pt("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:Pt("WebGLState: Invalid blending: ",q);break}_=null,w=null,A=null,C=null,y.set(0,0,0),M=0,m=q,T=zt}return}$e=$e||Se,me=me||le,et=et||Ae,(Se!==x||$e!==S)&&(n.blendEquationSeparate(H[Se],H[$e]),x=Se,S=$e),(le!==_||Ae!==w||me!==A||et!==C)&&(n.blendFuncSeparate(Y[le],Y[Ae],Y[me],Y[et]),_=le,w=Ae,A=me,C=et),(Ke.equals(y)===!1||Kt!==M)&&(n.blendColor(Ke.r,Ke.g,Ke.b,Kt),y.copy(Ke),M=Kt),m=q,T=!1}function de(q,Se){q.side===Na?Te(n.CULL_FACE):oe(n.CULL_FACE);let le=q.side===ei;Se&&(le=!le),fe(le),q.blending===Ar&&q.transparent===!1?j(Da):j(q.blending,q.blendEquation,q.blendSrc,q.blendDst,q.blendEquationAlpha,q.blendSrcAlpha,q.blendDstAlpha,q.blendColor,q.blendAlpha,q.premultipliedAlpha),o.setFunc(q.depthFunc),o.setTest(q.depthTest),o.setMask(q.depthWrite),s.setMask(q.colorWrite);const Ae=q.stencilWrite;r.setTest(Ae),Ae&&(r.setMask(q.stencilWriteMask),r.setFunc(q.stencilFunc,q.stencilRef,q.stencilFuncMask),r.setOp(q.stencilFail,q.stencilZFail,q.stencilZPass)),kt(q.polygonOffset,q.polygonOffsetFactor,q.polygonOffsetUnits),q.alphaToCoverage===!0?oe(n.SAMPLE_ALPHA_TO_COVERAGE):Te(n.SAMPLE_ALPHA_TO_COVERAGE)}function fe(q){L!==q&&(q?n.frontFace(n.CW):n.frontFace(n.CCW),L=q)}function Ve(q){q!==dR?(oe(n.CULL_FACE),q!==P&&(q===h2?n.cullFace(n.BACK):q===pR?n.cullFace(n.FRONT):n.cullFace(n.FRONT_AND_BACK))):Te(n.CULL_FACE),P=q}function st(q){q!==z&&(N&&n.lineWidth(q),z=q)}function kt(q,Se,le){q?(oe(n.POLYGON_OFFSET_FILL),(R!==Se||B!==le)&&(R=Se,B=le,o.getReversed()&&(Se=-Se),n.polygonOffset(Se,le))):Te(n.POLYGON_OFFSET_FILL)}function Ue(q){q?oe(n.SCISSOR_TEST):Te(n.SCISSOR_TEST)}function Ze(q){q===void 0&&(q=n.TEXTURE0+K-1),te!==q&&(n.activeTexture(q),te=q)}function F(q,Se,le){le===void 0&&(te===null?le=n.TEXTURE0+K-1:le=te);let Ae=ce[le];Ae===void 0&&(Ae={type:void 0,texture:void 0},ce[le]=Ae),(Ae.type!==q||Ae.texture!==Se)&&(te!==le&&(n.activeTexture(le),te=le),n.bindTexture(q,Se||ne[q]),Ae.type=q,Ae.texture=Se)}function lt(){const q=ce[te];q!==void 0&&q.type!==void 0&&(n.bindTexture(q.type,null),q.type=void 0,q.texture=void 0)}function Je(){try{n.compressedTexImage2D(...arguments)}catch(q){Pt("WebGLState:",q)}}function I(){try{n.compressedTexImage3D(...arguments)}catch(q){Pt("WebGLState:",q)}}function k(){try{n.texSubImage2D(...arguments)}catch(q){Pt("WebGLState:",q)}}function W(){try{n.texSubImage3D(...arguments)}catch(q){Pt("WebGLState:",q)}}function J(){try{n.compressedTexSubImage2D(...arguments)}catch(q){Pt("WebGLState:",q)}}function ae(){try{n.compressedTexSubImage3D(...arguments)}catch(q){Pt("WebGLState:",q)}}function ve(){try{n.texStorage2D(...arguments)}catch(q){Pt("WebGLState:",q)}}function be(){try{n.texStorage3D(...arguments)}catch(q){Pt("WebGLState:",q)}}function se(){try{n.texImage2D(...arguments)}catch(q){Pt("WebGLState:",q)}}function re(){try{n.texImage3D(...arguments)}catch(q){Pt("WebGLState:",q)}}function ke(q){return h[q]!==void 0?h[q]:n.getParameter(q)}function Fe(q,Se){h[q]!==Se&&(n.pixelStorei(q,Se),h[q]=Se)}function Me(q){ct.equals(q)===!1&&(n.scissor(q.x,q.y,q.z,q.w),ct.copy(q))}function _e(q){ot.equals(q)===!1&&(n.viewport(q.x,q.y,q.z,q.w),ot.copy(q))}function Xe(q,Se){let le=c.get(Se);le===void 0&&(le=new WeakMap,c.set(Se,le));let Ae=le.get(q);Ae===void 0&&(Ae=n.getUniformBlockIndex(Se,q.name),le.set(q,Ae))}function nt(q,Se){const Ae=c.get(Se).get(q);l.get(Se)!==Ae&&(n.uniformBlockBinding(Se,Ae,q.__bindingPointIndex),l.set(Se,Ae))}function ht(){n.disable(n.BLEND),n.disable(n.CULL_FACE),n.disable(n.DEPTH_TEST),n.disable(n.POLYGON_OFFSET_FILL),n.disable(n.SCISSOR_TEST),n.disable(n.STENCIL_TEST),n.disable(n.SAMPLE_ALPHA_TO_COVERAGE),n.blendEquation(n.FUNC_ADD),n.blendFunc(n.ONE,n.ZERO),n.blendFuncSeparate(n.ONE,n.ZERO,n.ONE,n.ZERO),n.blendColor(0,0,0,0),n.colorMask(!0,!0,!0,!0),n.clearColor(0,0,0,0),n.depthMask(!0),n.depthFunc(n.LESS),o.setReversed(!1),n.clearDepth(1),n.stencilMask(4294967295),n.stencilFunc(n.ALWAYS,0,4294967295),n.stencilOp(n.KEEP,n.KEEP,n.KEEP),n.clearStencil(0),n.cullFace(n.BACK),n.frontFace(n.CCW),n.polygonOffset(0,0),n.activeTexture(n.TEXTURE0),n.bindFramebuffer(n.FRAMEBUFFER,null),n.bindFramebuffer(n.DRAW_FRAMEBUFFER,null),n.bindFramebuffer(n.READ_FRAMEBUFFER,null),n.useProgram(null),n.lineWidth(1),n.scissor(0,0,n.canvas.width,n.canvas.height),n.viewport(0,0,n.canvas.width,n.canvas.height),n.pixelStorei(n.PACK_ALIGNMENT,4),n.pixelStorei(n.UNPACK_ALIGNMENT,4),n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1),n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),n.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,n.BROWSER_DEFAULT_WEBGL),n.pixelStorei(n.PACK_ROW_LENGTH,0),n.pixelStorei(n.PACK_SKIP_PIXELS,0),n.pixelStorei(n.PACK_SKIP_ROWS,0),n.pixelStorei(n.UNPACK_ROW_LENGTH,0),n.pixelStorei(n.UNPACK_IMAGE_HEIGHT,0),n.pixelStorei(n.UNPACK_SKIP_PIXELS,0),n.pixelStorei(n.UNPACK_SKIP_ROWS,0),n.pixelStorei(n.UNPACK_SKIP_IMAGES,0),p={},h={},te=null,ce={},d={},u=new WeakMap,f=[],v=null,g=!1,m=null,x=null,_=null,w=null,S=null,A=null,C=null,y=new It(0,0,0),M=0,T=!1,L=null,P=null,z=null,R=null,B=null,ct.set(0,0,n.canvas.width,n.canvas.height),ot.set(0,0,n.canvas.width,n.canvas.height),s.reset(),o.reset(),r.reset()}return{buffers:{color:s,depth:o,stencil:r},enable:oe,disable:Te,bindFramebuffer:We,drawBuffers:Re,useProgram:$,setBlending:j,setMaterial:de,setFlipSided:fe,setCullFace:Ve,setLineWidth:st,setPolygonOffset:kt,setScissorTest:Ue,activeTexture:Ze,bindTexture:F,unbindTexture:lt,compressedTexImage2D:Je,compressedTexImage3D:I,texImage2D:se,texImage3D:re,pixelStorei:Fe,getParameter:ke,updateUBOMapping:Xe,uniformBlockBinding:nt,texStorage2D:ve,texStorage3D:be,texSubImage2D:k,texSubImage3D:W,compressedTexSubImage2D:J,compressedTexSubImage3D:ae,scissor:Me,viewport:_e,reset:ht}}function FI(n,e,t,i,a,s,o){const r=e.has("WEBGL_multisampled_render_to_texture")?e.get("WEBGL_multisampled_render_to_texture"):null,l=typeof navigator>"u"?!1:/OculusBrowser/g.test(navigator.userAgent),c=new ut,p=new WeakMap,h=new Set;let d;const u=new WeakMap;let f=!1;try{f=typeof OffscreenCanvas<"u"&&new OffscreenCanvas(1,1).getContext("2d")!==null}catch{}function v(I,k){return f?new OffscreenCanvas(I,k):hh("canvas")}function g(I,k,W){let J=1;const ae=Je(I);if((ae.width>W||ae.height>W)&&(J=W/Math.max(ae.width,ae.height)),J<1)if(typeof HTMLImageElement<"u"&&I instanceof HTMLImageElement||typeof HTMLCanvasElement<"u"&&I instanceof HTMLCanvasElement||typeof ImageBitmap<"u"&&I instanceof ImageBitmap||typeof VideoFrame<"u"&&I instanceof VideoFrame){const ve=Math.floor(J*ae.width),be=Math.floor(J*ae.height);d===void 0&&(d=v(ve,be));const se=k?v(ve,be):d;return se.width=ve,se.height=be,se.getContext("2d").drawImage(I,0,0,ve,be),rt("WebGLRenderer: Texture has been resized from ("+ae.width+"x"+ae.height+") to ("+ve+"x"+be+")."),se}else return"data"in I&&rt("WebGLRenderer: Image in DataTexture is too big ("+ae.width+"x"+ae.height+")."),I;return I}function m(I){return I.generateMipmaps}function x(I){n.generateMipmap(I)}function _(I){return I.isWebGLCubeRenderTarget?n.TEXTURE_CUBE_MAP:I.isWebGL3DRenderTarget?n.TEXTURE_3D:I.isWebGLArrayRenderTarget||I.isCompressedArrayTexture?n.TEXTURE_2D_ARRAY:n.TEXTURE_2D}function w(I,k,W,J,ae,ve=!1){if(I!==null){if(n[I]!==void 0)return n[I];rt("WebGLRenderer: Attempt to use non-existing WebGL internal format '"+I+"'")}let be;J&&(be=e.get("EXT_texture_norm16"),be||rt("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension"));let se=k;if(k===n.RED&&(W===n.FLOAT&&(se=n.R32F),W===n.HALF_FLOAT&&(se=n.R16F),W===n.UNSIGNED_BYTE&&(se=n.R8),W===n.UNSIGNED_SHORT&&be&&(se=be.R16_EXT),W===n.SHORT&&be&&(se=be.R16_SNORM_EXT)),k===n.RED_INTEGER&&(W===n.UNSIGNED_BYTE&&(se=n.R8UI),W===n.UNSIGNED_SHORT&&(se=n.R16UI),W===n.UNSIGNED_INT&&(se=n.R32UI),W===n.BYTE&&(se=n.R8I),W===n.SHORT&&(se=n.R16I),W===n.INT&&(se=n.R32I)),k===n.RG&&(W===n.FLOAT&&(se=n.RG32F),W===n.HALF_FLOAT&&(se=n.RG16F),W===n.UNSIGNED_BYTE&&(se=n.RG8),W===n.UNSIGNED_SHORT&&be&&(se=be.RG16_EXT),W===n.SHORT&&be&&(se=be.RG16_SNORM_EXT)),k===n.RG_INTEGER&&(W===n.UNSIGNED_BYTE&&(se=n.RG8UI),W===n.UNSIGNED_SHORT&&(se=n.RG16UI),W===n.UNSIGNED_INT&&(se=n.RG32UI),W===n.BYTE&&(se=n.RG8I),W===n.SHORT&&(se=n.RG16I),W===n.INT&&(se=n.RG32I)),k===n.RGB_INTEGER&&(W===n.UNSIGNED_BYTE&&(se=n.RGB8UI),W===n.UNSIGNED_SHORT&&(se=n.RGB16UI),W===n.UNSIGNED_INT&&(se=n.RGB32UI),W===n.BYTE&&(se=n.RGB8I),W===n.SHORT&&(se=n.RGB16I),W===n.INT&&(se=n.RGB32I)),k===n.RGBA_INTEGER&&(W===n.UNSIGNED_BYTE&&(se=n.RGBA8UI),W===n.UNSIGNED_SHORT&&(se=n.RGBA16UI),W===n.UNSIGNED_INT&&(se=n.RGBA32UI),W===n.BYTE&&(se=n.RGBA8I),W===n.SHORT&&(se=n.RGBA16I),W===n.INT&&(se=n.RGBA32I)),k===n.RGB&&(W===n.UNSIGNED_SHORT&&be&&(se=be.RGB16_EXT),W===n.SHORT&&be&&(se=be.RGB16_SNORM_EXT),W===n.UNSIGNED_INT_5_9_9_9_REV&&(se=n.RGB9_E5),W===n.UNSIGNED_INT_10F_11F_11F_REV&&(se=n.R11F_G11F_B10F)),k===n.RGBA){const re=ve?dh:St.getTransfer(ae);W===n.FLOAT&&(se=n.RGBA32F),W===n.HALF_FLOAT&&(se=n.RGBA16F),W===n.UNSIGNED_BYTE&&(se=re===Bt?n.SRGB8_ALPHA8:n.RGBA8),W===n.UNSIGNED_SHORT&&be&&(se=be.RGBA16_EXT),W===n.SHORT&&be&&(se=be.RGBA16_SNORM_EXT),W===n.UNSIGNED_SHORT_4_4_4_4&&(se=n.RGBA4),W===n.UNSIGNED_SHORT_5_5_5_1&&(se=n.RGB5_A1)}return(se===n.R16F||se===n.R32F||se===n.RG16F||se===n.RG32F||se===n.RGBA16F||se===n.RGBA32F)&&e.get("EXT_color_buffer_float"),se}function S(I,k){let W;return I?k===null||k===ia||k===Lc?W=n.DEPTH24_STENCIL8:k===aa?W=n.DEPTH32F_STENCIL8:k===Rc&&(W=n.DEPTH24_STENCIL8,rt("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")):k===null||k===ia||k===Lc?W=n.DEPTH_COMPONENT24:k===aa?W=n.DEPTH_COMPONENT32F:k===Rc&&(W=n.DEPTH_COMPONENT16),W}function A(I,k){return m(I)===!0||I.isFramebufferTexture&&I.minFilter!==Sn&&I.minFilter!==Cn?Math.log2(Math.max(k.width,k.height))+1:I.mipmaps!==void 0&&I.mipmaps.length>0?I.mipmaps.length:I.isCompressedTexture&&Array.isArray(I.image)?k.mipmaps.length:1}function C(I){const k=I.target;k.removeEventListener("dispose",C),M(k),k.isVideoTexture&&p.delete(k),k.isHTMLTexture&&h.delete(k)}function y(I){const k=I.target;k.removeEventListener("dispose",y),L(k)}function M(I){const k=i.get(I);if(k.__webglInit===void 0)return;const W=I.source,J=u.get(W);if(J){const ae=J[k.__cacheKey];ae.usedTimes--,ae.usedTimes===0&&T(I),Object.keys(J).length===0&&u.delete(W)}i.remove(I)}function T(I){const k=i.get(I);n.deleteTexture(k.__webglTexture);const W=I.source,J=u.get(W);delete J[k.__cacheKey],o.memory.textures--}function L(I){const k=i.get(I);if(I.depthTexture&&(I.depthTexture.dispose(),i.remove(I.depthTexture)),I.isWebGLCubeRenderTarget)for(let J=0;J<6;J++){if(Array.isArray(k.__webglFramebuffer[J]))for(let ae=0;ae<k.__webglFramebuffer[J].length;ae++)n.deleteFramebuffer(k.__webglFramebuffer[J][ae]);else n.deleteFramebuffer(k.__webglFramebuffer[J]);k.__webglDepthbuffer&&n.deleteRenderbuffer(k.__webglDepthbuffer[J])}else{if(Array.isArray(k.__webglFramebuffer))for(let J=0;J<k.__webglFramebuffer.length;J++)n.deleteFramebuffer(k.__webglFramebuffer[J]);else n.deleteFramebuffer(k.__webglFramebuffer);if(k.__webglDepthbuffer&&n.deleteRenderbuffer(k.__webglDepthbuffer),k.__webglMultisampledFramebuffer&&n.deleteFramebuffer(k.__webglMultisampledFramebuffer),k.__webglColorRenderbuffer)for(let J=0;J<k.__webglColorRenderbuffer.length;J++)k.__webglColorRenderbuffer[J]&&n.deleteRenderbuffer(k.__webglColorRenderbuffer[J]);k.__webglDepthRenderbuffer&&n.deleteRenderbuffer(k.__webglDepthRenderbuffer)}const W=I.textures;for(let J=0,ae=W.length;J<ae;J++){const ve=i.get(W[J]);ve.__webglTexture&&(n.deleteTexture(ve.__webglTexture),o.memory.textures--),i.remove(W[J])}i.remove(I)}let P=0;function z(){P=0}function R(){return P}function B(I){P=I}function K(){const I=P;return I>=a.maxTextures&&rt("WebGLTextures: Trying to use "+(I+1)+" texture units while this GPU supports only "+a.maxTextures),P+=1,I}function N(I){const k=[];return k.push(I.wrapS),k.push(I.wrapT),k.push(I.wrapR||0),k.push(I.magFilter),k.push(I.minFilter),k.push(I.anisotropy),k.push(I.internalFormat),k.push(I.format),k.push(I.type),k.push(I.generateMipmaps),k.push(I.premultiplyAlpha),k.push(I.flipY),k.push(I.unpackAlignment),k.push(I.colorSpace),k.join()}function V(I,k){const W=i.get(I);if(I.isVideoTexture&&F(I),I.isRenderTargetTexture===!1&&I.isExternalTexture!==!0&&I.version>0&&W.__version!==I.version){const J=I.image;if(J===null)rt("WebGLRenderer: Texture marked for update but no image data found.");else if(J.complete===!1)rt("WebGLRenderer: Texture marked for update but image is incomplete");else{Te(W,I,k);return}}else I.isExternalTexture&&(W.__webglTexture=I.sourceTexture?I.sourceTexture:null);t.bindTexture(n.TEXTURE_2D,W.__webglTexture,n.TEXTURE0+k)}function Z(I,k){const W=i.get(I);if(I.isRenderTargetTexture===!1&&I.version>0&&W.__version!==I.version){Te(W,I,k);return}else I.isExternalTexture&&(W.__webglTexture=I.sourceTexture?I.sourceTexture:null);t.bindTexture(n.TEXTURE_2D_ARRAY,W.__webglTexture,n.TEXTURE0+k)}function te(I,k){const W=i.get(I);if(I.isRenderTargetTexture===!1&&I.version>0&&W.__version!==I.version){Te(W,I,k);return}t.bindTexture(n.TEXTURE_3D,W.__webglTexture,n.TEXTURE0+k)}function ce(I,k){const W=i.get(I);if(I.isCubeDepthTexture!==!0&&I.version>0&&W.__version!==I.version){We(W,I,k);return}t.bindTexture(n.TEXTURE_CUBE_MAP,W.__webglTexture,n.TEXTURE0+k)}const Ne={[Bg]:n.REPEAT,[Oa]:n.CLAMP_TO_EDGE,[Hg]:n.MIRRORED_REPEAT},He={[Sn]:n.NEAREST,[IR]:n.NEAREST_MIPMAP_NEAREST,[nh]:n.NEAREST_MIPMAP_LINEAR,[Cn]:n.LINEAR,[Gg]:n.LINEAR_MIPMAP_NEAREST,[_o]:n.LINEAR_MIPMAP_LINEAR},ct={[zR]:n.NEVER,[HR]:n.ALWAYS,[OR]:n.LESS,[Tv]:n.LEQUAL,[UR]:n.EQUAL,[Ev]:n.GEQUAL,[FR]:n.GREATER,[BR]:n.NOTEQUAL};function ot(I,k){if(k.type===aa&&e.has("OES_texture_float_linear")===!1&&(k.magFilter===Cn||k.magFilter===Gg||k.magFilter===nh||k.magFilter===_o||k.minFilter===Cn||k.minFilter===Gg||k.minFilter===nh||k.minFilter===_o)&&rt("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."),n.texParameteri(I,n.TEXTURE_WRAP_S,Ne[k.wrapS]),n.texParameteri(I,n.TEXTURE_WRAP_T,Ne[k.wrapT]),(I===n.TEXTURE_3D||I===n.TEXTURE_2D_ARRAY)&&n.texParameteri(I,n.TEXTURE_WRAP_R,Ne[k.wrapR]),n.texParameteri(I,n.TEXTURE_MAG_FILTER,He[k.magFilter]),n.texParameteri(I,n.TEXTURE_MIN_FILTER,He[k.minFilter]),k.compareFunction&&(n.texParameteri(I,n.TEXTURE_COMPARE_MODE,n.COMPARE_REF_TO_TEXTURE),n.texParameteri(I,n.TEXTURE_COMPARE_FUNC,ct[k.compareFunction])),e.has("EXT_texture_filter_anisotropic")===!0){if(k.magFilter===Sn||k.minFilter!==nh&&k.minFilter!==_o||k.type===aa&&e.has("OES_texture_float_linear")===!1)return;if(k.anisotropy>1||i.get(k).__currentAnisotropy){const W=e.get("EXT_texture_filter_anisotropic");n.texParameterf(I,W.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(k.anisotropy,a.getMaxAnisotropy())),i.get(k).__currentAnisotropy=k.anisotropy}}}function ft(I,k){let W=!1;I.__webglInit===void 0&&(I.__webglInit=!0,k.addEventListener("dispose",C));const J=k.source;let ae=u.get(J);ae===void 0&&(ae={},u.set(J,ae));const ve=N(k);if(ve!==I.__cacheKey){ae[ve]===void 0&&(ae[ve]={texture:n.createTexture(),usedTimes:0},o.memory.textures++,W=!0),ae[ve].usedTimes++;const be=ae[I.__cacheKey];be!==void 0&&(ae[I.__cacheKey].usedTimes--,be.usedTimes===0&&T(k)),I.__cacheKey=ve,I.__webglTexture=ae[ve].texture}return W}function ne(I,k,W){return Math.floor(Math.floor(I/W)/k)}function oe(I,k,W,J){const ve=I.updateRanges;if(ve.length===0)t.texSubImage2D(n.TEXTURE_2D,0,0,0,k.width,k.height,W,J,k.data);else{ve.sort((Fe,Me)=>Fe.start-Me.start);let be=0;for(let Fe=1;Fe<ve.length;Fe++){const Me=ve[be],_e=ve[Fe],Xe=Me.start+Me.count,nt=ne(_e.start,k.width,4),ht=ne(Me.start,k.width,4);_e.start<=Xe+1&&nt===ht&&ne(_e.start+_e.count-1,k.width,4)===nt?Me.count=Math.max(Me.count,_e.start+_e.count-Me.start):(++be,ve[be]=_e)}ve.length=be+1;const se=t.getParameter(n.UNPACK_ROW_LENGTH),re=t.getParameter(n.UNPACK_SKIP_PIXELS),ke=t.getParameter(n.UNPACK_SKIP_ROWS);t.pixelStorei(n.UNPACK_ROW_LENGTH,k.width);for(let Fe=0,Me=ve.length;Fe<Me;Fe++){const _e=ve[Fe],Xe=Math.floor(_e.start/4),nt=Math.ceil(_e.count/4),ht=Xe%k.width,q=Math.floor(Xe/k.width),Se=nt,le=1;t.pixelStorei(n.UNPACK_SKIP_PIXELS,ht),t.pixelStorei(n.UNPACK_SKIP_ROWS,q),t.texSubImage2D(n.TEXTURE_2D,0,ht,q,Se,le,W,J,k.data)}I.clearUpdateRanges(),t.pixelStorei(n.UNPACK_ROW_LENGTH,se),t.pixelStorei(n.UNPACK_SKIP_PIXELS,re),t.pixelStorei(n.UNPACK_SKIP_ROWS,ke)}}function Te(I,k,W){let J=n.TEXTURE_2D;(k.isDataArrayTexture||k.isCompressedArrayTexture)&&(J=n.TEXTURE_2D_ARRAY),k.isData3DTexture&&(J=n.TEXTURE_3D);const ae=ft(I,k),ve=k.source;t.bindTexture(J,I.__webglTexture,n.TEXTURE0+W);const be=i.get(ve);if(ve.version!==be.__version||ae===!0){if(t.activeTexture(n.TEXTURE0+W),(typeof ImageBitmap<"u"&&k.image instanceof ImageBitmap)===!1){const le=St.getPrimaries(St.workingColorSpace),Ae=k.colorSpace===Cs?null:St.getPrimaries(k.colorSpace),$e=k.colorSpace===Cs||le===Ae?n.NONE:n.BROWSER_DEFAULT_WEBGL;t.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,k.flipY),t.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,k.premultiplyAlpha),t.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,$e)}t.pixelStorei(n.UNPACK_ALIGNMENT,k.unpackAlignment);let re=g(k.image,!1,a.maxTextureSize);re=lt(k,re);const ke=s.convert(k.format,k.colorSpace),Fe=s.convert(k.type);let Me=w(k.internalFormat,ke,Fe,k.normalized,k.colorSpace,k.isVideoTexture);ot(J,k);let _e;const Xe=k.mipmaps,nt=k.isVideoTexture!==!0,ht=be.__version===void 0||ae===!0,q=ve.dataReady,Se=A(k,re);if(k.isDepthTexture)Me=S(k.format===So,k.type),ht&&(nt?t.texStorage2D(n.TEXTURE_2D,1,Me,re.width,re.height):t.texImage2D(n.TEXTURE_2D,0,Me,re.width,re.height,0,ke,Fe,null));else if(k.isDataTexture)if(Xe.length>0){nt&&ht&&t.texStorage2D(n.TEXTURE_2D,Se,Me,Xe[0].width,Xe[0].height);for(let le=0,Ae=Xe.length;le<Ae;le++)_e=Xe[le],nt?q&&t.texSubImage2D(n.TEXTURE_2D,le,0,0,_e.width,_e.height,ke,Fe,_e.data):t.texImage2D(n.TEXTURE_2D,le,Me,_e.width,_e.height,0,ke,Fe,_e.data);k.generateMipmaps=!1}else nt?(ht&&t.texStorage2D(n.TEXTURE_2D,Se,Me,re.width,re.height),q&&oe(k,re,ke,Fe)):t.texImage2D(n.TEXTURE_2D,0,Me,re.width,re.height,0,ke,Fe,re.data);else if(k.isCompressedTexture)if(k.isCompressedArrayTexture){nt&&ht&&t.texStorage3D(n.TEXTURE_2D_ARRAY,Se,Me,Xe[0].width,Xe[0].height,re.depth);for(let le=0,Ae=Xe.length;le<Ae;le++)if(_e=Xe[le],k.format!==Ii)if(ke!==null)if(nt){if(q)if(k.layerUpdates.size>0){const $e=wk(_e.width,_e.height,k.format,k.type);for(const me of k.layerUpdates){const et=_e.data.subarray(me*$e/_e.data.BYTES_PER_ELEMENT,(me+1)*$e/_e.data.BYTES_PER_ELEMENT);t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,le,0,0,me,_e.width,_e.height,1,ke,et)}}else t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY,le,0,0,0,_e.width,_e.height,re.depth,ke,_e.data)}else t.compressedTexImage3D(n.TEXTURE_2D_ARRAY,le,Me,_e.width,_e.height,re.depth,0,_e.data,0,0);else rt("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()");else nt?q&&t.texSubImage3D(n.TEXTURE_2D_ARRAY,le,0,0,0,_e.width,_e.height,re.depth,ke,Fe,_e.data):t.texImage3D(n.TEXTURE_2D_ARRAY,le,Me,_e.width,_e.height,re.depth,0,ke,Fe,_e.data);k.layerUpdates.size>0&&k.clearLayerUpdates()}else{nt&&ht&&t.texStorage2D(n.TEXTURE_2D,Se,Me,Xe[0].width,Xe[0].height);for(let le=0,Ae=Xe.length;le<Ae;le++)_e=Xe[le],k.format!==Ii?ke!==null?nt?q&&t.compressedTexSubImage2D(n.TEXTURE_2D,le,0,0,_e.width,_e.height,ke,_e.data):t.compressedTexImage2D(n.TEXTURE_2D,le,Me,_e.width,_e.height,0,_e.data):rt("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"):nt?q&&t.texSubImage2D(n.TEXTURE_2D,le,0,0,_e.width,_e.height,ke,Fe,_e.data):t.texImage2D(n.TEXTURE_2D,le,Me,_e.width,_e.height,0,ke,Fe,_e.data)}else if(k.isDataArrayTexture)if(nt){if(ht&&t.texStorage3D(n.TEXTURE_2D_ARRAY,Se,Me,re.width,re.height,re.depth),q)if(k.layerUpdates.size>0){const le=wk(re.width,re.height,k.format,k.type);for(const Ae of k.layerUpdates){const $e=re.data.subarray(Ae*le/re.data.BYTES_PER_ELEMENT,(Ae+1)*le/re.data.BYTES_PER_ELEMENT);t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,Ae,re.width,re.height,1,ke,Fe,$e)}k.clearLayerUpdates()}else t.texSubImage3D(n.TEXTURE_2D_ARRAY,0,0,0,0,re.width,re.height,re.depth,ke,Fe,re.data)}else t.texImage3D(n.TEXTURE_2D_ARRAY,0,Me,re.width,re.height,re.depth,0,ke,Fe,re.data);else if(k.isData3DTexture)nt?(ht&&t.texStorage3D(n.TEXTURE_3D,Se,Me,re.width,re.height,re.depth),q&&t.texSubImage3D(n.TEXTURE_3D,0,0,0,0,re.width,re.height,re.depth,ke,Fe,re.data)):t.texImage3D(n.TEXTURE_3D,0,Me,re.width,re.height,re.depth,0,ke,Fe,re.data);else if(k.isFramebufferTexture){if(ht)if(nt)t.texStorage2D(n.TEXTURE_2D,Se,Me,re.width,re.height);else{let le=re.width,Ae=re.height;for(let $e=0;$e<Se;$e++)t.texImage2D(n.TEXTURE_2D,$e,Me,le,Ae,0,ke,Fe,null),le>>=1,Ae>>=1}}else if(k.isHTMLTexture){if("texElementImage2D"in n){const le=n.canvas;if(le.hasAttribute("layoutsubtree")||le.setAttribute("layoutsubtree","true"),re.parentNode!==le){le.appendChild(re),h.add(k),le.onpaint=Ae=>{const $e=Ae.changedElements;for(const me of h)$e.includes(me.image)&&(me.needsUpdate=!0)},le.requestPaint();return}if(n.texElementImage2D.length===3)n.texElementImage2D(n.TEXTURE_2D,n.RGBA8,re);else{const $e=n.RGBA,me=n.RGBA,et=n.UNSIGNED_BYTE;n.texElementImage2D(n.TEXTURE_2D,0,$e,me,et,re)}n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE)}}else if(Xe.length>0){if(nt&&ht){const le=Je(Xe[0]);t.texStorage2D(n.TEXTURE_2D,Se,Me,le.width,le.height)}for(let le=0,Ae=Xe.length;le<Ae;le++)_e=Xe[le],nt?q&&t.texSubImage2D(n.TEXTURE_2D,le,0,0,ke,Fe,_e):t.texImage2D(n.TEXTURE_2D,le,Me,ke,Fe,_e);k.generateMipmaps=!1}else if(nt){if(ht){const le=Je(re);t.texStorage2D(n.TEXTURE_2D,Se,Me,le.width,le.height)}q&&t.texSubImage2D(n.TEXTURE_2D,0,0,0,ke,Fe,re)}else t.texImage2D(n.TEXTURE_2D,0,Me,ke,Fe,re);m(k)&&x(J),be.__version=ve.version,k.onUpdate&&k.onUpdate(k)}I.__version=k.version}function We(I,k,W){if(k.image.length!==6)return;const J=ft(I,k),ae=k.source;t.bindTexture(n.TEXTURE_CUBE_MAP,I.__webglTexture,n.TEXTURE0+W);const ve=i.get(ae);if(ae.version!==ve.__version||J===!0){t.activeTexture(n.TEXTURE0+W);const be=St.getPrimaries(St.workingColorSpace),se=k.colorSpace===Cs?null:St.getPrimaries(k.colorSpace),re=k.colorSpace===Cs||be===se?n.NONE:n.BROWSER_DEFAULT_WEBGL;t.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,k.flipY),t.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL,k.premultiplyAlpha),t.pixelStorei(n.UNPACK_ALIGNMENT,k.unpackAlignment),t.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL,re);const ke=k.isCompressedTexture||k.image[0].isCompressedTexture,Fe=k.image[0]&&k.image[0].isDataTexture,Me=[];for(let me=0;me<6;me++)!ke&&!Fe?Me[me]=g(k.image[me],!0,a.maxCubemapSize):Me[me]=Fe?k.image[me].image:k.image[me],Me[me]=lt(k,Me[me]);const _e=Me[0],Xe=s.convert(k.format,k.colorSpace),nt=s.convert(k.type),ht=w(k.internalFormat,Xe,nt,k.normalized,k.colorSpace),q=k.isVideoTexture!==!0,Se=ve.__version===void 0||J===!0,le=ae.dataReady;let Ae=A(k,_e);ot(n.TEXTURE_CUBE_MAP,k);let $e;if(ke){q&&Se&&t.texStorage2D(n.TEXTURE_CUBE_MAP,Ae,ht,_e.width,_e.height);for(let me=0;me<6;me++){$e=Me[me].mipmaps;for(let et=0;et<$e.length;et++){const Ke=$e[et];k.format!==Ii?Xe!==null?q?le&&t.compressedTexSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+me,et,0,0,Ke.width,Ke.height,Xe,Ke.data):t.compressedTexImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+me,et,ht,Ke.width,Ke.height,0,Ke.data):rt("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()"):q?le&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+me,et,0,0,Ke.width,Ke.height,Xe,nt,Ke.data):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+me,et,ht,Ke.width,Ke.height,0,Xe,nt,Ke.data)}}}else{if($e=k.mipmaps,q&&Se){$e.length>0&&Ae++;const me=Je(Me[0]);t.texStorage2D(n.TEXTURE_CUBE_MAP,Ae,ht,me.width,me.height)}for(let me=0;me<6;me++)if(Fe){q?le&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+me,0,0,0,Me[me].width,Me[me].height,Xe,nt,Me[me].data):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+me,0,ht,Me[me].width,Me[me].height,0,Xe,nt,Me[me].data);for(let et=0;et<$e.length;et++){const Kt=$e[et].image[me].image;q?le&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+me,et+1,0,0,Kt.width,Kt.height,Xe,nt,Kt.data):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+me,et+1,ht,Kt.width,Kt.height,0,Xe,nt,Kt.data)}}else{q?le&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+me,0,0,0,Xe,nt,Me[me]):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+me,0,ht,Xe,nt,Me[me]);for(let et=0;et<$e.length;et++){const Ke=$e[et];q?le&&t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+me,et+1,0,0,Xe,nt,Ke.image[me]):t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+me,et+1,ht,Xe,nt,Ke.image[me])}}}m(k)&&x(n.TEXTURE_CUBE_MAP),ve.__version=ae.version,k.onUpdate&&k.onUpdate(k)}I.__version=k.version}function Re(I,k,W,J,ae,ve){const be=s.convert(W.format,W.colorSpace),se=s.convert(W.type),re=w(W.internalFormat,be,se,W.normalized,W.colorSpace),ke=i.get(k),Fe=i.get(W);if(Fe.__renderTarget=k,!ke.__hasExternalTextures){const Me=Math.max(1,k.width>>ve),_e=Math.max(1,k.height>>ve);ae===n.TEXTURE_3D||ae===n.TEXTURE_2D_ARRAY?t.texImage3D(ae,ve,re,Me,_e,k.depth,0,be,se,null):t.texImage2D(ae,ve,re,Me,_e,0,be,se,null)}t.bindFramebuffer(n.FRAMEBUFFER,I),Ze(k)?r.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER,J,ae,Fe.__webglTexture,0,Ue(k)):(ae===n.TEXTURE_2D||ae>=n.TEXTURE_CUBE_MAP_POSITIVE_X&&ae<=n.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&n.framebufferTexture2D(n.FRAMEBUFFER,J,ae,Fe.__webglTexture,ve),t.bindFramebuffer(n.FRAMEBUFFER,null)}function $(I,k,W){if(n.bindRenderbuffer(n.RENDERBUFFER,I),k.depthBuffer){const J=k.depthTexture,ae=J&&J.isDepthTexture?J.type:null,ve=S(k.stencilBuffer,ae),be=k.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT;Ze(k)?r.renderbufferStorageMultisampleEXT(n.RENDERBUFFER,Ue(k),ve,k.width,k.height):W?n.renderbufferStorageMultisample(n.RENDERBUFFER,Ue(k),ve,k.width,k.height):n.renderbufferStorage(n.RENDERBUFFER,ve,k.width,k.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,be,n.RENDERBUFFER,I)}else{const J=k.textures;for(let ae=0;ae<J.length;ae++){const ve=J[ae],be=s.convert(ve.format,ve.colorSpace),se=s.convert(ve.type),re=w(ve.internalFormat,be,se,ve.normalized,ve.colorSpace);Ze(k)?r.renderbufferStorageMultisampleEXT(n.RENDERBUFFER,Ue(k),re,k.width,k.height):W?n.renderbufferStorageMultisample(n.RENDERBUFFER,Ue(k),re,k.width,k.height):n.renderbufferStorage(n.RENDERBUFFER,re,k.width,k.height)}}n.bindRenderbuffer(n.RENDERBUFFER,null)}function H(I,k,W){const J=k.isWebGLCubeRenderTarget===!0;if(t.bindFramebuffer(n.FRAMEBUFFER,I),!(k.depthTexture&&k.depthTexture.isDepthTexture))throw new Error("THREE.WebGLTextures: renderTarget.depthTexture must be an instance of THREE.DepthTexture.");const ae=i.get(k.depthTexture);if(ae.__renderTarget=k,(!ae.__webglTexture||k.depthTexture.image.width!==k.width||k.depthTexture.image.height!==k.height)&&(k.depthTexture.image.width=k.width,k.depthTexture.image.height=k.height,k.depthTexture.needsUpdate=!0),J){if(ae.__webglInit===void 0&&(ae.__webglInit=!0,k.depthTexture.addEventListener("dispose",C)),ae.__webglTexture===void 0){ae.__webglTexture=n.createTexture(),t.bindTexture(n.TEXTURE_CUBE_MAP,ae.__webglTexture),ot(n.TEXTURE_CUBE_MAP,k.depthTexture);const ke=s.convert(k.depthTexture.format),Fe=s.convert(k.depthTexture.type);let Me;k.depthTexture.format===Ua?Me=n.DEPTH_COMPONENT24:k.depthTexture.format===So&&(Me=n.DEPTH24_STENCIL8);for(let _e=0;_e<6;_e++)n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X+_e,0,Me,k.width,k.height,0,ke,Fe,null)}}else V(k.depthTexture,0);const ve=ae.__webglTexture,be=Ue(k),se=J?n.TEXTURE_CUBE_MAP_POSITIVE_X+W:n.TEXTURE_2D,re=k.depthTexture.format===So?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT;if(k.depthTexture.format===Ua)Ze(k)?r.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER,re,se,ve,0,be):n.framebufferTexture2D(n.FRAMEBUFFER,re,se,ve,0);else if(k.depthTexture.format===So)Ze(k)?r.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER,re,se,ve,0,be):n.framebufferTexture2D(n.FRAMEBUFFER,re,se,ve,0);else throw new Error("THREE.WebGLTextures: Unknown depthTexture format.")}function Y(I){const k=i.get(I),W=I.isWebGLCubeRenderTarget===!0;if(k.__boundDepthTexture!==I.depthTexture){const J=I.depthTexture;if(k.__depthDisposeCallback&&k.__depthDisposeCallback(),J){const ae=()=>{delete k.__boundDepthTexture,delete k.__depthDisposeCallback,J.removeEventListener("dispose",ae)};J.addEventListener("dispose",ae),k.__depthDisposeCallback=ae}k.__boundDepthTexture=J}if(I.depthTexture&&!k.__autoAllocateDepthBuffer)if(W)for(let J=0;J<6;J++)H(k.__webglFramebuffer[J],I,J);else{const J=I.texture.mipmaps;J&&J.length>0?H(k.__webglFramebuffer[0],I,0):H(k.__webglFramebuffer,I,0)}else if(W){k.__webglDepthbuffer=[];for(let J=0;J<6;J++)if(t.bindFramebuffer(n.FRAMEBUFFER,k.__webglFramebuffer[J]),k.__webglDepthbuffer[J]===void 0)k.__webglDepthbuffer[J]=n.createRenderbuffer(),$(k.__webglDepthbuffer[J],I,!1);else{const ae=I.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ve=k.__webglDepthbuffer[J];n.bindRenderbuffer(n.RENDERBUFFER,ve),n.framebufferRenderbuffer(n.FRAMEBUFFER,ae,n.RENDERBUFFER,ve)}}else{const J=I.texture.mipmaps;if(J&&J.length>0?t.bindFramebuffer(n.FRAMEBUFFER,k.__webglFramebuffer[0]):t.bindFramebuffer(n.FRAMEBUFFER,k.__webglFramebuffer),k.__webglDepthbuffer===void 0)k.__webglDepthbuffer=n.createRenderbuffer(),$(k.__webglDepthbuffer,I,!1);else{const ae=I.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,ve=k.__webglDepthbuffer;n.bindRenderbuffer(n.RENDERBUFFER,ve),n.framebufferRenderbuffer(n.FRAMEBUFFER,ae,n.RENDERBUFFER,ve)}}t.bindFramebuffer(n.FRAMEBUFFER,null)}function j(I,k,W){const J=i.get(I);k!==void 0&&Re(J.__webglFramebuffer,I,I.texture,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,0),W!==void 0&&Y(I)}function de(I){const k=I.texture,W=i.get(I),J=i.get(k);I.addEventListener("dispose",y);const ae=I.textures,ve=I.isWebGLCubeRenderTarget===!0,be=ae.length>1;if(be||(J.__webglTexture===void 0&&(J.__webglTexture=n.createTexture()),J.__version=k.version,o.memory.textures++),ve){W.__webglFramebuffer=[];for(let se=0;se<6;se++)if(k.mipmaps&&k.mipmaps.length>0){W.__webglFramebuffer[se]=[];for(let re=0;re<k.mipmaps.length;re++)W.__webglFramebuffer[se][re]=n.createFramebuffer()}else W.__webglFramebuffer[se]=n.createFramebuffer()}else{if(k.mipmaps&&k.mipmaps.length>0){W.__webglFramebuffer=[];for(let se=0;se<k.mipmaps.length;se++)W.__webglFramebuffer[se]=n.createFramebuffer()}else W.__webglFramebuffer=n.createFramebuffer();if(be)for(let se=0,re=ae.length;se<re;se++){const ke=i.get(ae[se]);ke.__webglTexture===void 0&&(ke.__webglTexture=n.createTexture(),o.memory.textures++)}if(I.samples>0&&Ze(I)===!1){W.__webglMultisampledFramebuffer=n.createFramebuffer(),W.__webglColorRenderbuffer=[],t.bindFramebuffer(n.FRAMEBUFFER,W.__webglMultisampledFramebuffer);for(let se=0;se<ae.length;se++){const re=ae[se];W.__webglColorRenderbuffer[se]=n.createRenderbuffer(),n.bindRenderbuffer(n.RENDERBUFFER,W.__webglColorRenderbuffer[se]);const ke=s.convert(re.format,re.colorSpace),Fe=s.convert(re.type),Me=w(re.internalFormat,ke,Fe,re.normalized,re.colorSpace,I.isXRRenderTarget===!0),_e=Ue(I);n.renderbufferStorageMultisample(n.RENDERBUFFER,_e,Me,I.width,I.height),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0+se,n.RENDERBUFFER,W.__webglColorRenderbuffer[se])}n.bindRenderbuffer(n.RENDERBUFFER,null),I.depthBuffer&&(W.__webglDepthRenderbuffer=n.createRenderbuffer(),$(W.__webglDepthRenderbuffer,I,!0)),t.bindFramebuffer(n.FRAMEBUFFER,null)}}if(ve){t.bindTexture(n.TEXTURE_CUBE_MAP,J.__webglTexture),ot(n.TEXTURE_CUBE_MAP,k);for(let se=0;se<6;se++)if(k.mipmaps&&k.mipmaps.length>0)for(let re=0;re<k.mipmaps.length;re++)Re(W.__webglFramebuffer[se][re],I,k,n.COLOR_ATTACHMENT0,n.TEXTURE_CUBE_MAP_POSITIVE_X+se,re);else Re(W.__webglFramebuffer[se],I,k,n.COLOR_ATTACHMENT0,n.TEXTURE_CUBE_MAP_POSITIVE_X+se,0);m(k)&&x(n.TEXTURE_CUBE_MAP),t.unbindTexture()}else if(be){for(let se=0,re=ae.length;se<re;se++){const ke=ae[se],Fe=i.get(ke);let Me=n.TEXTURE_2D;(I.isWebGL3DRenderTarget||I.isWebGLArrayRenderTarget)&&(Me=I.isWebGL3DRenderTarget?n.TEXTURE_3D:n.TEXTURE_2D_ARRAY),t.bindTexture(Me,Fe.__webglTexture),ot(Me,ke),Re(W.__webglFramebuffer,I,ke,n.COLOR_ATTACHMENT0+se,Me,0),m(ke)&&x(Me)}t.unbindTexture()}else{let se=n.TEXTURE_2D;if((I.isWebGL3DRenderTarget||I.isWebGLArrayRenderTarget)&&(se=I.isWebGL3DRenderTarget?n.TEXTURE_3D:n.TEXTURE_2D_ARRAY),t.bindTexture(se,J.__webglTexture),ot(se,k),k.mipmaps&&k.mipmaps.length>0)for(let re=0;re<k.mipmaps.length;re++)Re(W.__webglFramebuffer[re],I,k,n.COLOR_ATTACHMENT0,se,re);else Re(W.__webglFramebuffer,I,k,n.COLOR_ATTACHMENT0,se,0);m(k)&&x(se),t.unbindTexture()}I.depthBuffer&&Y(I)}function fe(I){const k=I.textures;for(let W=0,J=k.length;W<J;W++){const ae=k[W];if(m(ae)){const ve=_(I),be=i.get(ae).__webglTexture;t.bindTexture(ve,be),x(ve),t.unbindTexture()}}}const Ve=[],st=[];function kt(I){if(I.samples>0){if(Ze(I)===!1){const k=I.textures,W=I.width,J=I.height;let ae=n.COLOR_BUFFER_BIT;const ve=I.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT,be=i.get(I),se=k.length>1;if(se)for(let ke=0;ke<k.length;ke++)t.bindFramebuffer(n.FRAMEBUFFER,be.__webglMultisampledFramebuffer),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0+ke,n.RENDERBUFFER,null),t.bindFramebuffer(n.FRAMEBUFFER,be.__webglFramebuffer),n.framebufferTexture2D(n.DRAW_FRAMEBUFFER,n.COLOR_ATTACHMENT0+ke,n.TEXTURE_2D,null,0);t.bindFramebuffer(n.READ_FRAMEBUFFER,be.__webglMultisampledFramebuffer);const re=I.texture.mipmaps;re&&re.length>0?t.bindFramebuffer(n.DRAW_FRAMEBUFFER,be.__webglFramebuffer[0]):t.bindFramebuffer(n.DRAW_FRAMEBUFFER,be.__webglFramebuffer);for(let ke=0;ke<k.length;ke++){if(I.resolveDepthBuffer&&(I.depthBuffer&&(ae|=n.DEPTH_BUFFER_BIT),I.stencilBuffer&&I.resolveStencilBuffer&&(ae|=n.STENCIL_BUFFER_BIT)),se){n.framebufferRenderbuffer(n.READ_FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.RENDERBUFFER,be.__webglColorRenderbuffer[ke]);const Fe=i.get(k[ke]).__webglTexture;n.framebufferTexture2D(n.DRAW_FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,Fe,0)}n.blitFramebuffer(0,0,W,J,0,0,W,J,ae,n.NEAREST),l===!0&&(Ve.length=0,st.length=0,Ve.push(n.COLOR_ATTACHMENT0+ke),I.depthBuffer&&I.storeMultisampledDepthBuffer===!1&&(Ve.push(ve),st.push(ve),n.invalidateFramebuffer(n.DRAW_FRAMEBUFFER,st)),n.invalidateFramebuffer(n.READ_FRAMEBUFFER,Ve))}if(t.bindFramebuffer(n.READ_FRAMEBUFFER,null),t.bindFramebuffer(n.DRAW_FRAMEBUFFER,null),se)for(let ke=0;ke<k.length;ke++){t.bindFramebuffer(n.FRAMEBUFFER,be.__webglMultisampledFramebuffer),n.framebufferRenderbuffer(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0+ke,n.RENDERBUFFER,be.__webglColorRenderbuffer[ke]);const Fe=i.get(k[ke]).__webglTexture;t.bindFramebuffer(n.FRAMEBUFFER,be.__webglFramebuffer),n.framebufferTexture2D(n.DRAW_FRAMEBUFFER,n.COLOR_ATTACHMENT0+ke,n.TEXTURE_2D,Fe,0)}t.bindFramebuffer(n.DRAW_FRAMEBUFFER,be.__webglMultisampledFramebuffer)}else if(I.depthBuffer&&I.storeMultisampledDepthBuffer===!1&&l){const k=I.stencilBuffer?n.DEPTH_STENCIL_ATTACHMENT:n.DEPTH_ATTACHMENT;n.invalidateFramebuffer(n.DRAW_FRAMEBUFFER,[k])}}}function Ue(I){return Math.min(a.maxSamples,I.samples)}function Ze(I){const k=i.get(I);return I.samples>0&&e.has("WEBGL_multisampled_render_to_texture")===!0&&k.__useRenderToTexture!==!1}function F(I){const k=o.render.frame;p.get(I)!==k&&(p.set(I,k),I.update())}function lt(I,k){const W=I.colorSpace,J=I.format,ae=I.type;return I.isCompressedTexture===!0||I.isVideoTexture===!0||W!==ch&&W!==Cs&&(St.getTransfer(W)===Bt?(J!==Ii||ae!==xi)&&rt("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType."):Pt("WebGLTextures: Unsupported texture color space:",W)),k}function Je(I){return typeof HTMLImageElement<"u"&&I instanceof HTMLImageElement?(c.width=I.naturalWidth||I.width,c.height=I.naturalHeight||I.height):typeof VideoFrame<"u"&&I instanceof VideoFrame?(c.width=I.displayWidth,c.height=I.displayHeight):(c.width=I.width,c.height=I.height),c}this.allocateTextureUnit=K,this.resetTextureUnits=z,this.getTextureUnits=R,this.setTextureUnits=B,this.setTexture2D=V,this.setTexture2DArray=Z,this.setTexture3D=te,this.setTextureCube=ce,this.rebindTextures=j,this.setupRenderTarget=de,this.updateRenderTargetMipmap=fe,this.updateMultisampleRenderTarget=kt,this.setupDepthRenderbuffer=Y,this.setupFrameBufferTexture=Re,this.useMultisampledRTT=Ze,this.isReversedDepthBuffer=function(){return t.buffers.depth.getReversed()}}function BI(n,e){function t(i,a=Cs){let s;const o=St.getTransfer(a);if(i===xi)return n.UNSIGNED_BYTE;if(i===Vg)return n.UNSIGNED_SHORT_4_4_4_4;if(i===Wg)return n.UNSIGNED_SHORT_5_5_5_1;if(i===E2)return n.UNSIGNED_INT_5_9_9_9_REV;if(i===C2)return n.UNSIGNED_INT_10F_11F_11F_REV;if(i===A2)return n.BYTE;if(i===T2)return n.SHORT;if(i===Rc)return n.UNSIGNED_SHORT;if(i===qg)return n.INT;if(i===ia)return n.UNSIGNED_INT;if(i===aa)return n.FLOAT;if(i===sa)return n.HALF_FLOAT;if(i===R2)return n.ALPHA;if(i===L2)return n.RGB;if(i===Ii)return n.RGBA;if(i===Ua)return n.DEPTH_COMPONENT;if(i===So)return n.DEPTH_STENCIL;if(i===P2)return n.RED;if(i===Xg)return n.RED_INTEGER;if(i===Mo)return n.RG;if(i===Kg)return n.RG_INTEGER;if(i===Yg)return n.RGBA_INTEGER;if(i===ih||i===ah||i===sh||i===oh)if(o===Bt)if(s=e.get("WEBGL_compressed_texture_s3tc_srgb"),s!==null){if(i===ih)return s.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(i===ah)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(i===sh)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(i===oh)return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(s=e.get("WEBGL_compressed_texture_s3tc"),s!==null){if(i===ih)return s.COMPRESSED_RGB_S3TC_DXT1_EXT;if(i===ah)return s.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(i===sh)return s.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(i===oh)return s.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(i===jg||i===Zg||i===Jg||i===Qg)if(s=e.get("WEBGL_compressed_texture_pvrtc"),s!==null){if(i===jg)return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(i===Zg)return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(i===Jg)return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(i===Qg)return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(i===ev||i===tv||i===nv||i===iv||i===av||i===rh||i===sv)if(s=e.get("WEBGL_compressed_texture_etc"),s!==null){if(i===ev||i===tv)return o===Bt?s.COMPRESSED_SRGB8_ETC2:s.COMPRESSED_RGB8_ETC2;if(i===nv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:s.COMPRESSED_RGBA8_ETC2_EAC;if(i===iv)return s.COMPRESSED_R11_EAC;if(i===av)return s.COMPRESSED_SIGNED_R11_EAC;if(i===rh)return s.COMPRESSED_RG11_EAC;if(i===sv)return s.COMPRESSED_SIGNED_RG11_EAC}else return null;if(i===ov||i===rv||i===lv||i===cv||i===dv||i===pv||i===hv||i===uv||i===fv||i===mv||i===gv||i===vv||i===xv||i===bv)if(s=e.get("WEBGL_compressed_texture_astc"),s!==null){if(i===ov)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:s.COMPRESSED_RGBA_ASTC_4x4_KHR;if(i===rv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:s.COMPRESSED_RGBA_ASTC_5x4_KHR;if(i===lv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:s.COMPRESSED_RGBA_ASTC_5x5_KHR;if(i===cv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:s.COMPRESSED_RGBA_ASTC_6x5_KHR;if(i===dv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:s.COMPRESSED_RGBA_ASTC_6x6_KHR;if(i===pv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:s.COMPRESSED_RGBA_ASTC_8x5_KHR;if(i===hv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:s.COMPRESSED_RGBA_ASTC_8x6_KHR;if(i===uv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:s.COMPRESSED_RGBA_ASTC_8x8_KHR;if(i===fv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:s.COMPRESSED_RGBA_ASTC_10x5_KHR;if(i===mv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:s.COMPRESSED_RGBA_ASTC_10x6_KHR;if(i===gv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:s.COMPRESSED_RGBA_ASTC_10x8_KHR;if(i===vv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:s.COMPRESSED_RGBA_ASTC_10x10_KHR;if(i===xv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:s.COMPRESSED_RGBA_ASTC_12x10_KHR;if(i===bv)return o===Bt?s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:s.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(i===yv||i===wv||i===kv)if(s=e.get("EXT_texture_compression_bptc"),s!==null){if(i===yv)return o===Bt?s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:s.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(i===wv)return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(i===kv)return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(i===_v||i===Sv||i===lh||i===Mv)if(s=e.get("EXT_texture_compression_rgtc"),s!==null){if(i===_v)return s.COMPRESSED_RED_RGTC1_EXT;if(i===Sv)return s.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(i===lh)return s.COMPRESSED_RED_GREEN_RGTC2_EXT;if(i===Mv)return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return i===Lc?n.UNSIGNED_INT_24_8:n[i]!==void 0?n[i]:null}return{convert:t}}const HI=`
8481
8481
  void main() {
8482
8482
 
8483
8483
  gl_Position = vec4( position, 1.0 );
@@ -8501,7 +8501,7 @@ void main() {
8501
8501
 
8502
8502
  }
8503
8503
 
8504
- }`;class qI{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){const i=new hk(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=i}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,i=new Pn({vertexShader:HI,fragmentShader:GI,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new Xa(new Uh(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class VI extends Rs{constructor(e,t){super();const i=this;let a=null,s=1,o=null,r="local-floor",l=1,c=null,p=null,h=null,d=null,u=null,f=null;const v=typeof XRWebGLBinding<"u",g=new qI,m={},x=t.getContextAttributes();let _=null,w=null;const S=[],A=[],C=new ut;let y=null,M=null;const T=new wi;T.viewport=new nn;const L=new wi;L.viewport=new nn;const P=[T,L],z=new P5;let R=null,B=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(ne){let oe=S[ne];return oe===void 0&&(oe=new zv,S[ne]=oe),oe.getTargetRaySpace()},this.getControllerGrip=function(ne){let oe=S[ne];return oe===void 0&&(oe=new zv,S[ne]=oe),oe.getGripSpace()},this.getHand=function(ne){let oe=S[ne];return oe===void 0&&(oe=new zv,S[ne]=oe),oe.getHandSpace()};function K(ne){const oe=A.indexOf(ne.inputSource);if(oe===-1)return;const Te=S[oe];Te!==void 0&&(Te.update(ne.inputSource,ne.frame,c||o),Te.dispatchEvent({type:ne.type,data:ne.inputSource}))}function N(){a.removeEventListener("select",K),a.removeEventListener("selectstart",K),a.removeEventListener("selectend",K),a.removeEventListener("squeeze",K),a.removeEventListener("squeezestart",K),a.removeEventListener("squeezeend",K),a.removeEventListener("end",N),a.removeEventListener("inputsourceschange",V);for(let ne=0;ne<S.length;ne++){const oe=A[ne];oe!==null&&(A[ne]=null,S[ne].disconnect(oe))}R=null,B=null,g.reset();for(const ne in m)delete m[ne];if(e.setRenderTarget(_),u=null,d=null,h=null,a=null,w=null,ft.stop(),i.isPresenting=!1,e.setPixelRatio(y),e.setSize(C.width,C.height,!1),M!==null){const ne=M.camera;ne.fov=M.fov,ne.zoom=M.zoom,ne.updateProjectionMatrix(),M=null}i.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(ne){s=ne,i.isPresenting===!0&&rt("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(ne){r=ne,i.isPresenting===!0&&rt("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return c||o},this.setReferenceSpace=function(ne){c=ne},this.getBaseLayer=function(){return d!==null?d:u},this.getBinding=function(){return h===null&&v&&(h=new XRWebGLBinding(a,t)),h},this.getFrame=function(){return f},this.getSession=function(){return a},this.setSession=async function(ne){if(a=ne,a!==null){if(_=e.getRenderTarget(),a.addEventListener("select",K),a.addEventListener("selectstart",K),a.addEventListener("selectend",K),a.addEventListener("squeeze",K),a.addEventListener("squeezestart",K),a.addEventListener("squeezeend",K),a.addEventListener("end",N),a.addEventListener("inputsourceschange",V),x.xrCompatible!==!0&&await t.makeXRCompatible(),y=e.getPixelRatio(),e.getSize(C),v&&"createProjectionLayer"in XRWebGLBinding.prototype){let Te=null,We=null,Re=null;x.depth&&(Re=x.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,Te=x.stencil?So:Ua,We=x.stencil?Lc:ia);const $={colorFormat:t.RGBA8,depthFormat:Re,scaleFactor:s};h=this.getBinding(),d=h.createProjectionLayer($),a.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),w=new $i(d.textureWidth,d.textureHeight,{format:Ii,type:xi,depthTexture:new Bc(d.textureWidth,d.textureHeight,We,void 0,void 0,void 0,void 0,void 0,void 0,Te),stencilBuffer:x.stencil,colorSpace:e.outputColorSpace,samples:x.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1,storeMultisampledDepthBuffer:d.ignoreDepthValues===!1,storeMultisampledStencilBuffer:d.ignoreDepthValues===!1})}else{const Te={antialias:x.antialias,alpha:!0,depth:x.depth,stencil:x.stencil,framebufferScaleFactor:s};u=new XRWebGLLayer(a,t,Te),a.updateRenderState({baseLayer:u}),e.setPixelRatio(1),e.setSize(u.framebufferWidth,u.framebufferHeight,!1),w=new $i(u.framebufferWidth,u.framebufferHeight,{format:Ii,type:xi,colorSpace:e.outputColorSpace,stencilBuffer:x.stencil,resolveDepthBuffer:u.ignoreDepthValues===!1,resolveStencilBuffer:u.ignoreDepthValues===!1,storeMultisampledDepthBuffer:u.ignoreDepthValues===!1,storeMultisampledStencilBuffer:u.ignoreDepthValues===!1})}w.isXRRenderTarget=!0,this.setFoveation(l),c=null,o=await a.requestReferenceSpace(r),ft.setContext(a),ft.start(),i.isPresenting=!0,i.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(a!==null)return a.environmentBlendMode},this.getDepthTexture=function(){return g.getDepthTexture()};function V(ne){for(let oe=0;oe<ne.removed.length;oe++){const Te=ne.removed[oe],We=A.indexOf(Te);We>=0&&(A[We]=null,S[We].disconnect(Te))}for(let oe=0;oe<ne.added.length;oe++){const Te=ne.added[oe];let We=A.indexOf(Te);if(We===-1){for(let $=0;$<S.length;$++)if($>=A.length){A.push(Te),We=$;break}else if(A[$]===null){A[$]=Te,We=$;break}if(We===-1)break}const Re=S[We];Re&&Re.connect(Te)}}const Z=new X,te=new X;function ce(ne,oe,Te){Z.setFromMatrixPosition(oe.matrixWorld),te.setFromMatrixPosition(Te.matrixWorld);const We=Z.distanceTo(te),Re=oe.projectionMatrix.elements,$=Te.projectionMatrix.elements,H=Re[14]/(Re[10]-1),Y=Re[14]/(Re[10]+1),j=(Re[9]+1)/Re[5],de=(Re[9]-1)/Re[5],fe=(Re[8]-1)/Re[0],Ve=($[8]+1)/$[0],st=H*fe,kt=H*Ve,Ue=We/(-fe+Ve),Ze=Ue*-fe;if(oe.matrixWorld.decompose(ne.position,ne.quaternion,ne.scale),ne.translateX(Ze),ne.translateZ(Ue),ne.matrixWorld.compose(ne.position,ne.quaternion,ne.scale),ne.matrixWorldInverse.copy(ne.matrixWorld).invert(),Re[10]===-1)ne.projectionMatrix.copy(oe.projectionMatrix),ne.projectionMatrixInverse.copy(oe.projectionMatrixInverse);else{const F=H+Ue,lt=Y+Ue,Je=st-Ze,I=kt+(We-Ze),k=j*Y/lt*F,W=de*Y/lt*F;ne.projectionMatrix.makePerspective(Je,I,k,W,F,lt),ne.projectionMatrixInverse.copy(ne.projectionMatrix).invert()}}function Ne(ne,oe){oe===null?ne.matrixWorld.copy(ne.matrix):ne.matrixWorld.multiplyMatrices(oe.matrixWorld,ne.matrix),ne.matrixWorldInverse.copy(ne.matrixWorld).invert()}this.updateCamera=function(ne){if(a===null)return;let oe=ne.near,Te=ne.far;g.texture!==null&&(g.depthNear>0&&(oe=g.depthNear),g.depthFar>0&&(Te=g.depthFar)),z.near=L.near=T.near=oe,z.far=L.far=T.far=Te,(R!==z.near||B!==z.far)&&(a.updateRenderState({depthNear:z.near,depthFar:z.far}),R=z.near,B=z.far),z.layers.mask=ne.layers.mask|6,T.layers.mask=z.layers.mask&-5,L.layers.mask=z.layers.mask&-3;const We=ne.parent,Re=z.cameras;Ne(z,We);for(let $=0;$<Re.length;$++)Ne(Re[$],We);Re.length===2?ce(z,T,L):z.projectionMatrix.copy(T.projectionMatrix),M===null&&ne.isPerspectiveCamera&&(M={camera:ne,fov:ne.fov,zoom:ne.zoom}),He(ne,z,We)};function He(ne,oe,Te){Te===null?ne.matrix.copy(oe.matrixWorld):(ne.matrix.copy(Te.matrixWorld),ne.matrix.invert(),ne.matrix.multiply(oe.matrixWorld)),ne.matrix.decompose(ne.position,ne.quaternion,ne.scale),ne.updateMatrixWorld(!0),ne.projectionMatrix.copy(oe.projectionMatrix),ne.projectionMatrixInverse.copy(oe.projectionMatrixInverse),ne.isPerspectiveCamera&&(ne.fov=Cv*2*Math.atan(1/ne.projectionMatrix.elements[5]),ne.zoom=1)}this.getCamera=function(){return z},this.getFoveation=function(){if(!(d===null&&u===null))return l},this.setFoveation=function(ne){l=ne,d!==null&&(d.fixedFoveation=ne),u!==null&&u.fixedFoveation!==void 0&&(u.fixedFoveation=ne)},this.hasDepthSensing=function(){return g.texture!==null},this.getDepthSensingMesh=function(){return g.getMesh(z)},this.getCameraTexture=function(ne){return m[ne]};let ct=null;function ot(ne,oe){if(p=oe.getViewerPose(c||o),f=oe,p!==null){const Te=p.views;u!==null&&(e.setRenderTargetFramebuffer(w,u.framebuffer),e.setRenderTarget(w));let We=!1;Te.length!==z.cameras.length&&(z.cameras.length=0,We=!0);for(let Y=0;Y<Te.length;Y++){const j=Te[Y];let de=null;if(u!==null)de=u.getViewport(j);else{const Ve=h.getViewSubImage(d,j);de=Ve.viewport,Y===0&&(e.setRenderTargetTextures(w,Ve.colorTexture,Ve.depthStencilTexture),e.setRenderTarget(w))}let fe=P[Y];fe===void 0&&(fe=new wi,fe.layers.enable(Y),fe.viewport=new nn,P[Y]=fe),fe.matrix.fromArray(j.transform.matrix),fe.matrix.decompose(fe.position,fe.quaternion,fe.scale),fe.projectionMatrix.fromArray(j.projectionMatrix),fe.projectionMatrixInverse.copy(fe.projectionMatrix).invert(),fe.viewport.set(de.x,de.y,de.width,de.height),Y===0&&(z.matrix.copy(fe.matrix),z.matrix.decompose(z.position,z.quaternion,z.scale)),We===!0&&z.cameras.push(fe)}const Re=a.enabledFeatures;if(Re&&Re.includes("depth-sensing")&&a.depthUsage=="gpu-optimized"&&v){h=i.getBinding();const Y=h.getDepthInformation(Te[0]);Y&&Y.isValid&&Y.texture&&g.init(Y,a.renderState)}if(Re&&Re.includes("camera-access")&&v){e.state.unbindTexture(),h=i.getBinding();for(let Y=0;Y<Te.length;Y++){const j=Te[Y].camera;if(j){let de=m[j];de||(de=new hk,m[j]=de);const fe=h.getCameraImage(j);de.sourceTexture=fe}}}}for(let Te=0;Te<S.length;Te++){const We=A[Te],Re=S[Te];We!==null&&Re!==void 0&&Re.update(We,oe,c||o)}ct&&ct(ne,oe),oe.detectedPlanes&&i.dispatchEvent({type:"planesdetected",data:oe}),f=null}const ft=new kk;ft.setAnimationLoop(ot),this.setAnimationLoop=function(ne){ct=ne},this.dispose=function(){}}}const WI=new en,Zk=new pt;Zk.set(-1,0,0,0,1,0,0,0,1);function XI(n,e){function t(g,m){g.matrixAutoUpdate===!0&&g.updateMatrix(),m.value.copy(g.matrix)}function i(g,m){m.color.getRGB(g.fogColor.value,fk(n)),m.isFog?(g.fogNear.value=m.near,g.fogFar.value=m.far):m.isFogExp2&&(g.fogDensity.value=m.density)}function a(g,m,x,_,w){m.isNodeMaterial?m.uniformsNeedUpdate=!1:m.isMeshBasicMaterial?s(g,m):m.isMeshLambertMaterial?(s(g,m),m.envMap&&(g.envMapIntensity.value=m.envMapIntensity)):m.isMeshToonMaterial?(s(g,m),h(g,m)):m.isMeshPhongMaterial?(s(g,m),p(g,m),m.envMap&&(g.envMapIntensity.value=m.envMapIntensity)):m.isMeshStandardMaterial?(s(g,m),d(g,m),m.isMeshPhysicalMaterial&&u(g,m,w)):m.isMeshMatcapMaterial?(s(g,m),f(g,m)):m.isMeshDepthMaterial?s(g,m):m.isMeshDistanceMaterial?(s(g,m),v(g,m)):m.isMeshNormalMaterial?s(g,m):m.isLineBasicMaterial?(o(g,m),m.isLineDashedMaterial&&r(g,m)):m.isPointsMaterial?l(g,m,x,_):m.isSpriteMaterial?c(g,m):m.isShadowMaterial?(g.color.value.copy(m.color),g.opacity.value=m.opacity):m.isShaderMaterial&&(m.uniformsNeedUpdate=!1)}function s(g,m){g.opacity.value=m.opacity,m.color&&g.diffuse.value.copy(m.color),m.emissive&&g.emissive.value.copy(m.emissive).multiplyScalar(m.emissiveIntensity),m.map&&(g.map.value=m.map,t(m.map,g.mapTransform)),m.alphaMap&&(g.alphaMap.value=m.alphaMap,t(m.alphaMap,g.alphaMapTransform)),m.bumpMap&&(g.bumpMap.value=m.bumpMap,t(m.bumpMap,g.bumpMapTransform),g.bumpScale.value=m.bumpScale,m.side===ei&&(g.bumpScale.value*=-1)),m.normalMap&&(g.normalMap.value=m.normalMap,t(m.normalMap,g.normalMapTransform),g.normalScale.value.copy(m.normalScale),m.side===ei&&g.normalScale.value.negate()),m.displacementMap&&(g.displacementMap.value=m.displacementMap,t(m.displacementMap,g.displacementMapTransform),g.displacementScale.value=m.displacementScale,g.displacementBias.value=m.displacementBias),m.emissiveMap&&(g.emissiveMap.value=m.emissiveMap,t(m.emissiveMap,g.emissiveMapTransform)),m.specularMap&&(g.specularMap.value=m.specularMap,t(m.specularMap,g.specularMapTransform)),m.alphaTest>0&&(g.alphaTest.value=m.alphaTest);const x=e.get(m),_=x.envMap,w=x.envMapRotation;_&&(g.envMap.value=_,g.envMapRotation.value.setFromMatrix4(WI.makeRotationFromEuler(w)).transpose(),_.isCubeTexture&&_.isRenderTargetTexture===!1&&g.envMapRotation.value.premultiply(Zk),g.reflectivity.value=m.reflectivity,g.ior.value=m.ior,g.refractionRatio.value=m.refractionRatio),m.lightMap&&(g.lightMap.value=m.lightMap,g.lightMapIntensity.value=m.lightMapIntensity,t(m.lightMap,g.lightMapTransform)),m.aoMap&&(g.aoMap.value=m.aoMap,g.aoMapIntensity.value=m.aoMapIntensity,t(m.aoMap,g.aoMapTransform))}function o(g,m){g.diffuse.value.copy(m.color),g.opacity.value=m.opacity,m.map&&(g.map.value=m.map,t(m.map,g.mapTransform))}function r(g,m){g.dashSize.value=m.dashSize,g.totalSize.value=m.dashSize+m.gapSize,g.scale.value=m.scale}function l(g,m,x,_){g.diffuse.value.copy(m.color),g.opacity.value=m.opacity,g.size.value=m.size*x,g.scale.value=_*.5,m.map&&(g.map.value=m.map,t(m.map,g.uvTransform)),m.alphaMap&&(g.alphaMap.value=m.alphaMap,t(m.alphaMap,g.alphaMapTransform)),m.alphaTest>0&&(g.alphaTest.value=m.alphaTest)}function c(g,m){g.diffuse.value.copy(m.color),g.opacity.value=m.opacity,g.rotation.value=m.rotation,m.map&&(g.map.value=m.map,t(m.map,g.mapTransform)),m.alphaMap&&(g.alphaMap.value=m.alphaMap,t(m.alphaMap,g.alphaMapTransform)),m.alphaTest>0&&(g.alphaTest.value=m.alphaTest)}function p(g,m){g.specular.value.copy(m.specular),g.shininess.value=Math.max(m.shininess,1e-4)}function h(g,m){m.gradientMap&&(g.gradientMap.value=m.gradientMap)}function d(g,m){g.metalness.value=m.metalness,m.metalnessMap&&(g.metalnessMap.value=m.metalnessMap,t(m.metalnessMap,g.metalnessMapTransform)),g.roughness.value=m.roughness,m.roughnessMap&&(g.roughnessMap.value=m.roughnessMap,t(m.roughnessMap,g.roughnessMapTransform)),m.envMap&&(g.envMapIntensity.value=m.envMapIntensity)}function u(g,m,x){g.ior.value=m.ior,m.sheen>0&&(g.sheenColor.value.copy(m.sheenColor).multiplyScalar(m.sheen),g.sheenRoughness.value=m.sheenRoughness,m.sheenColorMap&&(g.sheenColorMap.value=m.sheenColorMap,t(m.sheenColorMap,g.sheenColorMapTransform)),m.sheenRoughnessMap&&(g.sheenRoughnessMap.value=m.sheenRoughnessMap,t(m.sheenRoughnessMap,g.sheenRoughnessMapTransform))),m.clearcoat>0&&(g.clearcoat.value=m.clearcoat,g.clearcoatRoughness.value=m.clearcoatRoughness,m.clearcoatMap&&(g.clearcoatMap.value=m.clearcoatMap,t(m.clearcoatMap,g.clearcoatMapTransform)),m.clearcoatRoughnessMap&&(g.clearcoatRoughnessMap.value=m.clearcoatRoughnessMap,t(m.clearcoatRoughnessMap,g.clearcoatRoughnessMapTransform)),m.clearcoatNormalMap&&(g.clearcoatNormalMap.value=m.clearcoatNormalMap,t(m.clearcoatNormalMap,g.clearcoatNormalMapTransform),g.clearcoatNormalScale.value.copy(m.clearcoatNormalScale),m.side===ei&&g.clearcoatNormalScale.value.negate())),m.dispersion>0&&(g.dispersion.value=m.dispersion),m.retroreflectivity>0&&(g.retroreflectivity.value=m.retroreflectivity),m.iridescence>0&&(g.iridescence.value=m.iridescence,g.iridescenceIOR.value=m.iridescenceIOR,g.iridescenceThicknessMinimum.value=m.iridescenceThicknessRange[0],g.iridescenceThicknessMaximum.value=m.iridescenceThicknessRange[1],m.iridescenceMap&&(g.iridescenceMap.value=m.iridescenceMap,t(m.iridescenceMap,g.iridescenceMapTransform)),m.iridescenceThicknessMap&&(g.iridescenceThicknessMap.value=m.iridescenceThicknessMap,t(m.iridescenceThicknessMap,g.iridescenceThicknessMapTransform))),m.transmission>0&&(g.transmission.value=m.transmission,g.transmissionSamplerMap.value=x.texture,g.transmissionSamplerSize.value.set(x.width,x.height),m.transmissionMap&&(g.transmissionMap.value=m.transmissionMap,t(m.transmissionMap,g.transmissionMapTransform)),g.thickness.value=m.thickness,m.thicknessMap&&(g.thicknessMap.value=m.thicknessMap,t(m.thicknessMap,g.thicknessMapTransform)),g.attenuationDistance.value=m.attenuationDistance,g.attenuationColor.value.copy(m.attenuationColor)),m.anisotropy>0&&(g.anisotropyVector.value.set(m.anisotropy*Math.cos(m.anisotropyRotation),m.anisotropy*Math.sin(m.anisotropyRotation)),m.anisotropyMap&&(g.anisotropyMap.value=m.anisotropyMap,t(m.anisotropyMap,g.anisotropyMapTransform))),g.specularIntensity.value=m.specularIntensity,g.specularColor.value.copy(m.specularColor),m.specularColorMap&&(g.specularColorMap.value=m.specularColorMap,t(m.specularColorMap,g.specularColorMapTransform)),m.specularIntensityMap&&(g.specularIntensityMap.value=m.specularIntensityMap,t(m.specularIntensityMap,g.specularIntensityMapTransform))}function f(g,m){m.matcap&&(g.matcap.value=m.matcap)}function v(g,m){const x=e.get(m).light;g.referencePosition.value.setFromMatrixPosition(x.matrixWorld),g.nearDistance.value=x.shadow.camera.near,g.farDistance.value=x.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:a}}function KI(n,e,t,i){let a={},s={},o=[];const r=n.getParameter(n.MAX_UNIFORM_BUFFER_BINDINGS);function l(w,S){const A=S.program;i.uniformBlockBinding(w,A)}function c(w,S){let A=a[w.id];A===void 0&&(g(w),A=p(w),a[w.id]=A,w.addEventListener("dispose",x));const C=S.program;i.updateUBOMapping(w,C);const y=e.render.frame;s[w.id]!==y&&(d(w),s[w.id]=y)}function p(w){const S=h();w.__bindingPointIndex=S;const A=n.createBuffer(),C=w.__size,y=w.usage;return n.bindBuffer(n.UNIFORM_BUFFER,A),n.bufferData(n.UNIFORM_BUFFER,C,y),n.bindBuffer(n.UNIFORM_BUFFER,null),n.bindBufferBase(n.UNIFORM_BUFFER,S,A),A}function h(){for(let w=0;w<r;w++)if(o.indexOf(w)===-1)return o.push(w),w;return Pt("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function d(w){const S=a[w.id],A=w.uniforms,C=w.__cache;n.bindBuffer(n.UNIFORM_BUFFER,S);for(let y=0,M=A.length;y<M;y++){const T=A[y];if(Array.isArray(T))for(let L=0,P=T.length;L<P;L++)u(T[L],y,L,C);else u(T,y,0,C)}n.bindBuffer(n.UNIFORM_BUFFER,null)}function u(w,S,A,C){if(v(w,S,A,C)===!0){const y=w.__offset,M=w.value;if(Array.isArray(M)){let T=0;for(let L=0;L<M.length;L++){const P=M[L],z=m(P);f(P,w.__data,T),typeof P!="number"&&typeof P!="boolean"&&!P.isMatrix3&&!ArrayBuffer.isView(P)&&(T+=z.storage/Float32Array.BYTES_PER_ELEMENT)}}else f(M,w.__data,0);n.bufferSubData(n.UNIFORM_BUFFER,y,w.__data)}}function f(w,S,A){typeof w=="number"||typeof w=="boolean"?S[0]=w:w.isMatrix3?(S[0]=w.elements[0],S[1]=w.elements[1],S[2]=w.elements[2],S[3]=0,S[4]=w.elements[3],S[5]=w.elements[4],S[6]=w.elements[5],S[7]=0,S[8]=w.elements[6],S[9]=w.elements[7],S[10]=w.elements[8],S[11]=0):ArrayBuffer.isView(w)?S.set(new w.constructor(w.buffer,w.byteOffset,S.length)):w.toArray(S,A)}function v(w,S,A,C){const y=w.value,M=S+"_"+A;if(C[M]===void 0)return typeof y=="number"||typeof y=="boolean"?C[M]=y:ArrayBuffer.isView(y)?C[M]=y.slice():C[M]=y.clone(),!0;{const T=C[M];if(typeof y=="number"||typeof y=="boolean"){if(T!==y)return C[M]=y,!0}else{if(ArrayBuffer.isView(y))return!0;if(T.equals(y)===!1)return T.copy(y),!0}}return!1}function g(w){const S=w.uniforms;let A=0;const C=16;for(let M=0,T=S.length;M<T;M++){const L=Array.isArray(S[M])?S[M]:[S[M]];for(let P=0,z=L.length;P<z;P++){const R=L[P],B=Array.isArray(R.value)?R.value:[R.value];for(let K=0,N=B.length;K<N;K++){const V=B[K],Z=m(V),te=A%C,ce=te%Z.boundary,Ne=te+ce;A+=ce,Ne!==0&&C-Ne<Z.storage&&(A+=C-Ne),R.__data=new Float32Array(Z.storage/Float32Array.BYTES_PER_ELEMENT),R.__offset=A,A+=Z.storage}}}const y=A%C;return y>0&&(A+=C-y),w.__size=A,w.__cache={},this}function m(w){const S={boundary:0,storage:0};return typeof w=="number"||typeof w=="boolean"?(S.boundary=4,S.storage=4):w.isVector2?(S.boundary=8,S.storage=8):w.isVector3||w.isColor?(S.boundary=16,S.storage=12):w.isVector4?(S.boundary=16,S.storage=16):w.isMatrix3?(S.boundary=48,S.storage=48):w.isMatrix4?(S.boundary=64,S.storage=64):w.isTexture?rt("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(w)?(S.boundary=16,S.storage=w.byteLength):rt("WebGLRenderer: Unsupported uniform value type.",w),S}function x(w){const S=w.target;S.removeEventListener("dispose",x);const A=o.indexOf(S.__bindingPointIndex);o.splice(A,1),n.deleteBuffer(a[S.id]),delete a[S.id],delete s[S.id]}function _(){for(const w in a)n.deleteBuffer(a[w]);o=[],a={},s={}}return{bind:l,update:c,dispose:_}}const YI=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let da=null;function jI(){return da===null&&(da=new x5(YI,16,16,Mo,sa),da.name="DFG_LUT",da.minFilter=Cn,da.magFilter=Cn,da.wrapS=Oa,da.wrapT=Oa,da.generateMipmaps=!1,da.needsUpdate=!0),da}class ZI{constructor(e={}){const{canvas:t=W4(),context:i=null,depth:a=!0,stencil:s=!1,alpha:o=!1,antialias:r=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:p="default",failIfMajorPerformanceCaveat:h=!1,reversedDepthBuffer:d=!1,outputBufferType:u=xi}=e;this.isWebGLRenderer=!0;let f;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");f=i.getContextAttributes().alpha}else f=o;const v=u,g=new Set([Yg,Kg,Xg]),m=new Set([xi,ia,Rc,Lc,Vg,Wg]),x=new Uint32Array(4),_=new Int32Array(4),w=new X;let S=null,A=null;const C=[],y=[];let M=null;this.domElement=t,this.debug={checkShaderErrors:!0,diagnostics:{keywords:!1},onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=na,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const T=this;let L=!1,P=null,z=null,R=null,B=null;this._outputColorSpace=bi;let K=0,N=0,V=null,Z=-1,te=null;const ce=new nn,Ne=new nn;let He=null;const ct=new It(0);let ot=0,ft=t.width,ne=t.height,oe=1,Te=null,We=null;const Re=new nn(0,0,ft,ne),$=new nn(0,0,ft,ne);let H=!1;const Y=new ak;let j=!1,de=!1;const fe=new en,Ve=new X,st=new nn,kt={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let Ue=!1;function Ze(){return V===null?oe:1}let F=i;function lt(E,G){return t.getContext(E,G)}let Je,I,k,W,J,ae,ve,be,se,re,ke,Fe,Me,_e,Xe,nt,ht,q,Se,le,Ae,$e,me;try{const E={alpha:!0,depth:a,stencil:s,antialias:r,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:p,failIfMajorPerformanceCaveat:h};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${Lg}`),t.addEventListener("webglcontextlost",Kt,!1),t.addEventListener("webglcontextrestored",zt,!1),t.addEventListener("webglcontextcreationerror",Hi,!1),F===null){const G="webgl2";if(F=lt(G,E),F===null)throw lt(G)?new Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes."):new Error("THREE.WebGLRenderer: Error creating WebGL context.")}et()}catch(E){throw t.removeEventListener("webglcontextlost",Kt,!1),t.removeEventListener("webglcontextrestored",zt,!1),t.removeEventListener("webglcontextcreationerror",Hi,!1),Pt("WebGLRenderer: "+E.message),E}function et(){Je=new jP(F),Je.init(),Ae=new BI(F,Je),I=new FP(F,Je,e,Ae),k=new UI(F,Je),I.reversedDepthBuffer&&d&&k.buffers.depth.setReversed(!0),z=F.createFramebuffer(),R=F.createFramebuffer(),B=F.createFramebuffer(),W=new QP(F),J=new MI,ae=new FI(F,Je,k,J,I,Ae,W),ve=new YP(T),be=new N5(F),$e=new OP(F,be),se=new ZP(F,be,W,$e),re=new t6(F,se,be,$e,W),q=new e6(F,I,ae),Xe=new BP(J),ke=new SI(T,ve,Je,I,$e,Xe),Fe=new XI(T,J),Me=new TI,_e=new II(Je),ht=new zP(T,ve,k,re,f,l),nt=new OI(T,re,I),me=new KI(F,W,I,k),Se=new UP(F,Je,W),le=new JP(F,Je,W),W.programs=ke.programs,T.capabilities=I,T.extensions=Je,T.properties=J,T.renderLists=Me,T.shadowMap=nt,T.state=k,T.info=W}v!==xi&&(M=new i6(v,t.width,t.height,r,a,s));const Ke=new VI(T,F);this.xr=Ke,this.getContext=function(){return F},this.getContextAttributes=function(){return F.getContextAttributes()},this.forceContextLoss=function(){const E=Je.get("WEBGL_lose_context");E&&E.loseContext()},this.forceContextRestore=function(){const E=Je.get("WEBGL_lose_context");E&&E.restoreContext()},this.getPixelRatio=function(){return oe},this.setPixelRatio=function(E){E!==void 0&&(oe=E,this.setSize(ft,ne,!1))},this.getSize=function(E){return E.set(ft,ne)},this.setSize=function(E,G,ie=!0){if(Ke.isPresenting){rt("WebGLRenderer: Can't change size while VR device is presenting.");return}ft=E,ne=G,t.width=Math.floor(E*oe),t.height=Math.floor(G*oe),ie===!0&&(t.style.width=E+"px",t.style.height=G+"px"),M!==null&&M.setSize(t.width,t.height),this.setViewport(0,0,E,G)},this.getDrawingBufferSize=function(E){return E.set(ft*oe,ne*oe).floor()},this.setDrawingBufferSize=function(E,G,ie){ft=E,ne=G,oe=ie,t.width=Math.floor(E*ie),t.height=Math.floor(G*ie),this.setViewport(0,0,E,G)},this.setEffects=function(E){if(v===xi){Pt("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(E){for(let G=0;G<E.length;G++)if(E[G].isOutputPass===!0){rt("WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}M.setEffects(E||[])},this.getCurrentViewport=function(E){return E.copy(ce)},this.getViewport=function(E){return E.copy(Re)},this.setViewport=function(E,G,ie,Q){E.isVector4?Re.set(E.x,E.y,E.z,E.w):Re.set(E,G,ie,Q),k.viewport(ce.copy(Re).multiplyScalar(oe).round())},this.getScissor=function(E){return E.copy($)},this.setScissor=function(E,G,ie,Q){E.isVector4?$.set(E.x,E.y,E.z,E.w):$.set(E,G,ie,Q),k.scissor(Ne.copy($).multiplyScalar(oe).round())},this.getScissorTest=function(){return H},this.setScissorTest=function(E){k.setScissorTest(H=E)},this.setOpaqueSort=function(E){Te=E},this.setTransparentSort=function(E){We=E},this.getClearColor=function(E){return E.copy(ht.getClearColor())},this.setClearColor=function(){ht.setClearColor(...arguments)},this.getClearAlpha=function(){return ht.getClearAlpha()},this.setClearAlpha=function(){ht.setClearAlpha(...arguments)},this.clear=function(E=!0,G=!0,ie=!0){let Q=0;if(E){let ee=!1;if(V!==null){const Pe=V.texture.format;ee=g.has(Pe)}if(ee){const Pe=V.texture.type,Oe=m.has(Pe),Le=ht.getClearColor(),Ge=ht.getClearAlpha(),Ye=Le.r,vt=Le.g,wt=Le.b;Oe?(x[0]=Ye,x[1]=vt,x[2]=wt,x[3]=Ge,F.clearBufferuiv(F.COLOR,0,x)):(_[0]=Ye,_[1]=vt,_[2]=wt,_[3]=Ge,F.clearBufferiv(F.COLOR,0,_))}else Q|=F.COLOR_BUFFER_BIT}G&&(Q|=F.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),ie&&(Q|=F.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),Q!==0&&F.clear(Q)},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.setNodesHandler=function(E){E.setRenderer(this),P=E},this.dispose=function(){t.removeEventListener("webglcontextlost",Kt,!1),t.removeEventListener("webglcontextrestored",zt,!1),t.removeEventListener("webglcontextcreationerror",Hi,!1),ht.dispose(),Me.dispose(),_e.dispose(),J.dispose(),ve.dispose(),re.dispose(),$e.dispose(),me.dispose(),ke.dispose(),Ke.dispose(),Ke.removeEventListener("sessionstart",gS),Ke.removeEventListener("sessionend",vS),Fo.stop()};function Kt(E){E.preventDefault(),D2("WebGLRenderer: Context Lost."),L=!0}function zt(){D2("WebGLRenderer: Context Restored."),L=!1;const E=W.autoReset,G=nt.enabled,ie=nt.autoUpdate,Q=nt.needsUpdate,ee=nt.type;et(),W.autoReset=E,nt.enabled=G,nt.autoUpdate=ie,nt.needsUpdate=Q,nt.type=ee}function Hi(E){Pt("WebGLRenderer: A WebGL context could not be created. Reason: ",E.statusMessage)}function fa(E){const G=E.target;G.removeEventListener("dispose",fa),sz(G)}function sz(E){oz(E),J.remove(E)}function oz(E){const G=J.get(E).programs;G!==void 0&&(G.forEach(function(ie){ke.releaseProgram(ie)}),E.isShaderMaterial&&ke.releaseShaderCache(E))}this.renderBufferDirect=function(E,G,ie,Q,ee,Pe){G===null&&(G=kt);const Oe=ee.isMesh&&ee.matrixWorld.determinantAffine()<0,Le=cz(E,G,ie,Q,ee);k.setMaterial(Q,Oe);let Ge=ie.index,Ye=1;if(Q.wireframe===!0){if(Ge=se.getWireframeAttribute(ie),Ge===void 0)return;Ye=2}const vt=ie.drawRange,wt=ie.attributes.position;let qe=vt.start*Ye,Ot=(vt.start+vt.count)*Ye;Pe!==null&&(qe=Math.max(qe,Pe.start*Ye),Ot=Math.min(Ot,(Pe.start+Pe.count)*Ye)),Ge!==null?(qe=Math.max(qe,0),Ot=Math.min(Ot,Ge.count)):wt!=null&&(qe=Math.max(qe,0),Ot=Math.min(Ot,wt.count));const hn=Ot-qe;if(hn<0||hn===1/0)return;$e.setup(ee,Q,Le,ie,Ge);let Zt,Xt=Se;if(Ge!==null&&(Zt=be.get(Ge),Xt=le,Xt.setIndex(Zt)),ee.isMesh)Q.wireframe===!0?(k.setLineWidth(Q.wireframeLinewidth*Ze()),Xt.setMode(F.LINES)):Xt.setMode(F.TRIANGLES);else if(ee.isLine){let Nn=Q.linewidth;Nn===void 0&&(Nn=1),k.setLineWidth(Nn*Ze()),ee.isLineSegments?Xt.setMode(F.LINES):ee.isLineLoop?Xt.setMode(F.LINE_LOOP):Xt.setMode(F.LINE_STRIP)}else ee.isPoints?Xt.setMode(F.POINTS):ee.isSprite&&Xt.setMode(F.TRIANGLES);if(ee.isBatchedMesh)if(Je.get("WEBGL_multi_draw"))Xt.renderMultiDraw(ee._multiDrawStarts,ee._multiDrawCounts,ee._multiDrawCount);else{const Nn=ee._multiDrawStarts,ze=ee._multiDrawCounts,Kn=ee._multiDrawCount,Ct=Ge?be.get(Ge).bytesPerElement:1,ki=J.get(Q).currentProgram.getUniforms();for(let ma=0;ma<Kn;ma++)ki.setValue(F,"_gl_DrawID",ma),Xt.render(Nn[ma]/Ct,ze[ma])}else if(ee.isInstancedMesh)Xt.renderInstances(qe,hn,ee.count);else if(ie.isInstancedBufferGeometry){const Nn=ie._maxInstanceCount!==void 0?ie._maxInstanceCount:1/0,ze=Math.min(ie.instanceCount,Nn);Xt.renderInstances(qe,hn,ze)}else Xt.render(qe,hn)};function mS(E,G,ie,Q){P!==null&&E.isNodeMaterial&&P.setObject(Q,E),j===!0&&Xe.setState(E,ie,!1),E.transparent===!0&&E.side===Na&&E.forceSinglePass===!1?(E.side=ei,E.needsUpdate=!0,yu(E,G,Q),E.side=wo,E.needsUpdate=!0,yu(E,G,Q),E.side=Na):yu(E,G,Q)}this.compile=function(E,G,ie=null){ie===null&&(ie=E),P!==null&&P.renderStart(E,G,ie),A=_e.get(ie),A.init(G),y.push(A),ie.traverseVisible(function(ee){ee.isLight&&ee.layers.test(G.layers)&&(A.pushLight(ee),ee.castShadow&&A.pushShadow(ee))}),E!==ie&&E.traverseVisible(function(ee){ee.isLight&&ee.layers.test(G.layers)&&(A.pushLight(ee),ee.castShadow&&A.pushShadow(ee))}),A.setupLights(),P!==null&&P.updateLights(A.state.lightsArray),de=this.localClippingEnabled,j=Xe.init(this.clippingPlanes,de),j===!0&&Xe.setGlobalState(this.clippingPlanes,G),P!==null&&nt.render(A.state.shadowsArray,ie,G);const Q=new Set;return E.traverse(function(ee){if(!(ee.isMesh||ee.isPoints||ee.isLine||ee.isSprite))return;const Pe=ee.material;if(Pe)if(Array.isArray(Pe))for(let Oe=0;Oe<Pe.length;Oe++){const Le=Pe[Oe];mS(Le,ie,G,ee),Q.add(Le)}else mS(Pe,ie,G,ee),Q.add(Pe)}),A=y.pop(),P!==null&&P.renderEnd(),Q},this.compileAsync=function(E,G,ie=null){const Q=this.compile(E,G,ie);return new Promise(ee=>{function Pe(){if(Q.forEach(function(Oe){const Ge=J.get(Oe).currentProgram;(Ge===void 0||Ge.isReady())&&Q.delete(Oe)}),Q.size===0){ee(E);return}setTimeout(Pe,10)}Je.get("KHR_parallel_shader_compile")!==null?Pe():setTimeout(Pe,10)})};let cb=null;function rz(E){cb&&cb(E)}function gS(){Fo.stop()}function vS(){Fo.start()}const Fo=new kk;Fo.setAnimationLoop(rz),typeof self<"u"&&Fo.setContext(self),this.setAnimationLoop=function(E){cb=E,Ke.setAnimationLoop(E),E===null?Fo.stop():Fo.start()},Ke.addEventListener("sessionstart",gS),Ke.addEventListener("sessionend",vS),this.render=function(E,G){if(G!==void 0&&G.isCamera!==!0){Pt("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(L===!0)return;P!==null&&P.renderStart(E,G);const ie=Ke.enabled===!0&&Ke.isPresenting===!0,Q=M!==null&&(V===null||ie)&&M.begin(T,V);if(E.matrixWorldAutoUpdate===!0&&E.updateMatrixWorld(),G.parent===null&&G.matrixWorldAutoUpdate===!0&&G.updateMatrixWorld(),Ke.enabled===!0&&Ke.isPresenting===!0&&(M===null||M.isCompositing()===!1)&&(Ke.cameraAutoUpdate===!0&&Ke.updateCamera(G),G=Ke.getCamera()),E.isScene===!0&&E.onBeforeRender(T,E,G,V),A=_e.get(E,y.length),A.init(G),A.state.textureUnits=ae.getTextureUnits(),y.push(A),fe.multiplyMatrices(G.projectionMatrix,G.matrixWorldInverse),Y.setFromProjectionMatrix(fe,oa,G.reversedDepth),de=this.localClippingEnabled,j=Xe.init(this.clippingPlanes,de),S=Me.get(E,C.length),S.init(),C.push(S),Ke.enabled===!0&&Ke.isPresenting===!0){const Oe=T.xr.getDepthSensingMesh();Oe!==null&&db(Oe,G,-1/0,T.sortObjects)}db(E,G,0,T.sortObjects),S.finish(),P!==null&&P.updateLights(A.state.lightsArray),T.sortObjects===!0&&S.sort(Te,We),Ue=Ke.enabled===!1||Ke.isPresenting===!1||Ke.hasDepthSensing()===!1,Ue&&ht.addToRenderList(S,E),this.info.render.frame++,this.info.autoReset===!0&&this.info.reset(),j===!0&&Xe.beginShadows();const ee=A.state.shadowsArray;if(nt.render(ee,E,G),j===!0&&Xe.endShadows(),(Q&&M.hasRenderPass())===!1){const Oe=S.opaque,Le=S.transmissive;if(A.setupLights(),G.isArrayCamera){const Ge=G.cameras;if(Le.length>0)for(let Ye=0,vt=Ge.length;Ye<vt;Ye++){const wt=Ge[Ye];bS(Oe,Le,E,wt)}Ue&&ht.render(E);for(let Ye=0,vt=Ge.length;Ye<vt;Ye++){const wt=Ge[Ye];xS(S,E,wt,wt.viewport)}}else Le.length>0&&bS(Oe,Le,E,G),Ue&&ht.render(E),xS(S,E,G)}V!==null&&N===0&&(ae.updateMultisampleRenderTarget(V),ae.updateRenderTargetMipmap(V)),Q&&M.end(T),E.isScene===!0&&E.onAfterRender(T,E,G),$e.resetDefaultState(),Z=-1,te=null,y.pop(),y.length>0?(A=y[y.length-1],ae.setTextureUnits(A.state.textureUnits),j===!0&&Xe.setGlobalState(T.clippingPlanes,A.state.camera)):A=null,C.pop(),C.length>0?S=C[C.length-1]:S=null,P!==null&&P.renderEnd()};function db(E,G,ie,Q){if(E.visible===!1)return;if(E.layers.test(G.layers)){if(E.isGroup)ie=E.renderOrder;else if(E.isLOD)E.autoUpdate===!0&&E.update(G);else if(E.isLightProbeGrid)A.pushLightProbeGrid(E);else if(E.isLight)A.pushLight(E),E.castShadow&&A.pushShadow(E);else if(E.isSprite){if(!E.frustumCulled||E.intersectsFrustum(Y)){Q&&st.setFromMatrixPosition(E.matrixWorld).applyMatrix4(fe);const Oe=re.update(E),Le=E.material;Le.visible&&S.push(E,Oe,Le,ie,st.z,null,G)}}else if((E.isMesh||E.isLine||E.isPoints)&&(!E.frustumCulled||E.intersectsFrustum(Y))){const Oe=re.update(E),Le=E.material;if(Q&&(E.boundingSphere!==void 0?(E.boundingSphere===null&&E.computeBoundingSphere(),st.copy(E.boundingSphere.center)):(Oe.boundingSphere===null&&Oe.computeBoundingSphere(),st.copy(Oe.boundingSphere.center)),st.applyMatrix4(E.matrixWorld).applyMatrix4(fe)),Array.isArray(Le)){const Ge=Oe.groups;for(let Ye=0,vt=Ge.length;Ye<vt;Ye++){const wt=Ge[Ye],qe=Le[wt.materialIndex];qe&&qe.visible&&S.push(E,Oe,qe,ie,st.z,wt,G)}}else Le.visible&&S.push(E,Oe,Le,ie,st.z,null,G)}}const Pe=E.children;for(let Oe=0,Le=Pe.length;Oe<Le;Oe++)db(Pe[Oe],G,ie,Q)}function xS(E,G,ie,Q){const{opaque:ee,transmissive:Pe,transparent:Oe}=E;A.setupLightsView(ie),j===!0&&Xe.setGlobalState(T.clippingPlanes,ie),Q&&k.viewport(ce.copy(Q)),ee.length>0&&bu(ee,G,ie),Pe.length>0&&bu(Pe,G,ie),Oe.length>0&&bu(Oe,G,ie),k.buffers.depth.setTest(!0),k.buffers.depth.setMask(!0),k.buffers.color.setMask(!0),k.setPolygonOffset(!1)}function bS(E,G,ie,Q){if((ie.isScene===!0?ie.overrideMaterial:null)!==null)return;if(A.state.transmissionRenderTarget[Q.id]===void 0){const qe=Je.has("EXT_color_buffer_half_float")||Je.has("EXT_color_buffer_float");A.state.transmissionRenderTarget[Q.id]=new $i(1,1,{generateMipmaps:!0,type:qe?sa:xi,minFilter:_o,samples:Math.max(4,I.samples),stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,colorSpace:St.workingColorSpace})}const Pe=A.state.transmissionRenderTarget[Q.id],Oe=Q.viewport||ce;Pe.setSize(Oe.z*T.transmissionResolutionScale,Oe.w*T.transmissionResolutionScale);const Le=T.getRenderTarget(),Ge=T.getActiveCubeFace(),Ye=T.getActiveMipmapLevel();T.setRenderTarget(Pe),T.getClearColor(ct),ot=T.getClearAlpha(),ot<1&&T.setClearColor(16777215,.5),T.clear(),Ue&&ht.render(ie);const vt=T.toneMapping;T.toneMapping=na;const wt=Q.viewport;if(Q.viewport!==void 0&&(Q.viewport=void 0),A.setupLightsView(Q),j===!0&&Xe.setGlobalState(T.clippingPlanes,Q),bu(E,ie,Q),ae.updateMultisampleRenderTarget(Pe),ae.updateRenderTargetMipmap(Pe),Je.has("WEBGL_multisampled_render_to_texture")===!1){let qe=!1;for(let Ot=0,hn=G.length;Ot<hn;Ot++){const Zt=G[Ot],{object:Xt,geometry:Nn,material:ze,group:Kn}=Zt;if(ze.side===Na&&Xt.layers.test(Q.layers)){const Ct=ze.side;ze.side=ei,ze.needsUpdate=!0,yS(Xt,ie,Q,Nn,ze,Kn),ze.side=Ct,ze.needsUpdate=!0,qe=!0}}qe===!0&&(ae.updateMultisampleRenderTarget(Pe),ae.updateRenderTargetMipmap(Pe))}T.setRenderTarget(Le,Ge,Ye),T.setClearColor(ct,ot),wt!==void 0&&(Q.viewport=wt),T.toneMapping=vt}function bu(E,G,ie){const Q=G.isScene===!0?G.overrideMaterial:null;for(let ee=0,Pe=E.length;ee<Pe;ee++){const Oe=E[ee],{object:Le,geometry:Ge,group:Ye}=Oe;let vt=Oe.material;vt.allowOverride===!0&&Q!==null&&(vt=Q),Le.layers.test(ie.layers)&&yS(Le,G,ie,Ge,vt,Ye)}}function yS(E,G,ie,Q,ee,Pe){P!==null&&ee.isNodeMaterial&&P.setObject(E,ee),E.onBeforeRender(T,G,ie,Q,ee,Pe),E.modelViewMatrix.multiplyMatrices(ie.matrixWorldInverse,E.matrixWorld),E.normalMatrix.getNormalMatrix(E.modelViewMatrix),ee.onBeforeRender(T,G,ie,Q,E,Pe),ee.transparent===!0&&ee.side===Na&&ee.forceSinglePass===!1?(ee.side=ei,ee.needsUpdate=!0,T.renderBufferDirect(ie,G,Q,ee,E,Pe),ee.side=wo,ee.needsUpdate=!0,T.renderBufferDirect(ie,G,Q,ee,E,Pe),ee.side=Na):T.renderBufferDirect(ie,G,Q,ee,E,Pe),E.onAfterRender(T,G,ie,Q,ee,Pe)}function yu(E,G,ie){G.isScene!==!0&&(G=kt);const Q=J.get(E),ee=A.state.lights,Pe=A.state.shadowsArray,Oe=ee.state.version,Le=ke.getParameters(E,ee.state,Pe,G,ie,A.state.lightProbeGridArray),Ge=ke.getProgramCacheKey(Le);let Ye=Q.programs;Q.environment=E.isMeshStandardMaterial||E.isMeshLambertMaterial||E.isMeshPhongMaterial?G.environment:null,Q.fog=G.fog;const vt=E.isMeshStandardMaterial||E.isMeshLambertMaterial&&!E.envMap||E.isMeshPhongMaterial&&!E.envMap;Q.envMap=ve.get(E.envMap||Q.environment,vt),Q.envMapRotation=Q.environment!==null&&E.envMap===null?G.environmentRotation:E.envMapRotation,Ye===void 0&&(E.addEventListener("dispose",fa),Ye=new Map,Q.programs=Ye);let wt=Ye.get(Ge);if(wt!==void 0){if(Q.currentProgram===wt&&Q.lightsStateVersion===Oe)return kS(E,Le),wt}else Le.uniforms=ke.getUniforms(E),P!==null&&E.isNodeMaterial&&P.build(E,ie,Le),E.onBeforeCompile(Le,T),wt=ke.acquireProgram(Le,Ge),Ye.set(Ge,wt),Q.uniforms=Le.uniforms;const qe=Q.uniforms;return(!E.isShaderMaterial&&!E.isRawShaderMaterial||E.clipping===!0)&&(qe.clippingPlanes=Xe.uniform),kS(E,Le),Q.needsLights=pz(E),Q.lightsStateVersion=Oe,Q.needsLights&&(qe.ambientLightColor.value=ee.state.ambient,qe.lightProbe.value=ee.state.probe,qe.sunLights.value=ee.state.sun,qe.sunLightShadows.value=ee.state.sunShadow,qe.directionalLights.value=ee.state.directional,qe.directionalLightShadows.value=ee.state.directionalShadow,qe.spotLights.value=ee.state.spot,qe.spotLightShadows.value=ee.state.spotShadow,qe.rectAreaLights.value=ee.state.rectArea,qe.ltc_1.value=ee.state.rectAreaLTC1,qe.ltc_2.value=ee.state.rectAreaLTC2,qe.pointLights.value=ee.state.point,qe.pointLightShadows.value=ee.state.pointShadow,qe.hemisphereLights.value=ee.state.hemi,qe.sunShadowMatrix.value=ee.state.sunShadowMatrix,qe.sunShadowCascade.value=ee.state.sunShadowCascade,qe.directionalShadowMatrix.value=ee.state.directionalShadowMatrix,qe.spotLightMatrix.value=ee.state.spotLightMatrix,qe.spotLightMap.value=ee.state.spotLightMap,qe.pointShadowMatrix.value=ee.state.pointShadowMatrix),Q.lightProbeGrid=A.state.lightProbeGridArray.length>0,Q.currentProgram=wt,Q.uniformsList=null,wt}function wS(E){if(E.uniformsList===null){const G=E.currentProgram.getUniforms();E.uniformsList=Vh.seqWithValue(G.seq,E.uniforms)}return E.uniformsList}function kS(E,G){const ie=J.get(E);ie.outputColorSpace=G.outputColorSpace,ie.batching=G.batching,ie.batchingColor=G.batchingColor,ie.instancing=G.instancing,ie.instancingColor=G.instancingColor,ie.instancingMorph=G.instancingMorph,ie.skinning=G.skinning,ie.morphTargets=G.morphTargets,ie.morphNormals=G.morphNormals,ie.morphColors=G.morphColors,ie.morphTargetsCount=G.morphTargetsCount,ie.numClippingPlanes=G.numClippingPlanes,ie.numIntersection=G.numClipIntersection,ie.vertexAlphas=G.vertexAlphas,ie.vertexTangents=G.vertexTangents,ie.toneMapping=G.toneMapping}function lz(E,G){if(E.length===0)return null;if(E.length===1)return E[0].texture!==null?E[0]:null;w.setFromMatrixPosition(G.matrixWorld);for(let ie=0,Q=E.length;ie<Q;ie++){const ee=E[ie];if(ee.texture!==null&&ee.boundingBox.containsPoint(w))return ee}return null}function cz(E,G,ie,Q,ee){G.isScene!==!0&&(G=kt),ae.resetTextureUnits();const Pe=G.fog,Oe=Q.isMeshStandardMaterial||Q.isMeshLambertMaterial||Q.isMeshPhongMaterial?G.environment:null,Le=V===null?T.outputColorSpace:V.isXRRenderTarget===!0?V.texture.colorSpace:St.workingColorSpace,Ge=Q.isMeshStandardMaterial||Q.isMeshLambertMaterial&&!Q.envMap||Q.isMeshPhongMaterial&&!Q.envMap,Ye=ve.get(Q.envMap||Oe,Ge),vt=Q.vertexColors===!0&&!!ie.attributes.color&&ie.attributes.color.itemSize===4,wt=!!ie.attributes.tangent&&(!!Q.normalMap||Q.anisotropy>0),qe=!!ie.morphAttributes.position,Ot=!!ie.morphAttributes.normal,hn=!!ie.morphAttributes.color;let Zt=na;Q.toneMapped&&(V===null||V.isXRRenderTarget===!0)&&(Zt=T.toneMapping);const Xt=ie.morphAttributes.position||ie.morphAttributes.normal||ie.morphAttributes.color,Nn=Xt!==void 0?Xt.length:0,ze=J.get(Q),Kn=A.state.lights;if(j===!0&&(de===!0||E!==te)){const Yt=E===te&&Q.id===Z;Xe.setState(Q,E,Yt)}let Ct=!1;Q.version===ze.__version?(ze.needsLights&&ze.lightsStateVersion!==Kn.state.version||ze.outputColorSpace!==Le||ee.isBatchedMesh&&ze.batching===!1||!ee.isBatchedMesh&&ze.batching===!0||ee.isBatchedMesh&&ze.batchingColor===!0&&ee._colorsTexture===null||ee.isBatchedMesh&&ze.batchingColor===!1&&ee._colorsTexture!==null||ee.isInstancedMesh&&ze.instancing===!1||!ee.isInstancedMesh&&ze.instancing===!0||ee.isSkinnedMesh&&ze.skinning===!1||!ee.isSkinnedMesh&&ze.skinning===!0||ee.isInstancedMesh&&ze.instancingColor===!0&&ee.instanceColor===null||ee.isInstancedMesh&&ze.instancingColor===!1&&ee.instanceColor!==null||ee.isInstancedMesh&&ze.instancingMorph===!0&&ee.morphTexture===null||ee.isInstancedMesh&&ze.instancingMorph===!1&&ee.morphTexture!==null||ze.envMap!==Ye||Q.fog===!0&&ze.fog!==Pe||ze.numClippingPlanes!==void 0&&(ze.numClippingPlanes!==Xe.numPlanes||ze.numIntersection!==Xe.numIntersection)||ze.vertexAlphas!==vt||ze.vertexTangents!==wt||ze.morphTargets!==qe||ze.morphNormals!==Ot||ze.morphColors!==hn||ze.toneMapping!==Zt||ze.morphTargetsCount!==Nn||!!ze.lightProbeGrid!=A.state.lightProbeGridArray.length>0)&&(Ct=!0):(Ct=!0,ze.__version=Q.version);let ki=ze.currentProgram;Ct===!0&&(ki=yu(Q,G,ee),P&&Q.isNodeMaterial&&P.onUpdateProgram(Q,ki,ze));let ma=!1,Gs=!1,al=!1;const Vt=ki.getUniforms(),ln=ze.uniforms;if(k.useProgram(ki.program)&&(ma=!0,Gs=!0,al=!0),Q.id!==Z&&(Z=Q.id,Gs=!0),ze.needsLights){const Yt=lz(A.state.lightProbeGridArray,ee);ze.lightProbeGrid!==Yt&&(ze.lightProbeGrid=Yt,Gs=!0)}if(ma||te!==E){k.buffers.depth.getReversed()&&E.reversedDepth!==!0&&(E._reversedDepth=!0,E.updateProjectionMatrix()),Vt.setValue(F,"projectionMatrix",E.projectionMatrix),Vt.setValue(F,"viewMatrix",E.matrixWorldInverse);const Vs=Vt.map.cameraPosition;Vs!==void 0&&Vs.setValue(F,Ve.setFromMatrixPosition(E.matrixWorld)),I.logarithmicDepthBuffer&&Vt.setValue(F,"logDepthBufFC",2/(Math.log(E.far+1)/Math.LN2)),(Q.isMeshPhongMaterial||Q.isMeshToonMaterial||Q.isMeshLambertMaterial||Q.isMeshBasicMaterial||Q.isMeshStandardMaterial||Q.isShaderMaterial)&&Vt.setValue(F,"isOrthographic",E.isOrthographicCamera===!0),te!==E&&(te=E,Gs=!0,al=!0)}if(ze.needsLights&&(Kn.state.sunShadowMap.length>0&&Vt.setValue(F,"sunShadowMap",Kn.state.sunShadowMap,ae),Kn.state.directionalShadowMap.length>0&&Vt.setValue(F,"directionalShadowMap",Kn.state.directionalShadowMap,ae),Kn.state.spotShadowMap.length>0&&Vt.setValue(F,"spotShadowMap",Kn.state.spotShadowMap,ae),Kn.state.pointShadowMap.length>0&&Vt.setValue(F,"pointShadowMap",Kn.state.pointShadowMap,ae)),ee.isSkinnedMesh){Vt.setOptional(F,ee,"bindMatrix"),Vt.setOptional(F,ee,"bindMatrixInverse");const Yt=ee.skeleton;Yt&&(Yt.boneTexture===null&&Yt.computeBoneTexture(),Vt.setValue(F,"boneTexture",Yt.boneTexture,ae))}ee.isBatchedMesh&&(Vt.setOptional(F,ee,"batchingTexture"),Vt.setValue(F,"batchingTexture",ee._matricesTexture,ae),Vt.setOptional(F,ee,"batchingIdTexture"),Vt.setValue(F,"batchingIdTexture",ee._indirectTexture,ae),Vt.setOptional(F,ee,"batchingColorTexture"),ee._colorsTexture!==null&&Vt.setValue(F,"batchingColorTexture",ee._colorsTexture,ae));const qs=ie.morphAttributes;if((qs.position!==void 0||qs.normal!==void 0||qs.color!==void 0)&&q.update(ee,ie,ki),(Gs||ze.receiveShadow!==ee.receiveShadow)&&(ze.receiveShadow=ee.receiveShadow,Vt.setValue(F,"receiveShadow",ee.receiveShadow)),(Q.isMeshStandardMaterial||Q.isMeshLambertMaterial||Q.isMeshPhongMaterial)&&Q.envMap===null&&G.environment!==null&&(ln.envMapIntensity.value=G.environmentIntensity),ln.dfgLUT!==void 0&&(ln.dfgLUT.value=jI()),Gs){if(Vt.setValue(F,"toneMappingExposure",T.toneMappingExposure),ze.needsLights&&dz(ln,al),Pe&&Q.fog===!0&&Fe.refreshFogUniforms(ln,Pe),Fe.refreshMaterialUniforms(ln,Q,oe,ne,A.state.transmissionRenderTarget[E.id]),ze.needsLights&&ze.lightProbeGrid){const Yt=ze.lightProbeGrid;ln.probesSH.value=Yt.texture,ln.probesMin.value.copy(Yt.boundingBox.min),ln.probesMax.value.copy(Yt.boundingBox.max),ln.probesResolution.value.copy(Yt.resolution)}Vh.upload(F,wS(ze),ln,ae)}if(Q.isShaderMaterial&&Q.uniformsNeedUpdate===!0&&(Vh.upload(F,wS(ze),ln,ae),Q.uniformsNeedUpdate=!1),Q.isSpriteMaterial&&Vt.setValue(F,"center",ee.center),Vt.setValue(F,"modelViewMatrix",ee.modelViewMatrix),Vt.setValue(F,"normalMatrix",ee.normalMatrix),Vt.setValue(F,"modelMatrix",ee.matrixWorld),Q.uniformsGroups!==void 0){const Yt=Q.uniformsGroups;for(let Vs=0,sl=Yt.length;Vs<sl;Vs++){const SS=Yt[Vs];me.update(SS,ki),me.bind(SS,ki)}}return ki}function dz(E,G){E.ambientLightColor.needsUpdate=G,E.lightProbe.needsUpdate=G,E.sunLights.needsUpdate=G,E.sunLightShadows.needsUpdate=G,E.directionalLights.needsUpdate=G,E.directionalLightShadows.needsUpdate=G,E.pointLights.needsUpdate=G,E.pointLightShadows.needsUpdate=G,E.spotLights.needsUpdate=G,E.spotLightShadows.needsUpdate=G,E.rectAreaLights.needsUpdate=G,E.hemisphereLights.needsUpdate=G}function pz(E){return E.isMeshLambertMaterial||E.isMeshToonMaterial||E.isMeshPhongMaterial||E.isMeshStandardMaterial||E.isShadowMaterial||E.isShaderMaterial&&E.lights===!0}this.getActiveCubeFace=function(){return K},this.getActiveMipmapLevel=function(){return N},this.getRenderTarget=function(){return V},this.setRenderTargetTextures=function(E,G,ie){const Q=J.get(E);Q.__autoAllocateDepthBuffer=E.resolveDepthBuffer===!1,Q.__autoAllocateDepthBuffer===!1&&(Q.__useRenderToTexture=!1),J.get(E.texture).__webglTexture=G,J.get(E.depthTexture).__webglTexture=Q.__autoAllocateDepthBuffer?void 0:ie,Q.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(E,G){const ie=J.get(E);ie.__webglFramebuffer=G,ie.__useDefaultFramebuffer=G===void 0},this.setRenderTarget=function(E,G=0,ie=0){V=E,K=G,N=ie;let Q=null,ee=!1,Pe=!1;if(E){const Le=J.get(E);if(Le.__useDefaultFramebuffer!==void 0){k.bindFramebuffer(F.FRAMEBUFFER,Le.__webglFramebuffer),ce.copy(E.viewport),Ne.copy(E.scissor),He=E.scissorTest,k.viewport(ce),k.scissor(Ne),k.setScissorTest(He),Z=-1;return}else if(Le.__webglFramebuffer===void 0)ae.setupRenderTarget(E);else if(Le.__hasExternalTextures)ae.rebindTextures(E,J.get(E.texture).__webglTexture,J.get(E.depthTexture).__webglTexture);else if(E.depthBuffer){const vt=E.depthTexture;if(Le.__boundDepthTexture!==vt){if(vt!==null&&J.has(vt)&&(E.width!==vt.image.width||E.height!==vt.image.height))throw new Error("THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.");ae.setupDepthRenderbuffer(E)}}const Ge=E.texture;(Ge.isData3DTexture||Ge.isDataArrayTexture||Ge.isCompressedArrayTexture)&&(Pe=!0);const Ye=J.get(E).__webglFramebuffer;E.isWebGLCubeRenderTarget?(Array.isArray(Ye[G])?Q=Ye[G][ie]:Q=Ye[G],ee=!0):E.samples>0&&ae.useMultisampledRTT(E)===!1?Q=J.get(E).__webglMultisampledFramebuffer:Array.isArray(Ye)?Q=Ye[ie]:Q=Ye,ce.copy(E.viewport),Ne.copy(E.scissor),He=E.scissorTest}else ce.copy(Re).multiplyScalar(oe).floor(),Ne.copy($).multiplyScalar(oe).floor(),He=H;if(ie!==0&&(Q=z),k.bindFramebuffer(F.FRAMEBUFFER,Q)&&k.drawBuffers(E,Q),k.viewport(ce),k.scissor(Ne),k.setScissorTest(He),ee){const Le=J.get(E.texture);F.framebufferTexture2D(F.FRAMEBUFFER,F.COLOR_ATTACHMENT0,F.TEXTURE_CUBE_MAP_POSITIVE_X+G,Le.__webglTexture,ie)}else if(Pe){const Le=G;for(let Ge=0;Ge<E.textures.length;Ge++){const Ye=J.get(E.textures[Ge]);F.framebufferTextureLayer(F.FRAMEBUFFER,F.COLOR_ATTACHMENT0+Ge,Ye.__webglTexture,ie,Le)}}else if(E!==null&&ie!==0){const Le=J.get(E.texture);F.framebufferTexture2D(F.FRAMEBUFFER,F.COLOR_ATTACHMENT0,F.TEXTURE_2D,Le.__webglTexture,ie)}Z=-1};function _S(E){const G=J.get(E);return(G.__readFormat!==E.format||G.__readType!==E.type)&&(G.__readFormat=E.format,G.__readType=E.type,G.__formatReadable=I.textureFormatReadable(E.format),G.__typeReadable=I.textureTypeReadable(E.type)),G}this.readRenderTargetPixels=function(E,G,ie,Q,ee,Pe,Oe,Le=0){if(!(E&&E.isWebGLRenderTarget)){Pt("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Ge=J.get(E).__webglFramebuffer;if(E.isWebGLCubeRenderTarget&&Oe!==void 0&&(Ge=Ge[Oe]),Ge){k.bindFramebuffer(F.FRAMEBUFFER,Ge);try{const Ye=E.textures[Le],vt=Ye.format,wt=Ye.type;E.textures.length>1&&F.readBuffer(F.COLOR_ATTACHMENT0+Le);const qe=_S(Ye);if(qe.__formatReadable===!1){Pt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(qe.__typeReadable===!1){Pt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}G>=0&&G<=E.width-Q&&ie>=0&&ie<=E.height-ee&&F.readPixels(G,ie,Q,ee,Ae.convert(vt),Ae.convert(wt),Pe)}finally{const Ye=V!==null?J.get(V).__webglFramebuffer:null;k.bindFramebuffer(F.FRAMEBUFFER,Ye)}}},this.readRenderTargetPixelsAsync=async function(E,G,ie,Q,ee,Pe,Oe,Le=0){if(!(E&&E.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Ge=J.get(E).__webglFramebuffer;if(E.isWebGLCubeRenderTarget&&Oe!==void 0&&(Ge=Ge[Oe]),Ge)if(G>=0&&G<=E.width-Q&&ie>=0&&ie<=E.height-ee){k.bindFramebuffer(F.FRAMEBUFFER,Ge);const Ye=E.textures[Le],vt=Ye.format,wt=Ye.type;E.textures.length>1&&F.readBuffer(F.COLOR_ATTACHMENT0+Le);const qe=_S(Ye);if(qe.__formatReadable===!1)throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(qe.__typeReadable===!1)throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const Ot=F.createBuffer();F.bindBuffer(F.PIXEL_PACK_BUFFER,Ot),F.bufferData(F.PIXEL_PACK_BUFFER,Pe.byteLength,F.STREAM_READ),F.readPixels(G,ie,Q,ee,Ae.convert(vt),Ae.convert(wt),0),F.bindBuffer(F.PIXEL_PACK_BUFFER,null);const hn=V!==null?J.get(V).__webglFramebuffer:null;k.bindFramebuffer(F.FRAMEBUFFER,hn);const Zt=F.fenceSync(F.SYNC_GPU_COMMANDS_COMPLETE,0);return F.flush(),await X4(F,Zt,4),F.bindBuffer(F.PIXEL_PACK_BUFFER,Ot),F.getBufferSubData(F.PIXEL_PACK_BUFFER,0,Pe),F.bindBuffer(F.PIXEL_PACK_BUFFER,null),F.deleteBuffer(Ot),F.deleteSync(Zt),Pe}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(E,G=null,ie=0){const Q=Math.pow(2,-ie),ee=Math.floor(E.image.width*Q),Pe=Math.floor(E.image.height*Q),Oe=G!==null?G.x:0,Le=G!==null?G.y:0;ae.setTexture2D(E,0),F.copyTexSubImage2D(F.TEXTURE_2D,ie,0,0,Oe,Le,ee,Pe),k.unbindTexture()},this.copyTextureToTexture=function(E,G,ie=null,Q=null,ee=0,Pe=0){let Oe,Le,Ge,Ye,vt,wt,qe,Ot,hn;const Zt=E.isCompressedTexture?E.mipmaps[Pe]:E.image;if(ie!==null)Oe=ie.max.x-ie.min.x,Le=ie.max.y-ie.min.y,Ge=ie.isBox3?ie.max.z-ie.min.z:1,Ye=ie.min.x,vt=ie.min.y,wt=ie.isBox3?ie.min.z:0;else{const ln=Math.pow(2,-ee);Oe=Math.floor(Zt.width*ln),Le=Math.floor(Zt.height*ln),E.isDataArrayTexture?Ge=Zt.depth:E.isData3DTexture?Ge=Math.floor(Zt.depth*ln):Ge=1,Ye=0,vt=0,wt=0}Q!==null?(qe=Q.x,Ot=Q.y,hn=Q.z):(qe=0,Ot=0,hn=0);const Xt=Ae.convert(G.format),Nn=Ae.convert(G.type);let ze;G.isData3DTexture?(ae.setTexture3D(G,0),ze=F.TEXTURE_3D):G.isDataArrayTexture||G.isCompressedArrayTexture?(ae.setTexture2DArray(G,0),ze=F.TEXTURE_2D_ARRAY):(ae.setTexture2D(G,0),ze=F.TEXTURE_2D),k.activeTexture(F.TEXTURE0),k.pixelStorei(F.UNPACK_FLIP_Y_WEBGL,G.flipY),k.pixelStorei(F.UNPACK_PREMULTIPLY_ALPHA_WEBGL,G.premultiplyAlpha),k.pixelStorei(F.UNPACK_ALIGNMENT,G.unpackAlignment);const Kn=k.getParameter(F.UNPACK_ROW_LENGTH),Ct=k.getParameter(F.UNPACK_IMAGE_HEIGHT),ki=k.getParameter(F.UNPACK_SKIP_PIXELS),ma=k.getParameter(F.UNPACK_SKIP_ROWS),Gs=k.getParameter(F.UNPACK_SKIP_IMAGES);k.pixelStorei(F.UNPACK_ROW_LENGTH,Zt.width),k.pixelStorei(F.UNPACK_IMAGE_HEIGHT,Zt.height),k.pixelStorei(F.UNPACK_SKIP_PIXELS,Ye),k.pixelStorei(F.UNPACK_SKIP_ROWS,vt),k.pixelStorei(F.UNPACK_SKIP_IMAGES,wt);const al=E.isDataArrayTexture||E.isData3DTexture,Vt=G.isDataArrayTexture||G.isData3DTexture;if(E.isDepthTexture){const ln=J.get(E),qs=J.get(G),Yt=J.get(ln.__renderTarget),Vs=J.get(qs.__renderTarget);k.bindFramebuffer(F.READ_FRAMEBUFFER,Yt.__webglFramebuffer),k.bindFramebuffer(F.DRAW_FRAMEBUFFER,Vs.__webglFramebuffer);for(let sl=0;sl<Ge;sl++)al&&(F.framebufferTextureLayer(F.READ_FRAMEBUFFER,F.COLOR_ATTACHMENT0,J.get(E).__webglTexture,ee,wt+sl),F.framebufferTextureLayer(F.DRAW_FRAMEBUFFER,F.COLOR_ATTACHMENT0,J.get(G).__webglTexture,Pe,hn+sl)),F.blitFramebuffer(Ye,vt,Oe,Le,qe,Ot,Oe,Le,F.DEPTH_BUFFER_BIT,F.NEAREST);k.bindFramebuffer(F.READ_FRAMEBUFFER,null),k.bindFramebuffer(F.DRAW_FRAMEBUFFER,null)}else if(ee!==0||E.isRenderTargetTexture||J.has(E)){const ln=J.get(E),qs=J.get(G);k.bindFramebuffer(F.READ_FRAMEBUFFER,R),k.bindFramebuffer(F.DRAW_FRAMEBUFFER,B);for(let Yt=0;Yt<Ge;Yt++)al?F.framebufferTextureLayer(F.READ_FRAMEBUFFER,F.COLOR_ATTACHMENT0,ln.__webglTexture,ee,wt+Yt):F.framebufferTexture2D(F.READ_FRAMEBUFFER,F.COLOR_ATTACHMENT0,F.TEXTURE_2D,ln.__webglTexture,ee),Vt?F.framebufferTextureLayer(F.DRAW_FRAMEBUFFER,F.COLOR_ATTACHMENT0,qs.__webglTexture,Pe,hn+Yt):F.framebufferTexture2D(F.DRAW_FRAMEBUFFER,F.COLOR_ATTACHMENT0,F.TEXTURE_2D,qs.__webglTexture,Pe),ee!==0?F.blitFramebuffer(Ye,vt,Oe,Le,qe,Ot,Oe,Le,F.COLOR_BUFFER_BIT,F.NEAREST):Vt?F.copyTexSubImage3D(ze,Pe,qe,Ot,hn+Yt,Ye,vt,Oe,Le):F.copyTexSubImage2D(ze,Pe,qe,Ot,Ye,vt,Oe,Le);k.bindFramebuffer(F.READ_FRAMEBUFFER,null),k.bindFramebuffer(F.DRAW_FRAMEBUFFER,null)}else Vt?E.isDataTexture||E.isData3DTexture?F.texSubImage3D(ze,Pe,qe,Ot,hn,Oe,Le,Ge,Xt,Nn,Zt.data):G.isCompressedArrayTexture?F.compressedTexSubImage3D(ze,Pe,qe,Ot,hn,Oe,Le,Ge,Xt,Zt.data):F.texSubImage3D(ze,Pe,qe,Ot,hn,Oe,Le,Ge,Xt,Nn,Zt):E.isDataTexture?F.texSubImage2D(F.TEXTURE_2D,Pe,qe,Ot,Oe,Le,Xt,Nn,Zt.data):E.isCompressedTexture?F.compressedTexSubImage2D(F.TEXTURE_2D,Pe,qe,Ot,Zt.width,Zt.height,Xt,Zt.data):F.texSubImage2D(F.TEXTURE_2D,Pe,qe,Ot,Oe,Le,Xt,Nn,Zt);k.pixelStorei(F.UNPACK_ROW_LENGTH,Kn),k.pixelStorei(F.UNPACK_IMAGE_HEIGHT,Ct),k.pixelStorei(F.UNPACK_SKIP_PIXELS,ki),k.pixelStorei(F.UNPACK_SKIP_ROWS,ma),k.pixelStorei(F.UNPACK_SKIP_IMAGES,Gs),Pe===0&&G.generateMipmaps&&F.generateMipmap(ze),k.unbindTexture()},this.initRenderTarget=function(E){J.get(E).__webglFramebuffer===void 0&&ae.setupRenderTarget(E)},this.initTexture=function(E){E.isCubeTexture?ae.setTextureCube(E,0):E.isData3DTexture?ae.setTexture3D(E,0):E.isDataArrayTexture||E.isCompressedArrayTexture?ae.setTexture2DArray(E,0):ae.setTexture2D(E,0),k.unbindTexture()},this.resetState=function(){K=0,N=0,V=null,k.reset(),$e.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return oa}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=St._getDrawingBufferColorSpace(e),t.unpackColorSpace=St._getUnpackColorSpace()}}const Jk={type:"change"},dx={type:"start"},Qk={type:"end"},Xh=new Sh,e_=new Va,JI=Math.cos(70*j4.DEG2RAD),mn=new X,ni=2*Math.PI,Ht={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},px=1e-6;class QI extends I5{constructor(e,t=null){super(e,t),this.state=Ht.NONE,this.target=new X,this.cursor=new X,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.keyRotateSpeed=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:Sr.ROTATE,MIDDLE:Sr.DOLLY,RIGHT:Sr.PAN},this.touches={ONE:Mr.ROTATE,TWO:Mr.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new X,this._lastQuaternion=new Ls,this._lastTargetPosition=new X,this._quat=new Ls().setFromUnitVectors(e.up,new X(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new bk,this._sphericalDelta=new bk,this._scale=1,this._panOffset=new X,this._rotateStart=new ut,this._rotateEnd=new ut,this._rotateDelta=new ut,this._panStart=new ut,this._panEnd=new ut,this._panDelta=new ut,this._dollyStart=new ut,this._dollyEnd=new ut,this._dollyDelta=new ut,this._dollyDirection=new X,this._mouse=new ut,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=t$.bind(this),this._onPointerDown=e$.bind(this),this._onPointerUp=n$.bind(this),this._onContextMenu=c$.bind(this),this._onMouseWheel=s$.bind(this),this._onKeyDown=o$.bind(this),this._onTouchStart=r$.bind(this),this._onTouchMove=l$.bind(this),this._onMouseDown=i$.bind(this),this._onMouseMove=a$.bind(this),this._interceptControlDown=d$.bind(this),this._interceptControlUp=p$.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}set cursorStyle(e){this._cursorStyle=e,e==="grab"?this.domElement.style.cursor="grab":this.domElement.style.cursor="auto"}get cursorStyle(){return this._cursorStyle}connect(e){super.connect(e),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.state=Ht.NONE,this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents();const e=this.domElement.getRootNode();e.removeEventListener("keydown",this._interceptControlDown,{capture:!0}),e.removeEventListener("keyup",this._interceptControlUp,{capture:!0}),this._controlActive=!1,this._pointers.length=0,this._pointerPositions={},this.domElement.style.touchAction="",this.domElement.style.cursor="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(Jk),this.update(),this.state=Ht.NONE}pan(e,t){this._pan(e,t),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(e=null){const t=this.object.position;mn.copy(t).sub(this.target),mn.applyQuaternion(this._quat),this._spherical.setFromVector3(mn),this.autoRotate&&this.state===Ht.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 i=this.minAzimuthAngle,a=this.maxAzimuthAngle;isFinite(i)&&isFinite(a)&&(i<-Math.PI?i+=ni:i>Math.PI&&(i-=ni),a<-Math.PI?a+=ni:a>Math.PI&&(a-=ni),i<=a?this._spherical.theta=Math.max(i,Math.min(a,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(i+a)/2?Math.max(i,this._spherical.theta):Math.min(a,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 s=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const o=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),s=o!=this._spherical.radius}if(mn.setFromSpherical(this._spherical),mn.applyQuaternion(this._quatInverse),t.copy(this.target).add(mn),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 o=null;if(this.object.isPerspectiveCamera){const r=mn.length();o=this._clampDistance(r*this._scale);const l=r-o;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),s=!!l}else if(this.object.isOrthographicCamera){const r=new X(this._mouse.x,this._mouse.y,0);r.unproject(this.object);const l=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),s=l!==this.object.zoom;const c=new X(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(r),this.object.updateMatrixWorld(),o=mn.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;o!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(o).add(this.object.position):(Xh.origin.copy(this.object.position),Xh.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Xh.direction))<JI?this.object.lookAt(this.target):(e_.setFromNormalAndCoplanarPoint(this.object.up,this.target),Xh.intersectPlane(e_,this.target))))}else if(this.object.isOrthographicCamera){const o=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),o!==this.object.zoom&&(this.object.updateProjectionMatrix(),s=!0)}return this._scale=1,this._performCursorZoom=!1,s||this._lastPosition.distanceToSquared(this.object.position)>px||8*(1-this._lastQuaternion.dot(this.object.quaternion))>px||this._lastTargetPosition.distanceToSquared(this.target)>px?(this.dispatchEvent(Jk),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?ni/60*this.autoRotateSpeed*e:ni/60/60*this.autoRotateSpeed}_getZoomScale(e){const 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){mn.setFromMatrixColumn(t,0),mn.multiplyScalar(-e),this._panOffset.add(mn)}_panUp(e,t){this.screenSpacePanning===!0?mn.setFromMatrixColumn(t,1):(mn.setFromMatrixColumn(t,0),mn.crossVectors(this.object.up,mn)),mn.multiplyScalar(e),this._panOffset.add(mn)}_pan(e,t){const i=this.domElement;if(this.object.isPerspectiveCamera){const a=this.object.position;mn.copy(a).sub(this.target);let s=mn.length();s*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*s/i.clientHeight,this.object.matrix),this._panUp(2*t*s/i.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/i.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/i.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;const i=this.domElement.getBoundingClientRect(),a=e-i.left,s=t-i.top,o=i.width,r=i.height;this._mouse.x=a/o*2-1,this._mouse.y=-(s/r)*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);const t=this.domElement;this._rotateLeft(ni*this._rotateDelta.x/t.clientHeight),this._rotateUp(ni*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(ni*this.keyRotateSpeed/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(-ni*this.keyRotateSpeed/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(ni*this.keyRotateSpeed/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(-ni*this.keyRotateSpeed/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{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),a=.5*(e.pageY+t.y);this._rotateStart.set(i,a)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),a=.5*(e.pageY+t.y);this._panStart.set(i,a)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,a=e.pageY-t.y,s=Math.sqrt(i*i+a*a);this._dollyStart.set(0,s)}_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{const i=this._getSecondPointerPosition(e),a=.5*(e.pageX+i.x),s=.5*(e.pageY+i.y);this._rotateEnd.set(a,s)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(ni*this._rotateDelta.x/t.clientHeight),this._rotateUp(ni*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{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),a=.5*(e.pageY+t.y);this._panEnd.set(i,a)}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){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,a=e.pageY-t.y,s=Math.sqrt(i*i+a*a);this._dollyEnd.set(0,s),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const o=(e.pageX+t.x)*.5,r=(e.pageY+t.y)*.5;this._updateZoomParameters(o,r)}_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 ut,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,i={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:i.deltaY*=16;break;case 2:i.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(i.deltaY*=10),i}}function e$(n){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(n.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(n)&&(this._addPointer(n),n.pointerType==="touch"?this._onTouchStart(n):this._onMouseDown(n),this._cursorStyle==="grab"&&(this.domElement.style.cursor="grabbing")))}function t$(n){this.enabled!==!1&&(n.pointerType==="touch"?this._onTouchMove(n):this._onMouseMove(n))}function n$(n){switch(this._removePointer(n),this._pointers.length){case 0:this.domElement.releasePointerCapture(n.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(Qk),this.state=Ht.NONE,this._cursorStyle==="grab"&&(this.domElement.style.cursor="grab");break;case 1:const e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function i$(n){let e;switch(n.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case Sr.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(n),this.state=Ht.DOLLY;break;case Sr.ROTATE:if(n.ctrlKey||n.metaKey||n.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(n),this.state=Ht.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(n),this.state=Ht.ROTATE}break;case Sr.PAN:if(n.ctrlKey||n.metaKey||n.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(n),this.state=Ht.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(n),this.state=Ht.PAN}break;default:this.state=Ht.NONE}this.state!==Ht.NONE&&this.dispatchEvent(dx)}function a$(n){switch(this.state){case Ht.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(n);break;case Ht.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(n);break;case Ht.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(n);break}}function s$(n){this.enabled===!1||this.enableZoom===!1||this.state!==Ht.NONE||(n.preventDefault(),this.dispatchEvent(dx),this._handleMouseWheel(this._customWheelEvent(n)),this.dispatchEvent(Qk))}function o$(n){this.enabled!==!1&&this._handleKeyDown(n)}function r$(n){switch(this._trackPointer(n),this._pointers.length){case 1:switch(this.touches.ONE){case Mr.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(n),this.state=Ht.TOUCH_ROTATE;break;case Mr.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(n),this.state=Ht.TOUCH_PAN;break;default:this.state=Ht.NONE}break;case 2:switch(this.touches.TWO){case Mr.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(n),this.state=Ht.TOUCH_DOLLY_PAN;break;case Mr.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(n),this.state=Ht.TOUCH_DOLLY_ROTATE;break;default:this.state=Ht.NONE}break;default:this.state=Ht.NONE}this.state!==Ht.NONE&&this.dispatchEvent(dx)}function l$(n){switch(this._trackPointer(n),this.state){case Ht.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(n),this.update();break;case Ht.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(n),this.update();break;case Ht.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(n),this.update();break;case Ht.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(n),this.update();break;default:this.state=Ht.NONE}}function c$(n){this.enabled!==!1&&n.preventDefault()}function d$(n){n.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function p$(n){n.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function hx(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function Wc(n){let e=n>>>0||2654435769;return()=>{e=e+1831565813|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}function ux(n){const e=Math.max(1e-9,n());return Math.sqrt(-2*Math.log(e))*Math.cos(2*Math.PI*n())}function zs(n,e,t){let i=Math.imul(n,374761393)+Math.imul(e,668265263)+Math.imul(t,1274126177);return i=Math.imul(i^i>>>13,1274126177),((i^i>>>16)>>>0)/4294967296}function t_(n,e,t){const i=Math.floor(n),a=Math.floor(e),s=Math.floor(t),o=n-i,r=e-a,l=t-s,c=o*o*(3-2*o),p=r*r*(3-2*r),h=l*l*(3-2*l),d=(u,f,v)=>u+(f-u)*v;return d(d(d(zs(i,a,s),zs(i+1,a,s),c),d(zs(i,a+1,s),zs(i+1,a+1,s),c),p),d(d(zs(i,a,s+1),zs(i+1,a,s+1),c),d(zs(i,a+1,s+1),zs(i+1,a+1,s+1),c),p),h)}function h$(n,e,t){const a=1-Math.abs(2*t_(n*5.2+11.3,e*5.2*1.15,t*5.2)-1),s=1-Math.abs(2*t_(n*5.2*2.1,e*5.2*2.1+5.1,t*5.2*2.1-3.7)-1),o=Math.max(Math.pow(a,5),Math.pow(s,7)*.6);return Math.min(1,o*1.25)}const Kr={c:[.4,.06,0],a:[.52,.62,1]},fx={c:[.52,-.27,.14],a:[.3,.25,.56]},n_={c:[.25,-.44,-.66],a:[.3,.2,.3]};function Yr(n,e,t,i){const a=1-.1*Math.max(0,i),s=(e-n.c[0])/(n.a[0]*a);let o=(t-n.c[1])/(n.a[1]*a);o<0&&n===Kr&&(o*=1.35);const r=(i-n.c[2])/n.a[2];return Math.sqrt(s*s+o*o+r*r)}function Kh(n,e,t){const i=Math.abs(n);return i<.035?9:Math.min(Yr(Kr,i,e,t),Yr(fx,i,e,t))}function i_(n,e,t){const i=Math.abs(n);return i<.02?9:Yr(n_,i,e,t)}function u$(n,e,t,i=.9){return Kh(n,e,t)<i||i_(n,e,t)<i*.9}function a_(n,e=7){const t=Wc(e),i=new Float32Array(n*3),a=new Float32Array(n*3),s=new Float32Array(n);let o=0,r=n*60;for(;o<n&&r-- >0;){const l=t();let c=Kr,p=0;l<.78?c=Kr:l<.9?c=fx:l<.97?(c=n_,p=1):p=2;let h,d,u,f,v,g;if(p===2){const P=t(),z=t()*Math.PI*2,R=.1-P*.025;if(f=Math.cos(z),g=Math.sin(z),v=0,h=f*R,d=-.28-P*.55,u=-.28-P*.12+g*R,Kh(h,d,u)<1||i_(h,d,u)<1)continue;i.set([h,d,u],o*3),a.set([f,v,g],o*3),s[o]=.45+.2*t(),o++;continue}const m=t()*2-1,x=t()*Math.PI*2,_=Math.sqrt(1-m*m),w=t()<.5?-1:1;let S=_*Math.cos(x),A=_*Math.sin(x),C=m;h=c.c[0]+S*c.a[0],d=c.c[1]+A*c.a[1],u=c.c[2]+C*c.a[2];const y=Yr(c,h,d,u);if(h=c.c[0]+(h-c.c[0])/y,d=c.c[1]+(d-c.c[1])/y,u=c.c[2]+(u-c.c[2])/y,h<.035)continue;if(p===0){if(Yr(c===Kr?fx:Kr,h,d,u)<.985)continue}else if(Kh(h,d,u)<1)continue;f=(h-c.c[0])/(c.a[0]*c.a[0]),v=(d-c.c[1])/(c.a[1]*c.a[1]),g=(u-c.c[2])/(c.a[2]*c.a[2]);const M=Math.hypot(f,v,g)||1;f/=M,v/=M,g/=M;let T,L;if(p===1){const P=Math.abs(Math.sin(d*70+u*12));T=.35+.65*P,L=(1-P)*.018}else{const P=h$(h,d,u);if(P>.55&&t()<.55)continue;T=1-.9*P,L=P*.05}h-=f*L,d-=v*L,u-=g*L,S=h*w,i.set([S,d,u],o*3),a.set([f*w,v,g],o*3),s[o]=T,o++}return{pos:i,nrm:a,shade:s,count:o}}function f$(n,e=3){const t=Wc(e),i=[];for(;i.length<1800;){const l=(t()*2-1)*.95,c=(t()*2-1)*.75,p=(t()*2-1)*1.05,h=Kh(l,c,p);h>.42&&h<.72&&i.push([l,c,p])}const a=[];if(n<=0)return a;let s=0,o=-1/0;for(let l=0;l<i.length;l++){const c=i[l][2]+i[l][1]*.5-Math.abs(i[l][0])*.2;c>o&&(o=c,s=l)}a.push(i[s]);const r=i.map(l=>s_(l,i[s]));for(;a.length<n;){let l=0,c=-1;for(let p=0;p<i.length;p++)r[p]>c&&(c=r[p],l=p);if(c<=0){a.push(i[a.length*37%i.length]);continue}a.push(i[l]);for(let p=0;p<i.length;p++)r[p]=Math.min(r[p],s_(i[p],i[l]))}return a}function s_(n,e){const t=n[0]-e[0],i=n[1]-e[1],a=n[2]-e[2];return t*t+i*i+a*a}function m$(n,e,t){const i=Wc(hx(n));for(let a=0;a<40;a++){const s=t*(1+a*.03),o=e[0]+ux(i)*s*.8,r=e[1]+ux(i)*s*.8,l=e[2]+ux(i)*s*1.15;if(!(Math.sign(o)!==Math.sign(e[0])&&Math.abs(e[0])>.06)&&u$(o,r,l,.9))return[o,r,l]}return[e[0],e[1],e[2]]}function g$(n,e){const t=.62/Math.cbrt(Math.max(1,e));return Math.min(.3,Math.max(.045,t*(.22+.12*Math.cbrt(n))))}const mx=[3.05,1.35,1.55],Po=[0,-.02,-.04],o_=42;function gx(n){return n<.9?5.2:n<1.3?4.1:3.6}const pa=110,Xc=6e3,Yh=12*pa*2,v$=5*6e4,x$=5e3,b$=2e3,y$=`
8504
+ }`;class qI{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){const i=new hk(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=i}}getMesh(e){if(this.texture!==null&&this.mesh===null){const t=e.cameras[0].viewport,i=new Pn({vertexShader:HI,fragmentShader:GI,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new Xa(new Uh(20,20),i)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}}class VI extends Rs{constructor(e,t){super();const i=this;let a=null,s=1,o=null,r="local-floor",l=1,c=null,p=null,h=null,d=null,u=null,f=null;const v=typeof XRWebGLBinding<"u",g=new qI,m={},x=t.getContextAttributes();let _=null,w=null;const S=[],A=[],C=new ut;let y=null,M=null;const T=new wi;T.viewport=new nn;const L=new wi;L.viewport=new nn;const P=[T,L],z=new P5;let R=null,B=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(ne){let oe=S[ne];return oe===void 0&&(oe=new zv,S[ne]=oe),oe.getTargetRaySpace()},this.getControllerGrip=function(ne){let oe=S[ne];return oe===void 0&&(oe=new zv,S[ne]=oe),oe.getGripSpace()},this.getHand=function(ne){let oe=S[ne];return oe===void 0&&(oe=new zv,S[ne]=oe),oe.getHandSpace()};function K(ne){const oe=A.indexOf(ne.inputSource);if(oe===-1)return;const Te=S[oe];Te!==void 0&&(Te.update(ne.inputSource,ne.frame,c||o),Te.dispatchEvent({type:ne.type,data:ne.inputSource}))}function N(){a.removeEventListener("select",K),a.removeEventListener("selectstart",K),a.removeEventListener("selectend",K),a.removeEventListener("squeeze",K),a.removeEventListener("squeezestart",K),a.removeEventListener("squeezeend",K),a.removeEventListener("end",N),a.removeEventListener("inputsourceschange",V);for(let ne=0;ne<S.length;ne++){const oe=A[ne];oe!==null&&(A[ne]=null,S[ne].disconnect(oe))}R=null,B=null,g.reset();for(const ne in m)delete m[ne];if(e.setRenderTarget(_),u=null,d=null,h=null,a=null,w=null,ft.stop(),i.isPresenting=!1,e.setPixelRatio(y),e.setSize(C.width,C.height,!1),M!==null){const ne=M.camera;ne.fov=M.fov,ne.zoom=M.zoom,ne.updateProjectionMatrix(),M=null}i.dispatchEvent({type:"sessionend"})}this.setFramebufferScaleFactor=function(ne){s=ne,i.isPresenting===!0&&rt("WebXRManager: Cannot change framebuffer scale while presenting.")},this.setReferenceSpaceType=function(ne){r=ne,i.isPresenting===!0&&rt("WebXRManager: Cannot change reference space type while presenting.")},this.getReferenceSpace=function(){return c||o},this.setReferenceSpace=function(ne){c=ne},this.getBaseLayer=function(){return d!==null?d:u},this.getBinding=function(){return h===null&&v&&(h=new XRWebGLBinding(a,t)),h},this.getFrame=function(){return f},this.getSession=function(){return a},this.setSession=async function(ne){if(a=ne,a!==null){if(_=e.getRenderTarget(),a.addEventListener("select",K),a.addEventListener("selectstart",K),a.addEventListener("selectend",K),a.addEventListener("squeeze",K),a.addEventListener("squeezestart",K),a.addEventListener("squeezeend",K),a.addEventListener("end",N),a.addEventListener("inputsourceschange",V),x.xrCompatible!==!0&&await t.makeXRCompatible(),y=e.getPixelRatio(),e.getSize(C),v&&"createProjectionLayer"in XRWebGLBinding.prototype){let Te=null,We=null,Re=null;x.depth&&(Re=x.stencil?t.DEPTH24_STENCIL8:t.DEPTH_COMPONENT24,Te=x.stencil?So:Ua,We=x.stencil?Lc:ia);const $={colorFormat:t.RGBA8,depthFormat:Re,scaleFactor:s};h=this.getBinding(),d=h.createProjectionLayer($),a.updateRenderState({layers:[d]}),e.setPixelRatio(1),e.setSize(d.textureWidth,d.textureHeight,!1),w=new $i(d.textureWidth,d.textureHeight,{format:Ii,type:xi,depthTexture:new Bc(d.textureWidth,d.textureHeight,We,void 0,void 0,void 0,void 0,void 0,void 0,Te),stencilBuffer:x.stencil,colorSpace:e.outputColorSpace,samples:x.antialias?4:0,resolveDepthBuffer:d.ignoreDepthValues===!1,resolveStencilBuffer:d.ignoreDepthValues===!1,storeMultisampledDepthBuffer:d.ignoreDepthValues===!1,storeMultisampledStencilBuffer:d.ignoreDepthValues===!1})}else{const Te={antialias:x.antialias,alpha:!0,depth:x.depth,stencil:x.stencil,framebufferScaleFactor:s};u=new XRWebGLLayer(a,t,Te),a.updateRenderState({baseLayer:u}),e.setPixelRatio(1),e.setSize(u.framebufferWidth,u.framebufferHeight,!1),w=new $i(u.framebufferWidth,u.framebufferHeight,{format:Ii,type:xi,colorSpace:e.outputColorSpace,stencilBuffer:x.stencil,resolveDepthBuffer:u.ignoreDepthValues===!1,resolveStencilBuffer:u.ignoreDepthValues===!1,storeMultisampledDepthBuffer:u.ignoreDepthValues===!1,storeMultisampledStencilBuffer:u.ignoreDepthValues===!1})}w.isXRRenderTarget=!0,this.setFoveation(l),c=null,o=await a.requestReferenceSpace(r),ft.setContext(a),ft.start(),i.isPresenting=!0,i.dispatchEvent({type:"sessionstart"})}},this.getEnvironmentBlendMode=function(){if(a!==null)return a.environmentBlendMode},this.getDepthTexture=function(){return g.getDepthTexture()};function V(ne){for(let oe=0;oe<ne.removed.length;oe++){const Te=ne.removed[oe],We=A.indexOf(Te);We>=0&&(A[We]=null,S[We].disconnect(Te))}for(let oe=0;oe<ne.added.length;oe++){const Te=ne.added[oe];let We=A.indexOf(Te);if(We===-1){for(let $=0;$<S.length;$++)if($>=A.length){A.push(Te),We=$;break}else if(A[$]===null){A[$]=Te,We=$;break}if(We===-1)break}const Re=S[We];Re&&Re.connect(Te)}}const Z=new X,te=new X;function ce(ne,oe,Te){Z.setFromMatrixPosition(oe.matrixWorld),te.setFromMatrixPosition(Te.matrixWorld);const We=Z.distanceTo(te),Re=oe.projectionMatrix.elements,$=Te.projectionMatrix.elements,H=Re[14]/(Re[10]-1),Y=Re[14]/(Re[10]+1),j=(Re[9]+1)/Re[5],de=(Re[9]-1)/Re[5],fe=(Re[8]-1)/Re[0],Ve=($[8]+1)/$[0],st=H*fe,kt=H*Ve,Ue=We/(-fe+Ve),Ze=Ue*-fe;if(oe.matrixWorld.decompose(ne.position,ne.quaternion,ne.scale),ne.translateX(Ze),ne.translateZ(Ue),ne.matrixWorld.compose(ne.position,ne.quaternion,ne.scale),ne.matrixWorldInverse.copy(ne.matrixWorld).invert(),Re[10]===-1)ne.projectionMatrix.copy(oe.projectionMatrix),ne.projectionMatrixInverse.copy(oe.projectionMatrixInverse);else{const F=H+Ue,lt=Y+Ue,Je=st-Ze,I=kt+(We-Ze),k=j*Y/lt*F,W=de*Y/lt*F;ne.projectionMatrix.makePerspective(Je,I,k,W,F,lt),ne.projectionMatrixInverse.copy(ne.projectionMatrix).invert()}}function Ne(ne,oe){oe===null?ne.matrixWorld.copy(ne.matrix):ne.matrixWorld.multiplyMatrices(oe.matrixWorld,ne.matrix),ne.matrixWorldInverse.copy(ne.matrixWorld).invert()}this.updateCamera=function(ne){if(a===null)return;let oe=ne.near,Te=ne.far;g.texture!==null&&(g.depthNear>0&&(oe=g.depthNear),g.depthFar>0&&(Te=g.depthFar)),z.near=L.near=T.near=oe,z.far=L.far=T.far=Te,(R!==z.near||B!==z.far)&&(a.updateRenderState({depthNear:z.near,depthFar:z.far}),R=z.near,B=z.far),z.layers.mask=ne.layers.mask|6,T.layers.mask=z.layers.mask&-5,L.layers.mask=z.layers.mask&-3;const We=ne.parent,Re=z.cameras;Ne(z,We);for(let $=0;$<Re.length;$++)Ne(Re[$],We);Re.length===2?ce(z,T,L):z.projectionMatrix.copy(T.projectionMatrix),M===null&&ne.isPerspectiveCamera&&(M={camera:ne,fov:ne.fov,zoom:ne.zoom}),He(ne,z,We)};function He(ne,oe,Te){Te===null?ne.matrix.copy(oe.matrixWorld):(ne.matrix.copy(Te.matrixWorld),ne.matrix.invert(),ne.matrix.multiply(oe.matrixWorld)),ne.matrix.decompose(ne.position,ne.quaternion,ne.scale),ne.updateMatrixWorld(!0),ne.projectionMatrix.copy(oe.projectionMatrix),ne.projectionMatrixInverse.copy(oe.projectionMatrixInverse),ne.isPerspectiveCamera&&(ne.fov=Cv*2*Math.atan(1/ne.projectionMatrix.elements[5]),ne.zoom=1)}this.getCamera=function(){return z},this.getFoveation=function(){if(!(d===null&&u===null))return l},this.setFoveation=function(ne){l=ne,d!==null&&(d.fixedFoveation=ne),u!==null&&u.fixedFoveation!==void 0&&(u.fixedFoveation=ne)},this.hasDepthSensing=function(){return g.texture!==null},this.getDepthSensingMesh=function(){return g.getMesh(z)},this.getCameraTexture=function(ne){return m[ne]};let ct=null;function ot(ne,oe){if(p=oe.getViewerPose(c||o),f=oe,p!==null){const Te=p.views;u!==null&&(e.setRenderTargetFramebuffer(w,u.framebuffer),e.setRenderTarget(w));let We=!1;Te.length!==z.cameras.length&&(z.cameras.length=0,We=!0);for(let Y=0;Y<Te.length;Y++){const j=Te[Y];let de=null;if(u!==null)de=u.getViewport(j);else{const Ve=h.getViewSubImage(d,j);de=Ve.viewport,Y===0&&(e.setRenderTargetTextures(w,Ve.colorTexture,Ve.depthStencilTexture),e.setRenderTarget(w))}let fe=P[Y];fe===void 0&&(fe=new wi,fe.layers.enable(Y),fe.viewport=new nn,P[Y]=fe),fe.matrix.fromArray(j.transform.matrix),fe.matrix.decompose(fe.position,fe.quaternion,fe.scale),fe.projectionMatrix.fromArray(j.projectionMatrix),fe.projectionMatrixInverse.copy(fe.projectionMatrix).invert(),fe.viewport.set(de.x,de.y,de.width,de.height),Y===0&&(z.matrix.copy(fe.matrix),z.matrix.decompose(z.position,z.quaternion,z.scale)),We===!0&&z.cameras.push(fe)}const Re=a.enabledFeatures;if(Re&&Re.includes("depth-sensing")&&a.depthUsage=="gpu-optimized"&&v){h=i.getBinding();const Y=h.getDepthInformation(Te[0]);Y&&Y.isValid&&Y.texture&&g.init(Y,a.renderState)}if(Re&&Re.includes("camera-access")&&v){e.state.unbindTexture(),h=i.getBinding();for(let Y=0;Y<Te.length;Y++){const j=Te[Y].camera;if(j){let de=m[j];de||(de=new hk,m[j]=de);const fe=h.getCameraImage(j);de.sourceTexture=fe}}}}for(let Te=0;Te<S.length;Te++){const We=A[Te],Re=S[Te];We!==null&&Re!==void 0&&Re.update(We,oe,c||o)}ct&&ct(ne,oe),oe.detectedPlanes&&i.dispatchEvent({type:"planesdetected",data:oe}),f=null}const ft=new kk;ft.setAnimationLoop(ot),this.setAnimationLoop=function(ne){ct=ne},this.dispose=function(){}}}const WI=new en,Zk=new pt;Zk.set(-1,0,0,0,1,0,0,0,1);function XI(n,e){function t(g,m){g.matrixAutoUpdate===!0&&g.updateMatrix(),m.value.copy(g.matrix)}function i(g,m){m.color.getRGB(g.fogColor.value,fk(n)),m.isFog?(g.fogNear.value=m.near,g.fogFar.value=m.far):m.isFogExp2&&(g.fogDensity.value=m.density)}function a(g,m,x,_,w){m.isNodeMaterial?m.uniformsNeedUpdate=!1:m.isMeshBasicMaterial?s(g,m):m.isMeshLambertMaterial?(s(g,m),m.envMap&&(g.envMapIntensity.value=m.envMapIntensity)):m.isMeshToonMaterial?(s(g,m),h(g,m)):m.isMeshPhongMaterial?(s(g,m),p(g,m),m.envMap&&(g.envMapIntensity.value=m.envMapIntensity)):m.isMeshStandardMaterial?(s(g,m),d(g,m),m.isMeshPhysicalMaterial&&u(g,m,w)):m.isMeshMatcapMaterial?(s(g,m),f(g,m)):m.isMeshDepthMaterial?s(g,m):m.isMeshDistanceMaterial?(s(g,m),v(g,m)):m.isMeshNormalMaterial?s(g,m):m.isLineBasicMaterial?(o(g,m),m.isLineDashedMaterial&&r(g,m)):m.isPointsMaterial?l(g,m,x,_):m.isSpriteMaterial?c(g,m):m.isShadowMaterial?(g.color.value.copy(m.color),g.opacity.value=m.opacity):m.isShaderMaterial&&(m.uniformsNeedUpdate=!1)}function s(g,m){g.opacity.value=m.opacity,m.color&&g.diffuse.value.copy(m.color),m.emissive&&g.emissive.value.copy(m.emissive).multiplyScalar(m.emissiveIntensity),m.map&&(g.map.value=m.map,t(m.map,g.mapTransform)),m.alphaMap&&(g.alphaMap.value=m.alphaMap,t(m.alphaMap,g.alphaMapTransform)),m.bumpMap&&(g.bumpMap.value=m.bumpMap,t(m.bumpMap,g.bumpMapTransform),g.bumpScale.value=m.bumpScale,m.side===ei&&(g.bumpScale.value*=-1)),m.normalMap&&(g.normalMap.value=m.normalMap,t(m.normalMap,g.normalMapTransform),g.normalScale.value.copy(m.normalScale),m.side===ei&&g.normalScale.value.negate()),m.displacementMap&&(g.displacementMap.value=m.displacementMap,t(m.displacementMap,g.displacementMapTransform),g.displacementScale.value=m.displacementScale,g.displacementBias.value=m.displacementBias),m.emissiveMap&&(g.emissiveMap.value=m.emissiveMap,t(m.emissiveMap,g.emissiveMapTransform)),m.specularMap&&(g.specularMap.value=m.specularMap,t(m.specularMap,g.specularMapTransform)),m.alphaTest>0&&(g.alphaTest.value=m.alphaTest);const x=e.get(m),_=x.envMap,w=x.envMapRotation;_&&(g.envMap.value=_,g.envMapRotation.value.setFromMatrix4(WI.makeRotationFromEuler(w)).transpose(),_.isCubeTexture&&_.isRenderTargetTexture===!1&&g.envMapRotation.value.premultiply(Zk),g.reflectivity.value=m.reflectivity,g.ior.value=m.ior,g.refractionRatio.value=m.refractionRatio),m.lightMap&&(g.lightMap.value=m.lightMap,g.lightMapIntensity.value=m.lightMapIntensity,t(m.lightMap,g.lightMapTransform)),m.aoMap&&(g.aoMap.value=m.aoMap,g.aoMapIntensity.value=m.aoMapIntensity,t(m.aoMap,g.aoMapTransform))}function o(g,m){g.diffuse.value.copy(m.color),g.opacity.value=m.opacity,m.map&&(g.map.value=m.map,t(m.map,g.mapTransform))}function r(g,m){g.dashSize.value=m.dashSize,g.totalSize.value=m.dashSize+m.gapSize,g.scale.value=m.scale}function l(g,m,x,_){g.diffuse.value.copy(m.color),g.opacity.value=m.opacity,g.size.value=m.size*x,g.scale.value=_*.5,m.map&&(g.map.value=m.map,t(m.map,g.uvTransform)),m.alphaMap&&(g.alphaMap.value=m.alphaMap,t(m.alphaMap,g.alphaMapTransform)),m.alphaTest>0&&(g.alphaTest.value=m.alphaTest)}function c(g,m){g.diffuse.value.copy(m.color),g.opacity.value=m.opacity,g.rotation.value=m.rotation,m.map&&(g.map.value=m.map,t(m.map,g.mapTransform)),m.alphaMap&&(g.alphaMap.value=m.alphaMap,t(m.alphaMap,g.alphaMapTransform)),m.alphaTest>0&&(g.alphaTest.value=m.alphaTest)}function p(g,m){g.specular.value.copy(m.specular),g.shininess.value=Math.max(m.shininess,1e-4)}function h(g,m){m.gradientMap&&(g.gradientMap.value=m.gradientMap)}function d(g,m){g.metalness.value=m.metalness,m.metalnessMap&&(g.metalnessMap.value=m.metalnessMap,t(m.metalnessMap,g.metalnessMapTransform)),g.roughness.value=m.roughness,m.roughnessMap&&(g.roughnessMap.value=m.roughnessMap,t(m.roughnessMap,g.roughnessMapTransform)),m.envMap&&(g.envMapIntensity.value=m.envMapIntensity)}function u(g,m,x){g.ior.value=m.ior,m.sheen>0&&(g.sheenColor.value.copy(m.sheenColor).multiplyScalar(m.sheen),g.sheenRoughness.value=m.sheenRoughness,m.sheenColorMap&&(g.sheenColorMap.value=m.sheenColorMap,t(m.sheenColorMap,g.sheenColorMapTransform)),m.sheenRoughnessMap&&(g.sheenRoughnessMap.value=m.sheenRoughnessMap,t(m.sheenRoughnessMap,g.sheenRoughnessMapTransform))),m.clearcoat>0&&(g.clearcoat.value=m.clearcoat,g.clearcoatRoughness.value=m.clearcoatRoughness,m.clearcoatMap&&(g.clearcoatMap.value=m.clearcoatMap,t(m.clearcoatMap,g.clearcoatMapTransform)),m.clearcoatRoughnessMap&&(g.clearcoatRoughnessMap.value=m.clearcoatRoughnessMap,t(m.clearcoatRoughnessMap,g.clearcoatRoughnessMapTransform)),m.clearcoatNormalMap&&(g.clearcoatNormalMap.value=m.clearcoatNormalMap,t(m.clearcoatNormalMap,g.clearcoatNormalMapTransform),g.clearcoatNormalScale.value.copy(m.clearcoatNormalScale),m.side===ei&&g.clearcoatNormalScale.value.negate())),m.dispersion>0&&(g.dispersion.value=m.dispersion),m.retroreflectivity>0&&(g.retroreflectivity.value=m.retroreflectivity),m.iridescence>0&&(g.iridescence.value=m.iridescence,g.iridescenceIOR.value=m.iridescenceIOR,g.iridescenceThicknessMinimum.value=m.iridescenceThicknessRange[0],g.iridescenceThicknessMaximum.value=m.iridescenceThicknessRange[1],m.iridescenceMap&&(g.iridescenceMap.value=m.iridescenceMap,t(m.iridescenceMap,g.iridescenceMapTransform)),m.iridescenceThicknessMap&&(g.iridescenceThicknessMap.value=m.iridescenceThicknessMap,t(m.iridescenceThicknessMap,g.iridescenceThicknessMapTransform))),m.transmission>0&&(g.transmission.value=m.transmission,g.transmissionSamplerMap.value=x.texture,g.transmissionSamplerSize.value.set(x.width,x.height),m.transmissionMap&&(g.transmissionMap.value=m.transmissionMap,t(m.transmissionMap,g.transmissionMapTransform)),g.thickness.value=m.thickness,m.thicknessMap&&(g.thicknessMap.value=m.thicknessMap,t(m.thicknessMap,g.thicknessMapTransform)),g.attenuationDistance.value=m.attenuationDistance,g.attenuationColor.value.copy(m.attenuationColor)),m.anisotropy>0&&(g.anisotropyVector.value.set(m.anisotropy*Math.cos(m.anisotropyRotation),m.anisotropy*Math.sin(m.anisotropyRotation)),m.anisotropyMap&&(g.anisotropyMap.value=m.anisotropyMap,t(m.anisotropyMap,g.anisotropyMapTransform))),g.specularIntensity.value=m.specularIntensity,g.specularColor.value.copy(m.specularColor),m.specularColorMap&&(g.specularColorMap.value=m.specularColorMap,t(m.specularColorMap,g.specularColorMapTransform)),m.specularIntensityMap&&(g.specularIntensityMap.value=m.specularIntensityMap,t(m.specularIntensityMap,g.specularIntensityMapTransform))}function f(g,m){m.matcap&&(g.matcap.value=m.matcap)}function v(g,m){const x=e.get(m).light;g.referencePosition.value.setFromMatrixPosition(x.matrixWorld),g.nearDistance.value=x.shadow.camera.near,g.farDistance.value=x.shadow.camera.far}return{refreshFogUniforms:i,refreshMaterialUniforms:a}}function KI(n,e,t,i){let a={},s={},o=[];const r=n.getParameter(n.MAX_UNIFORM_BUFFER_BINDINGS);function l(w,S){const A=S.program;i.uniformBlockBinding(w,A)}function c(w,S){let A=a[w.id];A===void 0&&(g(w),A=p(w),a[w.id]=A,w.addEventListener("dispose",x));const C=S.program;i.updateUBOMapping(w,C);const y=e.render.frame;s[w.id]!==y&&(d(w),s[w.id]=y)}function p(w){const S=h();w.__bindingPointIndex=S;const A=n.createBuffer(),C=w.__size,y=w.usage;return n.bindBuffer(n.UNIFORM_BUFFER,A),n.bufferData(n.UNIFORM_BUFFER,C,y),n.bindBuffer(n.UNIFORM_BUFFER,null),n.bindBufferBase(n.UNIFORM_BUFFER,S,A),A}function h(){for(let w=0;w<r;w++)if(o.indexOf(w)===-1)return o.push(w),w;return Pt("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."),0}function d(w){const S=a[w.id],A=w.uniforms,C=w.__cache;n.bindBuffer(n.UNIFORM_BUFFER,S);for(let y=0,M=A.length;y<M;y++){const T=A[y];if(Array.isArray(T))for(let L=0,P=T.length;L<P;L++)u(T[L],y,L,C);else u(T,y,0,C)}n.bindBuffer(n.UNIFORM_BUFFER,null)}function u(w,S,A,C){if(v(w,S,A,C)===!0){const y=w.__offset,M=w.value;if(Array.isArray(M)){let T=0;for(let L=0;L<M.length;L++){const P=M[L],z=m(P);f(P,w.__data,T),typeof P!="number"&&typeof P!="boolean"&&!P.isMatrix3&&!ArrayBuffer.isView(P)&&(T+=z.storage/Float32Array.BYTES_PER_ELEMENT)}}else f(M,w.__data,0);n.bufferSubData(n.UNIFORM_BUFFER,y,w.__data)}}function f(w,S,A){typeof w=="number"||typeof w=="boolean"?S[0]=w:w.isMatrix3?(S[0]=w.elements[0],S[1]=w.elements[1],S[2]=w.elements[2],S[3]=0,S[4]=w.elements[3],S[5]=w.elements[4],S[6]=w.elements[5],S[7]=0,S[8]=w.elements[6],S[9]=w.elements[7],S[10]=w.elements[8],S[11]=0):ArrayBuffer.isView(w)?S.set(new w.constructor(w.buffer,w.byteOffset,S.length)):w.toArray(S,A)}function v(w,S,A,C){const y=w.value,M=S+"_"+A;if(C[M]===void 0)return typeof y=="number"||typeof y=="boolean"?C[M]=y:ArrayBuffer.isView(y)?C[M]=y.slice():C[M]=y.clone(),!0;{const T=C[M];if(typeof y=="number"||typeof y=="boolean"){if(T!==y)return C[M]=y,!0}else{if(ArrayBuffer.isView(y))return!0;if(T.equals(y)===!1)return T.copy(y),!0}}return!1}function g(w){const S=w.uniforms;let A=0;const C=16;for(let M=0,T=S.length;M<T;M++){const L=Array.isArray(S[M])?S[M]:[S[M]];for(let P=0,z=L.length;P<z;P++){const R=L[P],B=Array.isArray(R.value)?R.value:[R.value];for(let K=0,N=B.length;K<N;K++){const V=B[K],Z=m(V),te=A%C,ce=te%Z.boundary,Ne=te+ce;A+=ce,Ne!==0&&C-Ne<Z.storage&&(A+=C-Ne),R.__data=new Float32Array(Z.storage/Float32Array.BYTES_PER_ELEMENT),R.__offset=A,A+=Z.storage}}}const y=A%C;return y>0&&(A+=C-y),w.__size=A,w.__cache={},this}function m(w){const S={boundary:0,storage:0};return typeof w=="number"||typeof w=="boolean"?(S.boundary=4,S.storage=4):w.isVector2?(S.boundary=8,S.storage=8):w.isVector3||w.isColor?(S.boundary=16,S.storage=12):w.isVector4?(S.boundary=16,S.storage=16):w.isMatrix3?(S.boundary=48,S.storage=48):w.isMatrix4?(S.boundary=64,S.storage=64):w.isTexture?rt("WebGLRenderer: Texture samplers can not be part of an uniforms group."):ArrayBuffer.isView(w)?(S.boundary=16,S.storage=w.byteLength):rt("WebGLRenderer: Unsupported uniform value type.",w),S}function x(w){const S=w.target;S.removeEventListener("dispose",x);const A=o.indexOf(S.__bindingPointIndex);o.splice(A,1),n.deleteBuffer(a[S.id]),delete a[S.id],delete s[S.id]}function _(){for(const w in a)n.deleteBuffer(a[w]);o=[],a={},s={}}return{bind:l,update:c,dispose:_}}const YI=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let da=null;function jI(){return da===null&&(da=new x5(YI,16,16,Mo,sa),da.name="DFG_LUT",da.minFilter=Cn,da.magFilter=Cn,da.wrapS=Oa,da.wrapT=Oa,da.generateMipmaps=!1,da.needsUpdate=!0),da}class ZI{constructor(e={}){const{canvas:t=WR(),context:i=null,depth:a=!0,stencil:s=!1,alpha:o=!1,antialias:r=!1,premultipliedAlpha:l=!0,preserveDrawingBuffer:c=!1,powerPreference:p="default",failIfMajorPerformanceCaveat:h=!1,reversedDepthBuffer:d=!1,outputBufferType:u=xi}=e;this.isWebGLRenderer=!0;let f;if(i!==null){if(typeof WebGLRenderingContext<"u"&&i instanceof WebGLRenderingContext)throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163.");f=i.getContextAttributes().alpha}else f=o;const v=u,g=new Set([Yg,Kg,Xg]),m=new Set([xi,ia,Rc,Lc,Vg,Wg]),x=new Uint32Array(4),_=new Int32Array(4),w=new X;let S=null,A=null;const C=[],y=[];let M=null;this.domElement=t,this.debug={checkShaderErrors:!0,diagnostics:{keywords:!1},onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=na,this.toneMappingExposure=1,this.transmissionResolutionScale=1;const T=this;let L=!1,P=null,z=null,R=null,B=null;this._outputColorSpace=bi;let K=0,N=0,V=null,Z=-1,te=null;const ce=new nn,Ne=new nn;let He=null;const ct=new It(0);let ot=0,ft=t.width,ne=t.height,oe=1,Te=null,We=null;const Re=new nn(0,0,ft,ne),$=new nn(0,0,ft,ne);let H=!1;const Y=new ak;let j=!1,de=!1;const fe=new en,Ve=new X,st=new nn,kt={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0};let Ue=!1;function Ze(){return V===null?oe:1}let F=i;function lt(E,G){return t.getContext(E,G)}let Je,I,k,W,J,ae,ve,be,se,re,ke,Fe,Me,_e,Xe,nt,ht,q,Se,le,Ae,$e,me;try{const E={alpha:!0,depth:a,stencil:s,antialias:r,premultipliedAlpha:l,preserveDrawingBuffer:c,powerPreference:p,failIfMajorPerformanceCaveat:h};if("setAttribute"in t&&t.setAttribute("data-engine",`three.js r${Lg}`),t.addEventListener("webglcontextlost",Kt,!1),t.addEventListener("webglcontextrestored",zt,!1),t.addEventListener("webglcontextcreationerror",Hi,!1),F===null){const G="webgl2";if(F=lt(G,E),F===null)throw lt(G)?new Error("THREE.WebGLRenderer: Error creating WebGL context with your selected attributes."):new Error("THREE.WebGLRenderer: Error creating WebGL context.")}et()}catch(E){throw t.removeEventListener("webglcontextlost",Kt,!1),t.removeEventListener("webglcontextrestored",zt,!1),t.removeEventListener("webglcontextcreationerror",Hi,!1),Pt("WebGLRenderer: "+E.message),E}function et(){Je=new jP(F),Je.init(),Ae=new BI(F,Je),I=new FP(F,Je,e,Ae),k=new UI(F,Je),I.reversedDepthBuffer&&d&&k.buffers.depth.setReversed(!0),z=F.createFramebuffer(),R=F.createFramebuffer(),B=F.createFramebuffer(),W=new QP(F),J=new MI,ae=new FI(F,Je,k,J,I,Ae,W),ve=new YP(T),be=new N5(F),$e=new OP(F,be),se=new ZP(F,be,W,$e),re=new t6(F,se,be,$e,W),q=new e6(F,I,ae),Xe=new BP(J),ke=new SI(T,ve,Je,I,$e,Xe),Fe=new XI(T,J),Me=new TI,_e=new II(Je),ht=new zP(T,ve,k,re,f,l),nt=new OI(T,re,I),me=new KI(F,W,I,k),Se=new UP(F,Je,W),le=new JP(F,Je,W),W.programs=ke.programs,T.capabilities=I,T.extensions=Je,T.properties=J,T.renderLists=Me,T.shadowMap=nt,T.state=k,T.info=W}v!==xi&&(M=new i6(v,t.width,t.height,r,a,s));const Ke=new VI(T,F);this.xr=Ke,this.getContext=function(){return F},this.getContextAttributes=function(){return F.getContextAttributes()},this.forceContextLoss=function(){const E=Je.get("WEBGL_lose_context");E&&E.loseContext()},this.forceContextRestore=function(){const E=Je.get("WEBGL_lose_context");E&&E.restoreContext()},this.getPixelRatio=function(){return oe},this.setPixelRatio=function(E){E!==void 0&&(oe=E,this.setSize(ft,ne,!1))},this.getSize=function(E){return E.set(ft,ne)},this.setSize=function(E,G,ie=!0){if(Ke.isPresenting){rt("WebGLRenderer: Can't change size while VR device is presenting.");return}ft=E,ne=G,t.width=Math.floor(E*oe),t.height=Math.floor(G*oe),ie===!0&&(t.style.width=E+"px",t.style.height=G+"px"),M!==null&&M.setSize(t.width,t.height),this.setViewport(0,0,E,G)},this.getDrawingBufferSize=function(E){return E.set(ft*oe,ne*oe).floor()},this.setDrawingBufferSize=function(E,G,ie){ft=E,ne=G,oe=ie,t.width=Math.floor(E*ie),t.height=Math.floor(G*ie),this.setViewport(0,0,E,G)},this.setEffects=function(E){if(v===xi){Pt("WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.");return}if(E){for(let G=0;G<E.length;G++)if(E[G].isOutputPass===!0){rt("WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.");break}}M.setEffects(E||[])},this.getCurrentViewport=function(E){return E.copy(ce)},this.getViewport=function(E){return E.copy(Re)},this.setViewport=function(E,G,ie,Q){E.isVector4?Re.set(E.x,E.y,E.z,E.w):Re.set(E,G,ie,Q),k.viewport(ce.copy(Re).multiplyScalar(oe).round())},this.getScissor=function(E){return E.copy($)},this.setScissor=function(E,G,ie,Q){E.isVector4?$.set(E.x,E.y,E.z,E.w):$.set(E,G,ie,Q),k.scissor(Ne.copy($).multiplyScalar(oe).round())},this.getScissorTest=function(){return H},this.setScissorTest=function(E){k.setScissorTest(H=E)},this.setOpaqueSort=function(E){Te=E},this.setTransparentSort=function(E){We=E},this.getClearColor=function(E){return E.copy(ht.getClearColor())},this.setClearColor=function(){ht.setClearColor(...arguments)},this.getClearAlpha=function(){return ht.getClearAlpha()},this.setClearAlpha=function(){ht.setClearAlpha(...arguments)},this.clear=function(E=!0,G=!0,ie=!0){let Q=0;if(E){let ee=!1;if(V!==null){const Pe=V.texture.format;ee=g.has(Pe)}if(ee){const Pe=V.texture.type,Oe=m.has(Pe),Le=ht.getClearColor(),Ge=ht.getClearAlpha(),Ye=Le.r,vt=Le.g,wt=Le.b;Oe?(x[0]=Ye,x[1]=vt,x[2]=wt,x[3]=Ge,F.clearBufferuiv(F.COLOR,0,x)):(_[0]=Ye,_[1]=vt,_[2]=wt,_[3]=Ge,F.clearBufferiv(F.COLOR,0,_))}else Q|=F.COLOR_BUFFER_BIT}G&&(Q|=F.DEPTH_BUFFER_BIT,this.state.buffers.depth.setMask(!0)),ie&&(Q|=F.STENCIL_BUFFER_BIT,this.state.buffers.stencil.setMask(4294967295)),Q!==0&&F.clear(Q)},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.setNodesHandler=function(E){E.setRenderer(this),P=E},this.dispose=function(){t.removeEventListener("webglcontextlost",Kt,!1),t.removeEventListener("webglcontextrestored",zt,!1),t.removeEventListener("webglcontextcreationerror",Hi,!1),ht.dispose(),Me.dispose(),_e.dispose(),J.dispose(),ve.dispose(),re.dispose(),$e.dispose(),me.dispose(),ke.dispose(),Ke.dispose(),Ke.removeEventListener("sessionstart",gS),Ke.removeEventListener("sessionend",vS),Fo.stop()};function Kt(E){E.preventDefault(),D2("WebGLRenderer: Context Lost."),L=!0}function zt(){D2("WebGLRenderer: Context Restored."),L=!1;const E=W.autoReset,G=nt.enabled,ie=nt.autoUpdate,Q=nt.needsUpdate,ee=nt.type;et(),W.autoReset=E,nt.enabled=G,nt.autoUpdate=ie,nt.needsUpdate=Q,nt.type=ee}function Hi(E){Pt("WebGLRenderer: A WebGL context could not be created. Reason: ",E.statusMessage)}function fa(E){const G=E.target;G.removeEventListener("dispose",fa),sz(G)}function sz(E){oz(E),J.remove(E)}function oz(E){const G=J.get(E).programs;G!==void 0&&(G.forEach(function(ie){ke.releaseProgram(ie)}),E.isShaderMaterial&&ke.releaseShaderCache(E))}this.renderBufferDirect=function(E,G,ie,Q,ee,Pe){G===null&&(G=kt);const Oe=ee.isMesh&&ee.matrixWorld.determinantAffine()<0,Le=cz(E,G,ie,Q,ee);k.setMaterial(Q,Oe);let Ge=ie.index,Ye=1;if(Q.wireframe===!0){if(Ge=se.getWireframeAttribute(ie),Ge===void 0)return;Ye=2}const vt=ie.drawRange,wt=ie.attributes.position;let qe=vt.start*Ye,Ot=(vt.start+vt.count)*Ye;Pe!==null&&(qe=Math.max(qe,Pe.start*Ye),Ot=Math.min(Ot,(Pe.start+Pe.count)*Ye)),Ge!==null?(qe=Math.max(qe,0),Ot=Math.min(Ot,Ge.count)):wt!=null&&(qe=Math.max(qe,0),Ot=Math.min(Ot,wt.count));const hn=Ot-qe;if(hn<0||hn===1/0)return;$e.setup(ee,Q,Le,ie,Ge);let Zt,Xt=Se;if(Ge!==null&&(Zt=be.get(Ge),Xt=le,Xt.setIndex(Zt)),ee.isMesh)Q.wireframe===!0?(k.setLineWidth(Q.wireframeLinewidth*Ze()),Xt.setMode(F.LINES)):Xt.setMode(F.TRIANGLES);else if(ee.isLine){let Nn=Q.linewidth;Nn===void 0&&(Nn=1),k.setLineWidth(Nn*Ze()),ee.isLineSegments?Xt.setMode(F.LINES):ee.isLineLoop?Xt.setMode(F.LINE_LOOP):Xt.setMode(F.LINE_STRIP)}else ee.isPoints?Xt.setMode(F.POINTS):ee.isSprite&&Xt.setMode(F.TRIANGLES);if(ee.isBatchedMesh)if(Je.get("WEBGL_multi_draw"))Xt.renderMultiDraw(ee._multiDrawStarts,ee._multiDrawCounts,ee._multiDrawCount);else{const Nn=ee._multiDrawStarts,ze=ee._multiDrawCounts,Kn=ee._multiDrawCount,Ct=Ge?be.get(Ge).bytesPerElement:1,ki=J.get(Q).currentProgram.getUniforms();for(let ma=0;ma<Kn;ma++)ki.setValue(F,"_gl_DrawID",ma),Xt.render(Nn[ma]/Ct,ze[ma])}else if(ee.isInstancedMesh)Xt.renderInstances(qe,hn,ee.count);else if(ie.isInstancedBufferGeometry){const Nn=ie._maxInstanceCount!==void 0?ie._maxInstanceCount:1/0,ze=Math.min(ie.instanceCount,Nn);Xt.renderInstances(qe,hn,ze)}else Xt.render(qe,hn)};function mS(E,G,ie,Q){P!==null&&E.isNodeMaterial&&P.setObject(Q,E),j===!0&&Xe.setState(E,ie,!1),E.transparent===!0&&E.side===Na&&E.forceSinglePass===!1?(E.side=ei,E.needsUpdate=!0,yu(E,G,Q),E.side=wo,E.needsUpdate=!0,yu(E,G,Q),E.side=Na):yu(E,G,Q)}this.compile=function(E,G,ie=null){ie===null&&(ie=E),P!==null&&P.renderStart(E,G,ie),A=_e.get(ie),A.init(G),y.push(A),ie.traverseVisible(function(ee){ee.isLight&&ee.layers.test(G.layers)&&(A.pushLight(ee),ee.castShadow&&A.pushShadow(ee))}),E!==ie&&E.traverseVisible(function(ee){ee.isLight&&ee.layers.test(G.layers)&&(A.pushLight(ee),ee.castShadow&&A.pushShadow(ee))}),A.setupLights(),P!==null&&P.updateLights(A.state.lightsArray),de=this.localClippingEnabled,j=Xe.init(this.clippingPlanes,de),j===!0&&Xe.setGlobalState(this.clippingPlanes,G),P!==null&&nt.render(A.state.shadowsArray,ie,G);const Q=new Set;return E.traverse(function(ee){if(!(ee.isMesh||ee.isPoints||ee.isLine||ee.isSprite))return;const Pe=ee.material;if(Pe)if(Array.isArray(Pe))for(let Oe=0;Oe<Pe.length;Oe++){const Le=Pe[Oe];mS(Le,ie,G,ee),Q.add(Le)}else mS(Pe,ie,G,ee),Q.add(Pe)}),A=y.pop(),P!==null&&P.renderEnd(),Q},this.compileAsync=function(E,G,ie=null){const Q=this.compile(E,G,ie);return new Promise(ee=>{function Pe(){if(Q.forEach(function(Oe){const Ge=J.get(Oe).currentProgram;(Ge===void 0||Ge.isReady())&&Q.delete(Oe)}),Q.size===0){ee(E);return}setTimeout(Pe,10)}Je.get("KHR_parallel_shader_compile")!==null?Pe():setTimeout(Pe,10)})};let cb=null;function rz(E){cb&&cb(E)}function gS(){Fo.stop()}function vS(){Fo.start()}const Fo=new kk;Fo.setAnimationLoop(rz),typeof self<"u"&&Fo.setContext(self),this.setAnimationLoop=function(E){cb=E,Ke.setAnimationLoop(E),E===null?Fo.stop():Fo.start()},Ke.addEventListener("sessionstart",gS),Ke.addEventListener("sessionend",vS),this.render=function(E,G){if(G!==void 0&&G.isCamera!==!0){Pt("WebGLRenderer.render: camera is not an instance of THREE.Camera.");return}if(L===!0)return;P!==null&&P.renderStart(E,G);const ie=Ke.enabled===!0&&Ke.isPresenting===!0,Q=M!==null&&(V===null||ie)&&M.begin(T,V);if(E.matrixWorldAutoUpdate===!0&&E.updateMatrixWorld(),G.parent===null&&G.matrixWorldAutoUpdate===!0&&G.updateMatrixWorld(),Ke.enabled===!0&&Ke.isPresenting===!0&&(M===null||M.isCompositing()===!1)&&(Ke.cameraAutoUpdate===!0&&Ke.updateCamera(G),G=Ke.getCamera()),E.isScene===!0&&E.onBeforeRender(T,E,G,V),A=_e.get(E,y.length),A.init(G),A.state.textureUnits=ae.getTextureUnits(),y.push(A),fe.multiplyMatrices(G.projectionMatrix,G.matrixWorldInverse),Y.setFromProjectionMatrix(fe,oa,G.reversedDepth),de=this.localClippingEnabled,j=Xe.init(this.clippingPlanes,de),S=Me.get(E,C.length),S.init(),C.push(S),Ke.enabled===!0&&Ke.isPresenting===!0){const Oe=T.xr.getDepthSensingMesh();Oe!==null&&db(Oe,G,-1/0,T.sortObjects)}db(E,G,0,T.sortObjects),S.finish(),P!==null&&P.updateLights(A.state.lightsArray),T.sortObjects===!0&&S.sort(Te,We),Ue=Ke.enabled===!1||Ke.isPresenting===!1||Ke.hasDepthSensing()===!1,Ue&&ht.addToRenderList(S,E),this.info.render.frame++,this.info.autoReset===!0&&this.info.reset(),j===!0&&Xe.beginShadows();const ee=A.state.shadowsArray;if(nt.render(ee,E,G),j===!0&&Xe.endShadows(),(Q&&M.hasRenderPass())===!1){const Oe=S.opaque,Le=S.transmissive;if(A.setupLights(),G.isArrayCamera){const Ge=G.cameras;if(Le.length>0)for(let Ye=0,vt=Ge.length;Ye<vt;Ye++){const wt=Ge[Ye];bS(Oe,Le,E,wt)}Ue&&ht.render(E);for(let Ye=0,vt=Ge.length;Ye<vt;Ye++){const wt=Ge[Ye];xS(S,E,wt,wt.viewport)}}else Le.length>0&&bS(Oe,Le,E,G),Ue&&ht.render(E),xS(S,E,G)}V!==null&&N===0&&(ae.updateMultisampleRenderTarget(V),ae.updateRenderTargetMipmap(V)),Q&&M.end(T),E.isScene===!0&&E.onAfterRender(T,E,G),$e.resetDefaultState(),Z=-1,te=null,y.pop(),y.length>0?(A=y[y.length-1],ae.setTextureUnits(A.state.textureUnits),j===!0&&Xe.setGlobalState(T.clippingPlanes,A.state.camera)):A=null,C.pop(),C.length>0?S=C[C.length-1]:S=null,P!==null&&P.renderEnd()};function db(E,G,ie,Q){if(E.visible===!1)return;if(E.layers.test(G.layers)){if(E.isGroup)ie=E.renderOrder;else if(E.isLOD)E.autoUpdate===!0&&E.update(G);else if(E.isLightProbeGrid)A.pushLightProbeGrid(E);else if(E.isLight)A.pushLight(E),E.castShadow&&A.pushShadow(E);else if(E.isSprite){if(!E.frustumCulled||E.intersectsFrustum(Y)){Q&&st.setFromMatrixPosition(E.matrixWorld).applyMatrix4(fe);const Oe=re.update(E),Le=E.material;Le.visible&&S.push(E,Oe,Le,ie,st.z,null,G)}}else if((E.isMesh||E.isLine||E.isPoints)&&(!E.frustumCulled||E.intersectsFrustum(Y))){const Oe=re.update(E),Le=E.material;if(Q&&(E.boundingSphere!==void 0?(E.boundingSphere===null&&E.computeBoundingSphere(),st.copy(E.boundingSphere.center)):(Oe.boundingSphere===null&&Oe.computeBoundingSphere(),st.copy(Oe.boundingSphere.center)),st.applyMatrix4(E.matrixWorld).applyMatrix4(fe)),Array.isArray(Le)){const Ge=Oe.groups;for(let Ye=0,vt=Ge.length;Ye<vt;Ye++){const wt=Ge[Ye],qe=Le[wt.materialIndex];qe&&qe.visible&&S.push(E,Oe,qe,ie,st.z,wt,G)}}else Le.visible&&S.push(E,Oe,Le,ie,st.z,null,G)}}const Pe=E.children;for(let Oe=0,Le=Pe.length;Oe<Le;Oe++)db(Pe[Oe],G,ie,Q)}function xS(E,G,ie,Q){const{opaque:ee,transmissive:Pe,transparent:Oe}=E;A.setupLightsView(ie),j===!0&&Xe.setGlobalState(T.clippingPlanes,ie),Q&&k.viewport(ce.copy(Q)),ee.length>0&&bu(ee,G,ie),Pe.length>0&&bu(Pe,G,ie),Oe.length>0&&bu(Oe,G,ie),k.buffers.depth.setTest(!0),k.buffers.depth.setMask(!0),k.buffers.color.setMask(!0),k.setPolygonOffset(!1)}function bS(E,G,ie,Q){if((ie.isScene===!0?ie.overrideMaterial:null)!==null)return;if(A.state.transmissionRenderTarget[Q.id]===void 0){const qe=Je.has("EXT_color_buffer_half_float")||Je.has("EXT_color_buffer_float");A.state.transmissionRenderTarget[Q.id]=new $i(1,1,{generateMipmaps:!0,type:qe?sa:xi,minFilter:_o,samples:Math.max(4,I.samples),stencilBuffer:s,resolveDepthBuffer:!1,resolveStencilBuffer:!1,storeMultisampledDepthBuffer:!1,storeMultisampledStencilBuffer:!1,colorSpace:St.workingColorSpace})}const Pe=A.state.transmissionRenderTarget[Q.id],Oe=Q.viewport||ce;Pe.setSize(Oe.z*T.transmissionResolutionScale,Oe.w*T.transmissionResolutionScale);const Le=T.getRenderTarget(),Ge=T.getActiveCubeFace(),Ye=T.getActiveMipmapLevel();T.setRenderTarget(Pe),T.getClearColor(ct),ot=T.getClearAlpha(),ot<1&&T.setClearColor(16777215,.5),T.clear(),Ue&&ht.render(ie);const vt=T.toneMapping;T.toneMapping=na;const wt=Q.viewport;if(Q.viewport!==void 0&&(Q.viewport=void 0),A.setupLightsView(Q),j===!0&&Xe.setGlobalState(T.clippingPlanes,Q),bu(E,ie,Q),ae.updateMultisampleRenderTarget(Pe),ae.updateRenderTargetMipmap(Pe),Je.has("WEBGL_multisampled_render_to_texture")===!1){let qe=!1;for(let Ot=0,hn=G.length;Ot<hn;Ot++){const Zt=G[Ot],{object:Xt,geometry:Nn,material:ze,group:Kn}=Zt;if(ze.side===Na&&Xt.layers.test(Q.layers)){const Ct=ze.side;ze.side=ei,ze.needsUpdate=!0,yS(Xt,ie,Q,Nn,ze,Kn),ze.side=Ct,ze.needsUpdate=!0,qe=!0}}qe===!0&&(ae.updateMultisampleRenderTarget(Pe),ae.updateRenderTargetMipmap(Pe))}T.setRenderTarget(Le,Ge,Ye),T.setClearColor(ct,ot),wt!==void 0&&(Q.viewport=wt),T.toneMapping=vt}function bu(E,G,ie){const Q=G.isScene===!0?G.overrideMaterial:null;for(let ee=0,Pe=E.length;ee<Pe;ee++){const Oe=E[ee],{object:Le,geometry:Ge,group:Ye}=Oe;let vt=Oe.material;vt.allowOverride===!0&&Q!==null&&(vt=Q),Le.layers.test(ie.layers)&&yS(Le,G,ie,Ge,vt,Ye)}}function yS(E,G,ie,Q,ee,Pe){P!==null&&ee.isNodeMaterial&&P.setObject(E,ee),E.onBeforeRender(T,G,ie,Q,ee,Pe),E.modelViewMatrix.multiplyMatrices(ie.matrixWorldInverse,E.matrixWorld),E.normalMatrix.getNormalMatrix(E.modelViewMatrix),ee.onBeforeRender(T,G,ie,Q,E,Pe),ee.transparent===!0&&ee.side===Na&&ee.forceSinglePass===!1?(ee.side=ei,ee.needsUpdate=!0,T.renderBufferDirect(ie,G,Q,ee,E,Pe),ee.side=wo,ee.needsUpdate=!0,T.renderBufferDirect(ie,G,Q,ee,E,Pe),ee.side=Na):T.renderBufferDirect(ie,G,Q,ee,E,Pe),E.onAfterRender(T,G,ie,Q,ee,Pe)}function yu(E,G,ie){G.isScene!==!0&&(G=kt);const Q=J.get(E),ee=A.state.lights,Pe=A.state.shadowsArray,Oe=ee.state.version,Le=ke.getParameters(E,ee.state,Pe,G,ie,A.state.lightProbeGridArray),Ge=ke.getProgramCacheKey(Le);let Ye=Q.programs;Q.environment=E.isMeshStandardMaterial||E.isMeshLambertMaterial||E.isMeshPhongMaterial?G.environment:null,Q.fog=G.fog;const vt=E.isMeshStandardMaterial||E.isMeshLambertMaterial&&!E.envMap||E.isMeshPhongMaterial&&!E.envMap;Q.envMap=ve.get(E.envMap||Q.environment,vt),Q.envMapRotation=Q.environment!==null&&E.envMap===null?G.environmentRotation:E.envMapRotation,Ye===void 0&&(E.addEventListener("dispose",fa),Ye=new Map,Q.programs=Ye);let wt=Ye.get(Ge);if(wt!==void 0){if(Q.currentProgram===wt&&Q.lightsStateVersion===Oe)return kS(E,Le),wt}else Le.uniforms=ke.getUniforms(E),P!==null&&E.isNodeMaterial&&P.build(E,ie,Le),E.onBeforeCompile(Le,T),wt=ke.acquireProgram(Le,Ge),Ye.set(Ge,wt),Q.uniforms=Le.uniforms;const qe=Q.uniforms;return(!E.isShaderMaterial&&!E.isRawShaderMaterial||E.clipping===!0)&&(qe.clippingPlanes=Xe.uniform),kS(E,Le),Q.needsLights=pz(E),Q.lightsStateVersion=Oe,Q.needsLights&&(qe.ambientLightColor.value=ee.state.ambient,qe.lightProbe.value=ee.state.probe,qe.sunLights.value=ee.state.sun,qe.sunLightShadows.value=ee.state.sunShadow,qe.directionalLights.value=ee.state.directional,qe.directionalLightShadows.value=ee.state.directionalShadow,qe.spotLights.value=ee.state.spot,qe.spotLightShadows.value=ee.state.spotShadow,qe.rectAreaLights.value=ee.state.rectArea,qe.ltc_1.value=ee.state.rectAreaLTC1,qe.ltc_2.value=ee.state.rectAreaLTC2,qe.pointLights.value=ee.state.point,qe.pointLightShadows.value=ee.state.pointShadow,qe.hemisphereLights.value=ee.state.hemi,qe.sunShadowMatrix.value=ee.state.sunShadowMatrix,qe.sunShadowCascade.value=ee.state.sunShadowCascade,qe.directionalShadowMatrix.value=ee.state.directionalShadowMatrix,qe.spotLightMatrix.value=ee.state.spotLightMatrix,qe.spotLightMap.value=ee.state.spotLightMap,qe.pointShadowMatrix.value=ee.state.pointShadowMatrix),Q.lightProbeGrid=A.state.lightProbeGridArray.length>0,Q.currentProgram=wt,Q.uniformsList=null,wt}function wS(E){if(E.uniformsList===null){const G=E.currentProgram.getUniforms();E.uniformsList=Vh.seqWithValue(G.seq,E.uniforms)}return E.uniformsList}function kS(E,G){const ie=J.get(E);ie.outputColorSpace=G.outputColorSpace,ie.batching=G.batching,ie.batchingColor=G.batchingColor,ie.instancing=G.instancing,ie.instancingColor=G.instancingColor,ie.instancingMorph=G.instancingMorph,ie.skinning=G.skinning,ie.morphTargets=G.morphTargets,ie.morphNormals=G.morphNormals,ie.morphColors=G.morphColors,ie.morphTargetsCount=G.morphTargetsCount,ie.numClippingPlanes=G.numClippingPlanes,ie.numIntersection=G.numClipIntersection,ie.vertexAlphas=G.vertexAlphas,ie.vertexTangents=G.vertexTangents,ie.toneMapping=G.toneMapping}function lz(E,G){if(E.length===0)return null;if(E.length===1)return E[0].texture!==null?E[0]:null;w.setFromMatrixPosition(G.matrixWorld);for(let ie=0,Q=E.length;ie<Q;ie++){const ee=E[ie];if(ee.texture!==null&&ee.boundingBox.containsPoint(w))return ee}return null}function cz(E,G,ie,Q,ee){G.isScene!==!0&&(G=kt),ae.resetTextureUnits();const Pe=G.fog,Oe=Q.isMeshStandardMaterial||Q.isMeshLambertMaterial||Q.isMeshPhongMaterial?G.environment:null,Le=V===null?T.outputColorSpace:V.isXRRenderTarget===!0?V.texture.colorSpace:St.workingColorSpace,Ge=Q.isMeshStandardMaterial||Q.isMeshLambertMaterial&&!Q.envMap||Q.isMeshPhongMaterial&&!Q.envMap,Ye=ve.get(Q.envMap||Oe,Ge),vt=Q.vertexColors===!0&&!!ie.attributes.color&&ie.attributes.color.itemSize===4,wt=!!ie.attributes.tangent&&(!!Q.normalMap||Q.anisotropy>0),qe=!!ie.morphAttributes.position,Ot=!!ie.morphAttributes.normal,hn=!!ie.morphAttributes.color;let Zt=na;Q.toneMapped&&(V===null||V.isXRRenderTarget===!0)&&(Zt=T.toneMapping);const Xt=ie.morphAttributes.position||ie.morphAttributes.normal||ie.morphAttributes.color,Nn=Xt!==void 0?Xt.length:0,ze=J.get(Q),Kn=A.state.lights;if(j===!0&&(de===!0||E!==te)){const Yt=E===te&&Q.id===Z;Xe.setState(Q,E,Yt)}let Ct=!1;Q.version===ze.__version?(ze.needsLights&&ze.lightsStateVersion!==Kn.state.version||ze.outputColorSpace!==Le||ee.isBatchedMesh&&ze.batching===!1||!ee.isBatchedMesh&&ze.batching===!0||ee.isBatchedMesh&&ze.batchingColor===!0&&ee._colorsTexture===null||ee.isBatchedMesh&&ze.batchingColor===!1&&ee._colorsTexture!==null||ee.isInstancedMesh&&ze.instancing===!1||!ee.isInstancedMesh&&ze.instancing===!0||ee.isSkinnedMesh&&ze.skinning===!1||!ee.isSkinnedMesh&&ze.skinning===!0||ee.isInstancedMesh&&ze.instancingColor===!0&&ee.instanceColor===null||ee.isInstancedMesh&&ze.instancingColor===!1&&ee.instanceColor!==null||ee.isInstancedMesh&&ze.instancingMorph===!0&&ee.morphTexture===null||ee.isInstancedMesh&&ze.instancingMorph===!1&&ee.morphTexture!==null||ze.envMap!==Ye||Q.fog===!0&&ze.fog!==Pe||ze.numClippingPlanes!==void 0&&(ze.numClippingPlanes!==Xe.numPlanes||ze.numIntersection!==Xe.numIntersection)||ze.vertexAlphas!==vt||ze.vertexTangents!==wt||ze.morphTargets!==qe||ze.morphNormals!==Ot||ze.morphColors!==hn||ze.toneMapping!==Zt||ze.morphTargetsCount!==Nn||!!ze.lightProbeGrid!=A.state.lightProbeGridArray.length>0)&&(Ct=!0):(Ct=!0,ze.__version=Q.version);let ki=ze.currentProgram;Ct===!0&&(ki=yu(Q,G,ee),P&&Q.isNodeMaterial&&P.onUpdateProgram(Q,ki,ze));let ma=!1,Gs=!1,al=!1;const Vt=ki.getUniforms(),ln=ze.uniforms;if(k.useProgram(ki.program)&&(ma=!0,Gs=!0,al=!0),Q.id!==Z&&(Z=Q.id,Gs=!0),ze.needsLights){const Yt=lz(A.state.lightProbeGridArray,ee);ze.lightProbeGrid!==Yt&&(ze.lightProbeGrid=Yt,Gs=!0)}if(ma||te!==E){k.buffers.depth.getReversed()&&E.reversedDepth!==!0&&(E._reversedDepth=!0,E.updateProjectionMatrix()),Vt.setValue(F,"projectionMatrix",E.projectionMatrix),Vt.setValue(F,"viewMatrix",E.matrixWorldInverse);const Vs=Vt.map.cameraPosition;Vs!==void 0&&Vs.setValue(F,Ve.setFromMatrixPosition(E.matrixWorld)),I.logarithmicDepthBuffer&&Vt.setValue(F,"logDepthBufFC",2/(Math.log(E.far+1)/Math.LN2)),(Q.isMeshPhongMaterial||Q.isMeshToonMaterial||Q.isMeshLambertMaterial||Q.isMeshBasicMaterial||Q.isMeshStandardMaterial||Q.isShaderMaterial)&&Vt.setValue(F,"isOrthographic",E.isOrthographicCamera===!0),te!==E&&(te=E,Gs=!0,al=!0)}if(ze.needsLights&&(Kn.state.sunShadowMap.length>0&&Vt.setValue(F,"sunShadowMap",Kn.state.sunShadowMap,ae),Kn.state.directionalShadowMap.length>0&&Vt.setValue(F,"directionalShadowMap",Kn.state.directionalShadowMap,ae),Kn.state.spotShadowMap.length>0&&Vt.setValue(F,"spotShadowMap",Kn.state.spotShadowMap,ae),Kn.state.pointShadowMap.length>0&&Vt.setValue(F,"pointShadowMap",Kn.state.pointShadowMap,ae)),ee.isSkinnedMesh){Vt.setOptional(F,ee,"bindMatrix"),Vt.setOptional(F,ee,"bindMatrixInverse");const Yt=ee.skeleton;Yt&&(Yt.boneTexture===null&&Yt.computeBoneTexture(),Vt.setValue(F,"boneTexture",Yt.boneTexture,ae))}ee.isBatchedMesh&&(Vt.setOptional(F,ee,"batchingTexture"),Vt.setValue(F,"batchingTexture",ee._matricesTexture,ae),Vt.setOptional(F,ee,"batchingIdTexture"),Vt.setValue(F,"batchingIdTexture",ee._indirectTexture,ae),Vt.setOptional(F,ee,"batchingColorTexture"),ee._colorsTexture!==null&&Vt.setValue(F,"batchingColorTexture",ee._colorsTexture,ae));const qs=ie.morphAttributes;if((qs.position!==void 0||qs.normal!==void 0||qs.color!==void 0)&&q.update(ee,ie,ki),(Gs||ze.receiveShadow!==ee.receiveShadow)&&(ze.receiveShadow=ee.receiveShadow,Vt.setValue(F,"receiveShadow",ee.receiveShadow)),(Q.isMeshStandardMaterial||Q.isMeshLambertMaterial||Q.isMeshPhongMaterial)&&Q.envMap===null&&G.environment!==null&&(ln.envMapIntensity.value=G.environmentIntensity),ln.dfgLUT!==void 0&&(ln.dfgLUT.value=jI()),Gs){if(Vt.setValue(F,"toneMappingExposure",T.toneMappingExposure),ze.needsLights&&dz(ln,al),Pe&&Q.fog===!0&&Fe.refreshFogUniforms(ln,Pe),Fe.refreshMaterialUniforms(ln,Q,oe,ne,A.state.transmissionRenderTarget[E.id]),ze.needsLights&&ze.lightProbeGrid){const Yt=ze.lightProbeGrid;ln.probesSH.value=Yt.texture,ln.probesMin.value.copy(Yt.boundingBox.min),ln.probesMax.value.copy(Yt.boundingBox.max),ln.probesResolution.value.copy(Yt.resolution)}Vh.upload(F,wS(ze),ln,ae)}if(Q.isShaderMaterial&&Q.uniformsNeedUpdate===!0&&(Vh.upload(F,wS(ze),ln,ae),Q.uniformsNeedUpdate=!1),Q.isSpriteMaterial&&Vt.setValue(F,"center",ee.center),Vt.setValue(F,"modelViewMatrix",ee.modelViewMatrix),Vt.setValue(F,"normalMatrix",ee.normalMatrix),Vt.setValue(F,"modelMatrix",ee.matrixWorld),Q.uniformsGroups!==void 0){const Yt=Q.uniformsGroups;for(let Vs=0,sl=Yt.length;Vs<sl;Vs++){const SS=Yt[Vs];me.update(SS,ki),me.bind(SS,ki)}}return ki}function dz(E,G){E.ambientLightColor.needsUpdate=G,E.lightProbe.needsUpdate=G,E.sunLights.needsUpdate=G,E.sunLightShadows.needsUpdate=G,E.directionalLights.needsUpdate=G,E.directionalLightShadows.needsUpdate=G,E.pointLights.needsUpdate=G,E.pointLightShadows.needsUpdate=G,E.spotLights.needsUpdate=G,E.spotLightShadows.needsUpdate=G,E.rectAreaLights.needsUpdate=G,E.hemisphereLights.needsUpdate=G}function pz(E){return E.isMeshLambertMaterial||E.isMeshToonMaterial||E.isMeshPhongMaterial||E.isMeshStandardMaterial||E.isShadowMaterial||E.isShaderMaterial&&E.lights===!0}this.getActiveCubeFace=function(){return K},this.getActiveMipmapLevel=function(){return N},this.getRenderTarget=function(){return V},this.setRenderTargetTextures=function(E,G,ie){const Q=J.get(E);Q.__autoAllocateDepthBuffer=E.resolveDepthBuffer===!1,Q.__autoAllocateDepthBuffer===!1&&(Q.__useRenderToTexture=!1),J.get(E.texture).__webglTexture=G,J.get(E.depthTexture).__webglTexture=Q.__autoAllocateDepthBuffer?void 0:ie,Q.__hasExternalTextures=!0},this.setRenderTargetFramebuffer=function(E,G){const ie=J.get(E);ie.__webglFramebuffer=G,ie.__useDefaultFramebuffer=G===void 0},this.setRenderTarget=function(E,G=0,ie=0){V=E,K=G,N=ie;let Q=null,ee=!1,Pe=!1;if(E){const Le=J.get(E);if(Le.__useDefaultFramebuffer!==void 0){k.bindFramebuffer(F.FRAMEBUFFER,Le.__webglFramebuffer),ce.copy(E.viewport),Ne.copy(E.scissor),He=E.scissorTest,k.viewport(ce),k.scissor(Ne),k.setScissorTest(He),Z=-1;return}else if(Le.__webglFramebuffer===void 0)ae.setupRenderTarget(E);else if(Le.__hasExternalTextures)ae.rebindTextures(E,J.get(E.texture).__webglTexture,J.get(E.depthTexture).__webglTexture);else if(E.depthBuffer){const vt=E.depthTexture;if(Le.__boundDepthTexture!==vt){if(vt!==null&&J.has(vt)&&(E.width!==vt.image.width||E.height!==vt.image.height))throw new Error("THREE.WebGLRenderer: Attached DepthTexture is initialized to the incorrect size.");ae.setupDepthRenderbuffer(E)}}const Ge=E.texture;(Ge.isData3DTexture||Ge.isDataArrayTexture||Ge.isCompressedArrayTexture)&&(Pe=!0);const Ye=J.get(E).__webglFramebuffer;E.isWebGLCubeRenderTarget?(Array.isArray(Ye[G])?Q=Ye[G][ie]:Q=Ye[G],ee=!0):E.samples>0&&ae.useMultisampledRTT(E)===!1?Q=J.get(E).__webglMultisampledFramebuffer:Array.isArray(Ye)?Q=Ye[ie]:Q=Ye,ce.copy(E.viewport),Ne.copy(E.scissor),He=E.scissorTest}else ce.copy(Re).multiplyScalar(oe).floor(),Ne.copy($).multiplyScalar(oe).floor(),He=H;if(ie!==0&&(Q=z),k.bindFramebuffer(F.FRAMEBUFFER,Q)&&k.drawBuffers(E,Q),k.viewport(ce),k.scissor(Ne),k.setScissorTest(He),ee){const Le=J.get(E.texture);F.framebufferTexture2D(F.FRAMEBUFFER,F.COLOR_ATTACHMENT0,F.TEXTURE_CUBE_MAP_POSITIVE_X+G,Le.__webglTexture,ie)}else if(Pe){const Le=G;for(let Ge=0;Ge<E.textures.length;Ge++){const Ye=J.get(E.textures[Ge]);F.framebufferTextureLayer(F.FRAMEBUFFER,F.COLOR_ATTACHMENT0+Ge,Ye.__webglTexture,ie,Le)}}else if(E!==null&&ie!==0){const Le=J.get(E.texture);F.framebufferTexture2D(F.FRAMEBUFFER,F.COLOR_ATTACHMENT0,F.TEXTURE_2D,Le.__webglTexture,ie)}Z=-1};function _S(E){const G=J.get(E);return(G.__readFormat!==E.format||G.__readType!==E.type)&&(G.__readFormat=E.format,G.__readType=E.type,G.__formatReadable=I.textureFormatReadable(E.format),G.__typeReadable=I.textureTypeReadable(E.type)),G}this.readRenderTargetPixels=function(E,G,ie,Q,ee,Pe,Oe,Le=0){if(!(E&&E.isWebGLRenderTarget)){Pt("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");return}let Ge=J.get(E).__webglFramebuffer;if(E.isWebGLCubeRenderTarget&&Oe!==void 0&&(Ge=Ge[Oe]),Ge){k.bindFramebuffer(F.FRAMEBUFFER,Ge);try{const Ye=E.textures[Le],vt=Ye.format,wt=Ye.type;E.textures.length>1&&F.readBuffer(F.COLOR_ATTACHMENT0+Le);const qe=_S(Ye);if(qe.__formatReadable===!1){Pt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.");return}if(qe.__typeReadable===!1){Pt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.");return}G>=0&&G<=E.width-Q&&ie>=0&&ie<=E.height-ee&&F.readPixels(G,ie,Q,ee,Ae.convert(vt),Ae.convert(wt),Pe)}finally{const Ye=V!==null?J.get(V).__webglFramebuffer:null;k.bindFramebuffer(F.FRAMEBUFFER,Ye)}}},this.readRenderTargetPixelsAsync=async function(E,G,ie,Q,ee,Pe,Oe,Le=0){if(!(E&&E.isWebGLRenderTarget))throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.");let Ge=J.get(E).__webglFramebuffer;if(E.isWebGLCubeRenderTarget&&Oe!==void 0&&(Ge=Ge[Oe]),Ge)if(G>=0&&G<=E.width-Q&&ie>=0&&ie<=E.height-ee){k.bindFramebuffer(F.FRAMEBUFFER,Ge);const Ye=E.textures[Le],vt=Ye.format,wt=Ye.type;E.textures.length>1&&F.readBuffer(F.COLOR_ATTACHMENT0+Le);const qe=_S(Ye);if(qe.__formatReadable===!1)throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.");if(qe.__typeReadable===!1)throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.");const Ot=F.createBuffer();F.bindBuffer(F.PIXEL_PACK_BUFFER,Ot),F.bufferData(F.PIXEL_PACK_BUFFER,Pe.byteLength,F.STREAM_READ),F.readPixels(G,ie,Q,ee,Ae.convert(vt),Ae.convert(wt),0),F.bindBuffer(F.PIXEL_PACK_BUFFER,null);const hn=V!==null?J.get(V).__webglFramebuffer:null;k.bindFramebuffer(F.FRAMEBUFFER,hn);const Zt=F.fenceSync(F.SYNC_GPU_COMMANDS_COMPLETE,0);return F.flush(),await XR(F,Zt,4),F.bindBuffer(F.PIXEL_PACK_BUFFER,Ot),F.getBufferSubData(F.PIXEL_PACK_BUFFER,0,Pe),F.bindBuffer(F.PIXEL_PACK_BUFFER,null),F.deleteBuffer(Ot),F.deleteSync(Zt),Pe}else throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.")},this.copyFramebufferToTexture=function(E,G=null,ie=0){const Q=Math.pow(2,-ie),ee=Math.floor(E.image.width*Q),Pe=Math.floor(E.image.height*Q),Oe=G!==null?G.x:0,Le=G!==null?G.y:0;ae.setTexture2D(E,0),F.copyTexSubImage2D(F.TEXTURE_2D,ie,0,0,Oe,Le,ee,Pe),k.unbindTexture()},this.copyTextureToTexture=function(E,G,ie=null,Q=null,ee=0,Pe=0){let Oe,Le,Ge,Ye,vt,wt,qe,Ot,hn;const Zt=E.isCompressedTexture?E.mipmaps[Pe]:E.image;if(ie!==null)Oe=ie.max.x-ie.min.x,Le=ie.max.y-ie.min.y,Ge=ie.isBox3?ie.max.z-ie.min.z:1,Ye=ie.min.x,vt=ie.min.y,wt=ie.isBox3?ie.min.z:0;else{const ln=Math.pow(2,-ee);Oe=Math.floor(Zt.width*ln),Le=Math.floor(Zt.height*ln),E.isDataArrayTexture?Ge=Zt.depth:E.isData3DTexture?Ge=Math.floor(Zt.depth*ln):Ge=1,Ye=0,vt=0,wt=0}Q!==null?(qe=Q.x,Ot=Q.y,hn=Q.z):(qe=0,Ot=0,hn=0);const Xt=Ae.convert(G.format),Nn=Ae.convert(G.type);let ze;G.isData3DTexture?(ae.setTexture3D(G,0),ze=F.TEXTURE_3D):G.isDataArrayTexture||G.isCompressedArrayTexture?(ae.setTexture2DArray(G,0),ze=F.TEXTURE_2D_ARRAY):(ae.setTexture2D(G,0),ze=F.TEXTURE_2D),k.activeTexture(F.TEXTURE0),k.pixelStorei(F.UNPACK_FLIP_Y_WEBGL,G.flipY),k.pixelStorei(F.UNPACK_PREMULTIPLY_ALPHA_WEBGL,G.premultiplyAlpha),k.pixelStorei(F.UNPACK_ALIGNMENT,G.unpackAlignment);const Kn=k.getParameter(F.UNPACK_ROW_LENGTH),Ct=k.getParameter(F.UNPACK_IMAGE_HEIGHT),ki=k.getParameter(F.UNPACK_SKIP_PIXELS),ma=k.getParameter(F.UNPACK_SKIP_ROWS),Gs=k.getParameter(F.UNPACK_SKIP_IMAGES);k.pixelStorei(F.UNPACK_ROW_LENGTH,Zt.width),k.pixelStorei(F.UNPACK_IMAGE_HEIGHT,Zt.height),k.pixelStorei(F.UNPACK_SKIP_PIXELS,Ye),k.pixelStorei(F.UNPACK_SKIP_ROWS,vt),k.pixelStorei(F.UNPACK_SKIP_IMAGES,wt);const al=E.isDataArrayTexture||E.isData3DTexture,Vt=G.isDataArrayTexture||G.isData3DTexture;if(E.isDepthTexture){const ln=J.get(E),qs=J.get(G),Yt=J.get(ln.__renderTarget),Vs=J.get(qs.__renderTarget);k.bindFramebuffer(F.READ_FRAMEBUFFER,Yt.__webglFramebuffer),k.bindFramebuffer(F.DRAW_FRAMEBUFFER,Vs.__webglFramebuffer);for(let sl=0;sl<Ge;sl++)al&&(F.framebufferTextureLayer(F.READ_FRAMEBUFFER,F.COLOR_ATTACHMENT0,J.get(E).__webglTexture,ee,wt+sl),F.framebufferTextureLayer(F.DRAW_FRAMEBUFFER,F.COLOR_ATTACHMENT0,J.get(G).__webglTexture,Pe,hn+sl)),F.blitFramebuffer(Ye,vt,Oe,Le,qe,Ot,Oe,Le,F.DEPTH_BUFFER_BIT,F.NEAREST);k.bindFramebuffer(F.READ_FRAMEBUFFER,null),k.bindFramebuffer(F.DRAW_FRAMEBUFFER,null)}else if(ee!==0||E.isRenderTargetTexture||J.has(E)){const ln=J.get(E),qs=J.get(G);k.bindFramebuffer(F.READ_FRAMEBUFFER,R),k.bindFramebuffer(F.DRAW_FRAMEBUFFER,B);for(let Yt=0;Yt<Ge;Yt++)al?F.framebufferTextureLayer(F.READ_FRAMEBUFFER,F.COLOR_ATTACHMENT0,ln.__webglTexture,ee,wt+Yt):F.framebufferTexture2D(F.READ_FRAMEBUFFER,F.COLOR_ATTACHMENT0,F.TEXTURE_2D,ln.__webglTexture,ee),Vt?F.framebufferTextureLayer(F.DRAW_FRAMEBUFFER,F.COLOR_ATTACHMENT0,qs.__webglTexture,Pe,hn+Yt):F.framebufferTexture2D(F.DRAW_FRAMEBUFFER,F.COLOR_ATTACHMENT0,F.TEXTURE_2D,qs.__webglTexture,Pe),ee!==0?F.blitFramebuffer(Ye,vt,Oe,Le,qe,Ot,Oe,Le,F.COLOR_BUFFER_BIT,F.NEAREST):Vt?F.copyTexSubImage3D(ze,Pe,qe,Ot,hn+Yt,Ye,vt,Oe,Le):F.copyTexSubImage2D(ze,Pe,qe,Ot,Ye,vt,Oe,Le);k.bindFramebuffer(F.READ_FRAMEBUFFER,null),k.bindFramebuffer(F.DRAW_FRAMEBUFFER,null)}else Vt?E.isDataTexture||E.isData3DTexture?F.texSubImage3D(ze,Pe,qe,Ot,hn,Oe,Le,Ge,Xt,Nn,Zt.data):G.isCompressedArrayTexture?F.compressedTexSubImage3D(ze,Pe,qe,Ot,hn,Oe,Le,Ge,Xt,Zt.data):F.texSubImage3D(ze,Pe,qe,Ot,hn,Oe,Le,Ge,Xt,Nn,Zt):E.isDataTexture?F.texSubImage2D(F.TEXTURE_2D,Pe,qe,Ot,Oe,Le,Xt,Nn,Zt.data):E.isCompressedTexture?F.compressedTexSubImage2D(F.TEXTURE_2D,Pe,qe,Ot,Zt.width,Zt.height,Xt,Zt.data):F.texSubImage2D(F.TEXTURE_2D,Pe,qe,Ot,Oe,Le,Xt,Nn,Zt);k.pixelStorei(F.UNPACK_ROW_LENGTH,Kn),k.pixelStorei(F.UNPACK_IMAGE_HEIGHT,Ct),k.pixelStorei(F.UNPACK_SKIP_PIXELS,ki),k.pixelStorei(F.UNPACK_SKIP_ROWS,ma),k.pixelStorei(F.UNPACK_SKIP_IMAGES,Gs),Pe===0&&G.generateMipmaps&&F.generateMipmap(ze),k.unbindTexture()},this.initRenderTarget=function(E){J.get(E).__webglFramebuffer===void 0&&ae.setupRenderTarget(E)},this.initTexture=function(E){E.isCubeTexture?ae.setTextureCube(E,0):E.isData3DTexture?ae.setTexture3D(E,0):E.isDataArrayTexture||E.isCompressedArrayTexture?ae.setTexture2DArray(E,0):ae.setTexture2D(E,0),k.unbindTexture()},this.resetState=function(){K=0,N=0,V=null,k.reset(),$e.reset()},typeof __THREE_DEVTOOLS__<"u"&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}get coordinateSystem(){return oa}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e;const t=this.getContext();t.drawingBufferColorSpace=St._getDrawingBufferColorSpace(e),t.unpackColorSpace=St._getUnpackColorSpace()}}const Jk={type:"change"},dx={type:"start"},Qk={type:"end"},Xh=new Sh,e_=new Va,JI=Math.cos(70*jR.DEG2RAD),mn=new X,ni=2*Math.PI,Ht={NONE:-1,ROTATE:0,DOLLY:1,PAN:2,TOUCH_ROTATE:3,TOUCH_PAN:4,TOUCH_DOLLY_PAN:5,TOUCH_DOLLY_ROTATE:6},px=1e-6;class QI extends I5{constructor(e,t=null){super(e,t),this.state=Ht.NONE,this.target=new X,this.cursor=new X,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.keyRotateSpeed=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:Sr.ROTATE,MIDDLE:Sr.DOLLY,RIGHT:Sr.PAN},this.touches={ONE:Mr.ROTATE,TWO:Mr.DOLLY_PAN},this.target0=this.target.clone(),this.position0=this.object.position.clone(),this.zoom0=this.object.zoom,this._cursorStyle="auto",this._domElementKeyEvents=null,this._lastPosition=new X,this._lastQuaternion=new Ls,this._lastTargetPosition=new X,this._quat=new Ls().setFromUnitVectors(e.up,new X(0,1,0)),this._quatInverse=this._quat.clone().invert(),this._spherical=new bk,this._sphericalDelta=new bk,this._scale=1,this._panOffset=new X,this._rotateStart=new ut,this._rotateEnd=new ut,this._rotateDelta=new ut,this._panStart=new ut,this._panEnd=new ut,this._panDelta=new ut,this._dollyStart=new ut,this._dollyEnd=new ut,this._dollyDelta=new ut,this._dollyDirection=new X,this._mouse=new ut,this._performCursorZoom=!1,this._pointers=[],this._pointerPositions={},this._controlActive=!1,this._onPointerMove=t$.bind(this),this._onPointerDown=e$.bind(this),this._onPointerUp=n$.bind(this),this._onContextMenu=c$.bind(this),this._onMouseWheel=s$.bind(this),this._onKeyDown=o$.bind(this),this._onTouchStart=r$.bind(this),this._onTouchMove=l$.bind(this),this._onMouseDown=i$.bind(this),this._onMouseMove=a$.bind(this),this._interceptControlDown=d$.bind(this),this._interceptControlUp=p$.bind(this),this.domElement!==null&&this.connect(this.domElement),this.update()}set cursorStyle(e){this._cursorStyle=e,e==="grab"?this.domElement.style.cursor="grab":this.domElement.style.cursor="auto"}get cursorStyle(){return this._cursorStyle}connect(e){super.connect(e),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.state=Ht.NONE,this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.domElement.removeEventListener("pointercancel",this._onPointerUp),this.domElement.removeEventListener("wheel",this._onMouseWheel),this.domElement.removeEventListener("contextmenu",this._onContextMenu),this.stopListenToKeyEvents();const e=this.domElement.getRootNode();e.removeEventListener("keydown",this._interceptControlDown,{capture:!0}),e.removeEventListener("keyup",this._interceptControlUp,{capture:!0}),this._controlActive=!1,this._pointers.length=0,this._pointerPositions={},this.domElement.style.touchAction="",this.domElement.style.cursor="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(Jk),this.update(),this.state=Ht.NONE}pan(e,t){this._pan(e,t),this.update()}dollyIn(e){this._dollyIn(e),this.update()}dollyOut(e){this._dollyOut(e),this.update()}rotateLeft(e){this._rotateLeft(e),this.update()}rotateUp(e){this._rotateUp(e),this.update()}update(e=null){const t=this.object.position;mn.copy(t).sub(this.target),mn.applyQuaternion(this._quat),this._spherical.setFromVector3(mn),this.autoRotate&&this.state===Ht.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 i=this.minAzimuthAngle,a=this.maxAzimuthAngle;isFinite(i)&&isFinite(a)&&(i<-Math.PI?i+=ni:i>Math.PI&&(i-=ni),a<-Math.PI?a+=ni:a>Math.PI&&(a-=ni),i<=a?this._spherical.theta=Math.max(i,Math.min(a,this._spherical.theta)):this._spherical.theta=this._spherical.theta>(i+a)/2?Math.max(i,this._spherical.theta):Math.min(a,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 s=!1;if(this.zoomToCursor&&this._performCursorZoom||this.object.isOrthographicCamera)this._spherical.radius=this._clampDistance(this._spherical.radius);else{const o=this._spherical.radius;this._spherical.radius=this._clampDistance(this._spherical.radius*this._scale),s=o!=this._spherical.radius}if(mn.setFromSpherical(this._spherical),mn.applyQuaternion(this._quatInverse),t.copy(this.target).add(mn),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 o=null;if(this.object.isPerspectiveCamera){const r=mn.length();o=this._clampDistance(r*this._scale);const l=r-o;this.object.position.addScaledVector(this._dollyDirection,l),this.object.updateMatrixWorld(),s=!!l}else if(this.object.isOrthographicCamera){const r=new X(this._mouse.x,this._mouse.y,0);r.unproject(this.object);const l=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),this.object.updateProjectionMatrix(),s=l!==this.object.zoom;const c=new X(this._mouse.x,this._mouse.y,0);c.unproject(this.object),this.object.position.sub(c).add(r),this.object.updateMatrixWorld(),o=mn.length()}else console.warn("WARNING: OrbitControls.js encountered an unknown camera type - zoom to cursor disabled."),this.zoomToCursor=!1;o!==null&&(this.screenSpacePanning?this.target.set(0,0,-1).transformDirection(this.object.matrix).multiplyScalar(o).add(this.object.position):(Xh.origin.copy(this.object.position),Xh.direction.set(0,0,-1).transformDirection(this.object.matrix),Math.abs(this.object.up.dot(Xh.direction))<JI?this.object.lookAt(this.target):(e_.setFromNormalAndCoplanarPoint(this.object.up,this.target),Xh.intersectPlane(e_,this.target))))}else if(this.object.isOrthographicCamera){const o=this.object.zoom;this.object.zoom=Math.max(this.minZoom,Math.min(this.maxZoom,this.object.zoom/this._scale)),o!==this.object.zoom&&(this.object.updateProjectionMatrix(),s=!0)}return this._scale=1,this._performCursorZoom=!1,s||this._lastPosition.distanceToSquared(this.object.position)>px||8*(1-this._lastQuaternion.dot(this.object.quaternion))>px||this._lastTargetPosition.distanceToSquared(this.target)>px?(this.dispatchEvent(Jk),this._lastPosition.copy(this.object.position),this._lastQuaternion.copy(this.object.quaternion),this._lastTargetPosition.copy(this.target),!0):!1}_getAutoRotationAngle(e){return e!==null?ni/60*this.autoRotateSpeed*e:ni/60/60*this.autoRotateSpeed}_getZoomScale(e){const 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){mn.setFromMatrixColumn(t,0),mn.multiplyScalar(-e),this._panOffset.add(mn)}_panUp(e,t){this.screenSpacePanning===!0?mn.setFromMatrixColumn(t,1):(mn.setFromMatrixColumn(t,0),mn.crossVectors(this.object.up,mn)),mn.multiplyScalar(e),this._panOffset.add(mn)}_pan(e,t){const i=this.domElement;if(this.object.isPerspectiveCamera){const a=this.object.position;mn.copy(a).sub(this.target);let s=mn.length();s*=Math.tan(this.object.fov/2*Math.PI/180),this._panLeft(2*e*s/i.clientHeight,this.object.matrix),this._panUp(2*t*s/i.clientHeight,this.object.matrix)}else this.object.isOrthographicCamera?(this._panLeft(e*(this.object.right-this.object.left)/this.object.zoom/i.clientWidth,this.object.matrix),this._panUp(t*(this.object.top-this.object.bottom)/this.object.zoom/i.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;const i=this.domElement.getBoundingClientRect(),a=e-i.left,s=t-i.top,o=i.width,r=i.height;this._mouse.x=a/o*2-1,this._mouse.y=-(s/r)*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);const t=this.domElement;this._rotateLeft(ni*this._rotateDelta.x/t.clientHeight),this._rotateUp(ni*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(ni*this.keyRotateSpeed/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(-ni*this.keyRotateSpeed/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(ni*this.keyRotateSpeed/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(-ni*this.keyRotateSpeed/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{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),a=.5*(e.pageY+t.y);this._rotateStart.set(i,a)}}_handleTouchStartPan(e){if(this._pointers.length===1)this._panStart.set(e.pageX,e.pageY);else{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),a=.5*(e.pageY+t.y);this._panStart.set(i,a)}}_handleTouchStartDolly(e){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,a=e.pageY-t.y,s=Math.sqrt(i*i+a*a);this._dollyStart.set(0,s)}_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{const i=this._getSecondPointerPosition(e),a=.5*(e.pageX+i.x),s=.5*(e.pageY+i.y);this._rotateEnd.set(a,s)}this._rotateDelta.subVectors(this._rotateEnd,this._rotateStart).multiplyScalar(this.rotateSpeed);const t=this.domElement;this._rotateLeft(ni*this._rotateDelta.x/t.clientHeight),this._rotateUp(ni*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{const t=this._getSecondPointerPosition(e),i=.5*(e.pageX+t.x),a=.5*(e.pageY+t.y);this._panEnd.set(i,a)}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){const t=this._getSecondPointerPosition(e),i=e.pageX-t.x,a=e.pageY-t.y,s=Math.sqrt(i*i+a*a);this._dollyEnd.set(0,s),this._dollyDelta.set(0,Math.pow(this._dollyEnd.y/this._dollyStart.y,this.zoomSpeed)),this._dollyOut(this._dollyDelta.y),this._dollyStart.copy(this._dollyEnd);const o=(e.pageX+t.x)*.5,r=(e.pageY+t.y)*.5;this._updateZoomParameters(o,r)}_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 ut,this._pointerPositions[e.pointerId]=t),t.set(e.pageX,e.pageY)}_getSecondPointerPosition(e){const t=e.pointerId===this._pointers[0]?this._pointers[1]:this._pointers[0];return this._pointerPositions[t]}_customWheelEvent(e){const t=e.deltaMode,i={clientX:e.clientX,clientY:e.clientY,deltaY:e.deltaY};switch(t){case 1:i.deltaY*=16;break;case 2:i.deltaY*=100;break}return e.ctrlKey&&!this._controlActive&&(i.deltaY*=10),i}}function e$(n){this.enabled!==!1&&(this._pointers.length===0&&(this.domElement.setPointerCapture(n.pointerId),this.domElement.ownerDocument.addEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.addEventListener("pointerup",this._onPointerUp)),!this._isTrackingPointer(n)&&(this._addPointer(n),n.pointerType==="touch"?this._onTouchStart(n):this._onMouseDown(n),this._cursorStyle==="grab"&&(this.domElement.style.cursor="grabbing")))}function t$(n){this.enabled!==!1&&(n.pointerType==="touch"?this._onTouchMove(n):this._onMouseMove(n))}function n$(n){switch(this._removePointer(n),this._pointers.length){case 0:this.domElement.releasePointerCapture(n.pointerId),this.domElement.ownerDocument.removeEventListener("pointermove",this._onPointerMove),this.domElement.ownerDocument.removeEventListener("pointerup",this._onPointerUp),this.dispatchEvent(Qk),this.state=Ht.NONE,this._cursorStyle==="grab"&&(this.domElement.style.cursor="grab");break;case 1:const e=this._pointers[0],t=this._pointerPositions[e];this._onTouchStart({pointerId:e,pageX:t.x,pageY:t.y});break}}function i$(n){let e;switch(n.button){case 0:e=this.mouseButtons.LEFT;break;case 1:e=this.mouseButtons.MIDDLE;break;case 2:e=this.mouseButtons.RIGHT;break;default:e=-1}switch(e){case Sr.DOLLY:if(this.enableZoom===!1)return;this._handleMouseDownDolly(n),this.state=Ht.DOLLY;break;case Sr.ROTATE:if(n.ctrlKey||n.metaKey||n.shiftKey){if(this.enablePan===!1)return;this._handleMouseDownPan(n),this.state=Ht.PAN}else{if(this.enableRotate===!1)return;this._handleMouseDownRotate(n),this.state=Ht.ROTATE}break;case Sr.PAN:if(n.ctrlKey||n.metaKey||n.shiftKey){if(this.enableRotate===!1)return;this._handleMouseDownRotate(n),this.state=Ht.ROTATE}else{if(this.enablePan===!1)return;this._handleMouseDownPan(n),this.state=Ht.PAN}break;default:this.state=Ht.NONE}this.state!==Ht.NONE&&this.dispatchEvent(dx)}function a$(n){switch(this.state){case Ht.ROTATE:if(this.enableRotate===!1)return;this._handleMouseMoveRotate(n);break;case Ht.DOLLY:if(this.enableZoom===!1)return;this._handleMouseMoveDolly(n);break;case Ht.PAN:if(this.enablePan===!1)return;this._handleMouseMovePan(n);break}}function s$(n){this.enabled===!1||this.enableZoom===!1||this.state!==Ht.NONE||(n.preventDefault(),this.dispatchEvent(dx),this._handleMouseWheel(this._customWheelEvent(n)),this.dispatchEvent(Qk))}function o$(n){this.enabled!==!1&&this._handleKeyDown(n)}function r$(n){switch(this._trackPointer(n),this._pointers.length){case 1:switch(this.touches.ONE){case Mr.ROTATE:if(this.enableRotate===!1)return;this._handleTouchStartRotate(n),this.state=Ht.TOUCH_ROTATE;break;case Mr.PAN:if(this.enablePan===!1)return;this._handleTouchStartPan(n),this.state=Ht.TOUCH_PAN;break;default:this.state=Ht.NONE}break;case 2:switch(this.touches.TWO){case Mr.DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchStartDollyPan(n),this.state=Ht.TOUCH_DOLLY_PAN;break;case Mr.DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchStartDollyRotate(n),this.state=Ht.TOUCH_DOLLY_ROTATE;break;default:this.state=Ht.NONE}break;default:this.state=Ht.NONE}this.state!==Ht.NONE&&this.dispatchEvent(dx)}function l$(n){switch(this._trackPointer(n),this.state){case Ht.TOUCH_ROTATE:if(this.enableRotate===!1)return;this._handleTouchMoveRotate(n),this.update();break;case Ht.TOUCH_PAN:if(this.enablePan===!1)return;this._handleTouchMovePan(n),this.update();break;case Ht.TOUCH_DOLLY_PAN:if(this.enableZoom===!1&&this.enablePan===!1)return;this._handleTouchMoveDollyPan(n),this.update();break;case Ht.TOUCH_DOLLY_ROTATE:if(this.enableZoom===!1&&this.enableRotate===!1)return;this._handleTouchMoveDollyRotate(n),this.update();break;default:this.state=Ht.NONE}}function c$(n){this.enabled!==!1&&n.preventDefault()}function d$(n){n.key==="Control"&&(this._controlActive=!0,this.domElement.getRootNode().addEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function p$(n){n.key==="Control"&&(this._controlActive=!1,this.domElement.getRootNode().removeEventListener("keyup",this._interceptControlUp,{passive:!0,capture:!0}))}function hx(n){let e=2166136261;for(let t=0;t<n.length;t++)e^=n.charCodeAt(t),e=Math.imul(e,16777619);return e>>>0}function Wc(n){let e=n>>>0||2654435769;return()=>{e=e+1831565813|0;let t=Math.imul(e^e>>>15,1|e);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296}}function ux(n){const e=Math.max(1e-9,n());return Math.sqrt(-2*Math.log(e))*Math.cos(2*Math.PI*n())}function zs(n,e,t){let i=Math.imul(n,374761393)+Math.imul(e,668265263)+Math.imul(t,1274126177);return i=Math.imul(i^i>>>13,1274126177),((i^i>>>16)>>>0)/4294967296}function t_(n,e,t){const i=Math.floor(n),a=Math.floor(e),s=Math.floor(t),o=n-i,r=e-a,l=t-s,c=o*o*(3-2*o),p=r*r*(3-2*r),h=l*l*(3-2*l),d=(u,f,v)=>u+(f-u)*v;return d(d(d(zs(i,a,s),zs(i+1,a,s),c),d(zs(i,a+1,s),zs(i+1,a+1,s),c),p),d(d(zs(i,a,s+1),zs(i+1,a,s+1),c),d(zs(i,a+1,s+1),zs(i+1,a+1,s+1),c),p),h)}function h$(n,e,t){const a=1-Math.abs(2*t_(n*5.2+11.3,e*5.2*1.15,t*5.2)-1),s=1-Math.abs(2*t_(n*5.2*2.1,e*5.2*2.1+5.1,t*5.2*2.1-3.7)-1),o=Math.max(Math.pow(a,5),Math.pow(s,7)*.6);return Math.min(1,o*1.25)}const Kr={c:[.4,.06,0],a:[.52,.62,1]},fx={c:[.52,-.27,.14],a:[.3,.25,.56]},n_={c:[.25,-.44,-.66],a:[.3,.2,.3]};function Yr(n,e,t,i){const a=1-.1*Math.max(0,i),s=(e-n.c[0])/(n.a[0]*a);let o=(t-n.c[1])/(n.a[1]*a);o<0&&n===Kr&&(o*=1.35);const r=(i-n.c[2])/n.a[2];return Math.sqrt(s*s+o*o+r*r)}function Kh(n,e,t){const i=Math.abs(n);return i<.035?9:Math.min(Yr(Kr,i,e,t),Yr(fx,i,e,t))}function i_(n,e,t){const i=Math.abs(n);return i<.02?9:Yr(n_,i,e,t)}function u$(n,e,t,i=.9){return Kh(n,e,t)<i||i_(n,e,t)<i*.9}function a_(n,e=7){const t=Wc(e),i=new Float32Array(n*3),a=new Float32Array(n*3),s=new Float32Array(n);let o=0,r=n*60;for(;o<n&&r-- >0;){const l=t();let c=Kr,p=0;l<.78?c=Kr:l<.9?c=fx:l<.97?(c=n_,p=1):p=2;let h,d,u,f,v,g;if(p===2){const P=t(),z=t()*Math.PI*2,R=.1-P*.025;if(f=Math.cos(z),g=Math.sin(z),v=0,h=f*R,d=-.28-P*.55,u=-.28-P*.12+g*R,Kh(h,d,u)<1||i_(h,d,u)<1)continue;i.set([h,d,u],o*3),a.set([f,v,g],o*3),s[o]=.45+.2*t(),o++;continue}const m=t()*2-1,x=t()*Math.PI*2,_=Math.sqrt(1-m*m),w=t()<.5?-1:1;let S=_*Math.cos(x),A=_*Math.sin(x),C=m;h=c.c[0]+S*c.a[0],d=c.c[1]+A*c.a[1],u=c.c[2]+C*c.a[2];const y=Yr(c,h,d,u);if(h=c.c[0]+(h-c.c[0])/y,d=c.c[1]+(d-c.c[1])/y,u=c.c[2]+(u-c.c[2])/y,h<.035)continue;if(p===0){if(Yr(c===Kr?fx:Kr,h,d,u)<.985)continue}else if(Kh(h,d,u)<1)continue;f=(h-c.c[0])/(c.a[0]*c.a[0]),v=(d-c.c[1])/(c.a[1]*c.a[1]),g=(u-c.c[2])/(c.a[2]*c.a[2]);const M=Math.hypot(f,v,g)||1;f/=M,v/=M,g/=M;let T,L;if(p===1){const P=Math.abs(Math.sin(d*70+u*12));T=.35+.65*P,L=(1-P)*.018}else{const P=h$(h,d,u);if(P>.55&&t()<.55)continue;T=1-.9*P,L=P*.05}h-=f*L,d-=v*L,u-=g*L,S=h*w,i.set([S,d,u],o*3),a.set([f*w,v,g],o*3),s[o]=T,o++}return{pos:i,nrm:a,shade:s,count:o}}function f$(n,e=3){const t=Wc(e),i=[];for(;i.length<1800;){const l=(t()*2-1)*.95,c=(t()*2-1)*.75,p=(t()*2-1)*1.05,h=Kh(l,c,p);h>.42&&h<.72&&i.push([l,c,p])}const a=[];if(n<=0)return a;let s=0,o=-1/0;for(let l=0;l<i.length;l++){const c=i[l][2]+i[l][1]*.5-Math.abs(i[l][0])*.2;c>o&&(o=c,s=l)}a.push(i[s]);const r=i.map(l=>s_(l,i[s]));for(;a.length<n;){let l=0,c=-1;for(let p=0;p<i.length;p++)r[p]>c&&(c=r[p],l=p);if(c<=0){a.push(i[a.length*37%i.length]);continue}a.push(i[l]);for(let p=0;p<i.length;p++)r[p]=Math.min(r[p],s_(i[p],i[l]))}return a}function s_(n,e){const t=n[0]-e[0],i=n[1]-e[1],a=n[2]-e[2];return t*t+i*i+a*a}function m$(n,e,t){const i=Wc(hx(n));for(let a=0;a<40;a++){const s=t*(1+a*.03),o=e[0]+ux(i)*s*.8,r=e[1]+ux(i)*s*.8,l=e[2]+ux(i)*s*1.15;if(!(Math.sign(o)!==Math.sign(e[0])&&Math.abs(e[0])>.06)&&u$(o,r,l,.9))return[o,r,l]}return[e[0],e[1],e[2]]}function g$(n,e){const t=.62/Math.cbrt(Math.max(1,e));return Math.min(.3,Math.max(.045,t*(.22+.12*Math.cbrt(n))))}const mx=[3.05,1.35,1.55],Po=[0,-.02,-.04],o_=42;function gx(n){return n<.9?5.2:n<1.3?4.1:3.6}const pa=110,Xc=6e3,Yh=12*pa*2,v$=5*6e4,x$=5e3,b$=2e3,y$=`
8505
8505
  attribute vec3 aColor; attribute float aSize; attribute float aFlare; attribute float aDim; attribute float aPhase;
8506
8506
  uniform float uTime; uniform float uScale;
8507
8507
  varying vec3 vColor; varying float vAlpha; varying float vFlare;
@@ -8586,7 +8586,7 @@ void main() {
8586
8586
  } else {
8587
8587
  gl_FragColor = vec4(mix(vColor, vec3(1.0), core * 0.7) * (core + halo), (core + halo) * vAlpha);
8588
8588
  }
8589
- }`;function A$(n){return Math.max(4,Math.min(12,Math.floor(8e4/Math.max(1,n))))}function jh(n,e,t){let i=(Math.imul(n+1,2654435761)^Math.imul(e+7,2246822519)^Math.imul(t+3,3266489917))>>>0;return i=Math.imul(i^i>>>15,739982445)>>>0,i=Math.imul(i^i>>>12,695872825)>>>0,((i^i>>>15)>>>0)/4294967296}function bx(n,e,t,i,a,s){e>t&&([e,t]=[t,e],i=1-i);const o=n[e*3],r=n[e*3+1],l=n[e*3+2],c=n[t*3]-o,p=n[t*3+1]-r,h=n[t*3+2]-l,d=Math.hypot(c,p,h)||1e-6;let u=-h,f=0,v=c;Math.abs(p)>.9*d&&(u=0,f=h,v=-p);const g=Math.hypot(u,f,v)||1;u/=g,f/=g,v/=g;let m=(p*v-h*f)/d,x=(h*u-c*v)/d,_=(c*f-p*u)/d;const w=jh(e,t,0)*Math.PI*2,S=d*(.12+.16*jh(e,t,1)),A=u*Math.cos(w)+m*Math.sin(w),C=f*Math.cos(w)+x*Math.sin(w),y=v*Math.cos(w)+_*Math.sin(w),M=jh(e,t,2)<.65?-.8:.9,T=.86,L=(o+c/3)*T+A*S,P=(r+p/3)*T+C*S,z=(l+h/3)*T+y*S,R=(o+c*2/3)*T+A*S*M,B=(r+p*2/3)*T+C*S*M,K=(l+h*2/3)*T+y*S*M,N=1-i,V=N*N*N,Z=3*N*N*i,te=3*N*i*i,ce=i*i*i,Ne=Math.sin(i*Math.PI*(3+2*jh(e,t,3))+w)*Math.sin(Math.PI*i)*d*.035;m*=Ne,x*=Ne,_*=Ne,a[s]=V*o+Z*L+te*R+ce*(o+c)+m,a[s+1]=V*r+Z*P+te*B+ce*(r+p)+x,a[s+2]=V*l+Z*z+te*K+ce*(l+h)+_}function an(n,e,t=!0){const i=new ra(n,e);return t&&i.setUsage(q4),i}const r_=n=>n<.5?4*n*n*n:1-Math.pow(-2*n+2,3)/2;class T${constructor(e,t,i,a){this.scene=new d5,this.light=!1,this.dprCap=2,this.n=0,this.keys=[],this.pos=new Float32Array(0),this.tgt=new Float32Array(0),this.col=new Float32Array(0),this.base=new Float32Array(0),this.grow=new Float32Array(0),this.growT=new Float32Array(0),this.flare=new Float32Array(0),this.dim=new Float32Array(0),this.dimT=new Float32Array(0),this.sizeA=new Float32Array(0),this.phase=new Float32Array(0),this.active=new Set,this.ghosts=0,this.ghostTimer=0,this.noteGeo=new pn,this.linkPairs=new Int32Array(0),this.linkSeg=1,this.tmp3=new Float32Array(3),this.adjOff=new Int32Array(1),this.adj=new Int32Array(0),this.linkGeo=new pn,this.linksDirty=!1,this.hiGeo=new pn,this.hiFor=-1,this.shellGeo=new pn,this.sparks=[],this.sparkGeo=new pn,this.sparkPos=new Float32Array(Xc*3),this.sparkCol=new Float32Array(Xc*3),this.sparkSize=new Float32Array(Xc),this.sparkAlpha=new Float32Array(Xc),this.trailGeo=new pn,this.trailPos=new Float32Array(Yh*3),this.trailCol=new Float32Array(Yh*3),this.trailAlpha=new Float32Array(Yh),this.agents=new Map,this.dock=null,this.ambientAcc=0,this.r=Wc(1234),this.regionLabels=[],this.hiddenRegions=new Set,this.noteLabels=[],this.showLabels=!0,this.raf=0,this.running=!1,this.disposed=!1,this.time=0,this.last=0,this.lastInteract=performance.now(),this.autoRotate=!0,this.selected=-1,this.hovered=-1,this.pointer={x:0,y:0,dirty:!1,inside:!1},this.down=null,this.tween=null,this.zoomTween=null,this.width=1,this.height=1,this.sized=!1,this.fovTarget=42,this.tmp=new X,this.vp=new en,this.onWindowResize=()=>{(this.host.clientWidth!==this.width||this.host.clientHeight!==this.height)&&this.resize()},this.onMove=c=>{if(c.pointerType==="touch")return;const p=this.canvas.getBoundingClientRect();this.pointer.x=c.clientX-p.left,this.pointer.y=c.clientY-p.top,this.pointer.dirty=!0,this.pointer.inside=!0,this.running||this.pickHover()},this.onLeave=()=>{this.pointer.inside=!1,this.pointer.dirty=!0},this.onDown=c=>{this.down={x:c.clientX,y:c.clientY,t:performance.now()}},this.onUp=c=>{const p=this.down;if(this.down=null,!p||Math.hypot(c.clientX-p.x,c.clientY-p.y)>6||performance.now()-p.t>600)return;const h=this.canvas.getBoundingClientRect(),d=this.pick(c.clientX-h.left,c.clientY-h.top,c.pointerType==="touch"?26:16);this.cb.onPick(d)},this.host=e,this.labels=t,this.cb=i,this.reduced=a,this.autoRotate=!a,this.renderer=new ZI({antialias:!1,alpha:!0,powerPreference:"high-performance"}),this.renderer.setClearColor(0,0),this.canvas=this.renderer.domElement,this.canvas.className="brain-canvas",e.appendChild(this.canvas),this.camera=new wi(o_,1,.05,60),this.camera.position.set(...mx),this.controls=new QI(this.camera,this.canvas),this.controls.enableDamping=!0,this.controls.dampingFactor=.07,this.controls.rotateSpeed=.7,this.controls.zoomSpeed=.9,this.controls.minDistance=.35,this.controls.maxDistance=9,this.controls.autoRotateSpeed=.55,this.controls.target.set(...Po),this.controls.addEventListener("start",()=>{this.lastInteract=performance.now(),this.controls.autoRotate=!1,this.tween=null,this.zoomTween=null}),this.noteMat=new Pn({vertexShader:y$,fragmentShader:w$,uniforms:{uTime:{value:0},uScale:{value:400},uLight:{value:0}},transparent:!0,depthWrite:!1,blending:za}),this.notePts=new tx(this.noteGeo,this.noteMat),this.notePts.frustumCulled=!1,this.notePts.renderOrder=3,this.linkMat=new Pn({vertexShader:vx,fragmentShader:xx,uniforms:{uOpacity:{value:.14},uLight:{value:0}},transparent:!0,depthWrite:!1,blending:za}),this.linkObj=new Qv(this.linkGeo,this.linkMat),this.linkObj.frustumCulled=!1,this.linkObj.renderOrder=1,this.hiMat=new Pn({vertexShader:vx,fragmentShader:xx,uniforms:{uOpacity:{value:.85},uLight:{value:0}},transparent:!0,depthWrite:!1,blending:za}),this.hiObj=new Qv(this.hiGeo,this.hiMat),this.hiObj.frustumCulled=!1,this.hiObj.renderOrder=2;const s=a_(window.innerWidth<700?14e3:26e3);this.shellGeo.setAttribute("position",an(s.pos.subarray(0,s.count*3),3,!1)),this.shellGeo.setAttribute("normal",an(s.nrm.subarray(0,s.count*3),3,!1)),this.shellGeo.setAttribute("aShade",an(s.shade.subarray(0,s.count),1,!1)),this.shellMat=new Pn({vertexShader:k$,fragmentShader:_$,uniforms:{uTime:{value:0},uScale:{value:400},uSize:{value:.0105},uLight:{value:0},uFade:{value:1},uColA:{value:new X(.36,.42,.98)},uColB:{value:new X(.37,.92,.83)}},transparent:!0,depthWrite:!1,blending:za});const o=new tx(this.shellGeo,this.shellMat);o.frustumCulled=!1,o.renderOrder=0,this.sparkGeo.setAttribute("position",an(this.sparkPos,3)),this.sparkGeo.setAttribute("aColor",an(this.sparkCol,3)),this.sparkGeo.setAttribute("aSize",an(this.sparkSize,1)),this.sparkGeo.setAttribute("aAlpha",an(this.sparkAlpha,1)),this.sparkGeo.setDrawRange(0,0),this.sparkMat=new Pn({vertexShader:S$,fragmentShader:M$,uniforms:{uScale:{value:400},uLight:{value:0}},transparent:!0,depthWrite:!1,depthTest:!1,blending:za});const r=new tx(this.sparkGeo,this.sparkMat);r.frustumCulled=!1,r.renderOrder=5,this.trailGeo.setAttribute("position",an(this.trailPos,3)),this.trailGeo.setAttribute("aColor",an(this.trailCol,3)),this.trailGeo.setAttribute("aAlpha",an(this.trailAlpha,1)),this.trailGeo.setDrawRange(0,0),this.trailMat=new Pn({vertexShader:vx,fragmentShader:xx,uniforms:{uOpacity:{value:1},uLight:{value:0}},transparent:!0,depthWrite:!1,depthTest:!1,blending:za});const l=new Qv(this.trailGeo,this.trailMat);l.frustumCulled=!1,l.renderOrder=4,this.scene.add(o,this.linkObj,this.hiObj,this.notePts,l,r),this.reticle=document.createElement("div"),this.reticle.className="bl-reticle hidden",t.appendChild(this.reticle),this.ro=new ResizeObserver(()=>this.resize()),this.ro.observe(e),window.addEventListener("resize",this.onWindowResize),this.resize(),this.camera.position.copy(this.homePos()),this.canvas.addEventListener("pointermove",this.onMove),this.canvas.addEventListener("pointerdown",this.onDown),this.canvas.addEventListener("pointerup",this.onUp),this.canvas.addEventListener("pointerleave",this.onLeave)}resize(){const e=Math.max(1,this.host.clientWidth),t=Math.max(1,this.host.clientHeight);this.glide(),this.width=e,this.height=t;const i=Math.min(window.devicePixelRatio||1,this.dprCap);this.renderer.setPixelRatio(i),this.renderer.setSize(e,t,!1),this.camera.aspect=e/t,this.fovTarget=e/t<.9?58:42,(!this.sized||this.reduced)&&(this.camera.fov=this.fovTarget),this.sized=!0,this.applyFraming(),this.renderOnce()}glide(){const e=this.host.parentElement;if(!this.sized||this.reduced||!e)return;const t=this.canvas.getBoundingClientRect(),i=e.getBoundingClientRect(),a=t.left+t.width/2-(i.left+i.width/2),s=t.top+t.height/2-(i.top+i.height/2);if(!(Math.abs(a)<1&&Math.abs(s)<1)){for(const o of[this.host,this.labels])o.style.transition="none",o.style.transform=`translate3d(${a.toFixed(1)}px,${s.toFixed(1)}px,0)`;this.host.offsetWidth;for(const o of[this.host,this.labels])o.style.transition="transform .45s cubic-bezier(.2,.8,.2,1)",o.style.transform=""}}applyFraming(){this.camera.updateProjectionMatrix();const e=Math.min(window.devicePixelRatio||1,this.dprCap),t=this.height*e/(2*Math.tan(this.camera.fov*Math.PI/360));this.noteMat.uniforms.uScale.value=t,this.shellMat.uniforms.uScale.value=t,this.sparkMat.uniforms.uScale.value=t}easeFraming(e){if(this.camera.fov===this.fovTarget)return;const t=1-Math.exp(-e*9);this.camera.fov+=(this.fovTarget-this.camera.fov)*t,Math.abs(this.camera.fov-this.fovTarget)<=.01&&(this.camera.fov=this.fovTarget),this.applyFraming()}start(){if(this.running||this.disposed)return;this.running=!0,this.last=performance.now();const e=t=>{if(!this.running)return;this.raf=requestAnimationFrame(e);const i=Math.min(.05,(t-this.last)/1e3);this.last=t,this.easeFraming(i),this.frame(i,t)};this.raf=requestAnimationFrame(e)}stop(){this.running=!1,cancelAnimationFrame(this.raf)}dispose(){if(!this.disposed){this.stop(),this.disposed=!0,this.ro.disconnect(),window.removeEventListener("resize",this.onWindowResize),clearTimeout(this.ghostTimer),this.canvas.removeEventListener("pointermove",this.onMove),this.canvas.removeEventListener("pointerdown",this.onDown),this.canvas.removeEventListener("pointerup",this.onUp),this.canvas.removeEventListener("pointerleave",this.onLeave),this.controls.dispose();for(const e of[this.noteGeo,this.linkGeo,this.hiGeo,this.shellGeo,this.sparkGeo,this.trailGeo])e.dispose();for(const e of[this.noteMat,this.linkMat,this.hiMat,this.shellMat,this.sparkMat,this.trailMat])e.dispose();this.renderer.dispose(),this.renderer.forceContextLoss(),this.canvas.remove(),this.labels.innerHTML="",this.agents.clear()}}renderOnce(){this.disposed||this.renderer.render(this.scene,this.camera)}setTheme(e){this.light=e;const t=e?Ar:za;for(const s of[this.noteMat,this.linkMat,this.hiMat,this.shellMat,this.sparkMat,this.trailMat])s.blending=t,s.uniforms.uLight.value=e?1:0,s.needsUpdate=!0;const i=this.shellMat.uniforms.uColA.value,a=this.shellMat.uniforms.uColB.value;e?(i.set(.3,.36,.52),a.set(.2,.45,.5)):(i.set(.36,.42,.98),a.set(.37,.92,.83)),this.updateLinkOpacity(),this.renderOnce()}setAutoRotate(e){this.autoRotate=e&&!this.reduced,this.autoRotate?this.lastInteract=0:this.controls.autoRotate=!1}setLabels(e,t=e){this.showLabels=e||t,this.labels.classList.toggle("no-labels",!e&&!t),this.labels.classList.toggle("no-notes",!e),this.labels.classList.toggle("no-regions",!t)}setData(e,t,i){const a=new Map;for(let M=0;M<this.n;M++)this.growT[M]>0&&a.set(this.keys[M],M);const s=new Set(e.map(M=>M.key)),o=[];a.forEach((M,T)=>{s.has(T)||o.push(M)});const r=e.length+o.length,l=new Float32Array(r*3),c=new Float32Array(r*3),p=new Float32Array(r*3),h=new Float32Array(r),d=new Float32Array(r),u=new Float32Array(r),f=new Float32Array(r),v=new Float32Array(r),g=new Float32Array(r),m=new Float32Array(r),x=[],_=this.n===0,w=new Set;e.forEach((M,T)=>{x.push(M.key);const L=a.get(M.key);c.set(M.target,T*3);const P=p2(M.color);if(p.set(P,T*3),h[T]=M.size,u[T]=1,m[T]=hx(M.key)%6283/1e3,L!==void 0)l[T*3]=this.pos[L*3],l[T*3+1]=this.pos[L*3+1],l[T*3+2]=this.pos[L*3+2],d[T]=this.grow[L],f[T]=this.flare[L],v[T]=this.dim[L],g[T]=this.dimT[L],(l[T*3]!==c[T*3]||l[T*3+1]!==c[T*3+1]||l[T*3+2]!==c[T*3+2])&&w.add(T),(d[T]<1||f[T]>.001||v[T]!==g[T])&&w.add(T);else if(_&&!this.reduced){const z=1.25+this.r()*.2,R=Math.hypot(M.target[0],M.target[1],M.target[2])||1;l.set([M.target[0]/R*z,M.target[1]/R*z,M.target[2]/R*z],T*3),d[T]=0,w.add(T)}else _?(l.set(M.target,T*3),d[T]=1):(l.set(M.origin,T*3),d[T]=0,f[T]=1,w.add(T))}),o.forEach((M,T)=>{const L=e.length+T;x.push(this.keys[M]);for(let P=0;P<3;P++)l[L*3+P]=this.pos[M*3+P],c[L*3+P]=this.pos[M*3+P],p[L*3+P]=this.col[M*3+P];h[L]=this.base[M],d[L]=this.grow[M],u[L]=0,f[L]=.8,w.add(L)}),this.n=r,this.keys=x,this.pos=l,this.tgt=c,this.col=p,this.base=h,this.grow=d,this.growT=u,this.flare=f,this.dim=v,this.dimT=g,this.phase=m,this.sizeA=new Float32Array(r);for(let M=0;M<r;M++)this.sizeA[M]=h[M]*d[M];this.active=w,this.ghosts=o.length,this.sparks=this.sparks.filter(M=>M.target<0),this.selected>=0&&(this.selected=-1),this.hovered=-1,this.hiFor=-2,this.noteGeo.dispose(),this.noteGeo=new pn,this.noteGeo.setAttribute("position",an(this.pos,3)),this.noteGeo.setAttribute("aColor",an(this.col,3)),this.noteGeo.setAttribute("aSize",an(this.sizeA,1)),this.noteGeo.setAttribute("aFlare",an(this.flare,1)),this.noteGeo.setAttribute("aDim",an(this.dim,1)),this.noteGeo.setAttribute("aPhase",an(this.phase,1,!1)),this.notePts.geometry=this.noteGeo;const S=t.length;this.linkPairs=new Int32Array(S*2);const A=new Int32Array(r+1);t.forEach(([M,T],L)=>{this.linkPairs[L*2]=M,this.linkPairs[L*2+1]=T,A[M]++,A[T]++}),this.adjOff=new Int32Array(r+1);for(let M=0;M<r;M++)this.adjOff[M+1]=this.adjOff[M]+A[M];this.adj=new Int32Array(this.adjOff[r]);const C=this.adjOff.slice(0,r);t.forEach(([M,T])=>{this.adj[C[M]++]=T,this.adj[C[T]++]=M}),this.linkGeo.dispose(),this.linkGeo=new pn,this.linkSeg=A$(S);const y=S*this.linkSeg*2;this.linkGeo.setAttribute("position",an(new Float32Array(y*3),3)),this.linkGeo.setAttribute("aColor",an(new Float32Array(y*3),3)),this.linkGeo.setAttribute("aAlpha",an(new Float32Array(y),1)),this.linkObj.geometry=this.linkGeo,this.linksDirty=!0,this.fillLinks(!0),this.updateLinkOpacity();for(const M of this.regionLabels)M.el.remove();this.regionLabels=i.map(M=>{const T=document.createElement("div");return T.className="bl-region",T.style.setProperty("--c",M.color),T.textContent=M.name,this.labels.appendChild(T),{el:T,anchor:M.anchor,name:M.name}}),this.pickNoteLabels(),clearTimeout(this.ghostTimer),o.length&&(this.ghostTimer=window.setTimeout(()=>this.compact(),1400)),this.running||this.renderOnce()}compact(){if(this.disposed||!this.ghosts)return;const e=this.n-this.ghosts,t=[];for(let l=0;l<e;l++){const c=[this.tgt[l*3],this.tgt[l*3+1],this.tgt[l*3+2]],p=this.col.subarray(l*3,l*3+3),h="#"+Array.from(p,d=>Math.round(d*255).toString(16).padStart(2,"0")).join("");t.push({key:this.keys[l],target:c,origin:c,color:h,size:this.base[l]})}const i=[];for(let l=0;l<this.linkPairs.length;l+=2)this.linkPairs[l]<e&&this.linkPairs[l+1]<e&&i.push([this.linkPairs[l],this.linkPairs[l+1]]);const a=this.dimT.slice(0,e),s=this.regionLabels,o=this.selected;this.n=e,this.ghosts=0;const r=s.map(l=>({name:l.el.textContent||"",anchor:l.anchor,color:l.el.style.getPropertyValue("--c"),count:0}));this.setData(t,i,r),this.dimT.set(a),this.dim.set(a),o>=0&&o<e&&this.select(o)}updateLinkOpacity(){const e=this.linkPairs.length/2,t=Math.min(1,Math.sqrt(2500/Math.max(1,e)));this.linkMat.uniforms.uOpacity.value=(this.light?.15:.12)*Math.max(.35,t)}fillLinks(e=!1){const t=this.linkGeo,i=t.getAttribute("position"),a=t.getAttribute("aAlpha");if(this.linksDirty=!1,!i||!a)return;const s=i.array,o=a.array,r=e?t.getAttribute("aColor").array:null,l=this.linkPairs,c=this.linkSeg,p=new Float32Array(3*(c+1));for(let h=0,d=l.length/2;h<d;h++){const u=l[h*2],f=l[h*2+1];for(let g=0;g<=c;g++)bx(this.pos,u,f,g/c,p,g*3);const v=this.grow[u]*(1-this.dim[u]*.92)*this.grow[f]*(1-this.dim[f]*.92);for(let g=0;g<c;g++){const m=(h*c+g)*2;if(s.set(p.subarray(g*3,g*3+6),m*3),o[m]=v*(.5+.5*Math.sin(Math.PI*g/c)),o[m+1]=v*(.5+.5*Math.sin(Math.PI*(g+1)/c)),r)for(let x=0;x<2;x++){const _=(g+x)/c;for(let w=0;w<3;w++)r[(m+x)*3+w]=this.col[u*3+w]*(1-_)+this.col[f*3+w]*_}}}i.needsUpdate=!0,a.needsUpdate=!0,r&&(t.getAttribute("aColor").needsUpdate=!0),this.linksDirty=!1}buildHighlight(e){if(this.hiFor===e||(this.hiFor=e,this.hiGeo.dispose(),this.hiGeo=new pn,this.hiObj.geometry=this.hiGeo,e<0||e>=this.n))return;const t=this.neighbors(e),i=16,a=new Float32Array(t.length*i*6),s=new Float32Array(t.length*i*6),o=new Float32Array(t.length*i*2),r=new Float32Array(3*(i+1));t.forEach((l,c)=>{for(let p=0;p<=i;p++)bx(this.pos,e,l,p/i,r,p*3);for(let p=0;p<i;p++){const h=(c*i+p)*2;a.set(r.subarray(p*3,p*3+6),h*3);for(let d=0;d<2;d++){const u=(p+d)/i;o[h+d]=1-.45*u;for(let f=0;f<3;f++)s[(h+d)*3+f]=Math.min(1,this.col[e*3+f]*.6+.4)*(1-u)+this.col[l*3+f]*u}}}),this.hiGeo.setAttribute("position",an(a,3)),this.hiGeo.setAttribute("aColor",an(s,3,!1)),this.hiGeo.setAttribute("aAlpha",an(o,1,!1))}neighbors(e){return e<0||e>=this.n?[]:Array.from(this.adj.subarray(this.adjOff[e],this.adjOff[e+1]))}setDim(e){for(let t=0;t<this.n-this.ghosts;t++){const i=e?e(t):0;this.dimT[t]!==i&&(this.dimT[t]=i,this.active.add(t))}if(this.reduced){this.dim.set(this.dimT);const t=this.noteGeo.getAttribute("aDim");t&&(t.needsUpdate=!0),this.linksDirty=!0}this.running||this.renderOnce()}select(e){if(this.selected=e,this.buildHighlight(e),this.reticle.classList.toggle("hidden",e<0),e>=0){this.flareNote(e,.7);const t=this.col.subarray(e*3,e*3+3);this.reticle.style.setProperty("--c",`rgb(${t[0]*255|0},${t[1]*255|0},${t[2]*255|0})`)}}flareNote(e,t=1){e<0||e>=this.n||(this.flare[e]=Math.max(this.flare[e],t),this.active.add(e))}setDock(e){this.dock=e}dockWorld(){const e=this.dock?.(),t=this.canvas.getBoundingClientRect();if(!e||!t.width||!t.height)return null;this.camera.updateMatrixWorld();const i=new X((e.x-t.left)/t.width*2-1,-((e.y-t.top)/t.height*2-1),.5).unproject(this.camera),a=this.camera.position,s=i.sub(a).normalize(),o=a.distanceTo(this.controls.target)*.55;return[a.x+s.x*o,a.y+s.y*o,a.z+s.z*o]}agentHead(e){const t=this.agents.get(e);return t&&t.fade>.05?[t.head[0],t.head[1],t.head[2]]:null}positionOf(e){return[this.pos[e*3],this.pos[e*3+1],this.pos[e*3+2]]}focus(e,t){const i=new X(e[0],e[1],e[2]),a=this.camera.position.clone().sub(this.controls.target).normalize(),s=i.clone().setY(i.y*.5);s.length()>.15&&a.lerp(s.normalize(),.55).normalize();const o=i.clone().add(a.multiplyScalar(t));if(this.zoomTween=null,this.controls.autoRotate=!1,this.lastInteract=performance.now(),this.reduced){this.camera.position.copy(o),this.controls.target.copy(i),this.controls.update();return}this.tween={p0:this.camera.position.clone(),p1:o,t0:this.controls.target.clone(),t1:i,s:0,dur:1.1}}cameraView(){const e=this.canvas.getBoundingClientRect();if(!e.width||!e.height)return null;const t=this.camera.position,i=this.controls.target;return{eye:[t.x,t.y,t.z],target:[i.x,i.y,i.z],fov:this.camera.fov*Math.PI/180,rect:{x:e.left,y:e.top,w:e.width,h:e.height}}}projectToClient(e,t,i){const a=this.canvas.getBoundingClientRect();if(!a.width||!a.height)return null;this.camera.updateMatrixWorld();const s=new X(e,t,i).project(this.camera);return[a.left+(s.x+1)/2*a.width,a.top+(1-s.y)/2*a.height,s.z]}awayFromHome(){if(this.tween||this.zoomTween)return!0;const e=gx(this.camera.aspect),t=this.controls.target,i=this.camera.position.distanceTo(t);return t.distanceTo(new X(...Po))>e*.04||Math.abs(i-e)>e*.06}homePos(){return new X(...mx).normalize().multiplyScalar(gx(this.camera.aspect))}resetView(){const e=new X(...Po),t=this.homePos().length();if(this.tween=null,this.reduced){const i=this.camera.position.clone().sub(this.controls.target).normalize();this.controls.target.copy(e),this.camera.position.copy(e).addScaledVector(i,t),this.controls.update();return}this.zoomTween={d0:this.camera.position.distanceTo(this.controls.target),d1:t,t0:this.controls.target.clone(),t1:e,s:0,dur:.9}}zoomBy(e){const t=this.camera.position.distanceTo(this.controls.target),i=Math.max(this.controls.minDistance,Math.min(this.controls.maxDistance,t/e));if(this.halt(),this.reduced){const a=this.camera.position.clone().sub(this.controls.target).normalize();this.camera.position.copy(this.controls.target).addScaledVector(a,i),this.controls.update();return}this.zoomTween={d0:t,d1:i,t0:this.controls.target.clone(),t1:this.controls.target.clone(),s:0,dur:.35}}orbitBy(e,t){const i=this.controls.target,a=this.camera.position.clone().sub(i),s=a.length(),o=Math.atan2(a.x,a.z)+e,r=Math.max(.12,Math.min(Math.PI-.12,Math.acos(Math.max(-1,Math.min(1,a.y/s)))-t));this.orbitTo(o,r,.32)}orbitTo(e,t,i=.8){const a=this.controls.target,s=this.camera.position.clone().sub(a),o=s.length(),r=t??Math.acos(Math.max(-1,Math.min(1,s.y/o))),l=new X(Math.sin(r)*Math.sin(e),Math.cos(r),Math.sin(r)*Math.cos(e)).multiplyScalar(o).add(a);if(this.halt(),this.reduced){this.camera.position.copy(l),this.controls.update();return}this.tween={p0:this.camera.position.clone(),p1:l,t0:a.clone(),t1:a.clone(),s:0,dur:i,arc:!0}}goHome(){this.halt();const e=this.homePos().add(new X(...Po)),t=new X(...Po);if(this.reduced){this.camera.position.copy(e),this.controls.target.copy(t),this.controls.update();return}this.tween={p0:this.camera.position.clone(),p1:e,t0:this.controls.target.clone(),t1:t,s:0,dur:.9,arc:!0}}orientation(){const e=this.camera.position.clone().sub(this.controls.target),t=e.length()||1;return{yaw:Math.atan2(e.x,e.z),pitch:Math.asin(Math.max(-1,Math.min(1,e.y/t)))}}halt(){this.tween=null,this.zoomTween=null,this.controls.autoRotate=!1,this.lastInteract=performance.now()}activity(e,t,i,a){const s=performance.now();let o=this.agents.get(e);if(!o){const l=xn(e),c=hx(e),p=Wc(c),h=[(p()*2-1)*.5,(p()-.4)*.5,(p()*2-1)*.6],d=document.createElement("div");d.className="bl-agent",d.style.setProperty("--c",l),d.innerHTML="<b></b><span></span>",d.firstChild.textContent=xl(e),d.lastChild.textContent=e,this.labels.appendChild(d);const u=this.dockWorld();o={rgb:p2(l),head:u||[h[0],h[1]+.9,h[2]],vel:[0,0,0],target:h,seed:c%1e3/100,hist:new Float32Array(pa*3),histN:0,histI:0,last:s,energy:1,fade:0,busy:0,el:d},this.agents.set(e,o)}o.last=s,o.energy=1,t==="start"?o.busy++:o.busy=Math.max(0,o.busy-1);const r=a.filter(l=>l>=0&&l<this.n).slice(0,40);if(r.length){let l=0,c=0,p=0;for(const f of r)l+=this.pos[f*3],c+=this.pos[f*3+1],p+=this.pos[f*3+2];const h=1/r.length;o.target=[l*h*.85,c*h*.85,p*h*.85];const u=i===!1?[1,.35,.35]:o.rgb;r.forEach((f,v)=>{if(this.reduced){this.flareNote(f,1);return}this.spark(o.head,f,u,v*.07,t==="end"?.7:1.05,.085,1,!0)})}}spark(e,t,i,a,s,o,r,l,c,p){if(this.sparks.length>900)return;const h=c||this.positionOf(t),d=[e[0],e[1],e[2]],u=(d[0]+h[0])/2,f=(d[1]+h[1])/2,v=(d[2]+h[2])/2,m=Math.hypot(h[0]-d[0],h[1]-d[1],h[2]-d[2])*.35,x=[u*.7+(this.r()-.5)*m,f*.7+(this.r()-.5)*m,v*.7+(this.r()-.5)*m];this.sparks.push({a:d,b:h,c:x,target:t,t:0,dur:s,delay:a,rgb:i,size:o,alpha:r,strength:l?1:.35,echo:l,from:p})}pickHover(){this.pointer.dirty=!1;const e=this.pointer.inside?this.pick(this.pointer.x,this.pointer.y,14):-1;e!==this.hovered&&(this.hovered=e,this.selected<0&&this.buildHighlight(e)),this.cb.onHover(e,this.pointer.x,this.pointer.y)}pick(e,t,i){this.camera.updateMatrixWorld(),this.vp.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse);const a=this.vp.elements,s=this.width,o=this.height;let r=-1,l=i*i;for(let c=0,p=this.n-this.ghosts;c<p;c++){if(this.dimT[c]>.6)continue;const h=this.pos[c*3],d=this.pos[c*3+1],u=this.pos[c*3+2],f=a[3]*h+a[7]*d+a[11]*u+a[15];if(f<=.01)continue;const v=((a[0]*h+a[4]*d+a[8]*u+a[12])/f*.5+.5)*s,g=(.5-(a[1]*h+a[5]*d+a[9]*u+a[13])/f*.5)*o,m=v-e,x=g-t,_=m*m+x*x+f*2;_<l&&(l=_,r=c)}return r}project(e){return this.tmp.set(e[0],e[1],e[2]).project(this.camera),this.tmp.z>1?null:{x:(this.tmp.x*.5+.5)*this.width,y:(.5-this.tmp.y*.5)*this.height,depth:this.tmp.z}}pickNoteLabels(){for(const a of this.noteLabels)a.el.remove();const e=this.n-this.ghosts,t=e>4e3?5:8,i=Array.from({length:e},(a,s)=>s).filter(a=>this.dimT[a]<.5).sort((a,s)=>this.base[s]-this.base[a]).slice(0,t);this.noteLabels=i.map(a=>{const s=document.createElement("div");return s.className="bl-note",s.textContent=this.cb.labelOf(a),this.labels.appendChild(s),{el:s,index:a}})}setHiddenRegions(e){this.hiddenRegions=new Set(e),this.renderOnce()}refreshNoteLabels(){this.pickNoteLabels()}placeLabels(){const e=this.camera.position.distanceTo(this.controls.target),t=this.controls.target,i=this.camera.position,a=[],s=(o,r,l=1,c=!1)=>{const p=this.project(r);if(!p||p.x<-50||p.y<-20||p.x>this.width+50||p.y>this.height+20){o.style.opacity="0";return}if(c){for(let f=0;f<a.length;f+=2)if(Math.abs(a[f]-p.x)<110&&Math.abs(a[f+1]-p.y)<16){o.style.opacity="0";return}a.push(p.x,p.y)}const h=Math.hypot(r[0]-i.x,r[1]-i.y,r[2]-i.z),d=Math.hypot(t.x-i.x,t.y-i.y,t.z-i.z),u=Math.max(0,Math.min(1,(h-d+.4)/.8));o.style.opacity=String((1-u*.7)*l),o.style.transform=`translate3d(${p.x.toFixed(1)}px,${p.y.toFixed(1)}px,0)`};if(this.showLabels){for(const o of this.regionLabels)this.hiddenRegions.has(o.name)?o.el.style.opacity="0":s(o.el,o.anchor,e<1.2?.35:1,!0);for(const o of this.noteLabels)o.index>=this.n||s(o.el,this.positionOf(o.index),(1-this.dim[o.index])*Math.min(1,this.grow[o.index]),!0)}this.selected>=0&&s(this.reticle,this.positionOf(this.selected)),this.agents.forEach(o=>s(o.el,o.head,o.fade))}frame(e,t){if(this.reduced||(this.time+=e),this.noteMat.uniforms.uTime.value=this.time,this.shellMat.uniforms.uTime.value=this.time,this.zoomTween){const s=this.zoomTween;s.s=Math.min(1,s.s+e/s.dur);const o=r_(s.s),r=this.camera.position.clone().sub(this.controls.target).normalize();this.controls.target.lerpVectors(s.t0,s.t1,o),this.camera.position.copy(this.controls.target).addScaledVector(r,s.d0+(s.d1-s.d0)*o),s.s>=1&&(this.zoomTween=null)}if(this.tween){const s=this.tween;s.s=Math.min(1,s.s+e/s.dur);const o=r_(s.s);if(this.controls.target.lerpVectors(s.t0,s.t1,o),s.arc){const r=s.p0.clone().sub(s.t0),l=s.p1.clone().sub(s.t1),c=r.length()||1,p=l.length()||1,h=Math.atan2(r.x,r.z);let d=Math.atan2(l.x,l.z)-h;d-=Math.round(d/(Math.PI*2))*Math.PI*2;const u=Math.acos(Math.max(-1,Math.min(1,r.y/c))),f=Math.acos(Math.max(-1,Math.min(1,l.y/p))),v=h+d*o,g=u+(f-u)*o,m=c+(p-c)*o;this.camera.position.set(Math.sin(g)*Math.sin(v),Math.cos(g),Math.sin(g)*Math.cos(v)).multiplyScalar(m).add(this.controls.target)}else this.camera.position.lerpVectors(s.p0,s.p1,o);s.s>=1&&(this.tween=null)}else this.autoRotate&&!this.controls.autoRotate&&t-this.lastInteract>b$&&this.selected<0&&(this.controls.autoRotate=!0);this.controls.update(e);const i=this.camera.position.length();if(this.shellMat.uniforms.uFade.value=Math.max(.15,Math.min(1,(i-.6)/1.4)),this.active.size){const s=1-Math.exp(-e*3.2),o=1-Math.exp(-e*3.5),r=1-Math.exp(-e*7),l=Math.exp(-e*1.9);let c=!1,p=!1,h=!1;for(const u of this.active){let f=!0;for(let m=0;m<3;m++){const x=this.tgt[u*3+m]-this.pos[u*3+m];Math.abs(x)>1e-4?(this.pos[u*3+m]+=x*s,f=!1,c=!0):this.pos[u*3+m]=this.tgt[u*3+m]}const v=this.growT[u]-this.grow[u];v!==0&&(Math.abs(v)>.002?(this.grow[u]+=v*o,f=!1):this.grow[u]=this.growT[u],this.sizeA[u]=this.base[u]*this.grow[u],h=!0),this.flare[u]>.002?(this.flare[u]*=l,f=!1):this.flare[u]=0;const g=this.dimT[u]-this.dim[u];Math.abs(g)>.004?(this.dim[u]+=g*r,f=!1,p=!0):g!==0&&(this.dim[u]=this.dimT[u],p=!0),f&&this.active.delete(u)}const d=this.noteGeo;if(c&&(d.getAttribute("position").needsUpdate=!0),h&&(d.getAttribute("aSize").needsUpdate=!0),p&&(d.getAttribute("aDim").needsUpdate=!0),d.getAttribute("aFlare").needsUpdate=!0,(c||p||h)&&(this.linksDirty=!0),c&&this.hiFor>=0){const u=this.hiFor;this.hiFor=-2,this.buildHighlight(u)}}this.linksDirty&&this.fillLinks();const a=this.n-this.ghosts;if(!this.reduced&&a>1&&!document.hidden){this.ambientAcc+=e;const s=this.linkPairs.length?Math.max(.05,.35-a/2e4):.5;for(;this.ambientAcc>s;)if(this.ambientAcc-=s,this.linkPairs.length){const o=Math.floor(this.r()*(this.linkPairs.length/2));let r=this.linkPairs[o*2],l=this.linkPairs[o*2+1];if(this.r()<.5&&([r,l]=[l,r]),this.dimT[r]>.5||this.dimT[l]>.5)continue;const c=this.col.subarray(r*3,r*3+3);this.spark(this.positionOf(r),l,[c[0],c[1],c[2]],0,.9+this.r()*.6,.032,.55,!1,void 0,r)}else this.flareNote(Math.floor(this.r()*a),.35)}this.stepAgents(e,t),this.stepSparks(e),this.pointer.dirty&&this.pickHover(),this.placeLabels(),this.renderer.render(this.scene,this.camera)}stepSparks(e){let t=0;const i=(s,o,r,l,c,p)=>{t>=Xc||(this.sparkPos[t*3]=s,this.sparkPos[t*3+1]=o,this.sparkPos[t*3+2]=r,this.sparkCol[t*3]=l[0],this.sparkCol[t*3+1]=l[1],this.sparkCol[t*3+2]=l[2],this.sparkSize[t]=c,this.sparkAlpha[t]=p,t++)},a=[];for(const s of this.sparks){if(s.delay>0){s.delay-=e,a.push(s);continue}if(s.t+=e/s.dur,s.target>=0&&s.target<this.n&&(s.b[0]=this.pos[s.target*3],s.b[1]=this.pos[s.target*3+1],s.b[2]=this.pos[s.target*3+2]),s.t>=1){if(s.target>=0&&(this.flareNote(s.target,s.strength),s.echo)){const r=this.neighbors(s.target);for(let l=0;l<Math.min(4,r.length);l++){const c=r[Math.floor(this.r()*r.length)];this.spark(s.b,c,s.rgb,l*.05,.55,.04,.8,!1)}}continue}a.push(s);const o=s.echo?9:5;for(let r=0;r<o;r++){const l=s.t-r*(s.echo?.022:.03);if(l<0)break;let c,p,h;if(s.from!==void 0&&s.from<this.n&&s.target<this.n)bx(this.pos,s.from,s.target,l,this.tmp3,0),[c,p,h]=this.tmp3;else{const u=1-l;c=u*u*s.a[0]+2*u*l*s.c[0]+l*l*s.b[0],p=u*u*s.a[1]+2*u*l*s.c[1]+l*l*s.b[1],h=u*u*s.a[2]+2*u*l*s.c[2]+l*l*s.b[2]}const d=1-r/o;i(c,p,h,s.rgb,s.size*(.35+.65*d),s.alpha*d*d)}}this.sparks=a,this.agents.forEach(s=>{if(s.fade<=.01)return;const o=.5+.5*Math.sin(this.time*4+s.seed);i(s.head[0],s.head[1],s.head[2],s.rgb,(.32+.12*o+s.energy*.25)*(s.busy?1.15:.85),.32*s.fade),i(s.head[0],s.head[1],s.head[2],s.rgb,.1+s.energy*.05,s.fade);for(let r=2;r<s.histN;r+=3){const l=(s.histI-1-r+pa*2)%pa,c=1-r/s.histN;i(s.hist[l*3],s.hist[l*3+1],s.hist[l*3+2],s.rgb,.05*c+.012,.5*c*c*s.fade)}}),this.sparkGeo.setDrawRange(0,t);for(const s of["position","aColor","aSize","aAlpha"]){const o=this.sparkGeo.getAttribute(s);o.clearUpdateRanges();const r=s==="position"||s==="aColor"?3:1;o.addUpdateRange(0,Math.max(1,t*r)),o.needsUpdate=!0}}stepAgents(e,t){let i=0;this.agents.forEach((a,s)=>{const o=t-a.last,r=o>x$&&a.busy===0?this.dockWorld():null;r&&(a.target=r);const l=!!r&&Math.hypot(a.head[0]-r[0],a.head[1]-r[1],a.head[2]-r[2])<.35,c=o<v$&&!l;if(a.fade+=((c?1:0)-a.fade)*Math.min(1,e*2.5),a.energy*=Math.exp(-e*.8),!c&&a.fade<.02){a.el.remove(),this.agents.delete(s);return}if(this.reduced)a.head=[a.target[0],a.target[1],a.target[2]];else{const p=this.time,h=.09+.06*a.energy,d=a.target[0]+Math.sin(p*1.3+a.seed)*h,u=a.target[1]+Math.sin(p*1.7+a.seed*2)*h,f=a.target[2]+Math.sin(p*1.1+a.seed*3)*h;for(let v=0;v<3;v++){const m=((v===0?d:v===1?u:f)-a.head[v])*7-a.vel[v]*3.6;a.vel[v]+=m*e,a.head[v]+=a.vel[v]*e}}a.hist.set(a.head,a.histI*3),a.histI=(a.histI+1)%pa,a.histN=Math.min(pa,a.histN+1),a.el.classList.toggle("busy",a.busy>0);for(let p=0;p<a.histN-1&&i+2<=Yh;p++){const h=(a.histI-1-p+pa*2)%pa,d=(a.histI-2-p+pa*2)%pa,u=Math.pow(1-p/a.histN,1.6)*a.fade,f=Math.pow(1-(p+1)/a.histN,1.6)*a.fade;this.trailPos.set(a.hist.subarray(h*3,h*3+3),i*3),this.trailPos.set(a.hist.subarray(d*3,d*3+3),i*3+3),this.trailCol.set(a.rgb,i*3),this.trailCol.set(a.rgb,i*3+3),this.trailAlpha[i]=u,this.trailAlpha[i+1]=f,i+=2}}),this.trailGeo.setDrawRange(0,i);for(const a of["position","aColor","aAlpha"])this.trailGeo.getAttribute(a).needsUpdate=!0}}const E$=`
8589
+ }`;function A$(n){return Math.max(4,Math.min(12,Math.floor(8e4/Math.max(1,n))))}function jh(n,e,t){let i=(Math.imul(n+1,2654435761)^Math.imul(e+7,2246822519)^Math.imul(t+3,3266489917))>>>0;return i=Math.imul(i^i>>>15,739982445)>>>0,i=Math.imul(i^i>>>12,695872825)>>>0,((i^i>>>15)>>>0)/4294967296}function bx(n,e,t,i,a,s){e>t&&([e,t]=[t,e],i=1-i);const o=n[e*3],r=n[e*3+1],l=n[e*3+2],c=n[t*3]-o,p=n[t*3+1]-r,h=n[t*3+2]-l,d=Math.hypot(c,p,h)||1e-6;let u=-h,f=0,v=c;Math.abs(p)>.9*d&&(u=0,f=h,v=-p);const g=Math.hypot(u,f,v)||1;u/=g,f/=g,v/=g;let m=(p*v-h*f)/d,x=(h*u-c*v)/d,_=(c*f-p*u)/d;const w=jh(e,t,0)*Math.PI*2,S=d*(.12+.16*jh(e,t,1)),A=u*Math.cos(w)+m*Math.sin(w),C=f*Math.cos(w)+x*Math.sin(w),y=v*Math.cos(w)+_*Math.sin(w),M=jh(e,t,2)<.65?-.8:.9,T=.86,L=(o+c/3)*T+A*S,P=(r+p/3)*T+C*S,z=(l+h/3)*T+y*S,R=(o+c*2/3)*T+A*S*M,B=(r+p*2/3)*T+C*S*M,K=(l+h*2/3)*T+y*S*M,N=1-i,V=N*N*N,Z=3*N*N*i,te=3*N*i*i,ce=i*i*i,Ne=Math.sin(i*Math.PI*(3+2*jh(e,t,3))+w)*Math.sin(Math.PI*i)*d*.035;m*=Ne,x*=Ne,_*=Ne,a[s]=V*o+Z*L+te*R+ce*(o+c)+m,a[s+1]=V*r+Z*P+te*B+ce*(r+p)+x,a[s+2]=V*l+Z*z+te*K+ce*(l+h)+_}function an(n,e,t=!0){const i=new ra(n,e);return t&&i.setUsage(qR),i}const r_=n=>n<.5?4*n*n*n:1-Math.pow(-2*n+2,3)/2;class T${constructor(e,t,i,a){this.scene=new d5,this.light=!1,this.dprCap=2,this.n=0,this.keys=[],this.pos=new Float32Array(0),this.tgt=new Float32Array(0),this.col=new Float32Array(0),this.base=new Float32Array(0),this.grow=new Float32Array(0),this.growT=new Float32Array(0),this.flare=new Float32Array(0),this.dim=new Float32Array(0),this.dimT=new Float32Array(0),this.sizeA=new Float32Array(0),this.phase=new Float32Array(0),this.active=new Set,this.ghosts=0,this.ghostTimer=0,this.noteGeo=new pn,this.linkPairs=new Int32Array(0),this.linkSeg=1,this.tmp3=new Float32Array(3),this.adjOff=new Int32Array(1),this.adj=new Int32Array(0),this.linkGeo=new pn,this.linksDirty=!1,this.hiGeo=new pn,this.hiFor=-1,this.shellGeo=new pn,this.sparks=[],this.sparkGeo=new pn,this.sparkPos=new Float32Array(Xc*3),this.sparkCol=new Float32Array(Xc*3),this.sparkSize=new Float32Array(Xc),this.sparkAlpha=new Float32Array(Xc),this.trailGeo=new pn,this.trailPos=new Float32Array(Yh*3),this.trailCol=new Float32Array(Yh*3),this.trailAlpha=new Float32Array(Yh),this.agents=new Map,this.dock=null,this.ambientAcc=0,this.r=Wc(1234),this.regionLabels=[],this.hiddenRegions=new Set,this.noteLabels=[],this.showLabels=!0,this.raf=0,this.running=!1,this.disposed=!1,this.time=0,this.last=0,this.lastInteract=performance.now(),this.autoRotate=!0,this.selected=-1,this.hovered=-1,this.pointer={x:0,y:0,dirty:!1,inside:!1},this.down=null,this.tween=null,this.zoomTween=null,this.width=1,this.height=1,this.sized=!1,this.fovTarget=42,this.tmp=new X,this.vp=new en,this.onWindowResize=()=>{(this.host.clientWidth!==this.width||this.host.clientHeight!==this.height)&&this.resize()},this.onMove=c=>{if(c.pointerType==="touch")return;const p=this.canvas.getBoundingClientRect();this.pointer.x=c.clientX-p.left,this.pointer.y=c.clientY-p.top,this.pointer.dirty=!0,this.pointer.inside=!0,this.running||this.pickHover()},this.onLeave=()=>{this.pointer.inside=!1,this.pointer.dirty=!0},this.onDown=c=>{this.down={x:c.clientX,y:c.clientY,t:performance.now()}},this.onUp=c=>{const p=this.down;if(this.down=null,!p||Math.hypot(c.clientX-p.x,c.clientY-p.y)>6||performance.now()-p.t>600)return;const h=this.canvas.getBoundingClientRect(),d=this.pick(c.clientX-h.left,c.clientY-h.top,c.pointerType==="touch"?26:16);this.cb.onPick(d)},this.host=e,this.labels=t,this.cb=i,this.reduced=a,this.autoRotate=!a,this.renderer=new ZI({antialias:!1,alpha:!0,powerPreference:"high-performance"}),this.renderer.setClearColor(0,0),this.canvas=this.renderer.domElement,this.canvas.className="brain-canvas",e.appendChild(this.canvas),this.camera=new wi(o_,1,.05,60),this.camera.position.set(...mx),this.controls=new QI(this.camera,this.canvas),this.controls.enableDamping=!0,this.controls.dampingFactor=.07,this.controls.rotateSpeed=.7,this.controls.zoomSpeed=.9,this.controls.minDistance=.35,this.controls.maxDistance=9,this.controls.autoRotateSpeed=.55,this.controls.target.set(...Po),this.controls.addEventListener("start",()=>{this.lastInteract=performance.now(),this.controls.autoRotate=!1,this.tween=null,this.zoomTween=null}),this.noteMat=new Pn({vertexShader:y$,fragmentShader:w$,uniforms:{uTime:{value:0},uScale:{value:400},uLight:{value:0}},transparent:!0,depthWrite:!1,blending:za}),this.notePts=new tx(this.noteGeo,this.noteMat),this.notePts.frustumCulled=!1,this.notePts.renderOrder=3,this.linkMat=new Pn({vertexShader:vx,fragmentShader:xx,uniforms:{uOpacity:{value:.14},uLight:{value:0}},transparent:!0,depthWrite:!1,blending:za}),this.linkObj=new Qv(this.linkGeo,this.linkMat),this.linkObj.frustumCulled=!1,this.linkObj.renderOrder=1,this.hiMat=new Pn({vertexShader:vx,fragmentShader:xx,uniforms:{uOpacity:{value:.85},uLight:{value:0}},transparent:!0,depthWrite:!1,blending:za}),this.hiObj=new Qv(this.hiGeo,this.hiMat),this.hiObj.frustumCulled=!1,this.hiObj.renderOrder=2;const s=a_(window.innerWidth<700?14e3:26e3);this.shellGeo.setAttribute("position",an(s.pos.subarray(0,s.count*3),3,!1)),this.shellGeo.setAttribute("normal",an(s.nrm.subarray(0,s.count*3),3,!1)),this.shellGeo.setAttribute("aShade",an(s.shade.subarray(0,s.count),1,!1)),this.shellMat=new Pn({vertexShader:k$,fragmentShader:_$,uniforms:{uTime:{value:0},uScale:{value:400},uSize:{value:.0105},uLight:{value:0},uFade:{value:1},uColA:{value:new X(.36,.42,.98)},uColB:{value:new X(.37,.92,.83)}},transparent:!0,depthWrite:!1,blending:za});const o=new tx(this.shellGeo,this.shellMat);o.frustumCulled=!1,o.renderOrder=0,this.sparkGeo.setAttribute("position",an(this.sparkPos,3)),this.sparkGeo.setAttribute("aColor",an(this.sparkCol,3)),this.sparkGeo.setAttribute("aSize",an(this.sparkSize,1)),this.sparkGeo.setAttribute("aAlpha",an(this.sparkAlpha,1)),this.sparkGeo.setDrawRange(0,0),this.sparkMat=new Pn({vertexShader:S$,fragmentShader:M$,uniforms:{uScale:{value:400},uLight:{value:0}},transparent:!0,depthWrite:!1,depthTest:!1,blending:za});const r=new tx(this.sparkGeo,this.sparkMat);r.frustumCulled=!1,r.renderOrder=5,this.trailGeo.setAttribute("position",an(this.trailPos,3)),this.trailGeo.setAttribute("aColor",an(this.trailCol,3)),this.trailGeo.setAttribute("aAlpha",an(this.trailAlpha,1)),this.trailGeo.setDrawRange(0,0),this.trailMat=new Pn({vertexShader:vx,fragmentShader:xx,uniforms:{uOpacity:{value:1},uLight:{value:0}},transparent:!0,depthWrite:!1,depthTest:!1,blending:za});const l=new Qv(this.trailGeo,this.trailMat);l.frustumCulled=!1,l.renderOrder=4,this.scene.add(o,this.linkObj,this.hiObj,this.notePts,l,r),this.reticle=document.createElement("div"),this.reticle.className="bl-reticle hidden",t.appendChild(this.reticle),this.ro=new ResizeObserver(()=>this.resize()),this.ro.observe(e),window.addEventListener("resize",this.onWindowResize),this.resize(),this.camera.position.copy(this.homePos()),this.canvas.addEventListener("pointermove",this.onMove),this.canvas.addEventListener("pointerdown",this.onDown),this.canvas.addEventListener("pointerup",this.onUp),this.canvas.addEventListener("pointerleave",this.onLeave)}resize(){const e=Math.max(1,this.host.clientWidth),t=Math.max(1,this.host.clientHeight);this.glide(),this.width=e,this.height=t;const i=Math.min(window.devicePixelRatio||1,this.dprCap);this.renderer.setPixelRatio(i),this.renderer.setSize(e,t,!1),this.camera.aspect=e/t,this.fovTarget=e/t<.9?58:42,(!this.sized||this.reduced)&&(this.camera.fov=this.fovTarget),this.sized=!0,this.applyFraming(),this.renderOnce()}glide(){const e=this.host.parentElement;if(!this.sized||this.reduced||!e)return;const t=this.canvas.getBoundingClientRect(),i=e.getBoundingClientRect(),a=t.left+t.width/2-(i.left+i.width/2),s=t.top+t.height/2-(i.top+i.height/2);if(!(Math.abs(a)<1&&Math.abs(s)<1)){for(const o of[this.host,this.labels])o.style.transition="none",o.style.transform=`translate3d(${a.toFixed(1)}px,${s.toFixed(1)}px,0)`;this.host.offsetWidth;for(const o of[this.host,this.labels])o.style.transition="transform .45s cubic-bezier(.2,.8,.2,1)",o.style.transform=""}}applyFraming(){this.camera.updateProjectionMatrix();const e=Math.min(window.devicePixelRatio||1,this.dprCap),t=this.height*e/(2*Math.tan(this.camera.fov*Math.PI/360));this.noteMat.uniforms.uScale.value=t,this.shellMat.uniforms.uScale.value=t,this.sparkMat.uniforms.uScale.value=t}easeFraming(e){if(this.camera.fov===this.fovTarget)return;const t=1-Math.exp(-e*9);this.camera.fov+=(this.fovTarget-this.camera.fov)*t,Math.abs(this.camera.fov-this.fovTarget)<=.01&&(this.camera.fov=this.fovTarget),this.applyFraming()}start(){if(this.running||this.disposed)return;this.running=!0,this.last=performance.now();const e=t=>{if(!this.running)return;this.raf=requestAnimationFrame(e);const i=Math.min(.05,(t-this.last)/1e3);this.last=t,this.easeFraming(i),this.frame(i,t)};this.raf=requestAnimationFrame(e)}stop(){this.running=!1,cancelAnimationFrame(this.raf)}dispose(){if(!this.disposed){this.stop(),this.disposed=!0,this.ro.disconnect(),window.removeEventListener("resize",this.onWindowResize),clearTimeout(this.ghostTimer),this.canvas.removeEventListener("pointermove",this.onMove),this.canvas.removeEventListener("pointerdown",this.onDown),this.canvas.removeEventListener("pointerup",this.onUp),this.canvas.removeEventListener("pointerleave",this.onLeave),this.controls.dispose();for(const e of[this.noteGeo,this.linkGeo,this.hiGeo,this.shellGeo,this.sparkGeo,this.trailGeo])e.dispose();for(const e of[this.noteMat,this.linkMat,this.hiMat,this.shellMat,this.sparkMat,this.trailMat])e.dispose();this.renderer.dispose(),this.renderer.forceContextLoss(),this.canvas.remove(),this.labels.innerHTML="",this.agents.clear()}}renderOnce(){this.disposed||this.renderer.render(this.scene,this.camera)}setTheme(e){this.light=e;const t=e?Ar:za;for(const s of[this.noteMat,this.linkMat,this.hiMat,this.shellMat,this.sparkMat,this.trailMat])s.blending=t,s.uniforms.uLight.value=e?1:0,s.needsUpdate=!0;const i=this.shellMat.uniforms.uColA.value,a=this.shellMat.uniforms.uColB.value;e?(i.set(.3,.36,.52),a.set(.2,.45,.5)):(i.set(.36,.42,.98),a.set(.37,.92,.83)),this.updateLinkOpacity(),this.renderOnce()}setAutoRotate(e){this.autoRotate=e&&!this.reduced,this.autoRotate?this.lastInteract=0:this.controls.autoRotate=!1}setLabels(e,t=e){this.showLabels=e||t,this.labels.classList.toggle("no-labels",!e&&!t),this.labels.classList.toggle("no-notes",!e),this.labels.classList.toggle("no-regions",!t)}setData(e,t,i){const a=new Map;for(let M=0;M<this.n;M++)this.growT[M]>0&&a.set(this.keys[M],M);const s=new Set(e.map(M=>M.key)),o=[];a.forEach((M,T)=>{s.has(T)||o.push(M)});const r=e.length+o.length,l=new Float32Array(r*3),c=new Float32Array(r*3),p=new Float32Array(r*3),h=new Float32Array(r),d=new Float32Array(r),u=new Float32Array(r),f=new Float32Array(r),v=new Float32Array(r),g=new Float32Array(r),m=new Float32Array(r),x=[],_=this.n===0,w=new Set;e.forEach((M,T)=>{x.push(M.key);const L=a.get(M.key);c.set(M.target,T*3);const P=p2(M.color);if(p.set(P,T*3),h[T]=M.size,u[T]=1,m[T]=hx(M.key)%6283/1e3,L!==void 0)l[T*3]=this.pos[L*3],l[T*3+1]=this.pos[L*3+1],l[T*3+2]=this.pos[L*3+2],d[T]=this.grow[L],f[T]=this.flare[L],v[T]=this.dim[L],g[T]=this.dimT[L],(l[T*3]!==c[T*3]||l[T*3+1]!==c[T*3+1]||l[T*3+2]!==c[T*3+2])&&w.add(T),(d[T]<1||f[T]>.001||v[T]!==g[T])&&w.add(T);else if(_&&!this.reduced){const z=1.25+this.r()*.2,R=Math.hypot(M.target[0],M.target[1],M.target[2])||1;l.set([M.target[0]/R*z,M.target[1]/R*z,M.target[2]/R*z],T*3),d[T]=0,w.add(T)}else _?(l.set(M.target,T*3),d[T]=1):(l.set(M.origin,T*3),d[T]=0,f[T]=1,w.add(T))}),o.forEach((M,T)=>{const L=e.length+T;x.push(this.keys[M]);for(let P=0;P<3;P++)l[L*3+P]=this.pos[M*3+P],c[L*3+P]=this.pos[M*3+P],p[L*3+P]=this.col[M*3+P];h[L]=this.base[M],d[L]=this.grow[M],u[L]=0,f[L]=.8,w.add(L)}),this.n=r,this.keys=x,this.pos=l,this.tgt=c,this.col=p,this.base=h,this.grow=d,this.growT=u,this.flare=f,this.dim=v,this.dimT=g,this.phase=m,this.sizeA=new Float32Array(r);for(let M=0;M<r;M++)this.sizeA[M]=h[M]*d[M];this.active=w,this.ghosts=o.length,this.sparks=this.sparks.filter(M=>M.target<0),this.selected>=0&&(this.selected=-1),this.hovered=-1,this.hiFor=-2,this.noteGeo.dispose(),this.noteGeo=new pn,this.noteGeo.setAttribute("position",an(this.pos,3)),this.noteGeo.setAttribute("aColor",an(this.col,3)),this.noteGeo.setAttribute("aSize",an(this.sizeA,1)),this.noteGeo.setAttribute("aFlare",an(this.flare,1)),this.noteGeo.setAttribute("aDim",an(this.dim,1)),this.noteGeo.setAttribute("aPhase",an(this.phase,1,!1)),this.notePts.geometry=this.noteGeo;const S=t.length;this.linkPairs=new Int32Array(S*2);const A=new Int32Array(r+1);t.forEach(([M,T],L)=>{this.linkPairs[L*2]=M,this.linkPairs[L*2+1]=T,A[M]++,A[T]++}),this.adjOff=new Int32Array(r+1);for(let M=0;M<r;M++)this.adjOff[M+1]=this.adjOff[M]+A[M];this.adj=new Int32Array(this.adjOff[r]);const C=this.adjOff.slice(0,r);t.forEach(([M,T])=>{this.adj[C[M]++]=T,this.adj[C[T]++]=M}),this.linkGeo.dispose(),this.linkGeo=new pn,this.linkSeg=A$(S);const y=S*this.linkSeg*2;this.linkGeo.setAttribute("position",an(new Float32Array(y*3),3)),this.linkGeo.setAttribute("aColor",an(new Float32Array(y*3),3)),this.linkGeo.setAttribute("aAlpha",an(new Float32Array(y),1)),this.linkObj.geometry=this.linkGeo,this.linksDirty=!0,this.fillLinks(!0),this.updateLinkOpacity();for(const M of this.regionLabels)M.el.remove();this.regionLabels=i.map(M=>{const T=document.createElement("div");return T.className="bl-region",T.style.setProperty("--c",M.color),T.textContent=M.name,this.labels.appendChild(T),{el:T,anchor:M.anchor,name:M.name}}),this.pickNoteLabels(),clearTimeout(this.ghostTimer),o.length&&(this.ghostTimer=window.setTimeout(()=>this.compact(),1400)),this.running||this.renderOnce()}compact(){if(this.disposed||!this.ghosts)return;const e=this.n-this.ghosts,t=[];for(let l=0;l<e;l++){const c=[this.tgt[l*3],this.tgt[l*3+1],this.tgt[l*3+2]],p=this.col.subarray(l*3,l*3+3),h="#"+Array.from(p,d=>Math.round(d*255).toString(16).padStart(2,"0")).join("");t.push({key:this.keys[l],target:c,origin:c,color:h,size:this.base[l]})}const i=[];for(let l=0;l<this.linkPairs.length;l+=2)this.linkPairs[l]<e&&this.linkPairs[l+1]<e&&i.push([this.linkPairs[l],this.linkPairs[l+1]]);const a=this.dimT.slice(0,e),s=this.regionLabels,o=this.selected;this.n=e,this.ghosts=0;const r=s.map(l=>({name:l.el.textContent||"",anchor:l.anchor,color:l.el.style.getPropertyValue("--c"),count:0}));this.setData(t,i,r),this.dimT.set(a),this.dim.set(a),o>=0&&o<e&&this.select(o)}updateLinkOpacity(){const e=this.linkPairs.length/2,t=Math.min(1,Math.sqrt(2500/Math.max(1,e)));this.linkMat.uniforms.uOpacity.value=(this.light?.15:.12)*Math.max(.35,t)}fillLinks(e=!1){const t=this.linkGeo,i=t.getAttribute("position"),a=t.getAttribute("aAlpha");if(this.linksDirty=!1,!i||!a)return;const s=i.array,o=a.array,r=e?t.getAttribute("aColor").array:null,l=this.linkPairs,c=this.linkSeg,p=new Float32Array(3*(c+1));for(let h=0,d=l.length/2;h<d;h++){const u=l[h*2],f=l[h*2+1];for(let g=0;g<=c;g++)bx(this.pos,u,f,g/c,p,g*3);const v=this.grow[u]*(1-this.dim[u]*.92)*this.grow[f]*(1-this.dim[f]*.92);for(let g=0;g<c;g++){const m=(h*c+g)*2;if(s.set(p.subarray(g*3,g*3+6),m*3),o[m]=v*(.5+.5*Math.sin(Math.PI*g/c)),o[m+1]=v*(.5+.5*Math.sin(Math.PI*(g+1)/c)),r)for(let x=0;x<2;x++){const _=(g+x)/c;for(let w=0;w<3;w++)r[(m+x)*3+w]=this.col[u*3+w]*(1-_)+this.col[f*3+w]*_}}}i.needsUpdate=!0,a.needsUpdate=!0,r&&(t.getAttribute("aColor").needsUpdate=!0),this.linksDirty=!1}buildHighlight(e){if(this.hiFor===e||(this.hiFor=e,this.hiGeo.dispose(),this.hiGeo=new pn,this.hiObj.geometry=this.hiGeo,e<0||e>=this.n))return;const t=this.neighbors(e),i=16,a=new Float32Array(t.length*i*6),s=new Float32Array(t.length*i*6),o=new Float32Array(t.length*i*2),r=new Float32Array(3*(i+1));t.forEach((l,c)=>{for(let p=0;p<=i;p++)bx(this.pos,e,l,p/i,r,p*3);for(let p=0;p<i;p++){const h=(c*i+p)*2;a.set(r.subarray(p*3,p*3+6),h*3);for(let d=0;d<2;d++){const u=(p+d)/i;o[h+d]=1-.45*u;for(let f=0;f<3;f++)s[(h+d)*3+f]=Math.min(1,this.col[e*3+f]*.6+.4)*(1-u)+this.col[l*3+f]*u}}}),this.hiGeo.setAttribute("position",an(a,3)),this.hiGeo.setAttribute("aColor",an(s,3,!1)),this.hiGeo.setAttribute("aAlpha",an(o,1,!1))}neighbors(e){return e<0||e>=this.n?[]:Array.from(this.adj.subarray(this.adjOff[e],this.adjOff[e+1]))}setDim(e){for(let t=0;t<this.n-this.ghosts;t++){const i=e?e(t):0;this.dimT[t]!==i&&(this.dimT[t]=i,this.active.add(t))}if(this.reduced){this.dim.set(this.dimT);const t=this.noteGeo.getAttribute("aDim");t&&(t.needsUpdate=!0),this.linksDirty=!0}this.running||this.renderOnce()}select(e){if(this.selected=e,this.buildHighlight(e),this.reticle.classList.toggle("hidden",e<0),e>=0){this.flareNote(e,.7);const t=this.col.subarray(e*3,e*3+3);this.reticle.style.setProperty("--c",`rgb(${t[0]*255|0},${t[1]*255|0},${t[2]*255|0})`)}}flareNote(e,t=1){e<0||e>=this.n||(this.flare[e]=Math.max(this.flare[e],t),this.active.add(e))}setDock(e){this.dock=e}dockWorld(){const e=this.dock?.(),t=this.canvas.getBoundingClientRect();if(!e||!t.width||!t.height)return null;this.camera.updateMatrixWorld();const i=new X((e.x-t.left)/t.width*2-1,-((e.y-t.top)/t.height*2-1),.5).unproject(this.camera),a=this.camera.position,s=i.sub(a).normalize(),o=a.distanceTo(this.controls.target)*.55;return[a.x+s.x*o,a.y+s.y*o,a.z+s.z*o]}agentHead(e){const t=this.agents.get(e);return t&&t.fade>.05?[t.head[0],t.head[1],t.head[2]]:null}positionOf(e){return[this.pos[e*3],this.pos[e*3+1],this.pos[e*3+2]]}focus(e,t){const i=new X(e[0],e[1],e[2]),a=this.camera.position.clone().sub(this.controls.target).normalize(),s=i.clone().setY(i.y*.5);s.length()>.15&&a.lerp(s.normalize(),.55).normalize();const o=i.clone().add(a.multiplyScalar(t));if(this.zoomTween=null,this.controls.autoRotate=!1,this.lastInteract=performance.now(),this.reduced){this.camera.position.copy(o),this.controls.target.copy(i),this.controls.update();return}this.tween={p0:this.camera.position.clone(),p1:o,t0:this.controls.target.clone(),t1:i,s:0,dur:1.1}}cameraView(){const e=this.canvas.getBoundingClientRect();if(!e.width||!e.height)return null;const t=this.camera.position,i=this.controls.target;return{eye:[t.x,t.y,t.z],target:[i.x,i.y,i.z],fov:this.camera.fov*Math.PI/180,rect:{x:e.left,y:e.top,w:e.width,h:e.height}}}projectToClient(e,t,i){const a=this.canvas.getBoundingClientRect();if(!a.width||!a.height)return null;this.camera.updateMatrixWorld();const s=new X(e,t,i).project(this.camera);return[a.left+(s.x+1)/2*a.width,a.top+(1-s.y)/2*a.height,s.z]}awayFromHome(){if(this.tween||this.zoomTween)return!0;const e=gx(this.camera.aspect),t=this.controls.target,i=this.camera.position.distanceTo(t);return t.distanceTo(new X(...Po))>e*.04||Math.abs(i-e)>e*.06}homePos(){return new X(...mx).normalize().multiplyScalar(gx(this.camera.aspect))}resetView(){const e=new X(...Po),t=this.homePos().length();if(this.tween=null,this.reduced){const i=this.camera.position.clone().sub(this.controls.target).normalize();this.controls.target.copy(e),this.camera.position.copy(e).addScaledVector(i,t),this.controls.update();return}this.zoomTween={d0:this.camera.position.distanceTo(this.controls.target),d1:t,t0:this.controls.target.clone(),t1:e,s:0,dur:.9}}zoomBy(e){const t=this.camera.position.distanceTo(this.controls.target),i=Math.max(this.controls.minDistance,Math.min(this.controls.maxDistance,t/e));if(this.halt(),this.reduced){const a=this.camera.position.clone().sub(this.controls.target).normalize();this.camera.position.copy(this.controls.target).addScaledVector(a,i),this.controls.update();return}this.zoomTween={d0:t,d1:i,t0:this.controls.target.clone(),t1:this.controls.target.clone(),s:0,dur:.35}}orbitBy(e,t){const i=this.controls.target,a=this.camera.position.clone().sub(i),s=a.length(),o=Math.atan2(a.x,a.z)+e,r=Math.max(.12,Math.min(Math.PI-.12,Math.acos(Math.max(-1,Math.min(1,a.y/s)))-t));this.orbitTo(o,r,.32)}orbitTo(e,t,i=.8){const a=this.controls.target,s=this.camera.position.clone().sub(a),o=s.length(),r=t??Math.acos(Math.max(-1,Math.min(1,s.y/o))),l=new X(Math.sin(r)*Math.sin(e),Math.cos(r),Math.sin(r)*Math.cos(e)).multiplyScalar(o).add(a);if(this.halt(),this.reduced){this.camera.position.copy(l),this.controls.update();return}this.tween={p0:this.camera.position.clone(),p1:l,t0:a.clone(),t1:a.clone(),s:0,dur:i,arc:!0}}goHome(){this.halt();const e=this.homePos().add(new X(...Po)),t=new X(...Po);if(this.reduced){this.camera.position.copy(e),this.controls.target.copy(t),this.controls.update();return}this.tween={p0:this.camera.position.clone(),p1:e,t0:this.controls.target.clone(),t1:t,s:0,dur:.9,arc:!0}}orientation(){const e=this.camera.position.clone().sub(this.controls.target),t=e.length()||1;return{yaw:Math.atan2(e.x,e.z),pitch:Math.asin(Math.max(-1,Math.min(1,e.y/t)))}}halt(){this.tween=null,this.zoomTween=null,this.controls.autoRotate=!1,this.lastInteract=performance.now()}activity(e,t,i,a){const s=performance.now();let o=this.agents.get(e);if(!o){const l=xn(e),c=hx(e),p=Wc(c),h=[(p()*2-1)*.5,(p()-.4)*.5,(p()*2-1)*.6],d=document.createElement("div");d.className="bl-agent",d.style.setProperty("--c",l),d.innerHTML="<b></b><span></span>",d.firstChild.textContent=xl(e),d.lastChild.textContent=e,this.labels.appendChild(d);const u=this.dockWorld();o={rgb:p2(l),head:u||[h[0],h[1]+.9,h[2]],vel:[0,0,0],target:h,seed:c%1e3/100,hist:new Float32Array(pa*3),histN:0,histI:0,last:s,energy:1,fade:0,busy:0,el:d},this.agents.set(e,o)}o.last=s,o.energy=1,t==="start"?o.busy++:o.busy=Math.max(0,o.busy-1);const r=a.filter(l=>l>=0&&l<this.n).slice(0,40);if(r.length){let l=0,c=0,p=0;for(const f of r)l+=this.pos[f*3],c+=this.pos[f*3+1],p+=this.pos[f*3+2];const h=1/r.length;o.target=[l*h*.85,c*h*.85,p*h*.85];const u=i===!1?[1,.35,.35]:o.rgb;r.forEach((f,v)=>{if(this.reduced){this.flareNote(f,1);return}this.spark(o.head,f,u,v*.07,t==="end"?.7:1.05,.085,1,!0)})}}spark(e,t,i,a,s,o,r,l,c,p){if(this.sparks.length>900)return;const h=c||this.positionOf(t),d=[e[0],e[1],e[2]],u=(d[0]+h[0])/2,f=(d[1]+h[1])/2,v=(d[2]+h[2])/2,m=Math.hypot(h[0]-d[0],h[1]-d[1],h[2]-d[2])*.35,x=[u*.7+(this.r()-.5)*m,f*.7+(this.r()-.5)*m,v*.7+(this.r()-.5)*m];this.sparks.push({a:d,b:h,c:x,target:t,t:0,dur:s,delay:a,rgb:i,size:o,alpha:r,strength:l?1:.35,echo:l,from:p})}pickHover(){this.pointer.dirty=!1;const e=this.pointer.inside?this.pick(this.pointer.x,this.pointer.y,14):-1;e!==this.hovered&&(this.hovered=e,this.selected<0&&this.buildHighlight(e)),this.cb.onHover(e,this.pointer.x,this.pointer.y)}pick(e,t,i){this.camera.updateMatrixWorld(),this.vp.multiplyMatrices(this.camera.projectionMatrix,this.camera.matrixWorldInverse);const a=this.vp.elements,s=this.width,o=this.height;let r=-1,l=i*i;for(let c=0,p=this.n-this.ghosts;c<p;c++){if(this.dimT[c]>.6)continue;const h=this.pos[c*3],d=this.pos[c*3+1],u=this.pos[c*3+2],f=a[3]*h+a[7]*d+a[11]*u+a[15];if(f<=.01)continue;const v=((a[0]*h+a[4]*d+a[8]*u+a[12])/f*.5+.5)*s,g=(.5-(a[1]*h+a[5]*d+a[9]*u+a[13])/f*.5)*o,m=v-e,x=g-t,_=m*m+x*x+f*2;_<l&&(l=_,r=c)}return r}project(e){return this.tmp.set(e[0],e[1],e[2]).project(this.camera),this.tmp.z>1?null:{x:(this.tmp.x*.5+.5)*this.width,y:(.5-this.tmp.y*.5)*this.height,depth:this.tmp.z}}pickNoteLabels(){for(const a of this.noteLabels)a.el.remove();const e=this.n-this.ghosts,t=e>4e3?5:8,i=Array.from({length:e},(a,s)=>s).filter(a=>this.dimT[a]<.5).sort((a,s)=>this.base[s]-this.base[a]).slice(0,t);this.noteLabels=i.map(a=>{const s=document.createElement("div");return s.className="bl-note",s.textContent=this.cb.labelOf(a),this.labels.appendChild(s),{el:s,index:a}})}setHiddenRegions(e){this.hiddenRegions=new Set(e),this.renderOnce()}refreshNoteLabels(){this.pickNoteLabels()}placeLabels(){const e=this.camera.position.distanceTo(this.controls.target),t=this.controls.target,i=this.camera.position,a=[],s=(o,r,l=1,c=!1)=>{const p=this.project(r);if(!p||p.x<-50||p.y<-20||p.x>this.width+50||p.y>this.height+20){o.style.opacity="0";return}if(c){for(let f=0;f<a.length;f+=2)if(Math.abs(a[f]-p.x)<110&&Math.abs(a[f+1]-p.y)<16){o.style.opacity="0";return}a.push(p.x,p.y)}const h=Math.hypot(r[0]-i.x,r[1]-i.y,r[2]-i.z),d=Math.hypot(t.x-i.x,t.y-i.y,t.z-i.z),u=Math.max(0,Math.min(1,(h-d+.4)/.8));o.style.opacity=String((1-u*.7)*l),o.style.transform=`translate3d(${p.x.toFixed(1)}px,${p.y.toFixed(1)}px,0)`};if(this.showLabels){for(const o of this.regionLabels)this.hiddenRegions.has(o.name)?o.el.style.opacity="0":s(o.el,o.anchor,e<1.2?.35:1,!0);for(const o of this.noteLabels)o.index>=this.n||s(o.el,this.positionOf(o.index),(1-this.dim[o.index])*Math.min(1,this.grow[o.index]),!0)}this.selected>=0&&s(this.reticle,this.positionOf(this.selected)),this.agents.forEach(o=>s(o.el,o.head,o.fade))}frame(e,t){if(this.reduced||(this.time+=e),this.noteMat.uniforms.uTime.value=this.time,this.shellMat.uniforms.uTime.value=this.time,this.zoomTween){const s=this.zoomTween;s.s=Math.min(1,s.s+e/s.dur);const o=r_(s.s),r=this.camera.position.clone().sub(this.controls.target).normalize();this.controls.target.lerpVectors(s.t0,s.t1,o),this.camera.position.copy(this.controls.target).addScaledVector(r,s.d0+(s.d1-s.d0)*o),s.s>=1&&(this.zoomTween=null)}if(this.tween){const s=this.tween;s.s=Math.min(1,s.s+e/s.dur);const o=r_(s.s);if(this.controls.target.lerpVectors(s.t0,s.t1,o),s.arc){const r=s.p0.clone().sub(s.t0),l=s.p1.clone().sub(s.t1),c=r.length()||1,p=l.length()||1,h=Math.atan2(r.x,r.z);let d=Math.atan2(l.x,l.z)-h;d-=Math.round(d/(Math.PI*2))*Math.PI*2;const u=Math.acos(Math.max(-1,Math.min(1,r.y/c))),f=Math.acos(Math.max(-1,Math.min(1,l.y/p))),v=h+d*o,g=u+(f-u)*o,m=c+(p-c)*o;this.camera.position.set(Math.sin(g)*Math.sin(v),Math.cos(g),Math.sin(g)*Math.cos(v)).multiplyScalar(m).add(this.controls.target)}else this.camera.position.lerpVectors(s.p0,s.p1,o);s.s>=1&&(this.tween=null)}else this.autoRotate&&!this.controls.autoRotate&&t-this.lastInteract>b$&&this.selected<0&&(this.controls.autoRotate=!0);this.controls.update(e);const i=this.camera.position.length();if(this.shellMat.uniforms.uFade.value=Math.max(.15,Math.min(1,(i-.6)/1.4)),this.active.size){const s=1-Math.exp(-e*3.2),o=1-Math.exp(-e*3.5),r=1-Math.exp(-e*7),l=Math.exp(-e*1.9);let c=!1,p=!1,h=!1;for(const u of this.active){let f=!0;for(let m=0;m<3;m++){const x=this.tgt[u*3+m]-this.pos[u*3+m];Math.abs(x)>1e-4?(this.pos[u*3+m]+=x*s,f=!1,c=!0):this.pos[u*3+m]=this.tgt[u*3+m]}const v=this.growT[u]-this.grow[u];v!==0&&(Math.abs(v)>.002?(this.grow[u]+=v*o,f=!1):this.grow[u]=this.growT[u],this.sizeA[u]=this.base[u]*this.grow[u],h=!0),this.flare[u]>.002?(this.flare[u]*=l,f=!1):this.flare[u]=0;const g=this.dimT[u]-this.dim[u];Math.abs(g)>.004?(this.dim[u]+=g*r,f=!1,p=!0):g!==0&&(this.dim[u]=this.dimT[u],p=!0),f&&this.active.delete(u)}const d=this.noteGeo;if(c&&(d.getAttribute("position").needsUpdate=!0),h&&(d.getAttribute("aSize").needsUpdate=!0),p&&(d.getAttribute("aDim").needsUpdate=!0),d.getAttribute("aFlare").needsUpdate=!0,(c||p||h)&&(this.linksDirty=!0),c&&this.hiFor>=0){const u=this.hiFor;this.hiFor=-2,this.buildHighlight(u)}}this.linksDirty&&this.fillLinks();const a=this.n-this.ghosts;if(!this.reduced&&a>1&&!document.hidden){this.ambientAcc+=e;const s=this.linkPairs.length?Math.max(.05,.35-a/2e4):.5;for(;this.ambientAcc>s;)if(this.ambientAcc-=s,this.linkPairs.length){const o=Math.floor(this.r()*(this.linkPairs.length/2));let r=this.linkPairs[o*2],l=this.linkPairs[o*2+1];if(this.r()<.5&&([r,l]=[l,r]),this.dimT[r]>.5||this.dimT[l]>.5)continue;const c=this.col.subarray(r*3,r*3+3);this.spark(this.positionOf(r),l,[c[0],c[1],c[2]],0,.9+this.r()*.6,.032,.55,!1,void 0,r)}else this.flareNote(Math.floor(this.r()*a),.35)}this.stepAgents(e,t),this.stepSparks(e),this.pointer.dirty&&this.pickHover(),this.placeLabels(),this.renderer.render(this.scene,this.camera)}stepSparks(e){let t=0;const i=(s,o,r,l,c,p)=>{t>=Xc||(this.sparkPos[t*3]=s,this.sparkPos[t*3+1]=o,this.sparkPos[t*3+2]=r,this.sparkCol[t*3]=l[0],this.sparkCol[t*3+1]=l[1],this.sparkCol[t*3+2]=l[2],this.sparkSize[t]=c,this.sparkAlpha[t]=p,t++)},a=[];for(const s of this.sparks){if(s.delay>0){s.delay-=e,a.push(s);continue}if(s.t+=e/s.dur,s.target>=0&&s.target<this.n&&(s.b[0]=this.pos[s.target*3],s.b[1]=this.pos[s.target*3+1],s.b[2]=this.pos[s.target*3+2]),s.t>=1){if(s.target>=0&&(this.flareNote(s.target,s.strength),s.echo)){const r=this.neighbors(s.target);for(let l=0;l<Math.min(4,r.length);l++){const c=r[Math.floor(this.r()*r.length)];this.spark(s.b,c,s.rgb,l*.05,.55,.04,.8,!1)}}continue}a.push(s);const o=s.echo?9:5;for(let r=0;r<o;r++){const l=s.t-r*(s.echo?.022:.03);if(l<0)break;let c,p,h;if(s.from!==void 0&&s.from<this.n&&s.target<this.n)bx(this.pos,s.from,s.target,l,this.tmp3,0),[c,p,h]=this.tmp3;else{const u=1-l;c=u*u*s.a[0]+2*u*l*s.c[0]+l*l*s.b[0],p=u*u*s.a[1]+2*u*l*s.c[1]+l*l*s.b[1],h=u*u*s.a[2]+2*u*l*s.c[2]+l*l*s.b[2]}const d=1-r/o;i(c,p,h,s.rgb,s.size*(.35+.65*d),s.alpha*d*d)}}this.sparks=a,this.agents.forEach(s=>{if(s.fade<=.01)return;const o=.5+.5*Math.sin(this.time*4+s.seed);i(s.head[0],s.head[1],s.head[2],s.rgb,(.32+.12*o+s.energy*.25)*(s.busy?1.15:.85),.32*s.fade),i(s.head[0],s.head[1],s.head[2],s.rgb,.1+s.energy*.05,s.fade);for(let r=2;r<s.histN;r+=3){const l=(s.histI-1-r+pa*2)%pa,c=1-r/s.histN;i(s.hist[l*3],s.hist[l*3+1],s.hist[l*3+2],s.rgb,.05*c+.012,.5*c*c*s.fade)}}),this.sparkGeo.setDrawRange(0,t);for(const s of["position","aColor","aSize","aAlpha"]){const o=this.sparkGeo.getAttribute(s);o.clearUpdateRanges();const r=s==="position"||s==="aColor"?3:1;o.addUpdateRange(0,Math.max(1,t*r)),o.needsUpdate=!0}}stepAgents(e,t){let i=0;this.agents.forEach((a,s)=>{const o=t-a.last,r=o>x$&&a.busy===0?this.dockWorld():null;r&&(a.target=r);const l=!!r&&Math.hypot(a.head[0]-r[0],a.head[1]-r[1],a.head[2]-r[2])<.35,c=o<v$&&!l;if(a.fade+=((c?1:0)-a.fade)*Math.min(1,e*2.5),a.energy*=Math.exp(-e*.8),!c&&a.fade<.02){a.el.remove(),this.agents.delete(s);return}if(this.reduced)a.head=[a.target[0],a.target[1],a.target[2]];else{const p=this.time,h=.09+.06*a.energy,d=a.target[0]+Math.sin(p*1.3+a.seed)*h,u=a.target[1]+Math.sin(p*1.7+a.seed*2)*h,f=a.target[2]+Math.sin(p*1.1+a.seed*3)*h;for(let v=0;v<3;v++){const m=((v===0?d:v===1?u:f)-a.head[v])*7-a.vel[v]*3.6;a.vel[v]+=m*e,a.head[v]+=a.vel[v]*e}}a.hist.set(a.head,a.histI*3),a.histI=(a.histI+1)%pa,a.histN=Math.min(pa,a.histN+1),a.el.classList.toggle("busy",a.busy>0);for(let p=0;p<a.histN-1&&i+2<=Yh;p++){const h=(a.histI-1-p+pa*2)%pa,d=(a.histI-2-p+pa*2)%pa,u=Math.pow(1-p/a.histN,1.6)*a.fade,f=Math.pow(1-(p+1)/a.histN,1.6)*a.fade;this.trailPos.set(a.hist.subarray(h*3,h*3+3),i*3),this.trailPos.set(a.hist.subarray(d*3,d*3+3),i*3+3),this.trailCol.set(a.rgb,i*3),this.trailCol.set(a.rgb,i*3+3),this.trailAlpha[i]=u,this.trailAlpha[i+1]=f,i+=2}}),this.trailGeo.setDrawRange(0,i);for(const a of["position","aColor","aAlpha"])this.trailGeo.getAttribute(a).needsUpdate=!0}}const E$=`
8590
8590
  #view-brain{padding:0;overflow:hidden}
8591
8591
  .brain{position:absolute;inset:0;overflow:hidden;isolation:isolate;color:var(--fg,#e6e9ef);
8592
8592
  --glass:var(--panel,#12161f);
@@ -8665,7 +8665,7 @@ void main() {
8665
8665
  <div class="brain-stage" data-el="stage"></div>
8666
8666
  <div class="brain-labels" data-el="labels"></div>
8667
8667
  <div class="brain-tip hidden" data-el="tip"></div>
8668
- <div class="brain-foot"><span class="brain-hint" data-el="hint">Drag to orbit · scroll to zoom · click a node</span></div>`}wireUi(){const e=this.els;this.chrome=new wg({page:"brain",root:this.root,search:{placeholder:"Find a node, #tag or in:folder",find:{items:()=>this.notes.map(t=>({id:t.path,name:t.name,folder:t.folder,region:t.folder,color:this.regions.get(t.folder)?.color||"#888",tags:t.tags,degree:t.degree})),hidden:t=>this.hidden.has(t),highlight:t=>{this.findHit=t,this.applyFilter()},pick:t=>{const i=this.notes.findIndex(a=>a.path===t.id);i>=0&&this.select(i,!0)},folder:t=>this.openFolder(t)}},labels:{get:()=>({nodes:this.prefs.labels,folders:this.prefs.regionLabels}),set:(t,i)=>{t==="nodes"?this.prefs.labels=i:this.prefs.regionLabels=i,Zh(this.prefs),this.scene?.setLabels(this.prefs.labels,this.prefs.regionLabels)},help:{nodes:"Names next to the nodes in the brain. The node under the pointer and the selected one always show theirs.",folders:"Region names (one region per folder) floating over the brain."}},filter:t=>this.renderFilter(t),changed:()=>{const t=yx(),i=this.prefs;return i.labels!==t.labels||i.regionLabels!==t.regionLabels||i.rotate!==t.rotate||this.hidden.size>0||!!this.findHit||this.selected>=0||this.card?.isOpen||!!this.scene?.awayFromHome()},reset:()=>{this.chrome.finder?.clear(),this.card.close(!0);const t=this.prefs.regions;this.prefs={...yx(),regions:t},Zh(this.prefs),this.scene?.setLabels(!0,!0),this.scene?.setAutoRotate(!0),this.setHidden([]),this.select(-1),this.scene?.goHome()},regions:{list:()=>Array.from(this.regions.values()).map(t=>({name:t.name,color:t.color,count:t.count,hidden:this.hidden.has(t.name)})),toggle:t=>{const i=new Set(this.hidden);i.has(t)?i.delete(t):i.add(t),this.setHidden(Array.from(i))},setAll:t=>this.setHidden(t?Array.from(this.regions.keys()):[]),focus:t=>this.openFolder(t)},nav:{zoom:t=>this.scene?.zoomBy(t),fit:()=>this.scene?.resetView(),nudge:(t,i)=>this.scene?.orbitBy(-t*.26,-i*.2),home:()=>{this.select(-1),this.scene?.goHome()}},minimap:(t,i,a,s)=>this.drawMini(t,i,a,s),minimapNav:(t,i)=>this.miniNav(t,i),onOverlay:()=>{this.select(-1),this.card.close(!0)}}),this.card=this.buildCard(),this.chromeTimer=window.setInterval(()=>{if(!this.scene||document.hidden)return;const t=this.scene.orientation();this.chrome.setOrientation(t.yaw,t.pitch),this.chrome.redrawMini()},120),this.root.addEventListener("keydown",t=>{t.target.closest("input,textarea,select")||(t.key==="/"||(t.ctrlKey||t.metaKey)&&t.key.toLowerCase()==="f")&&(t.preventDefault(),t.stopPropagation(),this.chrome.focusSearch())}),window.setTimeout(()=>e.hint.classList.add("gone"),7e3),this.root.addEventListener("keydown",t=>{t.key==="Escape"&&this.selected>=0&&this.select(-1)})}renderFilter(e){e.innerHTML="<h4>Brain</h4>"+(this.reduced?"":Ia("rotate","Rotate when idle",this.prefs.rotate,"The brain turns slowly by itself two seconds after you stop moving it. Only the 3D brain has this."))+'<div class="vc-hint">Drag to orbit · scroll to zoom · click a node · / to search · #tag finds tags</div>';const t=e.querySelector("[data-t=rotate]");t&&(t.onclick=()=>{this.prefs.rotate=!this.prefs.rotate,this.scene?.setAutoRotate(this.prefs.rotate),Zh(this.prefs),this.chrome.renderPanel()})}drawMini(e,t,i,a){const s=e.getContext("2d"),o=this.scene;if(!s||!o)return;const r=document.documentElement.dataset.theme==="light";s.setTransform(a,0,0,a,0,0),s.clearRect(0,0,t,i);const l=Math.min(t,i)/3.4,c=t/2,p=i/2,h=this.notes.length,d=Math.max(1,Math.ceil(h/2500));for(let A=0;A<h;A+=d){const C=this.notes[A];if(this.hidden.has(C.folder))continue;const[y,,M]=o.positionOf(A);s.fillStyle=this.regions.get(C.folder)?.color||"#888",s.globalAlpha=.75,s.fillRect(c+y*l-1,p+M*l-1,2,2)}s.globalAlpha=1,s.strokeStyle=r?"rgba(15,23,42,.18)":"rgba(230,233,239,.16)",s.lineWidth=1,s.beginPath(),s.ellipse(c,p,1.25*l,1.05*l,0,0,Math.PI*2),s.stroke();const u=o.cameraView();if(!u)return;const f=Math.atan2(u.eye[2]-u.target[2],u.eye[0]-u.target[0]),v=Math.min(t,i)/2-7,g=c+Math.cos(f)*v,m=p+Math.sin(f)*v,x=f+Math.PI,_=u.fov*.5*(u.rect.w/u.rect.h),w=v*1.25,S=r?"13,148,136":"94,234,212";s.strokeStyle=`rgba(${S},.18)`,s.beginPath(),s.arc(c,p,v,0,Math.PI*2),s.stroke(),s.save(),s.beginPath(),s.arc(c,p,v,0,Math.PI*2),s.clip(),s.fillStyle=`rgba(${S},.12)`,s.strokeStyle=`rgba(${S},.6)`,s.beginPath(),s.moveTo(g,m),s.lineTo(g+Math.cos(x-_)*w,m+Math.sin(x-_)*w),s.lineTo(g+Math.cos(x+_)*w,m+Math.sin(x+_)*w),s.closePath(),s.fill(),s.stroke(),s.restore(),s.fillStyle=`rgb(${S})`,s.beginPath(),s.arc(g,m,4,0,Math.PI*2),s.fill()}miniNav(e,t){const i=this.scene,a=i?.cameraView(),s=this.chrome.miniCanvas.getBoundingClientRect();if(!i||!a||!s.width)return;const o=Math.min(s.width,s.height)/3.4,r=(e*s.width-s.width/2)/o,l=(t*s.height-s.height/2)/o;Math.hypot(r-a.target[0],l-a.target[2])<.05||i.orbitTo(Math.atan2(r-a.target[0],l-a.target[2]),void 0,.6)}destroy(){Kd("brain",null),!this.destroyed&&(this.destroyed=!0,this.unsub.forEach(e=>e()),this.unsub=[],this.observers.forEach(e=>e.disconnect()),document.removeEventListener("visibilitychange",this.syncRunning),clearTimeout(this.refreshTimer),clearInterval(this.chromeTimer),this.chrome?.destroy(),this.scene?.dispose(),this.scene=null,this.root.remove())}refresh(){return this.loading?this.loading:(this.loading=(async()=>{try{const e=await tt("/api/graph");if(this.destroyed)return;D.graph.nodes=e.nodes||[],D.graph.links=e.links||[],this.apply(e.nodes||[],e.links||[])}catch(e){this.notes.length||(this.els.hint.textContent="Could not load the graph: "+e.message)}finally{this.loading=null}})(),this.loading)}apply(e,t){if(!this.scene)return;const i=this.selected>=0?this.notes[this.selected]?.path:"",a=this.tagIndex(),s=e.map(m=>{const x=String(m.path||m.id),_=typeof m.title=="string"&&m.title?m.title:String(m.id||Jh(x).replace(/\.md$/i,"")),w=Array.isArray(m.tags)?m.tags.map(String):a.get(x)||[];return{path:x,name:_,folder:m.folder||"Root",tags:w,degree:m.degree||0}}),o=new Map;s.forEach(m=>o.set(m.folder,(o.get(m.folder)||0)+1));const r=Array.from(o.entries()).sort((m,x)=>x[1]-m[1]||m[0].localeCompare(x[0])),l=f$(r.length),c=[...r].sort((m,x)=>m[0].localeCompare(x[0])).map(m=>m[0]);this.regions=new Map,r.forEach(([m,x],_)=>{const w=D.folderMeta[m];this.regions.set(m,{name:m,count:x,anchor:l[_],color:c4(c.indexOf(m),w&&w.color)})}),this.index=new Map;const p=new Map;s.forEach((m,x)=>{this.index.set(Fi(m.path),x);const _=Fi(Jh(m.path));p.has(_)||p.set(_,x);const w=Fi(m.name);p.has(w)||p.set(w,x)}),p.forEach((m,x)=>{this.index.has(x)||this.index.set(x,m)});const h=[];this.out=new Map,this.inc=new Map;const d=new Set;for(const m of t){const x=this.index.get(Fi(String(m.source))),_=this.index.get(Fi(String(m.target)));if(x===void 0||_===void 0||x===_)continue;const w=x<_?x+":"+_:_+":"+x;this.out.has(x)||this.out.set(x,[]),this.inc.has(_)||this.inc.set(_,[]),this.out.get(x).includes(_)||this.out.get(x).push(_),this.inc.get(_).includes(x)||this.inc.get(_).push(x),!d.has(w)&&(d.add(w),h.push([x,_]))}const u=new Array(s.length).fill(0);h.forEach(([m,x])=>{u[m]++,u[x]++});const f=s.length>6e3?.7:s.length>2e3?.85:1,v=s.map((m,x)=>{const _=this.regions.get(m.folder),w=g$(_.count,r.length);return{key:m.path,target:m$(m.path,_.anchor,w),origin:_.anchor,color:_.color,size:(.034+Math.min(.065,Math.sqrt(u[x]+m.degree*.3)*.011))*f}});this.notes=s;const g=Array.from(this.regions.values()).map(m=>({name:m.name,anchor:m.anchor,color:m.color,count:m.count}));if(this.scene.setDim(null),this.scene.setData(v,h,g),this.selected>=0&&(this.selected=-1),this.prefs.hidden.length&&(this.hidden=new Set(this.prefs.hidden.filter(m=>this.regions.has(m)))),this.renderRegions(),this.chrome?.finder?.update(),this.applyFilter(!1),this.scene.refreshNoteLabels(),i){const m=this.index.get(Fi(i));m!==void 0?this.select(m,!1):this.select(-1)}for(const m of this.pendingFlare.splice(0)){const x=this.index.get(Fi(m));x!==void 0&&this.scene.flareNote(x,1)}}tagIndex(){const e=new Map,t=D.tags.index;return t&&t.forEach((i,a)=>{for(const s of i){const o=s.path;o&&(e.has(o)||e.set(o,[]),e.get(o).push(a))}}),e}renderRegions(){this.chrome.refreshRegions()}setHidden(e){this.hidden=new Set(e.filter(t=>this.regions.has(t))),this.prefs.hidden=Array.from(this.hidden),Zh(this.prefs),this.renderRegions(),this.applyFilter()}focusRegion(e){const t=this.regions.get(e);if(!t||!this.scene||this.hidden.has(e))return;this.scene.focus(t.anchor,1.9);let i=0;for(let a=0;a<this.notes.length&&i<80;a++)this.notes[a].folder===e&&(this.scene.flareNote(a,1),i++)}matches(e){const t=this.notes[e];return!t||this.hidden.has(t.folder)?!1:!this.findHit||this.findHit.has(t.path)}applyFilter(e=!0){if(!this.scene)return;const t=!!(this.hidden.size||this.findHit);this.scene.setHiddenRegions(this.hidden),this.scene.setDim(t?i=>this.matches(i)?0:1:null),e&&this.scene.refreshNoteLabels()}hover(e,t,i){e>=0&&this.hidden.has(this.notes[e]?.folder)&&(e=-1);const a=this.els.tip;if(this.root.classList.toggle("hovering",e>=0),e<0||!this.notes[e]){a.classList.add("hidden");return}const s=this.notes[e],o=this.regions.get(s.folder),r=(this.out.get(e)?.length||0)+(this.inc.get(e)?.length||0);a.innerHTML=`<b>${b(s.name)}</b><div class="bt-f" style="--c:${O(o?.color||"#888")}"><i></i>${b(s.folder)} · ${r} link${r===1?"":"s"}</div>`+(s.tags.length?`<div class="brain-tags">${s.tags.slice(0,5).map(p=>`<span>#${b(p)}</span>`).join("")}</div>`:""),a.classList.remove("hidden");const l=this.root.clientWidth,c=t+280>l?t-290:t;a.style.left=c+"px",a.style.top=Math.min(i,this.root.clientHeight-90)+"px"}pick(e){if(e>=0&&this.hidden.has(this.notes[e]?.folder)&&(e=-1),e<0){this.selected>=0&&this.select(-1);return}this.select(e,!0)}select(e,t=!1){if(this.selected=e,this.scene?.select(e),e<0||!this.notes[e]){this.card.path&&!this.card.path.endsWith("/")&&this.card.close();return}this.els.tip.classList.add("hidden"),this.chrome.close();const i=this.notes[e];this.card.showNote(i.path,i.name,i.folder,this.regions.get(i.folder)?.color||"#888",i.tags),t&&this.scene&&this.scene.focus(this.scene.positionOf(e),1.15)}openFolder(e){this.focusRegion(e),this.regions.has(e)&&(this.selected>=0&&(this.selected=-1,this.scene?.select(-1)),this.chrome.close(),this.card.showFolder(e,this.regions.get(e).color,this.regions.get(e).count))}buildCard(){const e=i=>{const a=this.notes[i];return{path:a.path,name:a.name,color:this.regions.get(a.folder)?.color||"#888",degree:a.degree}},t=i=>this.notes.findIndex(a=>a.path===i);return new _g({root:this.root,focusNode:i=>{const a=t(i);a>=0&&this.scene&&this.scene.focus(this.scene.positionOf(a),1.15)},focusFolder:i=>this.focusRegion(i),onlyFolder:i=>this.setHidden(Array.from(this.regions.keys()).filter(a=>a!==i)),pick:i=>{const a=t(i);a>=0&&this.select(a,!0)},links:i=>{const a=t(i),s=this.out.get(a)||[],o=(this.inc.get(a)||[]).filter(r=>!s.includes(r));return{out:s.map(e),in:o.map(e)}},folderItems:i=>this.notes.map((a,s)=>[a,s]).filter(([a])=>a.folder===i).sort((a,s)=>s[0].degree-a[0].degree).map(([,a])=>e(a)),tag:i=>this.chrome.setQuery("#"+i+" "),home:()=>this.scene?.goHome(),closed:()=>{this.selected>=0&&(this.selected=-1,this.scene?.select(-1))}})}onActivity(e){if(!this.scene)return;const t=[];for(const i of e.paths||[]){const a=this.index.get(Fi(i))??this.index.get(Fi(Jh(i)));a!==void 0&&!t.includes(a)&&t.push(a)}this.scene.activity(e.actor||"agent",e.phase||"start",e.ok,t)}onMutation(e){const t=[e.path,e.to,e.new_path].find(i=>typeof i=="string");t&&this.pendingFlare.push(t),this.scheduleRefresh()}scheduleRefresh(){clearTimeout(this.refreshTimer),this.refreshTimer=window.setTimeout(()=>{this.refresh()},450)}}let Os=null;function L$(){return Os&&Os.alive()?Os.view():null}async function P$(){const n=document.getElementById("view-brain");if(n){if(Os&&Os.alive()){Os.scheduleRefresh();return}Os?.destroy(),Os=new R$(n)}}const rn=240,gn=136,jr=20,Bi=22,Io=24,Kc=140;function I$(){return{v:1,frames:{},cards:{}}}function wx(n){let e=Bi*2+rn,t=Io+Bi+gn;for(const i of n.cards)i.drag||(e=Math.max(e,i.x+rn+Bi),t=Math.max(t,i.y+gn+Bi));return{w:e,h:t}}function ii(n){const e=wx(n);return{x:n.x,y:n.y,w:Math.max(n.w,e.w),h:Math.max(n.h,e.h)}}function $o(n,e){return{x:n.x+e.x,y:n.y+e.y,w:rn,h:gn}}function Qh(n,e){return n.x<e.x+e.w&&n.x+n.w>e.x&&n.y<e.y+e.h&&n.y+n.h>e.y}function kx(n,e,t){return e>=n.x&&e<=n.x+n.w&&t>=n.y&&t<=n.y+n.h}function Zr(n){if(!n.cards.length)return;let e=1/0,t=1/0;for(const s of n.cards)e=Math.min(e,s.x),t=Math.min(t,s.y);const i=e<Bi?e-Bi:0,a=t<Io?t-Io:0;if(!(!i&&!a)){n.x+=i,n.y+=a;for(const s of n.cards)s.x-=i,s.y-=a}}function c_(n){return Math.max(1,Math.min(8,Math.round(Math.sqrt(n*1.5))))}function _x(n){const e=n.cards.slice().sort((a,s)=>s.mtime-a.mtime||a.name.localeCompare(s.name)),t=c_(e.length);e.forEach((a,s)=>{a.x=Bi+s%t*(rn+jr),a.y=Io+Math.floor(s/t)*(gn+jr)});const i=Math.max(1,Math.ceil(e.length/t));n.w=Bi*2+t*rn+(t-1)*jr,n.h=Io+Bi+i*gn+(i-1)*jr}function Sx(n,e=0,t=0){if(!n.length)return;const i=n.map(c=>({f:c,b:ii(c)})),a=i.reduce((c,p)=>c+(p.b.w+Kc)*(p.b.h+Kc),0),s=Math.max(Math.sqrt(a)*1.5,Math.max(...i.map(c=>c.b.w)));i.sort((c,p)=>c.f.name==="Root"?-1:p.f.name==="Root"?1:p.b.h-c.b.h||c.f.name.localeCompare(p.f.name));let o=e,r=t,l=0;for(const c of i)o>e&&o+c.b.w>e+s&&(o=e,r+=l+Kc,l=0),c.f.x=o,c.f.y=r,o+=c.b.w+Kc,l=Math.max(l,c.b.h)}function Mx(n,e){const t=c_(n.cards.length+1),i=n.cards.filter(a=>!0);for(let a=0;a<2e3;a++){const s=Bi+a%t*(rn+jr),o=Io+Math.floor(a/t)*(gn+jr),r={x:s-4,y:o-4,w:rn+8,h:gn+8};if(!i.some(l=>Qh(r,{x:l.x,y:l.y,w:rn,h:gn})))return{x:s,y:o}}return{x:Bi,y:Io+wx(n).h}}function $$(n){if(!n.length)return{x:0,y:0};let e=-1/0,t=1/0;for(const i of n){const a=ii(i);e=Math.max(e,a.x+a.w),t=Math.min(t,a.y)}return{x:e+Kc,y:t}}function Ax(n){if(!n.length)return null;let e=1/0,t=1/0,i=-1/0,a=-1/0;for(const s of n)e=Math.min(e,s.x),t=Math.min(t,s.y),i=Math.max(i,s.x+s.w),a=Math.max(a,s.y+s.h);return{x:e,y:t,w:i-e,h:a-t}}function eu(n,e){const t=n.split("/").pop()||n;return!e||e==="Root"?t:e+"/"+t}function N$(n,e){const t=n.split("/");return t[t.length-1]=e+".md",t.join("/")}function D$(n){return n.replace(/[^\w\s-]/g,"").trim().replace(/ /g,"_")}function z$(n){const e=String(n||"?").replace(/[_\-.@]+/g," ").trim().split(/\s+/).filter(Boolean);return e.length?e.length===1?e[0].slice(0,2).toUpperCase():(e[0][0]+e[1][0]).toUpperCase():"?"}function O$(n,e){const i=[e];let a=0;for(;i.length&&a++<200;){const s=i.shift(),o=ii(s),r={x:o.x-60,y:o.y-60,w:o.w+120,h:o.h+120};for(const l of n){if(l===s)continue;const c=ii(l);if(!Qh(r,c))continue;const p=o.y+o.h+60-c.y,h=o.x+o.w+60-c.x;c.y>=o.y&&(p<=h||c.x<o.x)?l.y+=p:c.x>=o.x?l.x+=h:l.y+=p,i.push(l)}}}const tu=[1,-1,0,0],nu=[0,0,1,-1];function iu(n,e){return e===0?[n.x+n.w,n.y+n.h/2]:e===1?[n.x,n.y+n.h/2]:e===2?[n.x+n.w/2,n.y+n.h]:[n.x+n.w/2,n.y]}function Tx(n,e,t){const i=Math.min(n[0],e[0]),a=Math.max(n[0],e[0]),s=Math.min(n[1],e[1]),o=Math.max(n[1],e[1]);return a>t.x&&i<t.x+t.w&&o>t.y&&s<t.y+t.h}function d_(n,e){return{x:n.x-e,y:n.y-e,w:n.w+e*2,h:n.h+e*2}}function p_(n){const e=[];for(const t of n){const i=e[e.length-1];if(!(i&&Math.abs(i[0]-t[0])<.01&&Math.abs(i[1]-t[1])<.01)){if(e.length>=2){const a=e[e.length-2],s=Math.abs(a[0]-i[0])<.01&&Math.abs(i[0]-t[0])<.01,o=Math.abs(a[1]-i[1])<.01&&Math.abs(i[1]-t[1])<.01;(s||o)&&e.pop()}e.push(t)}}return e}function h_(n,e,t,i){let a=0,s=0;for(let o=1;o<n.length;o++){const r=n[o-1],l=n[o];a+=Math.abs(l[0]-r[0])+Math.abs(l[1]-r[1]),o>1&&o<n.length-1&&(Tx(r,l,t)||Tx(r,l,i))&&(s+=2);for(const p of e)Tx(r,l,p)&&s++}return a+s*2400+(n.length-2)*40}function u_(n,e,t,i=9,a=9){let s=null,o=1/0;const r=d_(n,.5),l=d_(e,.5);for(let c=0;c<4;c++)for(let p=0;p<4;p++){const h=iu(n,c),d=iu(e,p),u=[h[0]+tu[c]*i,h[1]+nu[c]*i],f=[d[0]+tu[p]*i,d[1]+nu[p]*i],v=(tu[c]*(d[0]-h[0])+nu[c]*(d[1]-h[1])<-i?1:0)+(tu[p]*(h[0]-d[0])+nu[p]*(h[1]-d[1])<-i?1:0),g=[(u[0]+f[0])/2,u[0],f[0]],m=[(u[1]+f[1])/2,u[1],f[1]],x=Math.min(u[1],f[1]),_=Math.max(u[1],f[1]),w=Math.min(u[0],f[0]),S=Math.max(u[0],f[0]);for(const C of t)C.y<_&&C.y+C.h>x&&g.push(C.x-a,C.x+C.w+a),C.x<S&&C.x+C.w>w&&m.push(C.y-a,C.y+C.h+a);const A=(C,y)=>Array.from(new Set(C.map(M=>Math.round(M)))).sort((M,T)=>Math.abs(M-y)-Math.abs(T-y)).slice(0,9);for(const C of A(g,(u[0]+f[0])/2)){const y=p_([h,u,[C,u[1]],[C,f[1]],f,d]),M=h_(y,t,r,l)+v*300;M<o&&(o=M,s=y)}for(const C of A(m,(u[1]+f[1])/2)){const y=p_([h,u,[u[0],C],[f[0],C],f,d]),M=h_(y,t,r,l)+v*300;M<o&&(o=M,s=y)}}return s||[iu(n,0),iu(e,1)]}function U$(n,e,t){n.beginPath(),n.moveTo(e[0][0],e[0][1]);for(let a=1;a<e.length-1;a++){const s=e[a-1],o=e[a],r=e[a+1],l=Math.min(t,Math.hypot(o[0]-s[0],o[1]-s[1])/2,Math.hypot(r[0]-o[0],r[1]-o[1])/2);n.arcTo(o[0],o[1],r[0],r[1],l)}const i=e[e.length-1];n.lineTo(i[0],i[1]),n.stroke()}function Jr(n,e){const t=/^#?([0-9a-f]{6})$/i.exec(n.trim());if(!t)return`rgba(148,163,184,${e})`;const i=parseInt(t[1],16);return`rgba(${i>>16&255},${i>>8&255},${i&255},${e})`}const Yc=new Map,F$=60;function B$(n){let e=0;for(const t of n){e=e*31+t.x*7+t.y*13+t.cards.length|0;for(const i of t.cards)e=e*31+i.x*3+i.y*5|0}return n.length+":"+e}function H$(n,e,t,i,a){const s=[];for(const o of n===e?[n]:[n,e])for(const r of o.cards)r===t||r===i||s.push({x:o.x+r.x-4,y:o.y+r.y-4,w:rn+8,h:gn+8});for(const o of a){if(o===n||o===e)continue;const r=ii(o);s.push({x:r.x-12,y:r.y-12,w:r.w+24,h:r.h+24})}return s}function G$(n,e){const{cam:t,w:i,h:a,dpr:s}=e;n.setTransform(s,0,0,s,0,0),n.clearRect(0,0,i,a),n.setTransform(s*t.z,0,0,s*t.z,s*t.x,s*t.y);const o=-t.x/t.z,r=-t.y/t.z,l=o+i/t.z,c=r+a/t.z;if(e.paintCards)for(const v of e.frames){const g=e.color(v.name),m=e.light?"#ffffff":"#151a25",x=e.light?"rgba(15,23,42,.16)":"rgba(230,233,239,.16)";for(const _ of v.cards){const w=v.x+_.x,S=v.y+_.y;w>l||S>c||w+rn<o||S+gn<r||(n.fillStyle=m,n.beginPath(),n.roundRect(w,S,rn,gn,14),n.fill(),n.fillStyle=Jr(g,.9),n.fillRect(w,S+12,5,gn-24),n.fillStyle=e.light?"rgba(15,23,42,.5)":"rgba(230,233,239,.55)",n.fillRect(w+20,S+22,rn*.62,16),n.fillStyle=x,n.fillRect(w+20,S+56,rn-40,9),n.fillRect(w+20,S+74,rn*.55,9),e.selected.has(_.path)&&(n.strokeStyle=e.light?"#0d9488":"#5eead4",n.lineWidth=3/t.z,n.beginPath(),n.roundRect(w,S,rn,gn,14),n.stroke()))}}if(!e.showLinks||!e.links.length)return!1;const p=B$(e.frames);let h=F$,d=!1;const u=Math.max(1.2/t.z,1.2);for(const f of[0,1])for(const v of e.links){const g=e.frameOf(v.a),m=e.frameOf(v.b);if(!g||!m)continue;const x=!!e.focus&&(e.focus.has(v.a.path)||e.focus.has(v.b.path));if(f===1!==x)continue;const _=g.x+v.a.x,w=g.y+v.a.y,S=m.x+v.b.x,A=m.y+v.b.y,C=Math.min(_,S),y=Math.min(w,A),M=Math.max(_,S)+rn,T=Math.max(w,A)+gn;if(C>l||y>c||M<o||T<r)continue;const L=v.a.path+"\0"+v.b.path,P=_+","+w+","+S+","+A;let z=Yc.get(L);if(!z||z.sig!==p){const Te={x:_,y:w,w:rn,h:gn},We={x:S,y:A,w:rn,h:gn};h>0?(h--,z={sig:p,ends:P,pts:u_(Te,We,H$(g,m,v.a,v.b,e.frames))},Yc.set(L,z)):(d=!0,(!z||z.ends!==P)&&(z={sig:"",ends:P,pts:u_(Te,We,[])}),Yc.set(L,z))}const R=z.pts,[B,K]=R[0],[N,V]=R[R.length-1],[Z,te]=R[R.length-2],ce=Math.hypot(N-Z,V-te)||1,Ne=(Z-N)/ce,He=(te-V)/ce,ct=e.color(v.a.folder),ot=e.light?.42:.34,ft=x?.95:e.focus?.06:t.z<.3?ot*.45:t.z<.6?ot*.75:ot;n.strokeStyle=Jr(ct,ft),n.lineWidth=x?u*1.9:u,n.lineJoin="round",U$(n,R,14);const ne=(x?9:6)*Math.max(1,1/t.z)*.9,oe=Math.atan2(-He,-Ne);n.fillStyle=Jr(ct,x?1:ft+.1),n.beginPath(),n.moveTo(N,V),n.lineTo(N-Math.cos(oe-.45)*ne,V-Math.sin(oe-.45)*ne),n.lineTo(N-Math.cos(oe+.45)*ne,V-Math.sin(oe+.45)*ne),n.closePath(),n.fill(),n.beginPath(),n.arc(B,K,(x?3.2:2.2)*Math.max(1,1/t.z)*.8,0,Math.PI*2),n.fill()}return Yc.size>e.links.length*3+500&&Yc.clear(),d}function q$(n,e){n.setTransform(e.dpr,0,0,e.dpr,0,0),n.clearRect(0,0,e.w,e.h);const t=e.frames.map(h=>ii(h));let i=e.view.x,a=e.view.y,s=e.view.x+e.view.w,o=e.view.y+e.view.h;for(const h of t)i=Math.min(i,h.x),a=Math.min(a,h.y),s=Math.max(s,h.x+h.w),o=Math.max(o,h.y+h.h);const r=8,l=Math.min((e.w-r*2)/Math.max(1,s-i),(e.h-r*2)/Math.max(1,o-a)),c=r+(e.w-r*2-(s-i)*l)/2-i*l,p=r+(e.h-r*2-(o-a)*l)/2-a*l;return e.frames.forEach((h,d)=>{const u=t[d],f=e.color(h.name);n.fillStyle=Jr(f,e.light?.16:.14),n.strokeStyle=Jr(f,.6),n.lineWidth=1,n.fillRect(c+u.x*l,p+u.y*l,u.w*l,u.h*l),n.strokeRect(c+u.x*l+.5,p+u.y*l+.5,u.w*l-1,u.h*l-1),n.fillStyle=Jr(f,.75);for(const v of h.cards)n.fillRect(c+(h.x+v.x)*l,p+(h.y+v.y)*l,Math.max(1,rn*l),Math.max(1,gn*l))}),n.strokeStyle=e.light?"rgba(15,23,42,.75)":"rgba(230,233,239,.85)",n.lineWidth=1.5,n.fillStyle=e.light?"rgba(15,23,42,.05)":"rgba(230,233,239,.06)",n.fillRect(c+e.view.x*l,p+e.view.y*l,e.view.w*l,e.view.h*l),n.strokeRect(c+e.view.x*l,p+e.view.y*l,e.view.w*l,e.view.h*l),{s:l,ox:c,oy:p}}const f_="memora.canvas.excerpts",V$=3,ha=new Map,No=[],au=new Set;let m_=()=>{},g_=0,su=0;try{const n=sessionStorage.getItem(f_);if(n)for(const[e,t]of Object.entries(JSON.parse(n)))ha.set(e,t)}catch{}function W$(){clearTimeout(g_),g_=window.setTimeout(()=>{try{const n={};let e=0;for(const[t,i]of ha){if(e++>3e3)break;n[t]=i}sessionStorage.setItem(f_,JSON.stringify(n))}catch{}},800)}function X$(n){return String(n||"").replace(/^---[\s\S]*?\n---\s*/,"").replace(/^#\s+.*$/m,"").replace(/```[\s\S]*?```/g," ").replace(/!\[[^\]]*\]\([^)]*\)/g,"").replace(/\[\[([^\]|]+)\|([^\]]+)\]\]/g,"$2").replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/[#>*_`~|-]+/g," ").replace(/\s+/g," ").trim().slice(0,220)}function K$(n){m_=n}function Y$(n){return ha.get(n)}function j$(n){ha.delete(n)}function Z$(n,e){const t=ha.get(n);t&&(ha.delete(n),ha.set(e,t))}function J$(n,e){const t=ha.get(n);t&&t.m>=e||au.has(n)||No.some(i=>i.path===n)||(No.push({path:n,mtime:e}),Ex())}function Q$(n){for(let e=No.length-1;e>=0;e--)n.has(No[e].path)||No.splice(e,1)}function v_(n){su=Math.max(0,su+(n?1:-1)),su||Ex()}function Ex(){for(;!su&&au.size<V$&&No.length;){const n=No.pop();au.add(n.path),tt("/api/note?path="+encodeURIComponent(n.path)).then(e=>{const t=(e.tags&&e.tags.length?e.tags:Au(e.content)).slice(0,6);ha.set(n.path,{m:Math.max(n.mtime,Math.floor(Number(e.mtime)||0)),text:X$(e.content),tags:t}),W$(),m_(n.path)}).catch(()=>{ha.set(n.path,{m:n.mtime,text:"",tags:[]})}).finally(()=>{au.delete(n.path),Ex()})}}async function x_(n,e){const t=await dt("/api/move",{path:n,folder:e||"Root"});return t&&(t.path||t.to)||eu(n,e)}async function eN(n,e){const t=await dt("/api/rename",{path:n,name:e});return t&&t.path||n}async function tN(n,e){await dt("/api/folder-meta",{folder:n,color:e})}async function nN(n,e){const t={moved:[],failed:[]},i=n.slice(),a=async()=>{for(;i.length;){const s=i.shift();try{t.moved.push({from:s,to:await x_(s,e)})}catch(o){t.failed.push({path:s,error:o.message})}}};return await Promise.all([a(),a(),a()]),t}const Cx="canvas",b_="memora.layout."+Cx;let jc=null,Rx=0,Lx=null;function iN(){try{const n=localStorage.getItem(b_);if(!n)return null;const e=JSON.parse(n);return y_(e)?w_(e):null}catch{return null}}function aN(n){try{localStorage.setItem(b_,JSON.stringify({...n,_at:Date.now()}))}catch{}}function y_(n){const e=n;return!!e&&typeof e=="object"&&!!e.frames&&typeof e.frames=="object"&&!!e.cards&&typeof e.cards=="object"}const Px=(...n)=>n.every(e=>typeof e=="number"&&isFinite(e));function w_(n){const e={},t={};for(const[a,s]of Object.entries(n.frames))s&&Px(s.x,s.y,s.w,s.h)&&(e[a]=s);for(const[a,s]of Object.entries(n.cards))s&&Px(s.x,s.y)&&(t[a]=s);const i=n.view&&Px(n.view.x,n.view.y,n.view.z)&&n.view.z>0?n.view:void 0;return{...n,view:i,frames:e,cards:t}}async function sN(){const n=iN();try{const e=await tt("/api/ui/layout/"+Cx);if(jc=!0,y_(e&&e.data))return w_(e.data)}catch(e){const t=e.status;jc=t===404||t===405?!1:null}return n||I$()}async function Ix(){const n=Lx;if(Lx=null,!!n&&(aN(n),jc!==!1))try{await Dn("/api/ui/layout/"+Cx,{method:"PUT",body:{data:n}}),jc=!0}catch(e){const t=e.status;(t===404||t===405)&&(jc=!1)}}function oN(n,e=!1){Lx=n,clearTimeout(Rx),e?Ix():Rx=window.setTimeout(()=>{Ix()},700)}function rN(){clearTimeout(Rx),Ix()}const In=n=>`<svg viewBox="0 0 24 24" aria-hidden="true">${n}</svg>`,wn={pointer:In('<path d="M5 3l14 8-6.2 1.6L10 19z"/>'),hand:In('<path d="M8 13V5.5a1.5 1.5 0 0 1 3 0V12M11 11V4.5a1.5 1.5 0 0 1 3 0V12M14 11.5V6a1.5 1.5 0 0 1 3 0v8a6 6 0 0 1-6 6h-.6a6 6 0 0 1-4.6-2.2L3.6 14.6a1.6 1.6 0 0 1 2.3-2.2L8 14.5"/>'),fit:In('<path d="M4 9V5a1 1 0 0 1 1-1h4M15 4h4a1 1 0 0 1 1 1v4M20 15v4a1 1 0 0 1-1 1h-4M9 20H5a1 1 0 0 1-1-1v-4"/>'),tidy:In('<rect x="4" y="4" width="6.5" height="6.5" rx="1.5"/><rect x="13.5" y="4" width="6.5" height="6.5" rx="1.5"/><rect x="4" y="13.5" width="6.5" height="6.5" rx="1.5"/><rect x="13.5" y="13.5" width="6.5" height="6.5" rx="1.5"/>'),link:In('<path d="M5 18c4 0 4-12 9-12h5"/><circle cx="5" cy="18" r="1.6"/><path d="m16 3 3 3-3 3"/>'),help:In('<circle cx="12" cy="12" r="9"/><path d="M9.6 9.3a2.4 2.4 0 1 1 3.3 2.2c-.8.4-1.1.9-1.1 1.7M12 16.6h.01"/>'),open:In('<path d="M14 4h6v6M20 4l-8.5 8.5M18 14v4a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4"/>'),alL:In('<path d="M4 3v18M8 7h10M8 13h6M8 17h8"/>'),alC:In('<path d="M12 3v18M6 7h12M8 12h8M5 17h14"/>'),alR:In('<path d="M20 3v18M6 7h10M10 12h6M8 17h8"/>'),alT:In('<path d="M3 4h18M7 8v10M12 8v6M17 8v8"/>'),alM:In('<path d="M3 12h18M7 6v12M12 8v8M17 5v14"/>'),alB:In('<path d="M3 20h18M7 6v10M12 10v6M17 8v8"/>'),disH:In('<path d="M4 4v16M20 4v16"/><rect x="9.5" y="7" width="5" height="10" rx="1"/>'),disV:In('<path d="M4 4h16M4 20h16"/><rect x="7" y="9.5" width="10" height="5" rx="1"/>'),undo:In('<path d="M9 14 4 9l5-5"/><path d="M4 9h10.5a5.5 5.5 0 0 1 0 11H11"/>')},lN='<svg viewBox="0 0 18 18"><path d="M2 1.5l13 6.2-5.6 1.5L7 15z" fill="var(--ac)" stroke="#fff" stroke-width="1.3" stroke-linejoin="round"/></svg>';function $n(n,e,t,i=""){return`<button class="cv-btn ${i}" data-act="${n}" title="${b(t)}" aria-label="${b(t)}">${e}</button>`}function cN(n){const e=we("div","cv-ui cv-tools",$n("tool-select",wn.pointer,"Select (V)","on")+$n("tool-hand",wn.hand,"Hand (H, or hold Space)")+'<span class="cv-sep"></span><button class="cv-btn cv-zoom" data-act="zoom-100" title="Reset to 100% (Shift+0)">100%</button><span class="cv-sep"></span>'+$n("tidy",wn.tidy,"Tidy up (T: selection, Shift+T: whole board)")+$n("links",wn.link,"Show wikilinks (L)","on")+$n("help",wn.help,"Keyboard shortcuts (?)")),t=e.querySelector(".cv-zoom"),i=we("div","cv-ui cv-selbar hidden",'<span class="cnt"></span><span class="cv-fchips"></span>'+$n("sel-open",wn.open,"Preview and open (Enter)")+$n("fit-sel",wn.fit,"Focus the selection (Shift+2)")+'<span class="cv-sep"></span>'+$n("al-l",wn.alL,"Align left (Alt+A)")+$n("al-c",wn.alC,"Align horizontal centers (Alt+H)")+$n("al-r",wn.alR,"Align right (Alt+D)")+$n("al-t",wn.alT,"Align top (Alt+W)")+$n("al-m",wn.alM,"Align vertical centers (Alt+V)")+$n("al-b",wn.alB,"Align bottom (Alt+S)")+'<span class="cv-sep"></span>'+$n("dis-h",wn.disH,"Distribute horizontally (Alt+Shift+H)")+$n("dis-v",wn.disV,"Distribute vertically (Alt+Shift+V)")+'<span class="cv-sep"></span>'+$n("tidy",wn.tidy,"Tidy into a grid (T)")),a=we("div","cv-ui cv-toast",'<span class="msg"></span>');a.setAttribute("role","status"),a.setAttribute("aria-live","polite");const s=we("div","cv-ui cv-help hidden",dN());s.setAttribute("role","dialog"),s.setAttribute("aria-label","Canvas keyboard shortcuts");const o=we("div","cv-scrim hidden");return n.append(e,i,a,o,s),{tools:e,zoom:t,selbar:i,toast:a,help:s,scrim:o}}function dN(){const n=t=>t.split(" ").map(i=>`<kbd>${b(i)}</kbd>`).join("");return`<h3>Canvas shortcuts</h3>
8668
+ <div class="brain-foot"><span class="brain-hint" data-el="hint">Drag to orbit · scroll to zoom · click a node</span></div>`}wireUi(){const e=this.els;this.chrome=new wg({page:"brain",root:this.root,search:{placeholder:"Find a node, #tag or in:folder",find:{items:()=>this.notes.map(t=>({id:t.path,name:t.name,folder:t.folder,region:t.folder,color:this.regions.get(t.folder)?.color||"#888",tags:t.tags,degree:t.degree})),hidden:t=>this.hidden.has(t),highlight:t=>{this.findHit=t,this.applyFilter()},pick:t=>{const i=this.notes.findIndex(a=>a.path===t.id);i>=0&&this.select(i,!0)},folder:t=>this.openFolder(t)}},labels:{get:()=>({nodes:this.prefs.labels,folders:this.prefs.regionLabels}),set:(t,i)=>{t==="nodes"?this.prefs.labels=i:this.prefs.regionLabels=i,Zh(this.prefs),this.scene?.setLabels(this.prefs.labels,this.prefs.regionLabels)},help:{nodes:"Names next to the nodes in the brain. The node under the pointer and the selected one always show theirs.",folders:"Region names (one region per folder) floating over the brain."}},filter:t=>this.renderFilter(t),changed:()=>{const t=yx(),i=this.prefs;return i.labels!==t.labels||i.regionLabels!==t.regionLabels||i.rotate!==t.rotate||this.hidden.size>0||!!this.findHit||this.selected>=0||this.card?.isOpen||!!this.scene?.awayFromHome()},reset:()=>{this.chrome.finder?.clear(),this.card.close(!0);const t=this.prefs.regions;this.prefs={...yx(),regions:t},Zh(this.prefs),this.scene?.setLabels(!0,!0),this.scene?.setAutoRotate(!0),this.setHidden([]),this.select(-1),this.scene?.goHome()},regions:{list:()=>Array.from(this.regions.values()).map(t=>({name:t.name,color:t.color,count:t.count,hidden:this.hidden.has(t.name)})),toggle:t=>{const i=new Set(this.hidden);i.has(t)?i.delete(t):i.add(t),this.setHidden(Array.from(i))},setAll:t=>this.setHidden(t?Array.from(this.regions.keys()):[]),focus:t=>this.openFolder(t)},nav:{zoom:t=>this.scene?.zoomBy(t),fit:()=>this.scene?.resetView(),nudge:(t,i)=>this.scene?.orbitBy(-t*.26,-i*.2),home:()=>{this.select(-1),this.scene?.goHome()}},minimap:(t,i,a,s)=>this.drawMini(t,i,a,s),minimapNav:(t,i)=>this.miniNav(t,i),onOverlay:()=>{this.select(-1),this.card.close(!0)}}),this.card=this.buildCard(),this.chromeTimer=window.setInterval(()=>{if(!this.scene||document.hidden)return;const t=this.scene.orientation();this.chrome.setOrientation(t.yaw,t.pitch),this.chrome.redrawMini()},120),this.root.addEventListener("keydown",t=>{t.target.closest("input,textarea,select")||(t.key==="/"||(t.ctrlKey||t.metaKey)&&t.key.toLowerCase()==="f")&&(t.preventDefault(),t.stopPropagation(),this.chrome.focusSearch())}),window.setTimeout(()=>e.hint.classList.add("gone"),7e3),this.root.addEventListener("keydown",t=>{t.key==="Escape"&&this.selected>=0&&this.select(-1)})}renderFilter(e){e.innerHTML="<h4>Brain</h4>"+(this.reduced?"":Ia("rotate","Rotate when idle",this.prefs.rotate,"The brain turns slowly by itself two seconds after you stop moving it. Only the 3D brain has this."))+'<div class="vc-hint">Drag to orbit · scroll to zoom · click a node · / to search · #tag finds tags</div>';const t=e.querySelector("[data-t=rotate]");t&&(t.onclick=()=>{this.prefs.rotate=!this.prefs.rotate,this.scene?.setAutoRotate(this.prefs.rotate),Zh(this.prefs),this.chrome.renderPanel()})}drawMini(e,t,i,a){const s=e.getContext("2d"),o=this.scene;if(!s||!o)return;const r=document.documentElement.dataset.theme==="light";s.setTransform(a,0,0,a,0,0),s.clearRect(0,0,t,i);const l=Math.min(t,i)/3.4,c=t/2,p=i/2,h=this.notes.length,d=Math.max(1,Math.ceil(h/2500));for(let A=0;A<h;A+=d){const C=this.notes[A];if(this.hidden.has(C.folder))continue;const[y,,M]=o.positionOf(A);s.fillStyle=this.regions.get(C.folder)?.color||"#888",s.globalAlpha=.75,s.fillRect(c+y*l-1,p+M*l-1,2,2)}s.globalAlpha=1,s.strokeStyle=r?"rgba(15,23,42,.18)":"rgba(230,233,239,.16)",s.lineWidth=1,s.beginPath(),s.ellipse(c,p,1.25*l,1.05*l,0,0,Math.PI*2),s.stroke();const u=o.cameraView();if(!u)return;const f=Math.atan2(u.eye[2]-u.target[2],u.eye[0]-u.target[0]),v=Math.min(t,i)/2-7,g=c+Math.cos(f)*v,m=p+Math.sin(f)*v,x=f+Math.PI,_=u.fov*.5*(u.rect.w/u.rect.h),w=v*1.25,S=r?"13,148,136":"94,234,212";s.strokeStyle=`rgba(${S},.18)`,s.beginPath(),s.arc(c,p,v,0,Math.PI*2),s.stroke(),s.save(),s.beginPath(),s.arc(c,p,v,0,Math.PI*2),s.clip(),s.fillStyle=`rgba(${S},.12)`,s.strokeStyle=`rgba(${S},.6)`,s.beginPath(),s.moveTo(g,m),s.lineTo(g+Math.cos(x-_)*w,m+Math.sin(x-_)*w),s.lineTo(g+Math.cos(x+_)*w,m+Math.sin(x+_)*w),s.closePath(),s.fill(),s.stroke(),s.restore(),s.fillStyle=`rgb(${S})`,s.beginPath(),s.arc(g,m,4,0,Math.PI*2),s.fill()}miniNav(e,t){const i=this.scene,a=i?.cameraView(),s=this.chrome.miniCanvas.getBoundingClientRect();if(!i||!a||!s.width)return;const o=Math.min(s.width,s.height)/3.4,r=(e*s.width-s.width/2)/o,l=(t*s.height-s.height/2)/o;Math.hypot(r-a.target[0],l-a.target[2])<.05||i.orbitTo(Math.atan2(r-a.target[0],l-a.target[2]),void 0,.6)}destroy(){Kd("brain",null),!this.destroyed&&(this.destroyed=!0,this.unsub.forEach(e=>e()),this.unsub=[],this.observers.forEach(e=>e.disconnect()),document.removeEventListener("visibilitychange",this.syncRunning),clearTimeout(this.refreshTimer),clearInterval(this.chromeTimer),this.chrome?.destroy(),this.scene?.dispose(),this.scene=null,this.root.remove())}refresh(){return this.loading?this.loading:(this.loading=(async()=>{try{const e=await tt("/api/graph");if(this.destroyed)return;D.graph.nodes=e.nodes||[],D.graph.links=e.links||[],this.apply(e.nodes||[],e.links||[])}catch(e){this.notes.length||(this.els.hint.textContent="Could not load the graph: "+e.message)}finally{this.loading=null}})(),this.loading)}apply(e,t){if(!this.scene)return;const i=this.selected>=0?this.notes[this.selected]?.path:"",a=this.tagIndex(),s=e.map(m=>{const x=String(m.path||m.id),_=typeof m.title=="string"&&m.title?m.title:String(m.id||Jh(x).replace(/\.md$/i,"")),w=Array.isArray(m.tags)?m.tags.map(String):a.get(x)||[];return{path:x,name:_,folder:m.folder||"Root",tags:w,degree:m.degree||0}}),o=new Map;s.forEach(m=>o.set(m.folder,(o.get(m.folder)||0)+1));const r=Array.from(o.entries()).sort((m,x)=>x[1]-m[1]||m[0].localeCompare(x[0])),l=f$(r.length),c=[...r].sort((m,x)=>m[0].localeCompare(x[0])).map(m=>m[0]);this.regions=new Map,r.forEach(([m,x],_)=>{const w=D.folderMeta[m];this.regions.set(m,{name:m,count:x,anchor:l[_],color:cR(c.indexOf(m),w&&w.color)})}),this.index=new Map;const p=new Map;s.forEach((m,x)=>{this.index.set(Fi(m.path),x);const _=Fi(Jh(m.path));p.has(_)||p.set(_,x);const w=Fi(m.name);p.has(w)||p.set(w,x)}),p.forEach((m,x)=>{this.index.has(x)||this.index.set(x,m)});const h=[];this.out=new Map,this.inc=new Map;const d=new Set;for(const m of t){const x=this.index.get(Fi(String(m.source))),_=this.index.get(Fi(String(m.target)));if(x===void 0||_===void 0||x===_)continue;const w=x<_?x+":"+_:_+":"+x;this.out.has(x)||this.out.set(x,[]),this.inc.has(_)||this.inc.set(_,[]),this.out.get(x).includes(_)||this.out.get(x).push(_),this.inc.get(_).includes(x)||this.inc.get(_).push(x),!d.has(w)&&(d.add(w),h.push([x,_]))}const u=new Array(s.length).fill(0);h.forEach(([m,x])=>{u[m]++,u[x]++});const f=s.length>6e3?.7:s.length>2e3?.85:1,v=s.map((m,x)=>{const _=this.regions.get(m.folder),w=g$(_.count,r.length);return{key:m.path,target:m$(m.path,_.anchor,w),origin:_.anchor,color:_.color,size:(.034+Math.min(.065,Math.sqrt(u[x]+m.degree*.3)*.011))*f}});this.notes=s;const g=Array.from(this.regions.values()).map(m=>({name:m.name,anchor:m.anchor,color:m.color,count:m.count}));if(this.scene.setDim(null),this.scene.setData(v,h,g),this.selected>=0&&(this.selected=-1),this.prefs.hidden.length&&(this.hidden=new Set(this.prefs.hidden.filter(m=>this.regions.has(m)))),this.renderRegions(),this.chrome?.finder?.update(),this.applyFilter(!1),this.scene.refreshNoteLabels(),i){const m=this.index.get(Fi(i));m!==void 0?this.select(m,!1):this.select(-1)}for(const m of this.pendingFlare.splice(0)){const x=this.index.get(Fi(m));x!==void 0&&this.scene.flareNote(x,1)}}tagIndex(){const e=new Map,t=D.tags.index;return t&&t.forEach((i,a)=>{for(const s of i){const o=s.path;o&&(e.has(o)||e.set(o,[]),e.get(o).push(a))}}),e}renderRegions(){this.chrome.refreshRegions()}setHidden(e){this.hidden=new Set(e.filter(t=>this.regions.has(t))),this.prefs.hidden=Array.from(this.hidden),Zh(this.prefs),this.renderRegions(),this.applyFilter()}focusRegion(e){const t=this.regions.get(e);if(!t||!this.scene||this.hidden.has(e))return;this.scene.focus(t.anchor,1.9);let i=0;for(let a=0;a<this.notes.length&&i<80;a++)this.notes[a].folder===e&&(this.scene.flareNote(a,1),i++)}matches(e){const t=this.notes[e];return!t||this.hidden.has(t.folder)?!1:!this.findHit||this.findHit.has(t.path)}applyFilter(e=!0){if(!this.scene)return;const t=!!(this.hidden.size||this.findHit);this.scene.setHiddenRegions(this.hidden),this.scene.setDim(t?i=>this.matches(i)?0:1:null),e&&this.scene.refreshNoteLabels()}hover(e,t,i){e>=0&&this.hidden.has(this.notes[e]?.folder)&&(e=-1);const a=this.els.tip;if(this.root.classList.toggle("hovering",e>=0),e<0||!this.notes[e]){a.classList.add("hidden");return}const s=this.notes[e],o=this.regions.get(s.folder),r=(this.out.get(e)?.length||0)+(this.inc.get(e)?.length||0);a.innerHTML=`<b>${b(s.name)}</b><div class="bt-f" style="--c:${O(o?.color||"#888")}"><i></i>${b(s.folder)} · ${r} link${r===1?"":"s"}</div>`+(s.tags.length?`<div class="brain-tags">${s.tags.slice(0,5).map(p=>`<span>#${b(p)}</span>`).join("")}</div>`:""),a.classList.remove("hidden");const l=this.root.clientWidth,c=t+280>l?t-290:t;a.style.left=c+"px",a.style.top=Math.min(i,this.root.clientHeight-90)+"px"}pick(e){if(e>=0&&this.hidden.has(this.notes[e]?.folder)&&(e=-1),e<0){this.selected>=0&&this.select(-1);return}this.select(e,!0)}select(e,t=!1){if(this.selected=e,this.scene?.select(e),e<0||!this.notes[e]){this.card.path&&!this.card.path.endsWith("/")&&this.card.close();return}this.els.tip.classList.add("hidden"),this.chrome.close();const i=this.notes[e];this.card.showNote(i.path,i.name,i.folder,this.regions.get(i.folder)?.color||"#888",i.tags),t&&this.scene&&this.scene.focus(this.scene.positionOf(e),1.15)}openFolder(e){this.focusRegion(e),this.regions.has(e)&&(this.selected>=0&&(this.selected=-1,this.scene?.select(-1)),this.chrome.close(),this.card.showFolder(e,this.regions.get(e).color,this.regions.get(e).count))}buildCard(){const e=i=>{const a=this.notes[i];return{path:a.path,name:a.name,color:this.regions.get(a.folder)?.color||"#888",degree:a.degree}},t=i=>this.notes.findIndex(a=>a.path===i);return new _g({root:this.root,focusNode:i=>{const a=t(i);a>=0&&this.scene&&this.scene.focus(this.scene.positionOf(a),1.15)},focusFolder:i=>this.focusRegion(i),onlyFolder:i=>this.setHidden(Array.from(this.regions.keys()).filter(a=>a!==i)),pick:i=>{const a=t(i);a>=0&&this.select(a,!0)},links:i=>{const a=t(i),s=this.out.get(a)||[],o=(this.inc.get(a)||[]).filter(r=>!s.includes(r));return{out:s.map(e),in:o.map(e)}},folderItems:i=>this.notes.map((a,s)=>[a,s]).filter(([a])=>a.folder===i).sort((a,s)=>s[0].degree-a[0].degree).map(([,a])=>e(a)),tag:i=>this.chrome.setQuery("#"+i+" "),home:()=>this.scene?.goHome(),closed:()=>{this.selected>=0&&(this.selected=-1,this.scene?.select(-1))}})}onActivity(e){if(!this.scene)return;const t=[];for(const i of e.paths||[]){const a=this.index.get(Fi(i))??this.index.get(Fi(Jh(i)));a!==void 0&&!t.includes(a)&&t.push(a)}this.scene.activity(e.actor||"agent",e.phase||"start",e.ok,t)}onMutation(e){const t=[e.path,e.to,e.new_path].find(i=>typeof i=="string");t&&this.pendingFlare.push(t),this.scheduleRefresh()}scheduleRefresh(){clearTimeout(this.refreshTimer),this.refreshTimer=window.setTimeout(()=>{this.refresh()},450)}}let Os=null;function L$(){return Os&&Os.alive()?Os.view():null}async function P$(){const n=document.getElementById("view-brain");if(n){if(Os&&Os.alive()){Os.scheduleRefresh();return}Os?.destroy(),Os=new R$(n)}}const rn=240,gn=136,jr=20,Bi=22,Io=24,Kc=140;function I$(){return{v:1,frames:{},cards:{}}}function wx(n){let e=Bi*2+rn,t=Io+Bi+gn;for(const i of n.cards)i.drag||(e=Math.max(e,i.x+rn+Bi),t=Math.max(t,i.y+gn+Bi));return{w:e,h:t}}function ii(n){const e=wx(n);return{x:n.x,y:n.y,w:Math.max(n.w,e.w),h:Math.max(n.h,e.h)}}function $o(n,e){return{x:n.x+e.x,y:n.y+e.y,w:rn,h:gn}}function Qh(n,e){return n.x<e.x+e.w&&n.x+n.w>e.x&&n.y<e.y+e.h&&n.y+n.h>e.y}function kx(n,e,t){return e>=n.x&&e<=n.x+n.w&&t>=n.y&&t<=n.y+n.h}function Zr(n){if(!n.cards.length)return;let e=1/0,t=1/0;for(const s of n.cards)e=Math.min(e,s.x),t=Math.min(t,s.y);const i=e<Bi?e-Bi:0,a=t<Io?t-Io:0;if(!(!i&&!a)){n.x+=i,n.y+=a;for(const s of n.cards)s.x-=i,s.y-=a}}function c_(n){return Math.max(1,Math.min(8,Math.round(Math.sqrt(n*1.5))))}function _x(n){const e=n.cards.slice().sort((a,s)=>s.mtime-a.mtime||a.name.localeCompare(s.name)),t=c_(e.length);e.forEach((a,s)=>{a.x=Bi+s%t*(rn+jr),a.y=Io+Math.floor(s/t)*(gn+jr)});const i=Math.max(1,Math.ceil(e.length/t));n.w=Bi*2+t*rn+(t-1)*jr,n.h=Io+Bi+i*gn+(i-1)*jr}function Sx(n,e=0,t=0){if(!n.length)return;const i=n.map(c=>({f:c,b:ii(c)})),a=i.reduce((c,p)=>c+(p.b.w+Kc)*(p.b.h+Kc),0),s=Math.max(Math.sqrt(a)*1.5,Math.max(...i.map(c=>c.b.w)));i.sort((c,p)=>c.f.name==="Root"?-1:p.f.name==="Root"?1:p.b.h-c.b.h||c.f.name.localeCompare(p.f.name));let o=e,r=t,l=0;for(const c of i)o>e&&o+c.b.w>e+s&&(o=e,r+=l+Kc,l=0),c.f.x=o,c.f.y=r,o+=c.b.w+Kc,l=Math.max(l,c.b.h)}function Mx(n,e){const t=c_(n.cards.length+1),i=n.cards.filter(a=>!0);for(let a=0;a<2e3;a++){const s=Bi+a%t*(rn+jr),o=Io+Math.floor(a/t)*(gn+jr),r={x:s-4,y:o-4,w:rn+8,h:gn+8};if(!i.some(l=>Qh(r,{x:l.x,y:l.y,w:rn,h:gn})))return{x:s,y:o}}return{x:Bi,y:Io+wx(n).h}}function $$(n){if(!n.length)return{x:0,y:0};let e=-1/0,t=1/0;for(const i of n){const a=ii(i);e=Math.max(e,a.x+a.w),t=Math.min(t,a.y)}return{x:e+Kc,y:t}}function Ax(n){if(!n.length)return null;let e=1/0,t=1/0,i=-1/0,a=-1/0;for(const s of n)e=Math.min(e,s.x),t=Math.min(t,s.y),i=Math.max(i,s.x+s.w),a=Math.max(a,s.y+s.h);return{x:e,y:t,w:i-e,h:a-t}}function eu(n,e){const t=n.split("/").pop()||n;return!e||e==="Root"?t:e+"/"+t}function N$(n,e){const t=n.split("/");return t[t.length-1]=e+".md",t.join("/")}function D$(n){return n.replace(/[^\w\s-]/g,"").trim().replace(/ /g,"_")}function z$(n){const e=String(n||"?").replace(/[_\-.@]+/g," ").trim().split(/\s+/).filter(Boolean);return e.length?e.length===1?e[0].slice(0,2).toUpperCase():(e[0][0]+e[1][0]).toUpperCase():"?"}function O$(n,e){const i=[e];let a=0;for(;i.length&&a++<200;){const s=i.shift(),o=ii(s),r={x:o.x-60,y:o.y-60,w:o.w+120,h:o.h+120};for(const l of n){if(l===s)continue;const c=ii(l);if(!Qh(r,c))continue;const p=o.y+o.h+60-c.y,h=o.x+o.w+60-c.x;c.y>=o.y&&(p<=h||c.x<o.x)?l.y+=p:c.x>=o.x?l.x+=h:l.y+=p,i.push(l)}}}const tu=[1,-1,0,0],nu=[0,0,1,-1];function iu(n,e){return e===0?[n.x+n.w,n.y+n.h/2]:e===1?[n.x,n.y+n.h/2]:e===2?[n.x+n.w/2,n.y+n.h]:[n.x+n.w/2,n.y]}function Tx(n,e,t){const i=Math.min(n[0],e[0]),a=Math.max(n[0],e[0]),s=Math.min(n[1],e[1]),o=Math.max(n[1],e[1]);return a>t.x&&i<t.x+t.w&&o>t.y&&s<t.y+t.h}function d_(n,e){return{x:n.x-e,y:n.y-e,w:n.w+e*2,h:n.h+e*2}}function p_(n){const e=[];for(const t of n){const i=e[e.length-1];if(!(i&&Math.abs(i[0]-t[0])<.01&&Math.abs(i[1]-t[1])<.01)){if(e.length>=2){const a=e[e.length-2],s=Math.abs(a[0]-i[0])<.01&&Math.abs(i[0]-t[0])<.01,o=Math.abs(a[1]-i[1])<.01&&Math.abs(i[1]-t[1])<.01;(s||o)&&e.pop()}e.push(t)}}return e}function h_(n,e,t,i){let a=0,s=0;for(let o=1;o<n.length;o++){const r=n[o-1],l=n[o];a+=Math.abs(l[0]-r[0])+Math.abs(l[1]-r[1]),o>1&&o<n.length-1&&(Tx(r,l,t)||Tx(r,l,i))&&(s+=2);for(const p of e)Tx(r,l,p)&&s++}return a+s*2400+(n.length-2)*40}function u_(n,e,t,i=9,a=9){let s=null,o=1/0;const r=d_(n,.5),l=d_(e,.5);for(let c=0;c<4;c++)for(let p=0;p<4;p++){const h=iu(n,c),d=iu(e,p),u=[h[0]+tu[c]*i,h[1]+nu[c]*i],f=[d[0]+tu[p]*i,d[1]+nu[p]*i],v=(tu[c]*(d[0]-h[0])+nu[c]*(d[1]-h[1])<-i?1:0)+(tu[p]*(h[0]-d[0])+nu[p]*(h[1]-d[1])<-i?1:0),g=[(u[0]+f[0])/2,u[0],f[0]],m=[(u[1]+f[1])/2,u[1],f[1]],x=Math.min(u[1],f[1]),_=Math.max(u[1],f[1]),w=Math.min(u[0],f[0]),S=Math.max(u[0],f[0]);for(const C of t)C.y<_&&C.y+C.h>x&&g.push(C.x-a,C.x+C.w+a),C.x<S&&C.x+C.w>w&&m.push(C.y-a,C.y+C.h+a);const A=(C,y)=>Array.from(new Set(C.map(M=>Math.round(M)))).sort((M,T)=>Math.abs(M-y)-Math.abs(T-y)).slice(0,9);for(const C of A(g,(u[0]+f[0])/2)){const y=p_([h,u,[C,u[1]],[C,f[1]],f,d]),M=h_(y,t,r,l)+v*300;M<o&&(o=M,s=y)}for(const C of A(m,(u[1]+f[1])/2)){const y=p_([h,u,[u[0],C],[f[0],C],f,d]),M=h_(y,t,r,l)+v*300;M<o&&(o=M,s=y)}}return s||[iu(n,0),iu(e,1)]}function U$(n,e,t){n.beginPath(),n.moveTo(e[0][0],e[0][1]);for(let a=1;a<e.length-1;a++){const s=e[a-1],o=e[a],r=e[a+1],l=Math.min(t,Math.hypot(o[0]-s[0],o[1]-s[1])/2,Math.hypot(r[0]-o[0],r[1]-o[1])/2);n.arcTo(o[0],o[1],r[0],r[1],l)}const i=e[e.length-1];n.lineTo(i[0],i[1]),n.stroke()}function Jr(n,e){const t=/^#?([0-9a-f]{6})$/i.exec(n.trim());if(!t)return`rgba(148,163,184,${e})`;const i=parseInt(t[1],16);return`rgba(${i>>16&255},${i>>8&255},${i&255},${e})`}const Yc=new Map,F$=60;function B$(n){let e=0;for(const t of n){e=e*31+t.x*7+t.y*13+t.cards.length|0;for(const i of t.cards)e=e*31+i.x*3+i.y*5|0}return n.length+":"+e}function H$(n,e,t,i,a){const s=[];for(const o of n===e?[n]:[n,e])for(const r of o.cards)r===t||r===i||s.push({x:o.x+r.x-4,y:o.y+r.y-4,w:rn+8,h:gn+8});for(const o of a){if(o===n||o===e)continue;const r=ii(o);s.push({x:r.x-12,y:r.y-12,w:r.w+24,h:r.h+24})}return s}function G$(n,e){const{cam:t,w:i,h:a,dpr:s}=e;n.setTransform(s,0,0,s,0,0),n.clearRect(0,0,i,a),n.setTransform(s*t.z,0,0,s*t.z,s*t.x,s*t.y);const o=-t.x/t.z,r=-t.y/t.z,l=o+i/t.z,c=r+a/t.z;if(e.paintCards)for(const v of e.frames){const g=e.color(v.name),m=e.light?"#ffffff":"#151a25",x=e.light?"rgba(15,23,42,.16)":"rgba(230,233,239,.16)";for(const _ of v.cards){const w=v.x+_.x,S=v.y+_.y;w>l||S>c||w+rn<o||S+gn<r||(n.fillStyle=m,n.beginPath(),n.roundRect(w,S,rn,gn,14),n.fill(),n.fillStyle=Jr(g,.9),n.fillRect(w,S+12,5,gn-24),n.fillStyle=e.light?"rgba(15,23,42,.5)":"rgba(230,233,239,.55)",n.fillRect(w+20,S+22,rn*.62,16),n.fillStyle=x,n.fillRect(w+20,S+56,rn-40,9),n.fillRect(w+20,S+74,rn*.55,9),e.selected.has(_.path)&&(n.strokeStyle=e.light?"#0d9488":"#5eead4",n.lineWidth=3/t.z,n.beginPath(),n.roundRect(w,S,rn,gn,14),n.stroke()))}}if(!e.showLinks||!e.links.length)return!1;const p=B$(e.frames);let h=F$,d=!1;const u=Math.max(1.2/t.z,1.2);for(const f of[0,1])for(const v of e.links){const g=e.frameOf(v.a),m=e.frameOf(v.b);if(!g||!m)continue;const x=!!e.focus&&(e.focus.has(v.a.path)||e.focus.has(v.b.path));if(f===1!==x)continue;const _=g.x+v.a.x,w=g.y+v.a.y,S=m.x+v.b.x,A=m.y+v.b.y,C=Math.min(_,S),y=Math.min(w,A),M=Math.max(_,S)+rn,T=Math.max(w,A)+gn;if(C>l||y>c||M<o||T<r)continue;const L=v.a.path+"\0"+v.b.path,P=_+","+w+","+S+","+A;let z=Yc.get(L);if(!z||z.sig!==p){const Te={x:_,y:w,w:rn,h:gn},We={x:S,y:A,w:rn,h:gn};h>0?(h--,z={sig:p,ends:P,pts:u_(Te,We,H$(g,m,v.a,v.b,e.frames))},Yc.set(L,z)):(d=!0,(!z||z.ends!==P)&&(z={sig:"",ends:P,pts:u_(Te,We,[])}),Yc.set(L,z))}const R=z.pts,[B,K]=R[0],[N,V]=R[R.length-1],[Z,te]=R[R.length-2],ce=Math.hypot(N-Z,V-te)||1,Ne=(Z-N)/ce,He=(te-V)/ce,ct=e.color(v.a.folder),ot=e.light?.42:.34,ft=x?.95:e.focus?.06:t.z<.3?ot*.45:t.z<.6?ot*.75:ot;n.strokeStyle=Jr(ct,ft),n.lineWidth=x?u*1.9:u,n.lineJoin="round",U$(n,R,14);const ne=(x?9:6)*Math.max(1,1/t.z)*.9,oe=Math.atan2(-He,-Ne);n.fillStyle=Jr(ct,x?1:ft+.1),n.beginPath(),n.moveTo(N,V),n.lineTo(N-Math.cos(oe-.45)*ne,V-Math.sin(oe-.45)*ne),n.lineTo(N-Math.cos(oe+.45)*ne,V-Math.sin(oe+.45)*ne),n.closePath(),n.fill(),n.beginPath(),n.arc(B,K,(x?3.2:2.2)*Math.max(1,1/t.z)*.8,0,Math.PI*2),n.fill()}return Yc.size>e.links.length*3+500&&Yc.clear(),d}function q$(n,e){n.setTransform(e.dpr,0,0,e.dpr,0,0),n.clearRect(0,0,e.w,e.h);const t=e.frames.map(h=>ii(h));let i=e.view.x,a=e.view.y,s=e.view.x+e.view.w,o=e.view.y+e.view.h;for(const h of t)i=Math.min(i,h.x),a=Math.min(a,h.y),s=Math.max(s,h.x+h.w),o=Math.max(o,h.y+h.h);const r=8,l=Math.min((e.w-r*2)/Math.max(1,s-i),(e.h-r*2)/Math.max(1,o-a)),c=r+(e.w-r*2-(s-i)*l)/2-i*l,p=r+(e.h-r*2-(o-a)*l)/2-a*l;return e.frames.forEach((h,d)=>{const u=t[d],f=e.color(h.name);n.fillStyle=Jr(f,e.light?.16:.14),n.strokeStyle=Jr(f,.6),n.lineWidth=1,n.fillRect(c+u.x*l,p+u.y*l,u.w*l,u.h*l),n.strokeRect(c+u.x*l+.5,p+u.y*l+.5,u.w*l-1,u.h*l-1),n.fillStyle=Jr(f,.75);for(const v of h.cards)n.fillRect(c+(h.x+v.x)*l,p+(h.y+v.y)*l,Math.max(1,rn*l),Math.max(1,gn*l))}),n.strokeStyle=e.light?"rgba(15,23,42,.75)":"rgba(230,233,239,.85)",n.lineWidth=1.5,n.fillStyle=e.light?"rgba(15,23,42,.05)":"rgba(230,233,239,.06)",n.fillRect(c+e.view.x*l,p+e.view.y*l,e.view.w*l,e.view.h*l),n.strokeRect(c+e.view.x*l,p+e.view.y*l,e.view.w*l,e.view.h*l),{s:l,ox:c,oy:p}}const f_="memora.canvas.excerpts",V$=3,ha=new Map,No=[],au=new Set;let m_=()=>{},g_=0,su=0;try{const n=sessionStorage.getItem(f_);if(n)for(const[e,t]of Object.entries(JSON.parse(n)))ha.set(e,t)}catch{}function W$(){clearTimeout(g_),g_=window.setTimeout(()=>{try{const n={};let e=0;for(const[t,i]of ha){if(e++>3e3)break;n[t]=i}sessionStorage.setItem(f_,JSON.stringify(n))}catch{}},800)}function X$(n){return String(n||"").replace(/^---[\s\S]*?\n---\s*/,"").replace(/^#\s+.*$/m,"").replace(/```[\s\S]*?```/g," ").replace(/!\[[^\]]*\]\([^)]*\)/g,"").replace(/\[\[([^\]|]+)\|([^\]]+)\]\]/g,"$2").replace(/\[\[([^\]]+)\]\]/g,"$1").replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/[#>*_`~|-]+/g," ").replace(/\s+/g," ").trim().slice(0,220)}function K$(n){m_=n}function Y$(n){return ha.get(n)}function j$(n){ha.delete(n)}function Z$(n,e){const t=ha.get(n);t&&(ha.delete(n),ha.set(e,t))}function J$(n,e){const t=ha.get(n);t&&t.m>=e||au.has(n)||No.some(i=>i.path===n)||(No.push({path:n,mtime:e}),Ex())}function Q$(n){for(let e=No.length-1;e>=0;e--)n.has(No[e].path)||No.splice(e,1)}function v_(n){su=Math.max(0,su+(n?1:-1)),su||Ex()}function Ex(){for(;!su&&au.size<V$&&No.length;){const n=No.pop();au.add(n.path),tt("/api/note?path="+encodeURIComponent(n.path)).then(e=>{const t=(e.tags&&e.tags.length?e.tags:Au(e.content)).slice(0,6);ha.set(n.path,{m:Math.max(n.mtime,Math.floor(Number(e.mtime)||0)),text:X$(e.content),tags:t}),W$(),m_(n.path)}).catch(()=>{ha.set(n.path,{m:n.mtime,text:"",tags:[]})}).finally(()=>{au.delete(n.path),Ex()})}}async function x_(n,e){const t=await dt("/api/move",{path:n,folder:e||"Root"});return t&&(t.path||t.to)||eu(n,e)}async function eN(n,e){const t=await dt("/api/rename",{path:n,name:e});return t&&t.path||n}async function tN(n,e){await dt("/api/folder-meta",{folder:n,color:e})}async function nN(n,e){const t={moved:[],failed:[]},i=n.slice(),a=async()=>{for(;i.length;){const s=i.shift();try{t.moved.push({from:s,to:await x_(s,e)})}catch(o){t.failed.push({path:s,error:o.message})}}};return await Promise.all([a(),a(),a()]),t}const Cx="canvas",b_="memora.layout."+Cx;let jc=null,Rx=0,Lx=null;function iN(){try{const n=localStorage.getItem(b_);if(!n)return null;const e=JSON.parse(n);return y_(e)?w_(e):null}catch{return null}}function aN(n){try{localStorage.setItem(b_,JSON.stringify({...n,_at:Date.now()}))}catch{}}function y_(n){const e=n;return!!e&&typeof e=="object"&&!!e.frames&&typeof e.frames=="object"&&!!e.cards&&typeof e.cards=="object"}const Px=(...n)=>n.every(e=>typeof e=="number"&&isFinite(e));function w_(n){const e={},t={};for(const[a,s]of Object.entries(n.frames))s&&Px(s.x,s.y,s.w,s.h)&&(e[a]=s);for(const[a,s]of Object.entries(n.cards))s&&Px(s.x,s.y)&&(t[a]=s);const i=n.view&&Px(n.view.x,n.view.y,n.view.z)&&n.view.z>0?n.view:void 0;return{...n,view:i,frames:e,cards:t}}async function sN(){const n=iN();try{const e=await tt("/api/ui/layout/"+Cx);if(jc=!0,y_(e&&e.data))return w_(e.data)}catch(e){const t=e.status;jc=t===404||t===405?!1:null}return n||I$()}async function Ix(){const n=Lx;if(Lx=null,!!n&&(aN(n),jc!==!1))try{await Dn("/api/ui/layout/"+Cx,{method:"PUT",body:{data:n}}),jc=!0}catch(e){const t=e.status;(t===404||t===405)&&(jc=!1)}}function oN(n,e=!1){Lx=n,clearTimeout(Rx),e?Ix():Rx=window.setTimeout(()=>{Ix()},700)}function rN(){clearTimeout(Rx),Ix()}const In=n=>`<svg viewBox="0 0 24 24" aria-hidden="true">${n}</svg>`,wn={pointer:In('<path d="M5 3l14 8-6.2 1.6L10 19z"/>'),hand:In('<path d="M8 13V5.5a1.5 1.5 0 0 1 3 0V12M11 11V4.5a1.5 1.5 0 0 1 3 0V12M14 11.5V6a1.5 1.5 0 0 1 3 0v8a6 6 0 0 1-6 6h-.6a6 6 0 0 1-4.6-2.2L3.6 14.6a1.6 1.6 0 0 1 2.3-2.2L8 14.5"/>'),fit:In('<path d="M4 9V5a1 1 0 0 1 1-1h4M15 4h4a1 1 0 0 1 1 1v4M20 15v4a1 1 0 0 1-1 1h-4M9 20H5a1 1 0 0 1-1-1v-4"/>'),tidy:In('<rect x="4" y="4" width="6.5" height="6.5" rx="1.5"/><rect x="13.5" y="4" width="6.5" height="6.5" rx="1.5"/><rect x="4" y="13.5" width="6.5" height="6.5" rx="1.5"/><rect x="13.5" y="13.5" width="6.5" height="6.5" rx="1.5"/>'),link:In('<path d="M5 18c4 0 4-12 9-12h5"/><circle cx="5" cy="18" r="1.6"/><path d="m16 3 3 3-3 3"/>'),help:In('<circle cx="12" cy="12" r="9"/><path d="M9.6 9.3a2.4 2.4 0 1 1 3.3 2.2c-.8.4-1.1.9-1.1 1.7M12 16.6h.01"/>'),open:In('<path d="M14 4h6v6M20 4l-8.5 8.5M18 14v4a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4"/>'),alL:In('<path d="M4 3v18M8 7h10M8 13h6M8 17h8"/>'),alC:In('<path d="M12 3v18M6 7h12M8 12h8M5 17h14"/>'),alR:In('<path d="M20 3v18M6 7h10M10 12h6M8 17h8"/>'),alT:In('<path d="M3 4h18M7 8v10M12 8v6M17 8v8"/>'),alM:In('<path d="M3 12h18M7 6v12M12 8v8M17 5v14"/>'),alB:In('<path d="M3 20h18M7 6v10M12 10v6M17 8v8"/>'),disH:In('<path d="M4 4v16M20 4v16"/><rect x="9.5" y="7" width="5" height="10" rx="1"/>'),disV:In('<path d="M4 4h16M4 20h16"/><rect x="7" y="9.5" width="10" height="5" rx="1"/>'),undo:In('<path d="M9 14 4 9l5-5"/><path d="M4 9h10.5a5.5 5.5 0 0 1 0 11H11"/>')},lN='<svg viewBox="0 0 18 18"><path d="M2 1.5l13 6.2-5.6 1.5L7 15z" fill="var(--ac)" stroke="#fff" stroke-width="1.3" stroke-linejoin="round"/></svg>';function $n(n,e,t,i=""){return`<button class="cv-btn ${i}" data-act="${n}" title="${b(t)}" aria-label="${b(t)}">${e}</button>`}function cN(n){const e=we("div","cv-ui cv-tools",$n("tool-select",wn.pointer,"Select (V)","on")+$n("tool-hand",wn.hand,"Hand (H, or hold Space)")+'<span class="cv-sep"></span><button class="cv-btn cv-zoom" data-act="zoom-100" title="Reset to 100% (Shift+0)">100%</button><span class="cv-sep"></span>'+$n("tidy",wn.tidy,"Tidy up (T: selection, Shift+T: whole board)")+$n("links",wn.link,"Show wikilinks (L)","on")+$n("help",wn.help,"Keyboard shortcuts (?)")),t=e.querySelector(".cv-zoom"),i=we("div","cv-ui cv-selbar hidden",'<span class="cnt"></span><span class="cv-fchips"></span>'+$n("sel-open",wn.open,"Preview and open (Enter)")+$n("fit-sel",wn.fit,"Focus the selection (Shift+2)")+'<span class="cv-sep"></span>'+$n("al-l",wn.alL,"Align left (Alt+A)")+$n("al-c",wn.alC,"Align horizontal centers (Alt+H)")+$n("al-r",wn.alR,"Align right (Alt+D)")+$n("al-t",wn.alT,"Align top (Alt+W)")+$n("al-m",wn.alM,"Align vertical centers (Alt+V)")+$n("al-b",wn.alB,"Align bottom (Alt+S)")+'<span class="cv-sep"></span>'+$n("dis-h",wn.disH,"Distribute horizontally (Alt+Shift+H)")+$n("dis-v",wn.disV,"Distribute vertically (Alt+Shift+V)")+'<span class="cv-sep"></span>'+$n("tidy",wn.tidy,"Tidy into a grid (T)")),a=we("div","cv-ui cv-toast",'<span class="msg"></span>');a.setAttribute("role","status"),a.setAttribute("aria-live","polite");const s=we("div","cv-ui cv-help hidden",dN());s.setAttribute("role","dialog"),s.setAttribute("aria-label","Canvas keyboard shortcuts");const o=we("div","cv-scrim hidden");return n.append(e,i,a,o,s),{tools:e,zoom:t,selbar:i,toast:a,help:s,scrim:o}}function dN(){const n=t=>t.split(" ").map(i=>`<kbd>${b(i)}</kbd>`).join("");return`<h3>Canvas shortcuts</h3>
8669
8669
  <p>Drag a card into another folder frame to move the node on disk. Drag a frame by its name to rearrange the board; drop it onto another frame to move the whole folder there. Double-click a title to rename. On touch: drag to pan, pinch to zoom, long-press a card to move it, tap to preview.</p>
8670
8670
  <div class="cols">${[["Pan","Space+drag"],["Pan (mouse)","Middle-drag"],["Zoom at cursor","Ctrl+wheel"],["Zoom in / out","+ -"],["Zoom to fit","Shift+1"],["Zoom to selection","Shift+2"],["Zoom to 100%","Shift+0"],["Select / Hand tool","V H"],["Add to selection","Shift+click"],["Select all","Ctrl+A"],["Preview node","Enter"],["Open node","O"],["Rename","F2"],["Nudge","Arrows"],["Align left / right","Alt+A Alt+D"],["Align top / bottom","Alt+W Alt+S"],["Align centers","Alt+H Alt+V"],["Distribute","Alt+Shift+H/V"],["Tidy selection","T"],["Tidy whole board","Shift+T"],["Wikilinks","L"],["Minimap","M"],["Undo last move","Ctrl+Z"],["Clear / close","Esc"]].map(([t,i])=>`<div class="row"><span>${b(t)}</span><span>${n(i)}</span></div>`).join("")}</div>`}class pN{constructor(e){this.node=e,this.timer=0}show(e,t={}){clearTimeout(this.timer),this.node.classList.toggle("err",!!t.err),this.node.innerHTML=`<span class="msg">${b(e)}</span>${t.undo?`<button class="cv-btn" data-undo>${wn.undo}Undo</button>`:""}`;const i=this.node.querySelector("[data-undo]");if(i&&t.undo){const a=t.undo;i.onclick=()=>{this.hide(),a()}}this.node.classList.add("show"),this.timer=window.setTimeout(()=>this.hide(),t.ms??(t.undo?7e3:3600))}hide(){this.node.classList.remove("show")}}async function ou(n){v_(!0);try{return await n()}finally{v_(!1)}}const k_=(n,e)=>ou(()=>x_(n,e)),__=(n,e)=>ou(()=>eN(n,e)),$x=(n,e)=>ou(()=>nN(n,e)),hN=(n,e)=>ou(()=>tN(n,e)),Nx=.04,S_=4,M_=.45,uN=.2,Dx=600*1e3,fN=380;class mN{constructor(e){this.host=e,this.frames=new Map,this.cards=new Map,this.links=[],this.linkCount=new Map,this.layout={v:1,frames:{},cards:{}},this.cam={x:0,y:0,z:1},this.W=1,this.H=1,this.dpr=1,this.lod=0,this.sel=new Set,this.selFrames=new Set,this.hover=null,this.tool="select",this.space=!1,this.showLinks=!0,this.hiddenFrames=vN(),this.labelPrefs=bN(),this.pointers=new Map,this.g=null,this.zoomAnim=null,this.fly=null,this.inertia=null,this.tween=null,this.edge=null,this.raf=0,this.geomDirty=!0,this.miniAt=0,this.miniMap={s:1,ox:0,oy:0},this.movingTimer=0,this.camSaveTimer=0,this.active=!1,this.ready=!1,this.unsubs=[],this.cursors=new Map,this.undoStack=[],this.flashPending=new Set,this.linksTimer=0,this.syncTimer=0,this.decayTimer=0,this.busy=!1,this.needFit=!1,this.sizes=new WeakMap,this.onKeyBound=t=>this.onKey(t),this.onKeyUpBound=t=>{t.code==="Space"&&(this.space=!1,this.root.classList.toggle("hand",this.tool==="hand"))},this.onBlurBound=()=>{this.space=!1},this.frameOf=t=>this.frames.get(t.folder),this.hits=null,this.lastPointer=-1}async init(){this.build(),this.layout=await sN(),this.showLinks=this.layout.links!==!1,this.syncButtons(),this.sync(),this.layout.view&&isFinite(this.layout.view.z)&&(this.cam={...this.layout.view}),this.needFit=!0,this.ready=!0,this.fitIfNeeded(),this.activate(),this.loadLinks(),this.seedTouches(),gN(this.host,e=>e?this.activate():this.deactivate())}refresh(){this.ready&&(this.activate(),this.sync(),this.scheduleLinks())}build(){this.host.innerHTML="";const e=document.createElement("div");e.className="cv",e.tabIndex=-1,this.root=e,this.bg=document.createElement("div"),this.bg.className="cv-layer cv-bg",this.linkCv=document.createElement("canvas"),this.linkCv.className="cv-links",this.fg=document.createElement("div"),this.fg.className="cv-layer cv-fg",this.marquee=document.createElement("div"),this.marquee.className="cv-marquee hidden",this.empty=document.createElement("div"),this.empty.className="cv-empty hidden",this.empty.textContent="No nodes in this vault yet.",e.append(this.bg,this.linkCv,this.fg,this.marquee,this.empty),this.host.appendChild(e),this.ctx=this.linkCv.getContext("2d"),this.ui=cN(e),this.vc=this.buildViewChrome(e),this.applyLabelPrefs(),this.toast=new pN(this.ui.toast),this.panel=this.buildCard(e),e.addEventListener("pointerdown",t=>this.onDown(t)),e.addEventListener("pointermove",t=>this.onMove(t)),e.addEventListener("pointerup",t=>this.onUp(t)),e.addEventListener("pointercancel",t=>this.onUp(t,!0)),e.addEventListener("wheel",t=>this.onWheel(t),{passive:!1}),e.addEventListener("dblclick",t=>this.onDbl(t)),e.addEventListener("contextmenu",t=>{t.target.closest("input")||t.preventDefault()}),e.addEventListener("gesturestart",t=>t.preventDefault()),this.wireChrome(),new ResizeObserver(()=>this.resize()).observe(e),this.resize(),K$(t=>{const i=this.cards.get(t);i&&i.el&&this.fillCard(i)})}wireChrome(){const e=this.ui,t=i=>{const a=i.target.closest("[data-act]");a&&this.command(a.dataset.act||"")};e.tools.addEventListener("click",t),e.selbar.addEventListener("click",i=>{const a=i.target.closest("[data-fchip]");if(a){this.focusFolder(a.dataset.fchip||"");return}t(i)}),e.scrim.onclick=()=>this.toggleHelp(!1)}activate(){this.active||!this.ready||this.host.classList.contains("hidden")||(this.active=!0,this.vc.shown(),this.needFit=!0,window.addEventListener("keydown",this.onKeyBound),window.addEventListener("keyup",this.onKeyUpBound),window.addEventListener("blur",this.onBlurBound),this.unsubs.push(jn("activity",e=>this.onActivity(e))),this.unsubs.push(jn("mutation",e=>this.onMutation(e))),this.decayTimer=window.setInterval(()=>this.decayTouches(),3e4),this.resize(),this.kick(!0))}deactivate(){this.active&&(this.active=!1,window.removeEventListener("keydown",this.onKeyBound),window.removeEventListener("keyup",this.onKeyUpBound),window.removeEventListener("blur",this.onBlurBound),this.unsubs.forEach(e=>e()),this.unsubs=[],clearInterval(this.decayTimer),cancelAnimationFrame(this.raf),this.raf=0,this.cancelGesture(),this.pointers.clear(),this.edge=null,this.persist(!0),rN())}resize(){const e=this.root.getBoundingClientRect();!e.width||!e.height||(this.W=e.width,this.H=e.height,this.dpr=Math.min(2,window.devicePixelRatio||1),this.linkCv.width=Math.round(this.W*this.dpr),this.linkCv.height=Math.round(this.H*this.dpr),this.fitIfNeeded(),this.kick(!0))}sync(){const e=new Set,t=[],i=!Object.keys(this.layout.frames).length&&!this.frames.size;for(const a of Nb()){const s=D.tree[a]||[];if(!s.length)continue;let o=this.frames.get(a),r=!1;if(!o){const l=this.layout.frames[a];o={name:a,x:0,y:0,w:0,h:0,cards:[],el:null},l?Object.assign(o,{x:l.x,y:l.y,w:l.w,h:l.h}):(r=!0,t.push(o)),this.frames.set(a,o)}for(const l of s){e.add(l.path);let c=this.cards.get(l.path);if(c){const p=c.mtime!==l.mtime||c.name!==l.name;if(c.mtime=l.mtime,c.name=l.name||bt(l.path),c.folder!==a){const h=this.frames.get(c.folder);h&&(h.cards=h.cards.filter(u=>u!==c)),c.folder=a;const d=Mx(o);c.x=d.x,c.y=d.y,o.cards.push(c),this.flashPending.add(c.path)}p&&c.el&&this.fillCard(c)}else{const p=this.layout.cards[l.path];if(c={path:l.path,name:l.name||bt(l.path),folder:a,mtime:l.mtime,x:0,y:0,el:null,touch:null,drag:!1},p&&!r)c.x=p.x,c.y=p.y;else if(!r){const h=Mx(o);c.x=h.x,c.y=h.y}o.cards.push(c),this.cards.set(l.path,c),this.ready&&this.flashPending.add(l.path)}}}for(const[a,s]of this.cards){if(e.has(a))continue;const o=this.frames.get(s.folder);o&&(o.cards=o.cards.filter(r=>r!==s)),s.el?.remove(),this.cards.delete(a),this.sel.delete(a)}for(const[a,s]of this.frames)s.cards.length||(s.el?.remove(),s.el=null,this.frames.delete(a),this.selFrames.delete(a));for(const a of t)_x(a);if(i)Sx(Array.from(this.frames.values()));else if(t.length){const a=Array.from(this.frames.values()).filter(s=>!t.includes(s));for(const s of t){const o=$$(a);s.x=o.x,s.y=o.y,a.push(s)}}for(const a of this.frames.values()){Zr(a);const s=ii(a),o=Math.round(s.w)+"x"+Math.round(s.h);if(this.sizes.get(a)!==o&&((this.sizes.has(a)||!this.ready)&&this.separate(a),this.sizes.set(a,o)),a.el&&a.el.style.getPropertyValue("--fc")!==An(a.name)){this.fillFrame(a);for(const r of a.cards)r.el&&r.el.style.setProperty("--fc",An(r.folder))}}for(const a of this.flashPending){const s=this.cards.get(a);s&&s.el&&this.flash(s)}this.empty.classList.toggle("hidden",this.cards.size>0),this.fitIfNeeded(),this.paintInfo(),this.geomDirty=!0,this.persist(),this.kick(!0)}separate(e){e&&this.frames.has(e.name)&&O$(Array.from(this.frames.values()),e)}fitIfNeeded(){!this.needFit||!this.ready||this.W<50||!this.frames.size||(this.needFit=!1,this.fitTo(this.allBounds(),!1))}scheduleLinks(){clearTimeout(this.linksTimer),this.linksTimer=window.setTimeout(()=>{this.loadLinks()},500)}async loadLinks(){let e;try{e=await tt("/api/graph")}catch{return}const t=new Map;for(const o of e.nodes||[])o.path&&!t.has(o.id)&&t.set(o.id,o.path);const i=[],a=new Map,s=new Set;for(const o of e.links||[]){const r=this.cards.get(t.get(o.source)||""),l=this.cards.get(t.get(o.target)||"");if(!r||!l||r===l)continue;const c=r.path+`
8671
8671
  `+l.path;s.has(c)||(s.add(c),i.push({a:r,b:l}),a.set(r.path,(a.get(r.path)||0)+1),a.set(l.path,(a.get(l.path)||0)+1))}this.links=i,this.linkCount=a;for(const o of this.cards.values())o.el&&this.fillCard(o);this.paintInfo(),this.kick()}async seedTouches(){try{const e=await tt("/api/logs?range=1h&limit=300"),t=D.me?.user||D.me?.username||"",i=Date.now();for(const a of(e.events||[]).slice().reverse()){const s=String(a.actor||a.by||a.user||""),o=String(a.path||a.node&&a.node.path||"");if(!s||!o||s===t||s==="web"||s==="browser")continue;const r=Number(a.ts||0)*1e3;if(!r||i-r>Dx)continue;const l=this.findCard(o);l&&(!l.touch||l.touch.at<r)&&(l.touch={actor:s,label:String(a.action||a.label||a.event||"edit"),at:r,live:!1},l.el&&this.fillCard(l))}}catch{}}persist(e=!1){if(!this.ready)return;const t={},i={};for(const s of this.frames.values()){t[s.name]={x:Math.round(s.x),y:Math.round(s.y),w:Math.round(s.w),h:Math.round(s.h)};for(const o of s.cards)i[o.path]={x:Math.round(o.x),y:Math.round(o.y)}}const a={x:Math.round(this.cam.x),y:Math.round(this.cam.y),z:+this.cam.z.toFixed(4)};this.layout={v:1,view:a,frames:t,cards:i,links:this.showLinks,minimap:this.vc.prefs.minimap},oN(this.layout,e)}saveCamSoon(){clearTimeout(this.camSaveTimer),this.camSaveTimer=window.setTimeout(()=>this.persist(),900)}kick(e=!1){e&&(this.geomDirty=!0),!this.raf&&this.active&&(this.raf=requestAnimationFrame(t=>this.frame(t)))}markMoving(){this.root.classList.add("moving"),clearTimeout(this.movingTimer),this.movingTimer=window.setTimeout(()=>this.root.classList.remove("moving"),160)}frame(e){this.raf=0;let t=!1;const i=this.cam,a=i.z,s=i.x,o=i.y;if(this.fly){const l=Math.min(1,(e-this.fly.t0)/this.fly.ms),c=1-Math.pow(1-l,3),[p,h,d]=this.fly.c0,[u,f,v]=this.fly.c1,g=Math.exp(Math.log(d)+(Math.log(v)-Math.log(d))*c),m=p+(u-p)*c,x=h+(f-h)*c;i.z=g,i.x=this.W/2-m*g,i.y=this.H/2-x*g,l>=1?(this.fly=null,this.saveCamSoon()):t=!0}if(this.zoomAnim){const l=this.zoomAnim;let c=i.z+(l.zt-i.z)*.28;Math.abs(l.zt-c)<l.zt*.002?(c=l.zt,this.zoomAnim=null,this.saveCamSoon()):t=!0;const p=(l.ax-i.x)/i.z,h=(l.ay-i.y)/i.z;i.z=c,i.x=l.ax-p*c,i.y=l.ay-h*c}if(this.inertia){const l=this.inertia,c=Math.min(48,e-l.t||16);l.t=e,i.x+=l.vx*c,i.y+=l.vy*c;const p=Math.pow(.93,c/16);l.vx*=p,l.vy*=p,Math.hypot(l.vx,l.vy)<.015?(this.inertia=null,this.saveCamSoon()):t=!0}if(this.edge&&this.g&&(this.g.kind==="card-drag"||this.g.kind==="frame-drag")&&(i.x-=this.edge.vx,i.y-=this.edge.vy,this.dragMove(this.g.px,this.g.py),t=!0),this.tween){const l=this.tween,c=Math.min(1,(e-l.t0)/l.ms),p=c<.5?4*c*c*c:1-Math.pow(-2*c+2,3)/2;for(const h of l.items)h.o.x=h.fx+(h.tx-h.fx)*p,h.o.y=h.fy+(h.ty-h.fy)*p;this.geomDirty=!0,c>=1?this.tween=null:t=!0}const r=i.x!==s||i.y!==o||i.z!==a;r&&this.markMoving(),this.applyCam(),(r||this.geomDirty)&&this.virtualize(),this.geomDirty&&this.placeAll(),this.geomDirty=!1,this.drawLinks(),this.vc.prefs.minimap&&(e-this.miniAt>60||!t)&&(this.miniAt=e,this.drawMini()),t&&this.kick()}applyCam(){const{x:e,y:t,z:i}=this.cam,a=`translate(${e}px,${t}px) scale(${i})`;this.bg.style.transform=a,this.fg.style.transform=a;const s=this.root.style;s.setProperty("--z",String(i)),s.setProperty("--iz",String(1/i)),s.setProperty("--lz",String(Math.min(1/i,4.2)*(i<.6?1.15:1)));let o=24;for(;o*i<14;)o*=2;for(;o*i>56;)o/=2;const r=o*i;s.backgroundImage=`radial-gradient(circle, var(--cv-dot) ${i>.6?1.1:.9}px, transparent ${i>.6?1.5:1.3}px)`,s.backgroundSize=`${r}px ${r}px`,s.backgroundPosition=`${e%r}px ${t%r}px`;const l=i<uN?2:i<M_?1:0;l!==this.lod&&(this.lod=l,this.root.classList.toggle("lod1",l>=1),this.root.classList.toggle("lod2",l===2),this.geomDirty=!0),this.ui.zoom.textContent=Math.round(i*100)+"%"}viewBox(e=0){const t=this.cam.z;return{x:-this.cam.x/t-e/t,y:-this.cam.y/t-e/t,w:this.W/t+2*e/t,h:this.H/t+2*e/t}}virtualize(){const e=this.viewBox(240),t=new Set;for(const i of this.frames.values()){i.el||this.mountFrame(i);const a=this.hiddenFrames.has(i.name);i.el.style.display=a?"none":"";for(const s of i.cards){const o=!a&&(s.drag||s.el&&s.el.querySelector("input"));!a&&this.lod<2&&Qh(e,$o(i,s))||o?(t.add(s.path),s.el||(this.mountCard(s),this.placeCard(s,i))):s.el&&(s.el.remove(),s.el=null)}}Q$(t)}placeAll(){for(const e of this.frames.values()){this.placeFrame(e);for(const t of e.cards)t.el&&this.placeCard(t,e)}}mountFrame(e){const t=document.createElement("div");t.className="cv-frame",t.dataset.frame=e.name,t.innerHTML='<div class="cv-flabel" title="Drag to move the folder frame; double-click to rename"><i class="cv-fdot"></i><span class="cv-ftitle"></span><span class="cv-fcount"></span><button class="cv-fbtn" data-fact="tidy" title="Tidy this frame">⊞</button><button class="cv-fbtn" data-fact="color" title="Folder color">◐</button></div><div class="cv-fresize" title="Resize frame"></div>',e.el=t,this.bg.appendChild(t),this.fillFrame(e)}fillFrame(e){if(!e.el)return;e.el.style.setProperty("--fc",An(e.name));const t=e.el.querySelector(".cv-ftitle");t.querySelector("input")||(t.textContent=e.name),e.el.querySelector(".cv-fcount").textContent=String(e.cards.length),e.el.classList.toggle("sel",this.selFrames.has(e.name))}placeFrame(e){if(!e.el)return;const t=ii(e);e.el.style.transform=`translate(${t.x}px,${t.y}px)`,e.el.style.width=t.w+"px",e.el.style.height=t.h+"px";const i=e.el.querySelector(".cv-fcount");i&&i.textContent!==String(e.cards.length)&&(i.textContent=String(e.cards.length))}mountCard(e){const t=document.createElement("div");t.className="cv-card",t.dataset.path=e.path,e.el=t,this.fillCard(e),this.fg.appendChild(t),this.flashPending.has(e.path)&&this.flash(e)}fillCard(e){const t=e.el;if(!t||t.querySelector("input"))return;const i=Y$(e.path);(!i||i.m<e.mtime)&&J$(e.path,e.mtime);const a=i?i.tags.slice(0,3).map(l=>`<span>#${b(l)}</span>`).join(""):"",s=this.linkCount.get(e.path)||0,o=e.touch&&Date.now()-e.touch.at<Dx?e.touch:null,r=o?zn(o.actor):"";t.style.setProperty("--fc",An(e.folder)),r&&t.style.setProperty("--ac",r),t.classList.toggle("touched",!!o),t.classList.toggle("live",!!(o&&o.live)),t.classList.toggle("sel",this.sel.has(e.path)),this.markHit(e),t.innerHTML=`<div class="cv-ctitle"><span>${b(e.name)}</span></div>
@@ -9657,11 +9657,19 @@ plain \`cp\` of the live file). See [docs/INSTALL.md](docs/INSTALL.md#backups).
9657
9657
 
9658
9658
  ### Start, stop and restart
9659
9659
 
9660
- | Install | Start | Stop | Restart |
9661
- |---|---|---|---|
9662
- | Native (systemd) | \`sudo systemctl start memora\` | \`sudo systemctl stop memora\` | \`sudo systemctl restart memora\` |
9663
- | Docker | \`docker start memora\` | \`docker stop memora\` | \`docker restart memora\` |
9664
- | npm, Windows zip, source | \`memora\` (keep it running) | Ctrl+C in its terminal | stop, then start |
9660
+ \`\`\`bash
9661
+ memora-cli start # or /start in the console
9662
+ memora-cli stop # or /shutdown
9663
+ memora-cli restart # or /restart
9664
+ memora-cli uninstall # or /uninstall
9665
+ \`\`\`
9666
+
9667
+ They work out how this install runs: a systemd service is driven with
9668
+ \`systemctl\`, an npm, zip or source install runs in the background (pid and
9669
+ log in the state folder), and inside Docker the console prints the host
9670
+ commands (\`docker start / stop / restart memora\`). Uninstall asks, with a
9671
+ checklist, whether to also delete your settings and your vault; both are kept
9672
+ unless you tick them. Details: [docs/INSTALL.md](docs/INSTALL.md#uninstall-with-memora-cli).
9665
9673
 
9666
9674
  The owner can also **shut the server down from the browser**: Settings, Server,
9667
9675
  Shut down. Every browser and agent is disconnected until it is started again on
@@ -9728,7 +9736,7 @@ Contributions are welcome. Read [CONTRIBUTING.md](CONTRIBUTING.md) and the
9728
9736
  ## License
9729
9737
 
9730
9738
  MIT, see [LICENSE](LICENSE). Memora by Codrihub Tech.
9731
- `,QN="# Installing Memora\n\nMemora ships as two binaries plus a folder of web UI assets:\n\n| Piece | Role |\n|---|---|\n| `memora` | The server: HTTP API, MCP, web UI, and WebSocket on **one TCP port** (default `8400`) |\n| `memora-cli` | The operator console. Run it with no arguments for slash commands (`/guide`, `/web`, `/config`, ...) |\n| `assets/` | Web UI files, found through `MEMORA_ASSETS` |\n\nThere are two supported ways to run it as a service: **native** (systemd, via\n`install.sh`) and **Docker** (Compose). On Linux it can also be installed with\n**npm**, which is handy for trying it or running it under your own user. All\nend the same way: open the console, type `/web`, and finish setup in the\nbrowser.\n\n**Fastest path** (pick one, in this order of ease), then open the link the\nsetup command prints and enter the code:\n\n```bash\n# npm (Linux x86_64 / arm64, Node 18+)\nnpm install -g @codrihub/memora && memora\nmemora-cli setup --minutes 15 # in a second terminal\n\n# Docker: no clone or folder permissions needed (named volumes)\ndocker run -d --name memora --restart unless-stopped -p 8400:8400 \\\n -v memora-data:/data -v memora-state:/state ghcr.io/codrihub/memora:latest\ndocker exec -it memora memora-cli setup --minutes 15\n\n# Native installer (Linux server with systemd)\ncurl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh | sudo sh\nsudo memora-cli setup --minutes 15\n```\n\n- [Network exposure](#network-exposure)\n- [Native install](#native-install)\n- [Docker](#docker)\n- [npm](#npm)\n- [Windows zip](#windows-zip)\n- [Start, stop and restart](#start-stop-and-restart)\n- [Reverse proxy](#reverse-proxy)\n- [Backups](#backups)\n- [Automation: `--check` and `--upgrade`](#automation---check-and---upgrade)\n\n## Network exposure\n\nMemora opens exactly **one TCP port**. The HTTP API, MCP (`/mcp`), the web UI,\nand the realtime WebSocket (`/ws`) all share it. The local event intake\n`/_bus` answers on the same port but only to loopback clients.\n\nThe state database is embedded SQLite (`<state>/memora.db`). The server creates\nand migrates it on first start; it opens no port and needs no separate\ndatabase server or install.\n\nNothing else listens. Allow only that one port through the firewall, or none at\nall when a reverse proxy on the same host is the entry point\n(`--behind-proxy`).\n\n## Native install\n\nRequirements: Linux on x86_64 or aarch64 with systemd, `curl` (or `wget`),\n`tar`, `sha256sum`, and `git` (vault history uses it).\n\n```sh\n# Inspect first: https://github.com/Codrihub/memora/blob/main/scripts/install.sh\ncurl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh | sudo sh\n```\n\nPass flags after `sh -s --`, for example:\n\n```sh\ncurl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh \\\n | sudo sh -s -- --version 1.0.0 --behind-proxy\n```\n\nor download the script and run it: `sudo sh install.sh --help`.\n\nThe script is idempotent: running it again reinstalls the same files and keeps\nthe port and bind address of the existing unit unless you pass new ones.\n\n### What it does\n\n1. Downloads `memora-<version>-<arch>-linux.tar.gz` for this CPU from GitHub\n Releases (the latest, or `--version`), downloads `SHA256SUMS` from the same\n release, and refuses to continue if the checksum does not match.\n2. Installs the binaries atomically (copy to a temp file, then `mv`).\n3. Creates the system user and group `memora` (no login shell, home\n `/var/lib/memora`).\n4. Creates `/var/lib/memora/state` (`0700`) and `/var/lib/memora/vault`\n (`0750`), owned by `memora`.\n5. Writes `/etc/systemd/system/memora.service`, enables and starts it, waits\n for `/healthz`, then verifies the state database with `memora-cli db check`.\n6. Prints the next step and, when listening on every interface, a firewall\n hint.\n\n### Paths\n\n| Path | Content |\n|---|---|\n| `/usr/local/bin/memora`, `/usr/local/bin/memora-cli` | Binaries |\n| `/usr/local/share/memora/assets/` | Web UI |\n| `/usr/local/share/memora/VERSION` | Installed version (read by `--check`) |\n| `/usr/local/share/memora/install.sh` | Copy of the installer, used for `--upgrade`, `--check`, `--uninstall`, and `memora-cli update` |\n| `/var/lib/memora/state/` | `memora.db` (owner, API key hashes, sessions, settings, activity log), `backups/` |\n| `/var/lib/memora/vault/` | Suggested vault folder (chosen in the browser after the first sign-in) |\n| `/etc/systemd/system/memora.service` | The unit |\n\n`--prefix` moves the first four (default `/usr/local`), `--data-dir` moves the\nlast two (default `/var/lib/memora`).\n\n### Flags\n\n| Flag | Meaning |\n|---|---|\n| *(none)* | Install or reinstall the latest release |\n| `--version X.Y.Z` | Install that release |\n| `--from-source` | Build with `cargo build --release --locked` in the checkout the script lives in (`sudo ./scripts/install.sh --from-source`); built as `$SUDO_USER` |\n| `--from-dir PATH` | Install `PATH/memora`, `PATH/memora-cli`, `PATH/assets/` (an unpacked release, or your own build). Version from `--version`, else `PATH/VERSION` |\n| `--port N` | Port (default `8400`) |\n| `--bind ADDR` | Bind address (default `0.0.0.0`) |\n| `--behind-proxy` | Bind `127.0.0.1`; a reverse proxy on this host is the only entry |\n| `--prefix DIR` | Install prefix (default `/usr/local`) |\n| `--data-dir DIR` | Data root (default `/var/lib/memora`) |\n| `--no-start` | Install and enable, but do not start |\n| `--no-systemd` | Skip the unit and the system user (containers, tests); prints the command to start the server by hand |\n| `--upgrade` | Replace binaries and assets, keep state, restart the service if it was running |\n| `--force` | With `--upgrade`: reinstall even when already up to date |\n| `--uninstall` | Stop and remove the unit, binaries, and assets; keep data |\n| `--purge` | With `--uninstall`: also delete the data dir and the `memora` user (asks first) |\n| `--check` | Print `MEMORA_LATEST=` and `MEMORA_INSTALLED=`; change nothing |\n| `--yes`, `-y` | Never ask (needed for `--purge` without a terminal) |\n| `--dry-run` | Print every action, change nothing |\n| `--repo OWNER/NAME` | Download from another GitHub repository (forks); also settable as `MEMORA_REPO` |\n\n`MEMORA_RELEASES_URL` points the installer at a mirror that serves the same\nlayout as GitHub (`<url>/latest`, `<url>/download/vX.Y.Z/<file>`).\n\nRoot is required except for `--check`, `--dry-run`, and `--no-systemd` into a\nprefix you can write to.\n\n### Exit codes\n\n| Code | Meaning |\n|---|---|\n| `0` | Success |\n| `1` | Error (see the message) |\n| `2` | Bad usage |\n| `3` | Already up to date (`--upgrade`) |\n| `4` | Network or download failure |\n| `5` | Checksum mismatch or missing from `SHA256SUMS` |\n| `6` | Not running as root |\n| `7` | Unsupported OS or CPU |\n\n### The systemd unit\n\nThe installer writes this unit (shown with the default paths and port):\n\n```ini\n[Unit]\nDescription=Memora - long-term memory for AI agents (HTTP API + MCP + web UI)\nDocumentation=https://github.com/Codrihub/memora\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=simple\nUser=memora\nGroup=memora\nWorkingDirectory=/var/lib/memora\nEnvironment=HOME=/var/lib/memora\nEnvironment=MEMORA_STATE=/var/lib/memora/state\nEnvironment=MEMORA_ASSETS=/usr/local/share/memora/assets\nEnvironment=MEMORA_PORT=8400\nEnvironment=MEMORA_BIND=0.0.0.0\nEnvironment=MEMORA_VAULT=/var/lib/memora/vault\nEnvironment=GIT_AUTHOR_NAME=Memora\nEnvironment=GIT_AUTHOR_EMAIL=memora@localhost\nEnvironment=GIT_COMMITTER_NAME=Memora\nEnvironment=GIT_COMMITTER_EMAIL=memora@localhost\nEnvironment=RUST_LOG=info\nExecStart=/usr/local/bin/memora\nRestart=on-failure\nRestartSec=3\nTimeoutStopSec=15\nLimitNOFILE=65536\nUMask=0027\n\n# Hardening\nNoNewPrivileges=yes\nAmbientCapabilities=\nCapabilityBoundingSet=\nProtectSystem=strict\nReadWritePaths=/var/lib/memora\nProtectHome=yes\nPrivateTmp=yes\nPrivateDevices=yes\nProtectKernelTunables=yes\nProtectKernelModules=yes\nProtectKernelLogs=yes\nProtectControlGroups=yes\nProtectClock=yes\nProtectHostname=yes\nRestrictAddressFamilies=AF_UNIX AF_INET AF_INET6\nRestrictNamespaces=yes\nRestrictRealtime=yes\nRestrictSUIDSGID=yes\nLockPersonality=yes\nMemoryDenyWriteExecute=yes\nSystemCallArchitectures=native\nSystemCallFilter=@system-service\nSystemCallFilter=~@privileged\n\n[Install]\nWantedBy=multi-user.target\n```\n\nA port below 1024 adds `CAP_NET_BIND_SERVICE` instead of the empty capability\nset. There are no IP restrictions (`IPAddressDeny=`) by default; use the\nfirewall, `MEMORA_DOMAIN`, or the access rules in the UI.\n\nThe installer rewrites the unit on every run. Put local changes in a drop-in:\n\n```sh\nsudo systemctl edit memora # for example, a vault outside /var/lib/memora:\n# [Service]\n# ReadWritePaths=/srv/notes\nsudo systemctl restart memora\n```\n\nBecause of `ProtectSystem=strict` and `ProtectHome=yes`, the server can only\nwrite under `/var/lib/memora`. A vault anywhere else (including `/home`) needs\nthe drop-in above (and `ProtectHome=read-only` or `no` for `/home`).\n\n### Settings\n\nThe unit sets the basics (`MEMORA_STATE`, `MEMORA_ASSETS`, `MEMORA_PORT`,\n`MEMORA_BIND`, `MEMORA_VAULT`, `RUST_LOG`) as `Environment=` lines. Everything\nelse (`MEMORA_BASE_URL`, `MEMORA_DOMAIN`, `MEMORA_TRUSTED_PROXIES`, ...) is\nstored in the state database (table `server_config`). Edit it with the\nconsole: `sudo memora-cli` → `/config`, then `/restart`.\n\nA value stored with `/config` wins over the unit's `Environment=` lines; a key\nwith no stored value uses the environment. If you stored `MEMORA_PORT` with\n`/config` and later reinstall with `--port`, change or clear it in `/config`\ntoo, otherwise the stored value keeps applying. The provisioning owner\npassword and API key are environment-only and never stored (see\n[CONFIGURATION.md](CONFIGURATION.md)).\n\nSee [CONFIGURATION.md](CONFIGURATION.md) for every variable.\n\n### First run\n\n```sh\nsudo memora-cli # opens the console; it finds the running server itself\n/guide # step-by-step, or:\n/web # prints a one-time code\n```\n\nOpen `http://<host>:8400/login`, enter the code, create the owner account, then\nchoose the vault folder (`/var/lib/memora/vault` is suggested).\n\n### Day to day\n\n```sh\nsudo systemctl status memora\nsudo systemctl restart memora\nsudo journalctl -u memora -f\nsudo memora-cli # /status, /keys, /config, /restart, /mcp ...\n```\n\n### Upgrading\n\n```sh\nsudo /usr/local/share/memora/install.sh --upgrade # latest release\nsudo /usr/local/share/memora/install.sh --upgrade --version 1.0.1\nsudo memora-cli update # same, from the console\n```\n\nBinaries and assets are swapped atomically, the state directory and vault are\nuntouched, and the service is restarted if it was running. The server migrates\n`memora.db` itself on start. Take a `memora-cli db backup` before upgrading,\nand read the [CHANGELOG](../CHANGELOG.md) before a major version bump.\n\n### Uninstall\n\n```sh\nsudo /usr/local/share/memora/install.sh --uninstall # keeps /var/lib/memora and the memora user\nsudo /usr/local/share/memora/install.sh --uninstall --purge # also deletes notes, account, keys, and the user\n```\n\n### Firewall\n\nOpen only the Memora port, and only when clients connect directly:\n\n```sh\nsudo ufw allow 8400/tcp\n# or\nsudo firewall-cmd --permanent --add-port=8400/tcp && sudo firewall-cmd --reload\n```\n\nBehind a reverse proxy on the same host, install with `--behind-proxy` and open\nonly the proxy's 80/443.\n\n## Docker\n\n```sh\ngit clone https://github.com/Codrihub/memora.git && cd memora\nmkdir -p data state && sudo chown -R 1000:1000 data state\ndocker compose up -d\ndocker compose exec -it gateway memora-cli # then /guide, or /web\n```\n\n`docker compose up` pulls `ghcr.io/codrihub/memora:<version>`; if the image is\nnot available (or you set `IMAGE=memora:local`) it builds from the\n`Dockerfile`. Image tags: `<version>` (for example `1.0.0`), `<major>.<minor>`\n(for example `1.0`), and `latest` (stable releases only), for `linux/amd64`\nand `linux/arm64`. The compose file pins the release it ships with; set\n`IMAGE` in `.env` to run another tag.\n\n### Volumes: `/data` and `/state`\n\nBoth must be persistent (the Compose file bind-mounts `./data` and `./state`):\n\n- `/data` is the vault: your notes, their git history, the search index, and\n the event log. Lose it and the notes are gone.\n- `/state` holds `memora.db` (owner account, password hash, API key hashes,\n sessions, settings, setup/lock state, activity log). Lose it and\n every agent key stops working, the instance falls back to first-run setup,\n and anyone who reaches the port during that window could claim it.\n\nThe container runs as uid 1000; set `MEMORA_UID`/`MEMORA_GID` in `.env` if the\nhost directories belong to another user. `MEMORA_DATA_DIR` and\n`MEMORA_STATE_DIR` move the host directories, and `MEMORA_HTTP_PORT` changes\nthe published host port. See [CONFIGURATION.md](CONFIGURATION.md#docker-compose-env).\n\n### Verify\n\n```sh\ncurl -s http://127.0.0.1:8400/healthz\ndocker compose exec gateway memora-cli db check\ndocker compose exec gateway memora-cli status\nls -l state/memora.db\n```\n\n### Upgrading\n\n```sh\ngit pull\ndocker compose pull && docker compose up -d # or: docker compose up -d --build\n```\n\nSettings: `docker compose exec -it gateway memora-cli` → `/config`, then\n`docker compose restart gateway` (`/restart` cannot restart a container from\ninside).\n\n## npm\n\nRequirements: Linux on x86_64 or arm64, or Windows 10/11 on x64; Node 18 or\nnewer; and `git` (vault history uses it).\n\n```sh\nnpm install -g @codrihub/memora\nmkdir -p ~/memora && cd ~/memora\nMEMORA_VAULT=./vault MEMORA_STATE=./state memora\n# in a second terminal, same folder:\nMEMORA_STATE=./state memora-cli # then /guide, or /web\n```\n\nOn Windows, in PowerShell:\n\n```powershell\nnpm install -g @codrihub/memora\nmkdir ~\\memora; cd ~\\memora\n$env:MEMORA_VAULT = '.\\vault'; $env:MEMORA_STATE = '.\\state'; memora\n# in a second terminal, same folder:\n$env:MEMORA_STATE = '.\\state'; memora-cli # then /guide, or /web\n```\n\n`npx @codrihub/memora --version` runs it without a global install.\n\n`@codrihub/memora` holds the `memora` and `memora-cli` commands and the web UI\n(used unless `MEMORA_ASSETS` is set). The binaries come from\n`@codrihub/memora-linux-x64`, `@codrihub/memora-linux-arm64` or\n`@codrihub/memora-win32-x64`, optional dependencies npm installs only on a\nmatching machine. The Linux ones are the static binaries of the GitHub\nrelease with the same version, so glibc and musl distributions both work; the\nWindows one is built with a static C runtime and needs nothing else. There is\nno install script and nothing is downloaded at install time, so it works with\n`--ignore-scripts` and from a registry mirror; it does not work with\n`--omit=optional`, which leaves the binaries out. On macOS the commands print\nwhere to go instead: use [Docker](#docker) or build from source.\n\nThe npm install sets up no service, user or data folder: the server runs as\nyou, with `MEMORA_STATE` and `MEMORA_VAULT` where you point them (`./state`\nby default). Keep the state folder private (`chmod 700 state`; on Windows,\nkeep it under your user profile), since it holds the owner account and key\nhashes. On Windows, `memora-cli` runs every command as you: there is no root\nor service account to switch to. For a long-running server, prefer the\n[native install](#native-install).\n\nUpgrade with `npm install -g @codrihub/memora@latest` (`memora-cli update`\nprints this too) and restart the server; the state database is migrated on\nstart.\n\n## Windows zip\n\nEach GitHub release also carries `memora-<version>-x86_64-windows.zip`:\n`memora.exe`, `memora-cli.exe`, the web UI (`assets\\`), `LICENSE` and this\nREADME. It needs no installer, Node or runtime (static C runtime), and\n`memora.exe` finds the `assets` folder next to it. Check the download against\nthe release `SHA256SUMS` (`Get-FileHash memora-*.zip`), unzip it, then in\nPowerShell:\n\n```powershell\ncd memora-<version>-x86_64-windows\n$env:MEMORA_VAULT = '.\\vault'; $env:MEMORA_STATE = '.\\state'; .\\memora.exe\n# in a second window, same folder:\n$env:MEMORA_STATE = '.\\state'; .\\memora-cli.exe setup --minutes 15\n```\n\nOpen `http://localhost:8400/login` and enter the code. Like the npm install,\nit runs as you with no service; keep the folder under your user profile.\n\n## Start, stop and restart\n\n| Install | Start | Stop | Restart |\n|---|---|---|---|\n| Native (systemd) | `sudo systemctl start memora` | `sudo systemctl stop memora` | `sudo systemctl restart memora` |\n| Docker | `docker start memora` | `docker stop memora` | `docker restart memora` |\n| npm, Windows zip, source | `memora` (keep it running) | Ctrl+C in its terminal | stop, then start |\n\nFrom the browser, the owner can shut the server down in Settings, Server, Shut\ndown: the server answers, then stops gracefully and exits with status 0, the\nsame as Ctrl+C or `systemctl stop`. A supervisor that restarts a cleanly exited\nprocess starts it again (systemd `Restart=always`, Docker\n`--restart unless-stopped`); the installer's unit uses `Restart=on-failure`, so\nit stays stopped. API keys cannot shut the server down.\n\n## Reverse proxy\n\nRun Memora on loopback (`--behind-proxy` natively; in Docker set\n`MEMORA_HTTP_PORT=127.0.0.1:8400` in `.env`) and let the proxy terminate TLS.\nThen set, with `/config` or in `.env`:\n\n| Variable | Why |\n|---|---|\n| `MEMORA_BASE_URL=https://memory.example.com` | Public URL; links and MCP snippets use it, and its host becomes an allowed domain |\n| `MEMORA_DOMAIN=memory.example.com` | Only these hostnames are served; requests for the bare IP or other names get 404 |\n| `MEMORA_TRUSTED_PROXIES=203.0.113.10` | Proxies whose forwarding headers are believed. Loopback (same-host nginx, cloudflared) is always trusted; only list remote proxies |\n\nIn Docker, a proxy on the host reaches the container through the Docker\nnetwork, so the container sees the network's gateway address (for example\n`172.18.0.1`) instead of loopback. Add that address to\n`MEMORA_TRUSTED_PROXIES`, otherwise every request appears to come from it.\n\nThe proxy must forward `Host`, `X-Forwarded-For`, and `X-Forwarded-Proto`, and\nupgrade WebSockets on `/ws`. nginx and Caddy examples are in\n[DEPLOYMENT.md](DEPLOYMENT.md).\n\n## Backups\n\nBack up **both** the state database and the vault. The database is small but\ncritical.\n\nState, online (the server keeps running):\n\n```sh\nsudo memora-cli db backup # state/backups/memora-<UTC time>.db, keeps the newest 10\nsudo memora-cli db backup --to /var/backups/memora.db\nsudo memora-cli db check # integrity, permissions, sizes, last backup age\ndocker compose exec gateway memora-cli db backup # Docker: lands in ./state/backups/\n```\n\nThe copy is a consistent snapshot (`VACUUM INTO`), checked with\n`integrity_check`, mode 0600. Never `cp` a live `memora.db`: recent commits sit\nin `memora.db-wal`. Restore with the server stopped:\n\n```sh\nsudo systemctl stop memora\nsudo memora-cli db restore /var/backups/memora.db # verifies it; keeps the replaced DB in state/backups/\nsudo systemctl start memora\n```\n\nAlso keep a copy of `state/key-seal.bin`, which encrypts the sealed API key\ncopies. Vault and state together: archive both with the server stopped:\n\n```sh\nsudo systemctl stop memora\nsudo tar -C /var/lib/memora -czf memora-backup-$(date +%F).tar.gz state vault\nsudo systemctl start memora\n```\n\nKeep backups private: the database holds password and key hashes (never\nplaintext secrets).\n\n## Automation: `--check` and `--upgrade`\n\nThese are the contract for scripts and automation.\n\n```sh\n$ /usr/local/share/memora/install.sh --check\nMEMORA_LATEST=1.0.1\nMEMORA_INSTALLED=1.0.0\n```\n\n`MEMORA_INSTALLED` comes from `/usr/local/share/memora/VERSION` (written by\nthe installer), else from `memora --version`, else `unknown` (or `none` when\nnothing is installed). `MEMORA_LATEST` is `unknown` and the exit code `4` when\nGitHub cannot be reached. `--check` needs no root.\n\n```sh\n$ sudo /usr/local/share/memora/install.sh --upgrade --yes [--version X.Y.Z]\n...\nMEMORA_UPGRADE_RESULT=ok FROM=1.0.0 TO=1.0.1\n```\n\n`--upgrade --yes` never prompts. The last line of output is always\n`MEMORA_UPGRADE_RESULT=<ok|uptodate|error> FROM=<old> TO=<new>`, and the exit\ncode is `0` (ok), `3` (already up to date), `4` (network), `5` (checksum),\n`6` (not root), or `1`/`2` for other errors.\n",eD="# Configuration\n\nAll server state, settings included, lives in one SQLite database,\n`<MEMORA_STATE>/memora.db` (see [DATABASE.md](DATABASE.md)). Server settings are\nrows in the `server_config` table, edited with `memora-cli` (`/config` in the\nconsole). The process environment (systemd `Environment=`, Docker\n`environment:`) applies to every key that has no row.\n\n## Precedence\n\nFor each server setting:\n\n1. a row in `server_config` (set with `/config`), else\n2. the process environment (non-empty value), else\n3. the built-in default.\n\nThe server reads `server_config` once at startup, before anything else, so a\nchange made with `/config` applies after a restart (`/restart` for a native\ninstall, `docker compose restart gateway` in Docker). Clearing a value in\n`/config` deletes the row, and the environment or default applies again.\n\nA row wins over the environment. If you set `MEMORA_PORT` with `/config` and\nlater change the port in the systemd unit or `.env`, the row still applies\nuntil you clear it.\n\n## Server settings\n\n| Name | Default | Where it can live | What it does |\n|---|---|---|---|\n| `MEMORA_PORT` | `8400` | `server_config` or env | HTTP port (API, MCP, web UI, WebSocket). 1-65535. |\n| `MEMORA_BIND` | `127.0.0.1` | `server_config` or env | Bind address. `0.0.0.0` for every interface (the container image and the installer set it). |\n| `MEMORA_BASE_URL` | empty | `server_config` or env | Public URL, for example `https://memory.example.com`. Used for OAuth metadata and connection snippets; its host is also an allowed domain. |\n| `MEMORA_DOMAIN` | empty (any host) | `server_config` or env | Allowed hostnames, comma separated (`*.example.com` works). Requests for other hosts get 404. Loopback names are always allowed. |\n| `MEMORA_TRUSTED_PROXIES` | empty | `server_config` or env | IPs of remote reverse proxies whose forwarding headers are trusted. Loopback is always trusted. |\n| `MEMORA_ARM_TTL` | `300` | `server_config` or env | Accepted and validated (30-86400 seconds), but the server and `memora-cli` do not read it: the setup / reset window length comes from `memora-cli --minutes` (default 5 minutes). |\n| `MEMORA_VAULT` | empty (`data` as last resort) | `server_config` or env | Suggested vault folder. The vault in use is chosen in the browser (or with `memora-cli vault`) and stored in the `settings` table. |\n| `MEMORA_VAULT_AUTO` | `false` | `server_config` or env | `true` (also `1`, `yes`, `on`): use `MEMORA_VAULT` at startup instead of asking in the browser, only while no vault is configured and if the folder is writable. |\n| `MEMORA_ADMIN_USER` | `admin` | `server_config` or env | Name of the owner created at startup when no owner exists (needs `MEMORA_ADMIN_PASSWORD`). |\n| `RUST_LOG` | `info` | `server_config` or env | Log filter, for example `info` or `memora=debug`. |\n\n`server_config` accepts only these ten keys. Values are trimmed and validated\n(numbers in range, `true`/`false`, a valid user name, no control characters, at\nmost 2048 bytes).\n\n## Environment only\n\n| Name | Default | What it does |\n|---|---|---|\n| `MEMORA_ADMIN_PASSWORD`, `MEMORA_ADMIN_PASSWORD_FILE` | unset | Creates the owner at startup when none exists (at least 10 characters). Only the argon2id hash is stored; an existing owner is never replaced. |\n| `MEMORA_API_KEY`, `MEMORA_API_KEY_FILE` | unset | Installs an agent API key with id `k_env` and scopes `mcp`, `read`, `write` (at least 24 characters). Only its SHA-256 is stored; the key is replaced when the value changes. |\n| `MEMORA_STATE` | `state` (relative to the working directory) | State directory holding `memora.db`. Created with mode 0700 if missing. |\n| `MEMORA_ASSETS` | the `crates/http/assets` folder of the build tree | Directory of the web UI assets. |\n| `MEMORA_SETUP_HINT` | `memora-cli setup (run on the server)` | Hint returned by `GET /api/auth/state` and shown on the login screen. |\n| `MEMORA_UPDATE_CHECK` | `true` | Release check: shortly after start and then every 6 hours the server asks GitHub (`api.github.com/repos/Codrihub/memora/releases/latest`) for the newest release and the web UI shows when an update is available. `false` (also `0`, `no`, `off`) turns it off; no network call is made. |\n\nThe two secrets can never be stored in `server_config` (the schema rejects\nthem). The `_FILE` variants read the value from a file, for example a Docker\nsecret; a non-empty file wins over the plain variable.\n\nIn `/config`, `MEMORA_API_KEY` offers to create an API key directly, and\n`MEMORA_ADMIN_PASSWORD` points to `/setup` or `/reset`.\n\n## Instance settings (web UI)\n\nThe `settings` table holds one row, edited from the Settings page of the web UI:\n\n| Key | Default | Range | What it does |\n|---|---|---|---|\n| `realm` | `Memora` | 1-64 characters | Instance name shown in the UI and reported by `/api/config` and `/api/auth/state`. |\n| `session_ttl` | `10800` (3 hours) | 300-2592000 seconds | Idle timeout of a browser session. |\n| `session_max_age` | `0` | `0` or at least `session_ttl` | Absolute session lifetime in seconds. `0` means no cap. |\n| `min_password_len` | `10` | 10-256 | Minimum owner password length. |\n| `log_max_mb` | `8` | 1-512 | Size limit in MB of the vault event log (`.events.jsonl`). |\n| `log_max_days` | `0` | 0-3650 | Age limit in days of the vault event log. `0` means no age limit. |\n| `vault_path` | unset | absolute path | The vault folder. Set in the browser after the first sign-in, or with `memora-cli vault PATH`. |\n\n## memora-cli options\n\n| Option | Default | What it does |\n|---|---|---|\n| `--state <DIR>` | `$MEMORA_STATE`, else the state directory of the running `memora` server, else `./state` | State directory to work on. |\n| `--minutes <N>` | `5` | Window length for `setup` and `reset-password`, 1-60. |\n| `--ttl <SECONDS>` | | Window length in seconds (at most 3600). `--minutes` wins when both are given. |\n| `--create` | | With `vault PATH`: create the folder if it does not exist. |\n\nRun as root, `memora-cli` does all database work as the owner of the state\ndirectory, so no root-owned `memora.db*` files appear. See\n[INSTALL.md](INSTALL.md) and [DEPLOYMENT.md](DEPLOYMENT.md) for the commands.\n\n## Docker Compose (`.env`)\n\nThese variables are read by `docker-compose.yml`, not by Memora itself:\n\n| Name | Default | What it does |\n|---|---|---|\n| `COMPOSE_PROJECT_NAME` | `memora` | Compose project name, also the container name prefix. |\n| `IMAGE` | `ghcr.io/codrihub/memora:<version>` | Image to run or build. The compose file pins the release it ships with. |\n| `MEMORA_HTTP_PORT` | `8400` | Host port mapped to the container's port 8400. Use `127.0.0.1:8400` to publish on loopback only. |\n| `MEMORA_DATA_DIR` | `./data` | Host path mounted at `/data` (the vault). |\n| `MEMORA_STATE_DIR` | `./state` | Host path mounted at `/state` (the state directory). |\n| `MEMORA_UID`, `MEMORA_GID` | `1000` | uid:gid the container runs as. Must own both host directories. |\n| `MEMORA_ARM_TTL` | `300` | Passed to the container unchanged. |\n\nCompose also passes these through from `.env` to the container:\n`MEMORA_BASE_URL`, `MEMORA_DOMAIN`, `MEMORA_TRUSTED_PROXIES`,\n`MEMORA_VAULT_AUTO`, `MEMORA_ADMIN_USER`, `MEMORA_ADMIN_PASSWORD`,\n`MEMORA_ADMIN_PASSWORD_FILE`, `MEMORA_API_KEY`, `MEMORA_API_KEY_FILE`,\n`MEMORA_SETUP_HINT`, `MEMORA_UPDATE_CHECK`, and `RUST_LOG`.\n\nInside the container the image sets `MEMORA_VAULT=/data`,\n`MEMORA_STATE=/state`, `MEMORA_PORT=8400`, `MEMORA_BIND=0.0.0.0`,\n`MEMORA_ARM_TTL=300`, `MEMORA_ASSETS=/app/assets`, and `RUST_LOG=info`.\n\n## State directory\n\n| Path | Content |\n|---|---|\n| `memora.db` (+ `-wal`, `-shm`) | The state database: owner, API keys (hashes), tool switches and per-key permissions, OAuth clients and grants, privacy rules, sessions (hashed ids), setup window and lock state, access rules, settings, `server_config`, activity log. Mode 0600, WAL mode, must be on a local filesystem. See [DATABASE.md](DATABASE.md). |\n| `key-seal.bin` | 32-byte master key (mode 0600) that encrypts the copies of dashboard-created API keys, so the owner can show a key again. Created on first use. Back it up together with `memora.db`. |\n| `backups/` | `memora-cli db backup` output (newest 10 kept by default). |\n| `legacy-json-<unix time>/` | JSON state files found at startup, moved here after their one-time import into `memora.db`. |\n| `internal.token` | Created by the Docker entrypoint. Not used by Memora. |\n\n## Vault files\n\nThe vault holds the markdown notes plus derived and metadata files. See\n[ARCHITECTURE.md](ARCHITECTURE.md#vault-markdown-portable) for the full list.\nThe important ones for operations are `.git/` (history), `.fts.db`\n(rebuildable search index), `.events.jsonl` (event log), and `.Trash/`\n(soft-deleted notes).\n",tD='# MCP\n\nMemora exposes the vault to agents through the Model Context Protocol. The\nserver speaks JSON-RPC 2.0 over the Streamable HTTP transport at `/mcp`, on the\nsame port as the HTTP API and the web UI. There is one MCP endpoint and one tool\ncatalog.\n\n| | |\n|---|---|\n| Endpoint | `POST /mcp` |\n| Protocol versions | `2025-06-18` (preferred), `2025-03-26`, `2024-11-05` |\n| Auth | API key in `Authorization: Bearer <key>` or `X-API-Key: <key>`, or an OAuth 2.1 access token |\n| Discovery card | `GET /.well-known/mcp.json` (public) |\n| Readable catalog | `GET /tools` (HTML page, public) |\n| Catalog size | 74 tools, plus 5 admin tools for keys with the `admin` scope |\n\n`initialize` answers with the protocol version the client asks for when it is\none of the three above, and with `2025-06-18` otherwise.\n\n## Transport\n\n- Requests are JSON-RPC 2.0 objects sent with `POST /mcp`. Batches (JSON\n arrays) are not supported.\n- Responses are plain JSON (`application/json`). The server does not open SSE\n streams and does not issue an `Mcp-Session-Id`.\n- `GET` and `DELETE` on `/mcp` return `405 Method Not Allowed` with\n `Allow: POST`.\n- A notification (a `notifications/*` method without an `id`) gets\n `202 Accepted` and no body.\n- `/mcp` needs a configured vault. Until one is chosen it returns\n `409 {"error":"vault not configured","needs_vault":true}`.\n- A browser session (cookie) may also call `/mcp`. It then needs a same-origin\n request, like the rest of the JSON API.\n\nThe server speaks Streamable HTTP only. A client that can only launch local stdio\nservers can use a bridge such as `mcp-remote` (see below).\n\n## Connecting an agent\n\n### With an API key\n\nCreate a key in the web UI (Keys page), with `memora-cli` (`/keys`), or with\n`POST /api/keys`. The raw key (`memora_live_...`) is shown once. By default a key gets\nthe scopes `mcp`, `read` and `write` and may call every tool. See\n[Tool switches and per-key permissions](contracts/tools-permissions.md) to\nnarrow it.\n\nUse `http://localhost:8400/mcp` for a local install, or your public URL such as\n`https://memory.example.com/mcp` behind a reverse proxy. When the server sets\n`MEMORA_DOMAIN` or `MEMORA_BASE_URL`, requests for any other host get `404`, so\nuse that domain.\n\nClaude Code:\n\n```bash\nclaude mcp add --transport http memora https://memory.example.com/mcp \\\n --header "Authorization: Bearer memora_live_REPLACE_WITH_YOUR_KEY"\n```\n\nCursor, Windsurf and other clients with an `mcpServers` JSON config (VS Code\nuses the key `servers` in `.vscode/mcp.json`):\n\n```json\n{\n "mcpServers": {\n "memora": {\n "type": "http",\n "url": "http://localhost:8400/mcp",\n "headers": {\n "Authorization": "Bearer memora_live_REPLACE_WITH_YOUR_KEY"\n }\n }\n }\n}\n```\n\nCodex (`~/.codex/config.toml`), with the key in the `MEMORA_API_KEY`\nenvironment variable:\n\n```toml\n[mcp_servers.memora]\nurl = "https://memory.example.com/mcp"\nbearer_token_env_var = "MEMORA_API_KEY"\n```\n\nClients that only run local stdio servers, such as the Claude Desktop config\nfile, can bridge with `mcp-remote` (needs Node.js):\n\n```json\n{\n "mcpServers": {\n "memora": {\n "command": "npx",\n "args": [\n "-y", "mcp-remote", "https://memory.example.com/mcp",\n "--header", "Authorization: Bearer memora_live_REPLACE_WITH_YOUR_KEY"\n ]\n }\n }\n}\n```\n\nSome clients send the key as `X-API-Key: <key>` instead. Both headers are\naccepted.\n\n### With OAuth\n\nClients that support MCP authorization (for example Claude and ChatGPT custom\nconnectors, or Claude Code without a `--header`) can connect with only the URL:\n\n```bash\nclaude mcp add --transport http memora https://memory.example.com/mcp\n```\n\nThe flow:\n\n1. The client calls `/mcp` without credentials and gets `401` with\n `WWW-Authenticate: Bearer resource_metadata="https://memory.example.com/.well-known/oauth-protected-resource"`.\n2. It reads the protected resource metadata (RFC 9728) and the authorization\n server metadata at `/.well-known/oauth-authorization-server` (RFC 8414; also\n served at `/.well-known/openid-configuration` and under a `/mcp` suffix).\n3. It registers itself with dynamic client registration at\n `POST /oauth/register` (RFC 7591), or uses an HTTPS client metadata document\n URL as its `client_id`. The owner can also register clients in the web UI.\n Redirect URIs must be HTTPS, or plain HTTP on `localhost`, `127.0.0.1` or\n `[::1]`.\n4. It opens `/oauth/authorize` (authorization code with PKCE `S256` only). The\n browser lands on the Memora sign-in page, and the signed-in owner approves or\n denies the connection on a consent card. Codes are valid for 10 minutes.\n5. It exchanges the code at `POST /oauth/token` and receives an access token and\n a refresh token. The only OAuth scope is `mcp`.\n\nThe access token is a regular Memora API key named after the client. It starts\nwith the default scopes (`mcp`, `read`, `write`) and every tool, and it shows up\non the Keys page like any other key, so you can restrict, disable or delete it\nthere. The access token has no expiry. A `refresh_token` grant replaces it with\na fresh one (the old token stops working at once) and rotates the refresh token.\nDisabling or deleting the key ends the connection.\n\nSet `MEMORA_BASE_URL` (for example `https://memory.example.com`) when the server\nruns behind a proxy, so the issuer and endpoint URLs in the metadata are the\npublic ones. Without it the server derives them from the request headers.\n\n### Test from a shell\n\n```bash\ncurl -s -X POST http://localhost:8400/mcp \\\n -H "Authorization: Bearer memora_live_REPLACE_WITH_YOUR_KEY" \\\n -H "Content-Type: application/json" \\\n -d \'{"jsonrpc":"2.0","id":1,"method":"tools/list"}\'\n```\n\n## Discovery card\n\n`GET /.well-known/mcp.json` needs no auth and returns:\n\n| Field | Value |\n|---|---|\n| `name` | `memora` |\n| `version` | The server version |\n| `description` | One-line description of the server |\n| `mcp` | `{endpoint: "/mcp", transports: ["streamable-http"], protocolVersion: "2025-06-18"}` |\n| `auth` | `{type: "api-key", headers: ["Authorization: Bearer <key>", "X-API-Key: <key>"], oauth: "/.well-known/oauth-authorization-server"}` |\n| `capabilities` | `{tools: true, resources: true, prompts: false}` |\n| `tools` | Every catalog tool as `{name, category, description, enabled}`. `enabled` is `false` for tools switched off on this server. Admin tools are not listed. |\n| `resources` | `[{uri, name}]` for the three resources below |\n\nThe card is the same for every caller. To see what a given key may call, use\n`tools/list` with that key.\n\n## Methods\n\n| Method | Purpose |\n|---|---|\n| `initialize` | Handshake. Returns `protocolVersion`, `serverInfo` (`{name, version}`) and `capabilities` (`tools` and `resources`, both with `listChanged: false`). |\n| `notifications/initialized` | Client notification. Without an `id` it gets `202 Accepted`. |\n| `tools/list` | The tools the caller may use, each with `name`, `description` (what it does and when to use it), `inputSchema`, and `_meta.category`. |\n| `tools/call` | Runs one tool. Params are `{name, arguments}`. |\n| `resources/list` | Lists the three resources below. |\n| `resources/read` | Reads one resource. Params are `{uri}`. |\n\nThere are no prompts, no pagination cursors and no change notifications.\n\n### Resources\n\n| URI | Content |\n|---|---|\n| `memory://catalog` | Every catalog tool with `name`, `category`, `description`, `when`, and `inputSchema` (JSON) |\n| `memory://schema` | Data shapes for a note, a folder, the graph, and activity (JSON) |\n| `memory://guide` | A short guide for agents using the vault (Markdown) |\n\n`resources/read` returns `{contents: [{uri, mimeType, text}]}`.\n\n## Results and errors\n\nA successful tool call returns the tool\'s JSON result as text:\n\n```json\n{\n "jsonrpc": "2.0",\n "id": 2,\n "result": {\n "content": [{ "type": "text", "text": "{...}" }],\n "isError": false\n }\n}\n```\n\nA tool that fails (bad arguments, note not found, unknown tool name) returns the\nsame envelope with `isError: true` and the error message as the text. The HTTP\nstatus stays `200`.\n\nJSON-RPC errors:\n\n| Code | When |\n|---|---|\n| `-32700` | The body is not valid JSON (HTTP `400`). |\n| `-32600` | The body is not a JSON-RPC request object (HTTP `400`). |\n| `-32601` | Unknown method: `unsupported method: <method>`. |\n| `-32602` | `resources/read` with an unknown URI: `unknown resource: <uri>`. |\n| `-32003` | The tool exists but the caller may not use it. Messages: `tool not allowed for this API key: <name>`, `tool disabled on this server: <name>`, `API key lacks the \'write\' scope for tool: <name>`. |\n\nHTTP errors before JSON-RPC runs:\n\n| Status | When |\n|---|---|\n| `401` | No key, or a key that is unknown, disabled, deleted or replaced by a roll (`invalid API key`). Carries a `WWW-Authenticate` header that points OAuth clients at the protected resource metadata. |\n| `403` | The key lacks the `mcp` scope (`{"error":"API key lacks the \'mcp\' scope","required_scope":"mcp"}`), or a browser request failed the same-origin check. |\n| `405` | Any method other than `POST`. |\n| `409` | No vault is configured yet. |\n| `429` | Rate limit or cooldown after failed attempts. |\n\n## What each key sees\n\n`tools/list` is filtered per caller:\n\n- A tool switched off on the server is hidden for everyone.\n- A key whose tool list is not `"*"` only sees the tools in its list.\n- A key without the `write` scope only sees read-only tools.\n- Admin tools are added for keys with the `admin` scope (and for browser\n sessions).\n\n`tools/call` on a tool that `tools/list` would hide returns `-32003`. Details\nare in [Tool switches and per-key permissions](contracts/tools-permissions.md).\n\n### Privacy rules\n\nThe owner can hide notes and folders from specific agents (web UI,\n`/api/privacy`, or the `privacy_*` admin tools). For an API key covered by a\nrule, every tool works as if the hidden paths did not exist: they are left out\nof listings, search, the graph, tags, events, logs, locks and folder metadata; a\nhidden path named in an argument is answered as not found, for reads and writes\nalike; and folder operations that would carry hidden items along are refused.\nIf the rules cannot be read, the key sees nothing (fail closed). Browser\nsessions are never filtered.\n\n## Tools\n\nR = read-only (needs only the `mcp` scope). W = changes the vault or server\nstate (also needs the `write` scope). Unless marked required, arguments are\noptional. Paths are vault-relative, for example `Projects/Plan.md`.\n\n### Notes (`note`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `list_memory` | R | none | Every note grouped by folder: `{folder: [{path, name, folder, mtime}]}`. |\n| `read_memory` | R | `path` (string, required) | Markdown body, frontmatter, tags and backlinks of one note. |\n| `create_memory` | W | `title` (string, required), `folder` (string, default `Memory`; `Root` or empty for the top level), `content` (string; default is a stub with `created` frontmatter and a heading) | Creates `<folder>/<title>.md` and returns `{ok, path}`. |\n| `save_memory` | W | `path` (string, required), `content` (string, required) | Replaces the whole note. |\n| `patch_memory` | W | `path` (string, required), `ops` (array, required) | Partial edits. Each op is an object: `{op:"append", text}`, `{op:"prepend", text}`, `{op:"replace", find, with}`, `{op:"set_field", field, value}`, `{op:"add_tag", tag}`, `{op:"remove_tag", tag}`. |\n| `delete_memory` | W | `path` (string, required) | Deletes a note (recoverable from git history). |\n| `move_memory` | W | `path` (string, required), `folder` (string, required) | Moves a note into another folder. Wikilinks resolve by note name, so they keep working. |\n| `rename_memory` | W | `path` (string, required), `new_name` (string, required) | Renames a note in its folder. |\n\n### Search (`search`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_stats` | R | none | Counts of notes, links and folders. |\n| `search_memory` | R | `q` (string, required; `query` is accepted as an alias), `limit` (integer, default 12) | Search titles and bodies. Supports `tag:x` and `#x`. |\n\n### Query (`query`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `query_memory` | R | `folder`, `tags`, `author`, `type`, `status` (strings), `limit` (integer, default 50) | Filter notes by frontmatter. |\n| `find_similar` | R | `path` (string, required), `limit` (integer, default 8) | Notes most similar to one note (shared tags and words). |\n| `suggest_links` | R | `path` (string, required), `limit` (integer, default 8) | Similar notes not yet linked from this one. |\n| `list_tags` | R | none | Every tag with its usage count. |\n| `rename_tag` | W | `old` (string, required), `new` (string, required) | Renames a tag across the vault. |\n| `merge_tag` | W | `a` (string, required), `b` (string, required) | Merges tag `a` into tag `b` across every note. |\n\n### Tags (`tag`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_tags` | R | `path` (string; not in the advertised schema) | Every tag with its count, or the tags of one note when `path` is given. |\n| `search_by_tag` | R | `tag` (string, required), `limit` (integer, default 50; not in the advertised schema) | Every note carrying a tag. |\n| `add_tags` | W | `path` (string, required), `tags` (string, required, comma-separated) | Adds tags to a note. A leading `#` is stripped. |\n| `remove_tags` | W | `path` (string, required), `tags` (string, required, comma-separated) | Removes tags from a note. |\n| `set_tags` | W | `path` (string, required), `tags` (string, required, comma-separated) | Replaces a note\'s tag list. |\n\n### Folders (`folder`, `ops`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `list_folders` | R | none | `{count, folders: [{name, count, color}]}`. |\n| `create_folder` | W | `name` (string, required) | Creates a folder. |\n| `rename_folder` | W | `folder` (string, required), `name` (string, required, one segment) | Renames a folder in place. Notes, sub folders, color and icon move along. |\n| `move_folder` | W | `folder` (string, required), `into` (string; empty or `Root` = top level) | Moves a folder with everything in it. |\n| `move_folder_contents` | W | `folder` (string, required), `into` (string; empty = top level) | Moves everything inside a folder into another folder, then removes the empty folder. Name clashes get a `-N` suffix. |\n| `delete_folder` | W | `folder` (string, required) | Deletes a folder. Its notes move to Root. |\n| `folder_stats` | R | `folder` (string, required) | Note count and metadata for one folder. |\n| `get_folder_meta` | R | `folder` (string) | Color, icon and description of one folder, or of every folder. |\n| `set_folder_meta` | W | `folder` (string, required), `color`, `icon`, `desc` (strings) | Sets folder display metadata. A field sent as an empty string is cleared. |\n\n### Graph (`graph`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_graph` | R | none | Whole graph: `{nodes: [{id, path, folder, color, degree, tags, mtime}], links: [{source, target}]}`. |\n| `get_neighbors` | R | `path` (string, required), `depth` (integer, default 1) | Notes within N hops. |\n| `get_subgraph` | R | `path` (string, required), `depth` (integer, default 1), `max_nodes` (integer, default 60) | Subgraph around one note. |\n| `find_path` | R | `source` (string, required), `target` (string, required) | Shortest wikilink path between two notes. |\n| `get_hubs` | R | `limit` (integer, default 10) | Most connected notes. |\n| `get_isolated` | R | none | Notes with no links in or out. |\n| `link_stats` | R | `path` (string, required) | Outgoing, incoming and unresolved links of one note. |\n| `broken_links` | R | none | Wikilinks pointing at notes that do not exist. |\n\n### Versioning (`version`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_history` | R | `path` (string, required), `limit` (integer, default 20) | Git history of a note. A single entry is returned as an object, several as an array. |\n| `get_note_at` | R | `path` (string, required), `rev` (string, required) | `{ok, path, rev, content}` at a revision. |\n| `diff` | R | `path` (string, required), `rev_a` (string, required), `rev_b` (string) | Diff between two revisions, or `rev_a` against the working tree. |\n| `restore_memory` | W | `path` (string, required), `rev` (string, required) | Restores a note to a revision. |\n| `snapshot` | W | `label` (string, required) | Tags the whole vault (git tag). |\n| `soft_delete` | W | `path` (string, required) | Moves a note to `.Trash`. |\n| `restore_trash` | W | `name` (string, required), `into` (string, default `Root`) | Restores a note from `.Trash` into a folder. |\n\n### Bulk writes (`write`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `batch_create` | W | `notes` (array, required) of `{title, folder (default Root), content}` | Creates many notes in one call. |\n| `duplicate_memory` | W | `path` (string, required) | Copies a note as `<name>-copy` in the same folder. |\n| `merge_memory` | W | `paths` (array of strings, required), `into` (string, required) | Merges several notes into one target note. |\n| `template_create` | W | `template` (string, required), `title` (string, required), `folder` (string, default `Root`), `variables` (object) | Creates a note from a file in `Templates/` with `{{var}}` substitution. |\n| `bulk_replace` | W | `find` (string, required), `replace` (string, required), `folder` (string), `regex` (boolean, default false), `dry_run` (boolean, default false) | Find and replace across notes. Needs `write` even with `dry_run`. |\n| `bulk_delete` | W | `paths` (array of strings), `folder` (string) | Deletes many notes by list or by folder. |\n\n### Collaboration (`collab`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `lock_node` | W | `path` (string, required), `owner` (string, default the caller), `ttl` (integer seconds, default 300) | Soft lock on a note. |\n| `release_lock` | W | `path` (string, required), `owner` (string, default the caller) | Releases a lock. |\n| `get_locks` | R | none | Active locks. |\n| `mention_agent` | W | `agent` (string, required), `path` (string, required), `message` (string) | Writes `> @agent: message` into a note. |\n| `get_assignments` | R | `agent` (string) | Notes with `assigned_to` in their frontmatter. |\n\n### Activity and health (`ops`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_events` | R | `since` (number, unix time), `folder`, `actor` (strings), `limit` (integer, default 50) | Recent note created, updated and deleted events. |\n| `presence` | R | `window` (integer seconds, default 300) | Agents active within the window. |\n| `get_logs` | R | `range` (string, default `1d`; also `7d`, `today`, `yesterday`), `actor` (string), `limit` (integer, default 100) | Activity log for a period. |\n| `search_logs` | R | `q` (string, required), `range` (string, default `7d`), `actor` (string), `limit` (integer, default 100) | Keyword search in the activity log. |\n| `digest` | R | `folder` (string), `since` (number) | Event counts per actor and per type. |\n| `healthcheck` | R | none | Note count, broken links, orphans and git status. |\n| `stale_detection` | R | `days` (integer, default 30) | Notes untouched for more than N days. |\n\n### Identity (`identity`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `set_my_name` | W | `name` (string, required) | Sets the display alias shown in the activity feed and log. |\n| `set_my_color` | W | `color` (string, required; `#rrggbb`, or `""` to reset) | Sets the calling API key\'s display color. Fails for browser sessions. |\n| `list_actors` | R | none | `{me, aliases}`: the caller and every known alias. |\n\n### Import and export (`interop`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `export_memory` | W | `paths` (array of strings, required; notes or folders), `out_path` (string) | Writes a zip of the given paths to the server\'s exchange folder and returns `{ok, path, name, bytes}`, where `path` and `name` are the zip\'s file name. `out_path` is a plain file name ending in `.zip` (letters, digits, `.`, `_`, `-`, at most 120 characters); the default is `memora-export-<time>.zip`. |\n| `import_memory` | W | `zip_path` (string, required), `overwrite` (boolean, default false) | Imports notes from a zip in the exchange folder, by the file name `export_memory` returned. |\n\nThe exchange folder is `memora-exchange` in the server\'s temporary directory.\nTools never read or write anywhere else on the server\'s disk.\n\n### Checks, to-dos and pins (`ux`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_todos` | R | `path` (string) | Open checklist items (`- [ ]`) in one note or the whole vault. |\n| `follow_ups` | R | none | Notes whose status is still awaiting action. |\n| `validate_memory` | R | `path` (string, required) | Checks frontmatter, created date, tags and links of a note. |\n| `list_pins` | R | none | The owner\'s pinned notes and folders in sidebar order: `{count, pins:[{kind, path, position, missing}]}`. `missing` is true when the path no longer exists (renamed or deleted outside Memora). |\n| `pin` | W | `path` (string, required), `kind` (`note` or `folder`; default: what the path is on disk), `position` (integer from 0; default: the end) | Pins an existing note or folder, or moves its pin. A note path may leave out `.md`. At most 200 pins. Returns the list. |\n| `unpin` | W | `path` (string, required), `kind` | Removes a pin; the note or folder is not touched. Returns the list with `removed`. |\n\nPins are shared by every browser of the owner (`/api/pins`). They follow their note or\nfolder through renames and moves done by Memora (over MCP or HTTP, including notes inside\na moved folder) and are removed when the item is deleted or moved to the trash; deleting a\nfolder removes every pin under it. A key whose privacy rules hide a path neither lists\nnor changes its pin, and `position` counts only the pins the key can see.\n\n### Admin tools (`admin`)\n\nListed and callable only for keys with the `admin` scope (and for browser\nsessions). They are not part of the switchable catalog: global tool switches and\na key\'s tool list do not apply to them, and they do not need `write`.\n\n| Tool | Arguments | Purpose |\n|---|---|---|\n| `admin_list_tools` | none | `{tools: [{name, category, description, enabled}]}` for every catalog tool. |\n| `admin_set_tool` | `name` (string, required), `enabled` (boolean, required) | Switches a catalog tool on or off for every key. Returns `{ok, name, enabled}`. |\n| `privacy_list` | `path` (string), `kind` (`node` or `folder`) | Without `path`: every privacy rule. With `path`: that note or folder\'s own rule, the folder rules it inherits, and which agents can see it. |\n| `privacy_set` | `path` (string, required), `agents` (array of key ids or names, required; a comma-separated string also works), `kind` (`node` or `folder`), `mode` (`deny` or `allow_only`, default `deny`) | Replaces the rule on a path. `deny` hides it from the listed agents; `allow_only` hides it from every other agent, including keys created later. `deny` with no agents removes the rule. A node rule follows its note through renames and moves. |\n| `privacy_clear` | `path` (string, required), `kind` (`node` or `folder`) | Removes the path\'s own rule. Rules on parent folders still apply. |\n\nWhen `kind` is omitted it is taken from the path on disk: a folder if a folder\nexists there, otherwise a note.\n\n## Identity and tracking\n\nEvery tool call is published to the web UI\'s realtime activity stream as an\n`ai_activity` start and end pair, named after the API key (or the signed-in\nuser), with the note paths involved. Calls are also counted per key: the Keys\npage and `GET /api/keys` show each key\'s `uses`, `last_ip`, and the tools it has\ncalled recently. `initialize` registers the connection under the key\'s name\n(`GET /api/aliases`). `set_my_name` changes the alias shown in the activity\nfeed and log, and `set_my_color` changes the key\'s color in the UI. See\n[API.md](API.md) for the HTTP endpoints.\n',nD='# HTTP API\n\nThe `memora` binary serves the HTTP API, the MCP endpoint, the OAuth endpoints,\nthe web UI, and the WebSocket on one port. This document lists the HTTP endpoints.\n\n## Authentication\n\nThe Auth column in the tables below uses these levels:\n\n- None: reachable without credentials.\n- Session: requires the `memora_sess` cookie set by a successful login.\n- Key (`scope`): an API key sent as `Authorization: Bearer <key>` or `X-API-Key: <key>`\n that carries the named scope.\n- Session or key (`scope`): either of the above.\n- Session only: an API key is not enough. API keys get `401` (or `403` where noted).\n- +CSRF: the same-origin check described below applies.\n\n### API key scopes\n\nA key carries any of the scopes `mcp`, `read`, `write`, and `admin`. New keys get\n`mcp`, `read`, and `write` unless other scopes are requested. The scope a route\nneeds is decided by its path and method:\n\n| Scope | Routes |\n|---|---|\n| `mcp` | `/mcp` |\n| `admin` | `/api/tools`, `/api/keys` and `/api/keys/*`, `/api/access` and `/api/access/*`, `/api/logs/settings`, `/api/oauth/clients` and `/api/oauth/clients/*`, `/api/privacy` and `/api/privacy/*` |\n| `read` | Every other `GET` or `HEAD` under `/api/` |\n| `write` | Every other method under `/api/` |\n\nA key without the needed scope gets `403 {error, required_scope}`. A missing key\ngets `401`; for `/mcp` the `401` carries a `WWW-Authenticate` header,\n`Bearer resource_metadata="<base>/.well-known/oauth-protected-resource"`, so OAuth\ncapable clients can start sign-in. An invalid key gets `401` and is logged; an\nIP that keeps presenting invalid keys is put on a cooldown (`429`).\n\n`/api/auth/*` never accepts an API key: without a valid session it answers `401`.\n\nAPI keys see the vault through their privacy rules (see [Privacy](#privacy)):\nnotes and folders hidden from a key behave as if they do not exist. A browser\nsession sees everything.\n\n### CSRF\n\nWrite endpoints that accept a session check the request origin whenever a\nsession cookie is present: `Origin` (or, without it, `Referer`) must match the\nrequest `Host` (or an `X-Forwarded-Host` sent by a trusted proxy), and\n`Sec-Fetch-Site: cross-site` is refused. A failed check is\n`403 {"error":"origin mismatch"}`. Requests without a session cookie (API-key\nclients) pass, since a browser cannot attach an API key on its own.\n\nThe public auth forms (`/api/auth/login`, `/api/auth/verify`,\n`/api/auth/bootstrap`, `/api/auth/reset`) also refuse a foreign or `null`\n`Origin` when no cookie exists yet. A request with neither `Origin` nor\n`Referer` (curl, the CLI) passes.\n\n### Locked instance\n\nWhile the instance is LOCKED, `/api/*` and `/mcp` answer\n`423 {error, locked: true, hint}` except for `/api/auth/state`, `/api/auth/verify`,\n`/api/auth/login`, `/api/auth/logout`, `/api/auth/bootstrap`, and\n`/api/auth/reset`. Other pages redirect to `/login?locked=1`; static assets,\n`/login`, `/logout`, `/healthz`, and `/favicon.ico` are still served.\n`/api/auth/login` itself answers `423` while locked.\n\n### Vault not configured\n\nUntil a vault folder is configured, `/mcp` and every `/api/*` route except\n`/api/auth/*`, `/api/settings*`, `/api/config`, `/api/keys*`, `/api/tools`,\n`/api/access*`, and `/api/ui/*` answer\n`409 {"error":"vault not configured", "needs_vault":true}`.\n\n### Limits and other gates\n\n- Requests for a host outside the configured domain list get a bare `404`.\n- Access rules (see `/api/access`) can block a caller:\n `403 {"error":"access denied by stack rule", ip}`.\n- Per-IP rate limits answer `429` with a `Retry-After` header and\n `{error, limited, cooldown, retry_after}`. Login, code check, setup, reset, profile,\n password, and username changes have a stricter limit and a cooldown after\n repeated failed attempts. Requests from the machine itself and `/healthz` are\n not limited.\n- A request that takes longer than 30 seconds is answered with `408`.\n- A password hashing pool that is busy answers `503` with `Retry-After: 2`.\n\nResponses are JSON unless stated otherwise. Errors are `{"error": "..."}`. Vault\nerrors map to `404` for not-found (including paths hidden from the caller) and\n`400` for bad input.\n\n## Health and discovery\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/healthz` | None | `{ok, server}` for unauthenticated callers from other machines. A signed-in browser or a caller on the same machine gets `{ok, server, version, vault_configured, vault, armed, locked, base_url, base_url_configured}`. |\n| GET | `/.well-known/mcp.json` | None | The MCP discovery card: `{name, version, description, mcp, auth, capabilities, tools, resources}`. `tools` lists the full catalog with `enabled` per tool. |\n| GET | `/tools` | None | An HTML rendering of the tool catalog. A signed-in browser gets the app shell instead. |\n| POST | `/mcp` | Key (`mcp`), or Session (+CSRF) | MCP over streamable HTTP (JSON-RPC in, JSON-RPC out). See [MCP.md](MCP.md). A session has full access; a key is limited by its tool grant. Notifications get `202` with no body. Malformed JSON is `400` with a JSON-RPC error. Other methods get `405` with `Allow: POST`. |\n\n## Auth\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/auth/state` | None | `{bootstrap, realm, min_password_len, gateway, armed, locked, setup_hint, ready, checks:{vault, state}, code_required, cooldown, vault_configured}`. Adds `signed_out` (`password_changed` or `signed_out_remotely`) when the browser\'s session was ended on purpose, and `mode`, `expires_in`, `ttl` while a setup or reset window is open. |\n| POST | `/api/auth/verify` | None (+CSRF) | Checks the setup code shown on the server before the setup or reset form is shown. Body: `{code}`. Returns `{ok, mode, expires_in, user}`. `403` when no window is open or the instance is not ready. A wrong code closes the window and voids the code: `403 {error, burned:true}`. |\n| POST | `/api/auth/login` | None (+CSRF) | `{ok, user, expires_in, redirect}` and sets the session cookie. Body: `{username, password}`. `400` when a field is missing, `401` on bad credentials, `403` if the account is disabled, `423` if locked, `429` during a cooldown. |\n| POST | `/api/auth/logout` | None (+CSRF) | `{ok:true}`. Ends the session named by the cookie, if any, and clears the cookie. |\n| POST | `/api/auth/bootstrap` | None (+CSRF) | Creates the owner account. Body: `{code, username, password}`. Returns `{ok, user, redirect, persisted}` and sets a session cookie. The username is stored lowercase. `400` for an invalid username or password length; `403` unless a window is open, the code is right, the instance is ready, and no account exists. |\n| POST | `/api/auth/reset` | None (+CSRF) | Sets a new password for the single account, and may rename it. Body: `{code, username, password}`. Returns `{ok, user, persisted}`. Signs out every session. `400` for invalid input; `403` unless a window is open, the code is right, and an account exists. |\n| POST | `/api/auth/profile` | Session only (+CSRF) | With `password` in the body, changes the password exactly like `POST /api/settings/password` (body `{current, password, confirm}`). Otherwise sets `display_name` (at most 48 characters) and returns `{ok, changed, persisted, user, password_changed:false}`; with no `display_name` it returns `{ok, changed:false}`. |\n| GET | `/api/auth/me` | Session only | `{authenticated, user, enabled, expires_in}`. `401` without a session. |\n| GET | `/api/auth/events` | Session only | Recent entries of the security activity log, newest first: `{events:[{at, event, ip, user, detail, actor, actor_kind, actor_id}], count}`. `user` is the stored actor (`key:<id>` for API-key calls); `actor` is the display name (the key\'s current name, falling back to its id; the username for the browser), `actor_kind` is `agent` or `user` (null when there is no actor). Query: `limit` (default 200, max 2000), `q`. |\n\n## Pages\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/login` | None | The sign-in page. A signed-in browser is redirected to `/` unless the instance is locked or the query has `oauth` (the OAuth consent card). |\n| any | `/logout` | None | Ends the session, clears the cookie, and redirects to `/login`. A cross-site request only clears the cookie. |\n| GET | `/`, `/index.html` | Session | The web app shell. Without a session: `302` to `/login`. `503` when the UI assets are not installed. |\n| GET | App routes (see below) | Session | The same app shell as `/`. Without a session: `302` to `/login?r=<path>`, so sign-in returns to the page. |\n\nApp routes are the web app\'s client-side pages: `/brain`, `/nodes`, `/graph`,\n`/canvas`, `/tags`, `/activity`, `/agents`, `/access`, `/settings`,\n`/overview`, `/welcome`, the older names `/home`, `/vault`, `/logs`, `/keys`,\nand `/node/` or `/node/<percent-encoded vault path>`. The path is never used to\nread a file; a path holding NUL or another control character (raw or\npercent-encoded) is `400`. `/tools` is an app route for a signed-in browser and\nthe public tool catalog otherwise.\n\nHTML pages are sent with `Cache-Control: no-cache, no-store, must-revalidate`\nand a per-response CSP nonce.\n\nAny other `GET` that asks for HTML (`Accept: text/html`), is outside `/api/`,\n`/mcp`, `/oauth`, and `/.well-known`, and has no file extension in its last\nsegment gets the app shell (which shows its "page not found" view). Every other\nunmatched request is `404 {"error":"not found"}`.\n\n## Static assets\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/assets/{name}` | None | Static UI assets (whitelisted filenames only, else `404`). |\n| GET | `/app.js`, `/app.css`, `/login.css` | None | The UI bundle and styles. Revalidated on every load (`Cache-Control: no-cache`, ETag). |\n| GET | `/favicon.svg` | None | The icon. |\n| GET | `/favicon.ico` | None | `204` with no body. |\n| GET | `/manifest.webmanifest`, `/sw.js`, `/robots.txt`, `/offline.html`, `/icon-192.png`, `/icon-512.png`, `/icon-maskable-512.png`, `/apple-touch-icon.png` | None | PWA files and `robots.txt`. Images and the manifest are cached for 5 minutes; code is revalidated on every load. |\n\n## Vault\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/tree` | Session or key (`read`) | Notes grouped by folder. |\n| GET | `/api/note` | Session or key (`read`) | `{path, name, content, html, tags, frontmatter, backlinks, size, mtime}`. Query: `path` (`400` when empty). |\n| GET | `/api/vault/file` | Session or key (`read`) | The raw bytes of one image file in the vault (PNG, JPEG, GIF, WebP, AVIF, BMP, ICO; never SVG). Query: `path` (vault-relative). The file content must match its type. At most 10 MiB (`413`). Sent with an `ETag` (`304` on `If-None-Match`), `Cache-Control: private, max-age=300`, and a sandbox CSP. `400` invalid path, `403` path not allowed, `404` not found, `415` not an image. |\n| GET | `/api/folder-meta` | Session or key (`read`) | Folder metadata keyed by folder name. Query: `folder` (optional). |\n| POST | `/api/save` | Session or key (`write`, +CSRF) | `{ok, path}`. Body: `{path, content}`. Overwrites the note. |\n| POST | `/api/create` | Session or key (`write`, +CSRF) | `{ok, path}`. Body: `{title, folder?, content?}`. |\n| POST | `/api/rename` | Session or key (`write`, +CSRF) | `{ok, path}` with the new path. Body: `{path, name}`. |\n| POST | `/api/move` | Session or key (`write`, +CSRF) | `{ok, path}` with the new path. Body: `{path, folder?}`. |\n| POST | `/api/delete` | Session or key (`write`, +CSRF) | `{ok:true}`. Body: `{path}`. |\n| POST | `/api/folder` | Session or key (`write`, +CSRF) | `{ok, path}`. Body: `{name}`. |\n| POST | `/api/folder/rename` | Session or key (`write`, +CSRF) | `{ok, from, to, notes}`. Body: `{folder, name}`. |\n| POST | `/api/folder/move` | Session or key (`write`, +CSRF) | Moves a folder and everything in it. `{ok, from, to, notes}`. Body: `{folder, into}`; `into` empty or `Root` means the top level. |\n| POST | `/api/folder/move-contents` | Session or key (`write`, +CSRF) | Moves everything inside a folder into another one, then removes the emptied folder. Name clashes get a `-N` suffix. `{ok, from, to, moved}`. Body: `{folder, into}`; `into` empty or `Root` means the top level. |\n| POST | `/api/delete-folder` | Session or key (`write`, +CSRF) | Deletes a folder and moves its notes to the top level. `{ok, deleted_folder, moved_to_root}` where `moved_to_root` lists the new note paths. Body: `{folder}`. |\n| POST | `/api/folder-meta` | Session or key (`write`, +CSRF) | `{ok, folder}`. Body: `{folder, color?, icon?, desc?}`. |\n\nThe three folder operations also publish a `folder_changed` realtime event so\nopen browsers reload their tree.\n\n## Search and graph\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/search` | Session or key (`read`) | `{q, count, hits:[{path, name, folder, score, snippet}]}`, at most 20 hits. Query: `q`. Supports `tag:x` and `#x`. |\n| GET | `/api/stats` | Session or key (`read`) | `{notes, links, folders}`. |\n| GET | `/api/graph` | Session or key (`read`) | `{nodes:[{id, path, folder, color, degree, tags}], links:[{source, target}]}`. `tags` holds inline `#tags` plus frontmatter `tags` (as the note view reports them). Realtime `node_*` events\' `node` payload carries `tags` too. |\n| GET | `/api/aliases` | Session or key (`read`) | `{aliases:[{alias, key_id, key_name, first_seen, last_seen, connections, actor, actor_kind}]}`: one record per API key that sent MCP `initialize`, kept in memory until the server restarts. `key_name` and `actor` are the key\'s current name (fallback: the id). |\n| GET | `/api/actors` | Session or key (`read`) | `{actors:[{actor, alias, display, events, tools, last_ip, last_ts, seen_minutes_ago}], count}`. `seen_minutes_ago` is `-1` when the actor has no events. |\n\n## Privacy\n\nPrivacy rules hide notes or folders from chosen agents (API keys). A rule has a\n`kind` (`node` or `folder`), a `path`, a `mode` (`deny`: hidden from the listed\nkeys; `allow_only`: hidden from every key except the listed ones), and a list\nof keys. Folder rules apply to everything inside the folder.\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/privacy` | Session or key (`admin`) | `{count, rules:[{id, kind, path, mode, keys:[{id, name, color}], created_at, updated_at}], agents:[{id, name, color, enabled}]}`. |\n| GET | `/api/privacy/path` | Session or key (`admin`) | The privacy state of one path: `{path, kind, own, own_rules, inherited, agents:[{id, name, color, enabled, can_see, hidden_by}], private}`. `own` is `{mode, keys}` or `null`. Query: `path`, `kind` (optional; defaults to `folder` when the path is a folder on disk, else `node`). |\n| PUT | `/api/privacy/path` | Session or key (`admin`, +CSRF) | Replaces the rule on a path. Body: `{path, kind?, mode, keys}`. `mode` defaults to `deny`; `keys` is a list of key ids (or unique key names). `deny` with no keys removes the rule. Returns the same shape as `GET`. |\n| DELETE | `/api/privacy/path` | Session or key (`admin`, +CSRF) | Removes the rule on a path. Query: `path`, `kind` (optional). Returns the same shape as `GET`. |\n\nChanges are written to the activity log and publish a `privacy_changed`\nrealtime event.\n\n## API keys, tools, and access\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/keys` | Session or key (`admin`) | `{count, keys:[{id, name, enabled, scopes, tools, prefix, created, color, revealable, uses, last_ip, used_tools}]}`. `tools` is `"*"` or a list of tool names; `revealable` says whether the secret can be shown again; `used_tools` lists recently used tools and routes. |\n| POST | `/api/keys` | Session or key (`admin`, +CSRF) | Creates a key. Body: `{name?, tools?, scopes?, color?}`. `tools` is `"*"` or a list of tool names; `scopes` a list of scope names (an empty list means the defaults). Returns `{ok, id, key, name, prefix, persisted, color, tools, scopes}`. The raw `key` is returned once. `400` for an unknown tool or scope. |\n| POST | `/api/keys/roll` | Session or key (`admin`, +CSRF) | New secret for an existing id. Body: `{id}`. Returns `{ok, id, key, prefix, persisted}`. `404` for an unknown id. |\n| POST | `/api/keys/reveal` | Session only (+CSRF) | Shows the secret of a key created or rolled from the dashboard again. Body: `{id, current}` where `current` is the owner\'s password. Returns `{ok, id, key}`. `403` for a wrong password; `429` after 5 wrong passwords (5 minute pause); `404 {error:"not_stored", message}` when the secret is not stored (for example keys created by the CLI or by OAuth). |\n| POST | `/api/keys/update` | Session or key (`admin`, +CSRF) | Body: `{id, name?, enabled?, tools?, scopes?, color?}`. `color` as `""` or `null` clears it. Returns `{ok, id, name, enabled, color, tools, scopes, persisted}`. `400` for an unknown tool or scope, `404` for an unknown id. |\n| POST | `/api/keys/delete` | Session or key (`admin`, +CSRF) | `{ok, id, persisted}`. Moves the key to the trash. Body: `{id}`. |\n| POST | `/api/keys/restore` | Session or key (`admin`, +CSRF) | `{ok, id, persisted}`. Restores a deleted key. Body: `{id}`. `404` when no deleted key has that id. |\n| GET | `/api/tools` | Session or key (`admin`) | `{tools:[{name, category, description, enabled}]}`: the MCP tool catalog with the global on/off switch of each tool. |\n| POST | `/api/tools` | Session or key (`admin`, +CSRF) | Switches a tool on or off for every caller. Body: `{name, enabled}`. Returns `{ok, name, enabled}`. `400` for an unknown tool. |\n| GET | `/api/access` | Session or key (`admin`) | `{default_allow, rules, count}`. |\n| POST | `/api/access/test` | Session or key (`admin`) | `{action, would_lock_out_caller}` for the given address or domain. Body: `{ip?, domain?}`. |\n| POST | `/api/access/rules` | Session or key (`admin`, +CSRF) | `{ok, count, persisted}`. Body: `{op, kind, value, action}`. `op` is `add` (default) or `remove`. `kind` is `ip`, `range`, `cidr`, `domain`, or `all`; `value` is required unless `kind` is `all`. `action` is `allow` or `block` (default `block`). `remove` deletes every rule matching the given `kind` and `value`; `404` when none match. |\n| GET | `/api/config` | Session or key (`read`) | `{realm, min_password_len, session_ttl, vault, version, gateway, update}`. `update` is the cached release check: `{current, latest, available, url, checked_at, state}`, `state` one of `ok`, `none` (no release published), `error`, `disabled`, `pending`. |\n\n## Settings\n\nAll settings endpoints need a signed-in browser.\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/settings` | Session only | `{user, vault_configured, vault, vault_suggested, vault_writable, stats, min_password_len, expires_in, session_ttl, session_max_age, state_dir}`. `stats` is `{notes, links, folders}` or `null` without a vault. |\n| POST | `/api/settings/password` | Session only (+CSRF) | Body: `{current, password, confirm}`. Returns `{ok, user, password_changed, revoked_sessions, persisted}`. Every other session is signed out. `400` for a short, mismatched, or unchanged password; `403` for a wrong current password (counts toward the login cooldown). |\n| POST | `/api/settings/username` | Session only (+CSRF) | Renames the account. Body: `{username, current}`. Returns `{ok, user, changed}` (plus `persisted` when changed). The username is stored lowercase. Sessions stay signed in. `400` for an invalid username, `403` for a wrong password. |\n| POST | `/api/settings/vault` | Session only (+CSRF) | Sets the vault folder and switches the running server to it. Body: `{path, create?}`. `path` must be absolute, without `..`, writable, not a system folder, and not overlap the state folder; with `create` a missing folder is created (its parent must exist). Returns `{ok, vault, created, stats}`. `400` with a message when the folder is refused. |\n| GET | `/api/settings/sessions` | Session only | `{sessions:[{id, current, source, alias, ip, user_agent, created_at, last_seen, expires_in}], count}`: live browser sessions. API keys are not sessions and never appear here. |\n| POST | `/api/settings/sessions/revoke` | Session only (+CSRF) | Signs other browsers out. Body: `{id}` or `{others:true}`. Returns `{ok, revoked}`. `400` for the current session (use logout), `404` when the session has already ended. |\n| POST | `/api/settings/sessions/rename` | Session only (+CSRF) | Names a device. Body: `{id, alias}`; an empty alias clears it. Returns `{ok, alias}`. |\n| GET | `/api/settings/sessions/activity` | Session only | `{events, count, ip, since}`: activity log entries from that session\'s IP address since it signed in, API-key entries left out, newest first, at most 200. Query: `id`. |\n\nSession `id` values are the short ids returned by `GET /api/settings/sessions`\n(a unique prefix also works). An ambiguous or malformed id is `400`.\n\n## OAuth\n\nMemora is an OAuth 2.1 authorization server for remote MCP clients. Only the\nauthorization code flow with PKCE (`S256`) is supported. The access token is a\nnew API key named after the client, with the default scopes (`mcp`, `read`,\n`write`) and every tool; it appears on the Agents page like any other key and\nis revoked by deleting or disabling that key. URLs in the metadata use\n`MEMORA_BASE_URL` when it is set, else the scheme and host of the request.\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/.well-known/oauth-protected-resource`, `/.well-known/oauth-protected-resource/mcp` | None | Protected resource metadata (RFC 9728): `{resource, authorization_servers, bearer_methods_supported, scopes_supported, resource_name}`. |\n| GET | `/.well-known/oauth-authorization-server`, `/.well-known/oauth-authorization-server/mcp`, `/.well-known/openid-configuration` | None | Authorization server metadata (RFC 8414): `issuer`, the authorization, token, and registration endpoints, supported response types (`code`), grant types (`authorization_code`, `refresh_token`), PKCE methods (`S256`), token endpoint auth methods, `scopes_supported` (`mcp`), and `client_id_metadata_document_supported: true`. |\n| POST | `/oauth/register` | None | Dynamic client registration (RFC 7591). Body: `{redirect_uris, client_name?}`. `redirect_uris` holds 1 to 10 URIs, each HTTPS or plain HTTP on `localhost`, `127.0.0.1`, or `[::1]`, without a fragment. Returns `201 {client_id, client_name, redirect_uris, client_id_issued_at, token_endpoint_auth_method, grant_types, response_types}`. `400 {error, error_description}` for invalid metadata. |\n| GET | `/oauth/authorize` | None | `302` to `/login?oauth=1&<query>`, where the sign-in page shows a consent card (after sign-in when needed). |\n| POST | `/oauth/token` | None | Form-encoded or JSON body. `grant_type=authorization_code` with `code`, `code_verifier`, `client_id` (or HTTP Basic), and optional `redirect_uri`; or `grant_type=refresh_token` with `refresh_token` and optional `client_id`. Returns `{access_token, token_type:"Bearer", refresh_token, scope:"mcp"}`. Codes are single use and expire after 10 minutes. A refresh gives the same key a new secret and a new refresh token. Errors are `400 {error, error_description}` (`invalid_request`, `invalid_grant`, `unsupported_grant_type`). |\n| GET | `/api/oauth/request` | None | What the consent card shows for an authorization request. Query: the `/oauth/authorize` query. Returns `{ok:true, client:{id, name, kind}, redirect_host, signed_in, user}` or `{ok:false, error, error_description, redirect}`. |\n| POST | `/api/oauth/approve` | Session only (+CSRF) | Body: `{query, allow}` where `query` is the authorization request query. Returns `{ok:true, redirect}`: the client\'s redirect URI with a `code` when `allow` is `true`, else with `error=access_denied`. An invalid request returns `{ok:false, error, error_description, redirect}`. `401` without a session. |\n| GET | `/api/oauth/clients` | Session or key (`admin`) | `{clients:[{client_id, name, redirect_uris, kind, created_at, fetched_at}], connections:[{key_id, client_id}]}`. `kind` is `dcr` (registered), `cimd` (metadata document), or `manual` (added by the owner). |\n| POST | `/api/oauth/clients` | Session or key (`admin`, +CSRF) | Registers a client by hand. Body: `{name?, redirect_uris}`. Returns `{ok, client}`. `400` for invalid redirect URIs. |\n| POST | `/api/oauth/clients/delete` | Session or key (`admin`, +CSRF) | Forgets a client and its refresh tokens. Body: `{client_id}`. Returns `{ok, deleted}`. Keys issued to the client stay until they are deleted. |\n\nA `client_id` may also be an HTTPS URL of a client metadata document. The\nserver fetches it (public addresses only, no redirects, at most 64 KiB), checks\nthat its `client_id` matches the URL, and caches it for 24 hours.\n\n## Logs and activity\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/logs` | Session or key (`read`) | `{range, count, events}`, newest first, each event with a local `time`. Query: `range` (for example `1d`, `7d`, `today`, `yesterday`, `all`; default `1d`), `days` (used when `range` is absent, at most 7), `since` and `until` (unix seconds; override `range`), `limit` (default 400, max 2000), `actor`, `q`. |\n| GET | `/api/logs/settings` | Session or key (`admin`) | `{max_mb, max_days, stats:{bytes, lines, oldest, newest, max_bytes, max_days}}` for the vault event log. |\n| POST | `/api/logs/settings` | Session or key (`admin`, +CSRF) | Body: `{max_mb?, max_days?}` (1 to 512 MB; 0 to 3650 days, 0 meaning no age limit). Returns the same shape as `GET`. The log is trimmed to the new limits at once. `400` for out-of-range values. |\n| GET | `/api/events` | Session or key (`read`) | `{events, count}`: the vault event log (`.events.jsonl`), oldest first, the newest `limit` entries. Query: `since` (unix seconds), `folder`, `actor` (the key name for agents), `limit` (default 100, max 2000). |\n\n### Realtime\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/ws` | Session only | WebSocket upgrade. The `Origin` must be same-origin (`403` otherwise). `503` when too many clients are connected. |\n| POST | `/_bus` | Loopback only | Publishes a JSON object (at most 64 KiB) into the event stream. Returns `{ok:true}`. `403` for callers that are not on the same machine or that come through a proxy (any forwarding header), `400` for a body that is not a JSON object, `413` for a body or event that is too large. |\n\nOn connect the server sends a `hello` event with the client count, replays the\nlast 40 stored events (each marked `replay: true`), then streams live events.\nWhen a client leaves, the others get a `presence` event with the new count.\nMessages from the client are ignored; the server pings every 30 seconds and\ncloses a connection that has been silent for 75 seconds.\n\n### `ai_activity` events\n\nEvery MCP `tools/call` publishes a `start` and an `end` event sharing `call_id`:\n\n```json\n{"type":"ai_activity","phase":"start","call_id":"c1a2b3c4d5e6-0","actor":"research-bot",\n "actor_kind":"agent","actor_id":"k_1a2b3c4d","action":"read_memory","label":"Plan/Index.md",\n "paths":["Plan/Index.md"],"_ts":1760600000.12}\n{"type":"ai_activity","phase":"end","call_id":"c1a2b3c4d5e6-0","actor":"research-bot",\n "actor_kind":"agent","actor_id":"k_1a2b3c4d","action":"read_memory","label":"Plan/Index.md",\n "paths":["Plan/Index.md"],"ok":true,"ms":2,"_ts":1760600000.12}\n```\n\n- `actor`: the API key\'s name (fallback: key id) with `actor_kind: "agent"`; for a\n browser session the username with `actor_kind: "user"`. `actor_id` is the key id (or\n the username). Node events (`node_created`, ...) from the call carry the same `actor`.\n- `action`: the tool name.\n- `paths`: vault-relative note paths from the arguments (`path`, `paths`, `from`, `to`,\n `old_path`, `new_path`, `into` of `merge_memory`, `source`/`target` of `find_path`)\n plus note paths found in the result (search hits, the created or moved note), at\n most 20, each at most 512 bytes (longer paths are dropped). Whole-vault overviews\n (`get_graph`, `list_memory`, logs, ...) add no result paths.\n- Read-only tools publish `start` after running (so it carries the result paths),\n immediately followed by `end`; mutating tools publish `start` before running and `end`\n after, with the result paths added.\n- `end` adds `ok`, `ms`, and on failure `error` (at most 200 characters). `label` is at\n most 160 characters. `_ts` is the publish time in unix seconds. `end` events are\n realtime only: they are not written to `.events.jsonl` or the replay buffer.\n\n## UI layout\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/ui/layout/{name}` | Session only | `{name, data, updated_at}`; `data` and `updated_at` are `null` if never saved. |\n| PUT | `/api/ui/layout/{name}` | Session only (+CSRF) | `{ok:true, updated_at}`. Body: `{data: <any JSON>}`. |\n\n`name` is `[a-z0-9_-]{1,40}` (else `400`). API keys get `403`. `data` is stored as\nserialized JSON of at most 512 KiB (`413` above); the request body limit is 600 KiB.\nLayouts are stored in the `ui_layout` table of `memora.db`. The web UI uses them for\n`canvas` (card positions and frames) and `graph` (pinned positions).\n\n## Pins\n\nThe owner\'s pinned notes and folders (the sidebar\'s Pinned list), shared by every\nbrowser and device of the instance.\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/pins` | Session only | `{count, pins:[{kind, path, position, missing}]}` in display order. |\n| PUT | `/api/pins` | Session only (+CSRF) | Same as GET. Body: `{pins:[{kind, path}]}`, the whole ordered list (reorder, remove). |\n| POST | `/api/pins/pin` | Session only (+CSRF) | Same as GET. Body: `{kind, path, position?}`. Pins an existing note or folder at `position` (default: the end), or moves its pin there; `404` if it does not exist. |\n| POST | `/api/pins/unpin` | Session only (+CSRF) | Same as GET plus `removed`. Body: `{kind, path}`. |\n\n`kind` is `note` or `folder`. `path` is vault-relative as the tree shows it (notes end in\n`.md`): absolute paths, `..`, empty or hidden segments, `\\`, control characters and paths\nover 1024 characters get `400`, as do more than 200 pins. API keys get `403` (agents use\nthe MCP tools `list_pins`, `pin` and `unpin`). Bodies are limited to 256 KiB for `PUT`\nand 8 KiB for `pin`/`unpin` (`413`). `missing` is true when the path no longer exists,\nfor example after a rename outside Memora; such a pin is kept until it is removed.\n\nRenames, moves and deletes done by Memora (HTTP or MCP) rewrite or drop pins in the same\ndatabase transaction, including pins on notes and folders inside a moved folder;\nmoving an item to the trash or deleting it removes its pin, and deleting a folder\nremoves every pin under it. Every change publishes a `pins_changed` realtime event with\nno other data; open browsers reload the list. Pins are stored in the `pin` table of\n`memora.db`.\n\n## Status codes\n\n| Code | Meaning |\n|---|---|\n| 200 | Success. |\n| 201 | OAuth client registered. |\n| 202 | MCP notification accepted. |\n| 204 | `/favicon.ico`. |\n| 302 | Redirect (pages to `/login` without a session, `/login` to `/` when signed in, logout to `/login`, locked instance to `/login?locked=1`, `/oauth/authorize` to the consent page). |\n| 304 | Not modified (`/api/vault/file`, static assets). |\n| 400 | Bad request, for example a missing required field or an invalid value. |\n| 401 | Missing or invalid credentials, or a session-only endpoint called without a session. |\n| 403 | Blocked by an access rule, a CSRF origin mismatch, a missing key scope, a wrong password or setup code, or an endpoint that needs an open setup or reset window. |\n| 404 | Note, key, session, rule, or route not found; also any request for a host outside the domain list. |\n| 405 | `/mcp` called with a method other than `POST`. |\n| 408 | The request took longer than 30 seconds. |\n| 409 | No vault configured (`needs_vault: true`), or a state conflict. |\n| 413 | Body, layout, image, or event too large. |\n| 415 | `/api/vault/file` path is not an image. |\n| 423 | Instance is LOCKED. |\n| 429 | Rate limit or failed-attempt cooldown (`Retry-After` header). |\n| 500 | Internal error, for example the state database failed. |\n| 503 | UI assets are not installed, the password hashing pool is busy, or too many realtime clients. |\n',iD=`# Deployment
9739
+ `,QN="# Installing Memora\n\nMemora ships as two binaries plus a folder of web UI assets:\n\n| Piece | Role |\n|---|---|\n| `memora` | The server: HTTP API, MCP, web UI, and WebSocket on **one TCP port** (default `8400`) |\n| `memora-cli` | The operator console. Run it with no arguments for slash commands (`/guide`, `/web`, `/config`, ...) |\n| `assets/` | Web UI files, found through `MEMORA_ASSETS` |\n\nIt runs on Linux (x86_64, aarch64) and Windows 10/11 (x64). Install it with\n**npm** (Linux and Windows, runs as you), **Docker**, the **native** installer\n(a systemd service on Linux), the **Windows zip** or from source. All end the\nsame way: run `memora-cli setup`, open the link it prints and enter the code.\n\n**Fastest path** (pick one, in this order of ease), then open the link the\nsetup command prints and enter the code:\n\n```bash\n# npm (Linux x86_64 / arm64, Windows x64; Node 18+)\nnpm install -g @codrihub/memora && memora\nmemora-cli setup --minutes 15 # in a second terminal\n\n# Docker: no clone or folder permissions needed (named volumes)\ndocker run -d --name memora --restart unless-stopped -p 8400:8400 \\\n -v memora-data:/data -v memora-state:/state ghcr.io/codrihub/memora:latest\ndocker exec -it memora memora-cli setup --minutes 15\n\n# Native installer (Linux server with systemd)\ncurl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh | sudo sh\nsudo memora-cli setup --minutes 15\n```\n\n- [Network exposure](#network-exposure)\n- [Native install](#native-install)\n- [Docker](#docker)\n- [npm](#npm)\n- [Windows zip](#windows-zip)\n- [Start, stop and restart](#start-stop-and-restart)\n- [Uninstall with memora-cli](#uninstall-with-memora-cli)\n- [Reverse proxy](#reverse-proxy)\n- [Backups](#backups)\n- [Automation: `--check` and `--upgrade`](#automation---check-and---upgrade)\n\n## Network exposure\n\nMemora opens exactly **one TCP port**. The HTTP API, MCP (`/mcp`), the web UI,\nand the realtime WebSocket (`/ws`) all share it. The local event intake\n`/_bus` answers on the same port but only to loopback clients.\n\nThe state database is embedded SQLite (`<state>/memora.db`). The server creates\nand migrates it on first start; it opens no port and needs no separate\ndatabase server or install.\n\nNothing else listens. Allow only that one port through the firewall, or none at\nall when a reverse proxy on the same host is the entry point\n(`--behind-proxy`).\n\n## Native install\n\nRequirements: Linux on x86_64 or aarch64 with systemd, `curl` (or `wget`),\n`tar`, `sha256sum`, and `git` (vault history uses it).\n\n```sh\n# Inspect first: https://github.com/Codrihub/memora/blob/main/scripts/install.sh\ncurl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh | sudo sh\n```\n\nPass flags after `sh -s --`, for example:\n\n```sh\ncurl -fsSL https://raw.githubusercontent.com/Codrihub/memora/main/scripts/install.sh \\\n | sudo sh -s -- --version 1.0.0 --behind-proxy\n```\n\nor download the script and run it: `sudo sh install.sh --help`.\n\nThe script is idempotent: running it again reinstalls the same files and keeps\nthe port and bind address of the existing unit unless you pass new ones.\n\n### What it does\n\n1. Downloads `memora-<version>-<arch>-linux.tar.gz` for this CPU from GitHub\n Releases (the latest, or `--version`), downloads `SHA256SUMS` from the same\n release, and refuses to continue if the checksum does not match.\n2. Installs the binaries atomically (copy to a temp file, then `mv`).\n3. Creates the system user and group `memora` (no login shell, home\n `/var/lib/memora`).\n4. Creates `/var/lib/memora/state` (`0700`) and `/var/lib/memora/vault`\n (`0750`), owned by `memora`.\n5. Writes `/etc/systemd/system/memora.service`, enables and starts it, waits\n for `/healthz`, then verifies the state database with `memora-cli db check`.\n6. Prints the next step and, when listening on every interface, a firewall\n hint.\n\n### Paths\n\n| Path | Content |\n|---|---|\n| `/usr/local/bin/memora`, `/usr/local/bin/memora-cli` | Binaries |\n| `/usr/local/share/memora/assets/` | Web UI |\n| `/usr/local/share/memora/VERSION` | Installed version (read by `--check`) |\n| `/usr/local/share/memora/install.sh` | Copy of the installer, used for `--upgrade`, `--check`, `--uninstall`, and `memora-cli update` |\n| `/var/lib/memora/state/` | `memora.db` (owner, API key hashes, sessions, settings, activity log), `backups/` |\n| `/var/lib/memora/vault/` | Suggested vault folder (chosen in the browser after the first sign-in) |\n| `/etc/systemd/system/memora.service` | The unit |\n\n`--prefix` moves the first four (default `/usr/local`), `--data-dir` moves the\nlast two (default `/var/lib/memora`).\n\n### Flags\n\n| Flag | Meaning |\n|---|---|\n| *(none)* | Install or reinstall the latest release |\n| `--version X.Y.Z` | Install that release |\n| `--from-source` | Build with `cargo build --release --locked` in the checkout the script lives in (`sudo ./scripts/install.sh --from-source`); built as `$SUDO_USER` |\n| `--from-dir PATH` | Install `PATH/memora`, `PATH/memora-cli`, `PATH/assets/` (an unpacked release, or your own build). Version from `--version`, else `PATH/VERSION` |\n| `--port N` | Port (default `8400`) |\n| `--bind ADDR` | Bind address (default `0.0.0.0`) |\n| `--behind-proxy` | Bind `127.0.0.1`; a reverse proxy on this host is the only entry |\n| `--prefix DIR` | Install prefix (default `/usr/local`) |\n| `--data-dir DIR` | Data root (default `/var/lib/memora`) |\n| `--no-start` | Install and enable, but do not start |\n| `--no-systemd` | Skip the unit and the system user (containers, tests); prints the command to start the server by hand |\n| `--upgrade` | Replace binaries and assets, keep state, restart the service if it was running |\n| `--force` | With `--upgrade`: reinstall even when already up to date |\n| `--uninstall` | Stop and remove the unit, binaries, and assets; keep data |\n| `--purge` | With `--uninstall`: also delete the data dir and the `memora` user (asks first) |\n| `--check` | Print `MEMORA_LATEST=` and `MEMORA_INSTALLED=`; change nothing |\n| `--yes`, `-y` | Never ask (needed for `--purge` without a terminal) |\n| `--dry-run` | Print every action, change nothing |\n| `--repo OWNER/NAME` | Download from another GitHub repository (forks); also settable as `MEMORA_REPO` |\n\n`MEMORA_RELEASES_URL` points the installer at a mirror that serves the same\nlayout as GitHub (`<url>/latest`, `<url>/download/vX.Y.Z/<file>`).\n\nRoot is required except for `--check`, `--dry-run`, and `--no-systemd` into a\nprefix you can write to.\n\n### Exit codes\n\n| Code | Meaning |\n|---|---|\n| `0` | Success |\n| `1` | Error (see the message) |\n| `2` | Bad usage |\n| `3` | Already up to date (`--upgrade`) |\n| `4` | Network or download failure |\n| `5` | Checksum mismatch or missing from `SHA256SUMS` |\n| `6` | Not running as root |\n| `7` | Unsupported OS or CPU |\n\n### The systemd unit\n\nThe installer writes this unit (shown with the default paths and port):\n\n```ini\n[Unit]\nDescription=Memora - long-term memory for AI agents (HTTP API + MCP + web UI)\nDocumentation=https://github.com/Codrihub/memora\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=simple\nUser=memora\nGroup=memora\nWorkingDirectory=/var/lib/memora\nEnvironment=HOME=/var/lib/memora\nEnvironment=MEMORA_STATE=/var/lib/memora/state\nEnvironment=MEMORA_ASSETS=/usr/local/share/memora/assets\nEnvironment=MEMORA_PORT=8400\nEnvironment=MEMORA_BIND=0.0.0.0\nEnvironment=MEMORA_VAULT=/var/lib/memora/vault\nEnvironment=GIT_AUTHOR_NAME=Memora\nEnvironment=GIT_AUTHOR_EMAIL=memora@localhost\nEnvironment=GIT_COMMITTER_NAME=Memora\nEnvironment=GIT_COMMITTER_EMAIL=memora@localhost\nEnvironment=RUST_LOG=info\nExecStart=/usr/local/bin/memora\nRestart=on-failure\nRestartSec=3\nTimeoutStopSec=15\nLimitNOFILE=65536\nUMask=0027\n\n# Hardening\nNoNewPrivileges=yes\nAmbientCapabilities=\nCapabilityBoundingSet=\nProtectSystem=strict\nReadWritePaths=/var/lib/memora\nProtectHome=yes\nPrivateTmp=yes\nPrivateDevices=yes\nProtectKernelTunables=yes\nProtectKernelModules=yes\nProtectKernelLogs=yes\nProtectControlGroups=yes\nProtectClock=yes\nProtectHostname=yes\nRestrictAddressFamilies=AF_UNIX AF_INET AF_INET6\nRestrictNamespaces=yes\nRestrictRealtime=yes\nRestrictSUIDSGID=yes\nLockPersonality=yes\nMemoryDenyWriteExecute=yes\nSystemCallArchitectures=native\nSystemCallFilter=@system-service\nSystemCallFilter=~@privileged\n\n[Install]\nWantedBy=multi-user.target\n```\n\nA port below 1024 adds `CAP_NET_BIND_SERVICE` instead of the empty capability\nset. There are no IP restrictions (`IPAddressDeny=`) by default; use the\nfirewall, `MEMORA_DOMAIN`, or the access rules in the UI.\n\nThe installer rewrites the unit on every run. Put local changes in a drop-in:\n\n```sh\nsudo systemctl edit memora # for example, a vault outside /var/lib/memora:\n# [Service]\n# ReadWritePaths=/srv/notes\nsudo systemctl restart memora\n```\n\nBecause of `ProtectSystem=strict` and `ProtectHome=yes`, the server can only\nwrite under `/var/lib/memora`. A vault anywhere else (including `/home`) needs\nthe drop-in above (and `ProtectHome=read-only` or `no` for `/home`).\n\n### Settings\n\nThe unit sets the basics (`MEMORA_STATE`, `MEMORA_ASSETS`, `MEMORA_PORT`,\n`MEMORA_BIND`, `MEMORA_VAULT`, `RUST_LOG`) as `Environment=` lines. Everything\nelse (`MEMORA_BASE_URL`, `MEMORA_DOMAIN`, `MEMORA_TRUSTED_PROXIES`, ...) is\nstored in the state database (table `server_config`). Edit it with the\nconsole: `sudo memora-cli` → `/config`, then `/restart`.\n\nA value stored with `/config` wins over the unit's `Environment=` lines; a key\nwith no stored value uses the environment. If you stored `MEMORA_PORT` with\n`/config` and later reinstall with `--port`, change or clear it in `/config`\ntoo, otherwise the stored value keeps applying. The provisioning owner\npassword and API key are environment-only and never stored (see\n[CONFIGURATION.md](CONFIGURATION.md)).\n\nSee [CONFIGURATION.md](CONFIGURATION.md) for every variable.\n\n### First run\n\n```sh\nsudo memora-cli # opens the console; it finds the running server itself\n/guide # step-by-step, or:\n/web # prints a one-time code\n```\n\nOpen `http://<host>:8400/login`, enter the code, create the owner account, then\nchoose the vault folder (`/var/lib/memora/vault` is suggested).\n\n### Day to day\n\n```sh\nsudo systemctl status memora\nsudo systemctl restart memora\nsudo journalctl -u memora -f\nsudo memora-cli # /status, /keys, /config, /restart, /mcp ...\n```\n\n### Upgrading\n\n```sh\nsudo /usr/local/share/memora/install.sh --upgrade # latest release\nsudo /usr/local/share/memora/install.sh --upgrade --version 1.0.1\nsudo memora-cli update # same, from the console\n```\n\nBinaries and assets are swapped atomically, the state directory and vault are\nuntouched, and the service is restarted if it was running. The server migrates\n`memora.db` itself on start. Take a `memora-cli db backup` before upgrading,\nand read the [CHANGELOG](../CHANGELOG.md) before a major version bump.\n\n### Uninstall\n\n```sh\nsudo /usr/local/share/memora/install.sh --uninstall # keeps /var/lib/memora and the memora user\nsudo /usr/local/share/memora/install.sh --uninstall --purge # also deletes notes, account, keys, and the user\n```\n\nOr run `memora-cli uninstall`, which asks what to keep (see\n[Uninstall with memora-cli](#uninstall-with-memora-cli)).\n\n### Firewall\n\nOpen only the Memora port, and only when clients connect directly:\n\n```sh\nsudo ufw allow 8400/tcp\n# or\nsudo firewall-cmd --permanent --add-port=8400/tcp && sudo firewall-cmd --reload\n```\n\nBehind a reverse proxy on the same host, install with `--behind-proxy` and open\nonly the proxy's 80/443.\n\n## Docker\n\n```sh\ngit clone https://github.com/Codrihub/memora.git && cd memora\nmkdir -p data state && sudo chown -R 1000:1000 data state\ndocker compose up -d\ndocker compose exec -it gateway memora-cli # then /guide, or /web\n```\n\n`docker compose up` pulls `ghcr.io/codrihub/memora:<version>`; if the image is\nnot available (or you set `IMAGE=memora:local`) it builds from the\n`Dockerfile`. Image tags: `<version>` (for example `1.0.0`), `<major>.<minor>`\n(for example `1.0`), and `latest` (stable releases only), for `linux/amd64`\nand `linux/arm64`. The compose file pins the release it ships with; set\n`IMAGE` in `.env` to run another tag.\n\n### Volumes: `/data` and `/state`\n\nBoth must be persistent (the Compose file bind-mounts `./data` and `./state`):\n\n- `/data` is the vault: your notes, their git history, the search index, and\n the event log. Lose it and the notes are gone.\n- `/state` holds `memora.db` (owner account, password hash, API key hashes,\n sessions, settings, setup/lock state, activity log). Lose it and\n every agent key stops working, the instance falls back to first-run setup,\n and anyone who reaches the port during that window could claim it.\n\nThe container runs as uid 1000; set `MEMORA_UID`/`MEMORA_GID` in `.env` if the\nhost directories belong to another user. `MEMORA_DATA_DIR` and\n`MEMORA_STATE_DIR` move the host directories, and `MEMORA_HTTP_PORT` changes\nthe published host port. See [CONFIGURATION.md](CONFIGURATION.md#docker-compose-env).\n\n### Verify\n\n```sh\ncurl -s http://127.0.0.1:8400/healthz\ndocker compose exec gateway memora-cli db check\ndocker compose exec gateway memora-cli status\nls -l state/memora.db\n```\n\n### Upgrading\n\n```sh\ngit pull\ndocker compose pull && docker compose up -d # or: docker compose up -d --build\n```\n\nSettings: `docker compose exec -it gateway memora-cli` → `/config`, then\n`docker compose restart gateway` (`/restart` cannot restart a container from\ninside).\n\n## npm\n\nRequirements: Linux on x86_64 or arm64, or Windows 10/11 on x64; Node 18 or\nnewer; and `git` (vault history uses it).\n\n```sh\nnpm install -g @codrihub/memora\nmkdir -p ~/memora && cd ~/memora\nMEMORA_VAULT=./vault MEMORA_STATE=./state memora\n# in a second terminal, same folder:\nMEMORA_STATE=./state memora-cli # then /guide, or /web\n```\n\nOn Windows, in PowerShell:\n\n```powershell\nnpm install -g @codrihub/memora\nmkdir ~\\memora; cd ~\\memora\n$env:MEMORA_VAULT = '.\\vault'; $env:MEMORA_STATE = '.\\state'; memora\n# in a second terminal, same folder:\n$env:MEMORA_STATE = '.\\state'; memora-cli # then /guide, or /web\n```\n\n`npx @codrihub/memora --version` runs it without a global install.\n\n`@codrihub/memora` holds the `memora` and `memora-cli` commands and the web UI\n(used unless `MEMORA_ASSETS` is set). The binaries come from\n`@codrihub/memora-linux-x64`, `@codrihub/memora-linux-arm64` or\n`@codrihub/memora-win32-x64`, optional dependencies npm installs only on a\nmatching machine. The Linux ones are the static binaries of the GitHub\nrelease with the same version, so glibc and musl distributions both work; the\nWindows one is built with a static C runtime and needs nothing else. There is\nno install script and nothing is downloaded at install time, so it works with\n`--ignore-scripts` and from a registry mirror; it does not work with\n`--omit=optional`, which leaves the binaries out. On macOS the commands print\nwhere to go instead: use [Docker](#docker) or build from source.\n\nThe npm install sets up no service, user or data folder: the server runs as\nyou, with `MEMORA_STATE` and `MEMORA_VAULT` where you point them (`./state`\nby default). Keep the state folder private (`chmod 700 state`; on Windows,\nkeep it under your user profile), since it holds the owner account and key\nhashes. On Windows, `memora-cli` runs every command as you: there is no root\nor service account to switch to. For a long-running server, prefer the\n[native install](#native-install).\n\nUpgrade with `npm install -g @codrihub/memora@latest` (`memora-cli update`\nprints this too) and restart the server; the state database is migrated on\nstart.\n\n## Windows zip\n\nEach GitHub release also carries `memora-<version>-x86_64-windows.zip`:\n`memora.exe`, `memora-cli.exe`, the web UI (`assets\\`), `LICENSE` and this\nREADME. It needs no installer, Node or runtime (static C runtime), and\n`memora.exe` finds the `assets` folder next to it. Check the download against\nthe release `SHA256SUMS` (`Get-FileHash memora-*.zip`), unzip it, then in\nPowerShell:\n\n```powershell\ncd memora-<version>-x86_64-windows\n$env:MEMORA_VAULT = '.\\vault'; $env:MEMORA_STATE = '.\\state'; .\\memora.exe\n# in a second window, same folder:\n$env:MEMORA_STATE = '.\\state'; .\\memora-cli.exe setup --minutes 15\n```\n\nOpen `http://localhost:8400/login` and enter the code. Like the npm install,\nit runs as you with no service; keep the folder under your user profile.\n\n## Start, stop and restart\n\n`memora-cli start`, `stop` and `restart` (or `/start`, `/shutdown` and\n`/restart` in the console) work out how this install runs and do the right\nthing:\n\n| Install | What `memora-cli start / stop / restart` does | By hand |\n|---|---|---|\n| Native (systemd) | runs `systemctl start / stop / restart memora` (as root) | `sudo systemctl start memora` |\n| npm, Windows zip, source | runs the server in the background, with `memora.pid` and `memora.log` in the state folder; `stop` asks it to end and waits, `stop --force` kills it | run `memora` and keep it open; Ctrl+C stops it |\n| Docker | prints the host commands (a container cannot stop itself) | `docker start / stop / restart memora` |\n\nFrom the browser, the owner can shut the server down in Settings, Server, Shut\ndown: the server answers, then stops gracefully and exits with status 0, the\nsame as Ctrl+C or `systemctl stop`. A supervisor that restarts a cleanly exited\nprocess starts it again (systemd `Restart=always`, Docker\n`--restart unless-stopped`); the installer's unit uses `Restart=on-failure`, so\nit stays stopped. API keys cannot shut the server down.\n\n## Uninstall with memora-cli\n\n```bash\nmemora-cli uninstall # or /uninstall in the console\n```\n\nIt explains what it removes for this install (the service and program\nfiles, or the npm package, or the container), then shows a checklist; press\nspace to select and Enter to continue:\n\n- **Settings and accounts** (the state folder: database, keys, sessions)\n- **Vault notes** (your vault folder)\n\nBoth are **unticked**, so by default your settings and notes are kept and a\nlater install picks them up again. Deleting the vault asks you to type its\nfolder name. Before the state folder is deleted, a final database backup is\noffered. System folders, your home folder and the program's own folder are\nnever deleted.\n\n| Install | What uninstall does |\n|---|---|\n| Native (systemd) | runs the installed `install.sh --uninstall` (adds `--purge` only when both folders are the installer's own) |\n| npm | stops the server, deletes what you ticked, then tells you to run `npm uninstall -g @codrihub/memora` |\n| Windows zip, source | stops the server, deletes what you ticked; delete the program folder yourself |\n| Docker | prints `docker rm -f memora` and, for what you ticked, `docker volume rm memora-state` / `docker volume rm memora-data` |\n\nWithout a terminal it needs `--yes` and deletes only what the flags say:\n`memora-cli uninstall --yes [--delete-config] [--delete-vault]`.\n\n## Reverse proxy\n\nRun Memora on loopback (`--behind-proxy` natively; in Docker set\n`MEMORA_HTTP_PORT=127.0.0.1:8400` in `.env`) and let the proxy terminate TLS.\nThen set, with `/config` or in `.env`:\n\n| Variable | Why |\n|---|---|\n| `MEMORA_BASE_URL=https://memory.example.com` | Public URL; links and MCP snippets use it, and its host becomes an allowed domain |\n| `MEMORA_DOMAIN=memory.example.com` | Only these hostnames are served; requests for the bare IP or other names get 404 |\n| `MEMORA_TRUSTED_PROXIES=203.0.113.10` | Proxies whose forwarding headers are believed. Loopback (same-host nginx, cloudflared) is always trusted; only list remote proxies |\n\nIn Docker, a proxy on the host reaches the container through the Docker\nnetwork, so the container sees the network's gateway address (for example\n`172.18.0.1`) instead of loopback. Add that address to\n`MEMORA_TRUSTED_PROXIES`, otherwise every request appears to come from it.\n\nThe proxy must forward `Host`, `X-Forwarded-For`, and `X-Forwarded-Proto`, and\nupgrade WebSockets on `/ws`. nginx and Caddy examples are in\n[DEPLOYMENT.md](DEPLOYMENT.md).\n\n## Backups\n\nBack up **both** the state database and the vault. The database is small but\ncritical.\n\nState, online (the server keeps running):\n\n```sh\nsudo memora-cli db backup # state/backups/memora-<UTC time>.db, keeps the newest 10\nsudo memora-cli db backup --to /var/backups/memora.db\nsudo memora-cli db check # integrity, permissions, sizes, last backup age\ndocker compose exec gateway memora-cli db backup # Docker: lands in ./state/backups/\n```\n\nThe copy is a consistent snapshot (`VACUUM INTO`), checked with\n`integrity_check`, mode 0600. Never `cp` a live `memora.db`: recent commits sit\nin `memora.db-wal`. Restore with the server stopped:\n\n```sh\nsudo systemctl stop memora\nsudo memora-cli db restore /var/backups/memora.db # verifies it; keeps the replaced DB in state/backups/\nsudo systemctl start memora\n```\n\nAlso keep a copy of `state/key-seal.bin`, which encrypts the sealed API key\ncopies. Vault and state together: archive both with the server stopped:\n\n```sh\nsudo systemctl stop memora\nsudo tar -C /var/lib/memora -czf memora-backup-$(date +%F).tar.gz state vault\nsudo systemctl start memora\n```\n\nKeep backups private: the database holds password and key hashes (never\nplaintext secrets).\n\n## Automation: `--check` and `--upgrade`\n\nThese are the contract for scripts and automation.\n\n```sh\n$ /usr/local/share/memora/install.sh --check\nMEMORA_LATEST=1.0.1\nMEMORA_INSTALLED=1.0.0\n```\n\n`MEMORA_INSTALLED` comes from `/usr/local/share/memora/VERSION` (written by\nthe installer), else from `memora --version`, else `unknown` (or `none` when\nnothing is installed). `MEMORA_LATEST` is `unknown` and the exit code `4` when\nGitHub cannot be reached. `--check` needs no root.\n\n```sh\n$ sudo /usr/local/share/memora/install.sh --upgrade --yes [--version X.Y.Z]\n...\nMEMORA_UPGRADE_RESULT=ok FROM=1.0.0 TO=1.0.1\n```\n\n`--upgrade --yes` never prompts. The last line of output is always\n`MEMORA_UPGRADE_RESULT=<ok|uptodate|error> FROM=<old> TO=<new>`, and the exit\ncode is `0` (ok), `3` (already up to date), `4` (network), `5` (checksum),\n`6` (not root), or `1`/`2` for other errors.\n",eD="# Configuration\n\nAll server state, settings included, lives in one SQLite database,\n`<MEMORA_STATE>/memora.db` (see [DATABASE.md](DATABASE.md)). Server settings are\nrows in the `server_config` table, edited with `memora-cli` (`/config` in the\nconsole). The process environment (systemd `Environment=`, Docker\n`environment:`) applies to every key that has no row.\n\n## Precedence\n\nFor each server setting:\n\n1. a row in `server_config` (set with `/config`), else\n2. the process environment (non-empty value), else\n3. the built-in default.\n\nThe server reads `server_config` once at startup, before anything else, so a\nchange made with `/config` applies after a restart (`/restart` for a native\ninstall, `docker compose restart gateway` in Docker). Clearing a value in\n`/config` deletes the row, and the environment or default applies again.\n\nA row wins over the environment. If you set `MEMORA_PORT` with `/config` and\nlater change the port in the systemd unit or `.env`, the row still applies\nuntil you clear it.\n\n## Server settings\n\n| Name | Default | Where it can live | What it does |\n|---|---|---|---|\n| `MEMORA_PORT` | `8400` | `server_config` or env | HTTP port (API, MCP, web UI, WebSocket). 1-65535. |\n| `MEMORA_BIND` | `127.0.0.1` | `server_config` or env | Bind address. `0.0.0.0` for every interface (the container image and the installer set it). |\n| `MEMORA_BASE_URL` | empty | `server_config` or env | Public URL, for example `https://memory.example.com`. Used for OAuth metadata and connection snippets; its host is also an allowed domain. |\n| `MEMORA_DOMAIN` | empty (any host) | `server_config` or env | Allowed hostnames, comma separated (`*.example.com` works). Requests for other hosts get 404. Loopback names are always allowed. |\n| `MEMORA_TRUSTED_PROXIES` | empty | `server_config` or env | IPs of remote reverse proxies whose forwarding headers are trusted. Loopback is always trusted. |\n| `MEMORA_ARM_TTL` | `300` | `server_config` or env | Accepted and validated (30-86400 seconds), but the server and `memora-cli` do not read it: the setup / reset window length comes from `memora-cli --minutes` (default 5 minutes). |\n| `MEMORA_VAULT` | empty (`data` as last resort) | `server_config` or env | Suggested vault folder. The vault in use is chosen in the browser (or with `memora-cli vault`) and stored in the `settings` table. |\n| `MEMORA_VAULT_AUTO` | `false` | `server_config` or env | `true` (also `1`, `yes`, `on`): use `MEMORA_VAULT` at startup instead of asking in the browser, only while no vault is configured and if the folder is writable. |\n| `MEMORA_ADMIN_USER` | `admin` | `server_config` or env | Name of the owner created at startup when no owner exists (needs `MEMORA_ADMIN_PASSWORD`). |\n| `RUST_LOG` | `info` | `server_config` or env | Log filter, for example `info` or `memora=debug`. |\n\n`server_config` accepts only these ten keys. Values are trimmed and validated\n(numbers in range, `true`/`false`, a valid user name, no control characters, at\nmost 2048 bytes).\n\n## Environment only\n\n| Name | Default | What it does |\n|---|---|---|\n| `MEMORA_ADMIN_PASSWORD`, `MEMORA_ADMIN_PASSWORD_FILE` | unset | Creates the owner at startup when none exists (at least 10 characters). Only the argon2id hash is stored; an existing owner is never replaced. |\n| `MEMORA_API_KEY`, `MEMORA_API_KEY_FILE` | unset | Installs an agent API key with id `k_env` and scopes `mcp`, `read`, `write` (at least 24 characters). Only its SHA-256 is stored; the key is replaced when the value changes. |\n| `MEMORA_STATE` | `state` (relative to the working directory) | State directory holding `memora.db`. Created with mode 0700 if missing. |\n| `MEMORA_ASSETS` | the `crates/http/assets` folder of the build tree | Directory of the web UI assets. |\n| `MEMORA_SETUP_HINT` | `memora-cli setup (run on the server)` | Hint returned by `GET /api/auth/state` and shown on the login screen. |\n| `MEMORA_UPDATE_CHECK` | `true` | Release check: shortly after start and then every 6 hours the server asks GitHub (`api.github.com/repos/Codrihub/memora/releases/latest`) for the newest release and the web UI shows when an update is available. `false` (also `0`, `no`, `off`) turns it off; no network call is made. |\n\nThe two secrets can never be stored in `server_config` (the schema rejects\nthem). The `_FILE` variants read the value from a file, for example a Docker\nsecret; a non-empty file wins over the plain variable.\n\nIn `/config`, `MEMORA_API_KEY` offers to create an API key directly, and\n`MEMORA_ADMIN_PASSWORD` points to `/setup` or `/reset`.\n\n## Instance settings (web UI)\n\nThe `settings` table holds one row, edited from the Settings page of the web UI:\n\n| Key | Default | Range | What it does |\n|---|---|---|---|\n| `realm` | `Memora` | 1-64 characters | Instance name shown in the UI and reported by `/api/config` and `/api/auth/state`. |\n| `session_ttl` | `10800` (3 hours) | 300-2592000 seconds | Idle timeout of a browser session. |\n| `session_max_age` | `0` | `0` or at least `session_ttl` | Absolute session lifetime in seconds. `0` means no cap. |\n| `min_password_len` | `10` | 10-256 | Minimum owner password length. |\n| `log_max_mb` | `8` | 1-512 | Size limit in MB of the vault event log (`.events.jsonl`). |\n| `log_max_days` | `0` | 0-3650 | Age limit in days of the vault event log. `0` means no age limit. |\n| `vault_path` | unset | absolute path | The vault folder. Set in the browser after the first sign-in, or with `memora-cli vault PATH`. |\n\n## memora-cli options\n\n| Option | Default | What it does |\n|---|---|---|\n| `--state <DIR>` | `$MEMORA_STATE`, else the state directory of the running `memora` server, else `./state` | State directory to work on. |\n| `--minutes <N>` | `5` | Window length for `setup` and `reset-password`, 1-60. |\n| `--ttl <SECONDS>` | | Window length in seconds (at most 3600). `--minutes` wins when both are given. |\n| `--create` | | With `vault PATH`: create the folder if it does not exist. |\n\nRun as root, `memora-cli` does all database work as the owner of the state\ndirectory, so no root-owned `memora.db*` files appear. See\n[INSTALL.md](INSTALL.md) and [DEPLOYMENT.md](DEPLOYMENT.md) for the commands.\n\n## Docker Compose (`.env`)\n\nThese variables are read by `docker-compose.yml`, not by Memora itself:\n\n| Name | Default | What it does |\n|---|---|---|\n| `COMPOSE_PROJECT_NAME` | `memora` | Compose project name, also the container name prefix. |\n| `IMAGE` | `ghcr.io/codrihub/memora:<version>` | Image to run or build. The compose file pins the release it ships with. |\n| `MEMORA_HTTP_PORT` | `8400` | Host port mapped to the container's port 8400. Use `127.0.0.1:8400` to publish on loopback only. |\n| `MEMORA_DATA_DIR` | `./data` | Host path mounted at `/data` (the vault). |\n| `MEMORA_STATE_DIR` | `./state` | Host path mounted at `/state` (the state directory). |\n| `MEMORA_UID`, `MEMORA_GID` | `1000` | uid:gid the container runs as. Must own both host directories. |\n| `MEMORA_ARM_TTL` | `300` | Passed to the container unchanged. |\n\nCompose also passes these through from `.env` to the container:\n`MEMORA_BASE_URL`, `MEMORA_DOMAIN`, `MEMORA_TRUSTED_PROXIES`,\n`MEMORA_VAULT_AUTO`, `MEMORA_ADMIN_USER`, `MEMORA_ADMIN_PASSWORD`,\n`MEMORA_ADMIN_PASSWORD_FILE`, `MEMORA_API_KEY`, `MEMORA_API_KEY_FILE`,\n`MEMORA_SETUP_HINT`, `MEMORA_UPDATE_CHECK`, and `RUST_LOG`.\n\nInside the container the image sets `MEMORA_VAULT=/data`,\n`MEMORA_STATE=/state`, `MEMORA_PORT=8400`, `MEMORA_BIND=0.0.0.0`,\n`MEMORA_ARM_TTL=300`, `MEMORA_ASSETS=/app/assets`, and `RUST_LOG=info`.\n\n## State directory\n\n| Path | Content |\n|---|---|\n| `memora.db` (+ `-wal`, `-shm`) | The state database: owner, API keys (hashes), tool switches and per-key permissions, OAuth clients and grants, privacy rules, sessions (hashed ids), setup window and lock state, access rules, settings, `server_config`, activity log. Mode 0600, WAL mode, must be on a local filesystem. See [DATABASE.md](DATABASE.md). |\n| `key-seal.bin` | 32-byte master key (mode 0600) that encrypts the copies of dashboard-created API keys, so the owner can show a key again. Created on first use. Back it up together with `memora.db`. |\n| `backups/` | `memora-cli db backup` output (newest 10 kept by default). |\n| `legacy-json-<unix time>/` | JSON state files found at startup, moved here after their one-time import into `memora.db`. |\n| `internal.token` | Created by the Docker entrypoint. Not used by Memora. |\n\n## Vault files\n\nThe vault holds the markdown notes plus derived and metadata files. See\n[ARCHITECTURE.md](ARCHITECTURE.md#vault-markdown-portable) for the full list.\nThe important ones for operations are `.git/` (history), `.fts.db`\n(rebuildable search index), `.events.jsonl` (event log), and `.Trash/`\n(soft-deleted notes).\n",tD='# MCP\n\nMemora exposes the vault to agents through the Model Context Protocol. The\nserver speaks JSON-RPC 2.0 over the Streamable HTTP transport at `/mcp`, on the\nsame port as the HTTP API and the web UI. There is one MCP endpoint and one tool\ncatalog.\n\n| | |\n|---|---|\n| Endpoint | `POST /mcp` |\n| Protocol versions | `2025-06-18` (preferred), `2025-03-26`, `2024-11-05` |\n| Auth | API key in `Authorization: Bearer <key>` or `X-API-Key: <key>`, or an OAuth 2.1 access token |\n| Discovery card | `GET /.well-known/mcp.json` (public) |\n| Readable catalog | `GET /tools` (HTML page, public) |\n| Catalog size | 74 tools, plus 5 admin tools for keys with the `admin` scope |\n\n`initialize` answers with the protocol version the client asks for when it is\none of the three above, and with `2025-06-18` otherwise.\n\n## Transport\n\n- Requests are JSON-RPC 2.0 objects sent with `POST /mcp`. Batches (JSON\n arrays) are not supported.\n- Responses are plain JSON (`application/json`). The server does not open SSE\n streams and does not issue an `Mcp-Session-Id`.\n- `GET` and `DELETE` on `/mcp` return `405 Method Not Allowed` with\n `Allow: POST`.\n- A notification (a `notifications/*` method without an `id`) gets\n `202 Accepted` and no body.\n- `/mcp` needs a configured vault. Until one is chosen it returns\n `409 {"error":"vault not configured","needs_vault":true}`.\n- A browser session (cookie) may also call `/mcp`. It then needs a same-origin\n request, like the rest of the JSON API.\n\nThe server speaks Streamable HTTP only. A client that can only launch local stdio\nservers can use a bridge such as `mcp-remote` (see below).\n\n## Connecting an agent\n\n### With an API key\n\nCreate a key in the web UI (Keys page), with `memora-cli` (`/keys`), or with\n`POST /api/keys`. The raw key (`memora_live_...`) is shown once. By default a key gets\nthe scopes `mcp`, `read` and `write` and may call every tool. See\n[Tool switches and per-key permissions](contracts/tools-permissions.md) to\nnarrow it.\n\nUse `http://localhost:8400/mcp` for a local install, or your public URL such as\n`https://memory.example.com/mcp` behind a reverse proxy. When the server sets\n`MEMORA_DOMAIN` or `MEMORA_BASE_URL`, requests for any other host get `404`, so\nuse that domain.\n\nClaude Code:\n\n```bash\nclaude mcp add --transport http memora https://memory.example.com/mcp \\\n --header "Authorization: Bearer memora_live_REPLACE_WITH_YOUR_KEY"\n```\n\nCursor, Windsurf and other clients with an `mcpServers` JSON config (VS Code\nuses the key `servers` in `.vscode/mcp.json`):\n\n```json\n{\n "mcpServers": {\n "memora": {\n "type": "http",\n "url": "http://localhost:8400/mcp",\n "headers": {\n "Authorization": "Bearer memora_live_REPLACE_WITH_YOUR_KEY"\n }\n }\n }\n}\n```\n\nCodex (`~/.codex/config.toml`), with the key in the `MEMORA_API_KEY`\nenvironment variable:\n\n```toml\n[mcp_servers.memora]\nurl = "https://memory.example.com/mcp"\nbearer_token_env_var = "MEMORA_API_KEY"\n```\n\nClients that only run local stdio servers, such as the Claude Desktop config\nfile, can bridge with `mcp-remote` (needs Node.js):\n\n```json\n{\n "mcpServers": {\n "memora": {\n "command": "npx",\n "args": [\n "-y", "mcp-remote", "https://memory.example.com/mcp",\n "--header", "Authorization: Bearer memora_live_REPLACE_WITH_YOUR_KEY"\n ]\n }\n }\n}\n```\n\nSome clients send the key as `X-API-Key: <key>` instead. Both headers are\naccepted.\n\n### With OAuth\n\nClients that support MCP authorization (for example Claude and ChatGPT custom\nconnectors, or Claude Code without a `--header`) can connect with only the URL:\n\n```bash\nclaude mcp add --transport http memora https://memory.example.com/mcp\n```\n\nThe flow:\n\n1. The client calls `/mcp` without credentials and gets `401` with\n `WWW-Authenticate: Bearer resource_metadata="https://memory.example.com/.well-known/oauth-protected-resource"`.\n2. It reads the protected resource metadata (RFC 9728) and the authorization\n server metadata at `/.well-known/oauth-authorization-server` (RFC 8414; also\n served at `/.well-known/openid-configuration` and under a `/mcp` suffix).\n3. It registers itself with dynamic client registration at\n `POST /oauth/register` (RFC 7591), or uses an HTTPS client metadata document\n URL as its `client_id`. The owner can also register clients in the web UI.\n Redirect URIs must be HTTPS, or plain HTTP on `localhost`, `127.0.0.1` or\n `[::1]`.\n4. It opens `/oauth/authorize` (authorization code with PKCE `S256` only). The\n browser lands on the Memora sign-in page, and the signed-in owner approves or\n denies the connection on a consent card. Codes are valid for 10 minutes.\n5. It exchanges the code at `POST /oauth/token` and receives an access token and\n a refresh token. The only OAuth scope is `mcp`.\n\nThe access token is a regular Memora API key named after the client. It starts\nwith the default scopes (`mcp`, `read`, `write`) and every tool, and it shows up\non the Keys page like any other key, so you can restrict, disable or delete it\nthere. The access token has no expiry. A `refresh_token` grant replaces it with\na fresh one (the old token stops working at once) and rotates the refresh token.\nDisabling or deleting the key ends the connection.\n\nSet `MEMORA_BASE_URL` (for example `https://memory.example.com`) when the server\nruns behind a proxy, so the issuer and endpoint URLs in the metadata are the\npublic ones. Without it the server derives them from the request headers.\n\n### Test from a shell\n\n```bash\ncurl -s -X POST http://localhost:8400/mcp \\\n -H "Authorization: Bearer memora_live_REPLACE_WITH_YOUR_KEY" \\\n -H "Content-Type: application/json" \\\n -d \'{"jsonrpc":"2.0","id":1,"method":"tools/list"}\'\n```\n\n## Discovery card\n\n`GET /.well-known/mcp.json` needs no auth and returns:\n\n| Field | Value |\n|---|---|\n| `name` | `memora` |\n| `version` | The server version |\n| `description` | One-line description of the server |\n| `mcp` | `{endpoint: "/mcp", transports: ["streamable-http"], protocolVersion: "2025-06-18"}` |\n| `auth` | `{type: "api-key", headers: ["Authorization: Bearer <key>", "X-API-Key: <key>"], oauth: "/.well-known/oauth-authorization-server"}` |\n| `capabilities` | `{tools: true, resources: true, prompts: false}` |\n| `tools` | Every catalog tool as `{name, category, description, enabled}`. `enabled` is `false` for tools switched off on this server. Admin tools are not listed. |\n| `resources` | `[{uri, name}]` for the three resources below |\n\nThe card is the same for every caller. To see what a given key may call, use\n`tools/list` with that key.\n\n## Methods\n\n| Method | Purpose |\n|---|---|\n| `initialize` | Handshake. Returns `protocolVersion`, `serverInfo` (`{name, version}`) and `capabilities` (`tools` and `resources`, both with `listChanged: false`). |\n| `notifications/initialized` | Client notification. Without an `id` it gets `202 Accepted`. |\n| `tools/list` | The tools the caller may use, each with `name`, `description` (what it does and when to use it), `inputSchema`, and `_meta.category`. |\n| `tools/call` | Runs one tool. Params are `{name, arguments}`. |\n| `resources/list` | Lists the three resources below. |\n| `resources/read` | Reads one resource. Params are `{uri}`. |\n\nThere are no prompts, no pagination cursors and no change notifications.\n\n### Resources\n\n| URI | Content |\n|---|---|\n| `memory://catalog` | Every catalog tool with `name`, `category`, `description`, `when`, and `inputSchema` (JSON) |\n| `memory://schema` | Data shapes for a note, a folder, the graph, and activity (JSON) |\n| `memory://guide` | A short guide for agents using the vault (Markdown) |\n\n`resources/read` returns `{contents: [{uri, mimeType, text}]}`.\n\n## Results and errors\n\nA successful tool call returns the tool\'s JSON result as text:\n\n```json\n{\n "jsonrpc": "2.0",\n "id": 2,\n "result": {\n "content": [{ "type": "text", "text": "{...}" }],\n "isError": false\n }\n}\n```\n\nA tool that fails (bad arguments, note not found, unknown tool name) returns the\nsame envelope with `isError: true` and the error message as the text. The HTTP\nstatus stays `200`.\n\nJSON-RPC errors:\n\n| Code | When |\n|---|---|\n| `-32700` | The body is not valid JSON (HTTP `400`). |\n| `-32600` | The body is not a JSON-RPC request object (HTTP `400`). |\n| `-32601` | Unknown method: `unsupported method: <method>`. |\n| `-32602` | `resources/read` with an unknown URI: `unknown resource: <uri>`. |\n| `-32003` | The tool exists but the caller may not use it. Messages: `tool not allowed for this API key: <name>`, `tool disabled on this server: <name>`, `API key lacks the \'write\' scope for tool: <name>`. |\n\nHTTP errors before JSON-RPC runs:\n\n| Status | When |\n|---|---|\n| `401` | No key, or a key that is unknown, disabled, deleted or replaced by a roll (`invalid API key`). Carries a `WWW-Authenticate` header that points OAuth clients at the protected resource metadata. |\n| `403` | The key lacks the `mcp` scope (`{"error":"API key lacks the \'mcp\' scope","required_scope":"mcp"}`), or a browser request failed the same-origin check. |\n| `405` | Any method other than `POST`. |\n| `409` | No vault is configured yet. |\n| `429` | Rate limit or cooldown after failed attempts. |\n\n## What each key sees\n\n`tools/list` is filtered per caller:\n\n- A tool switched off on the server is hidden for everyone.\n- A key whose tool list is not `"*"` only sees the tools in its list.\n- A key without the `write` scope only sees read-only tools.\n- Admin tools are added for keys with the `admin` scope (and for browser\n sessions).\n\n`tools/call` on a tool that `tools/list` would hide returns `-32003`. Details\nare in [Tool switches and per-key permissions](contracts/tools-permissions.md).\n\n### Privacy rules\n\nThe owner can hide notes and folders from specific agents (web UI,\n`/api/privacy`, or the `privacy_*` admin tools). For an API key covered by a\nrule, every tool works as if the hidden paths did not exist: they are left out\nof listings, search, the graph, tags, events, logs, locks and folder metadata; a\nhidden path named in an argument is answered as not found, for reads and writes\nalike; and folder operations that would carry hidden items along are refused.\nIf the rules cannot be read, the key sees nothing (fail closed). Browser\nsessions are never filtered.\n\n## Tools\n\nR = read-only (needs only the `mcp` scope). W = changes the vault or server\nstate (also needs the `write` scope). Unless marked required, arguments are\noptional. Paths are vault-relative, for example `Projects/Plan.md`.\n\n### Notes (`note`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `list_memory` | R | none | Every note grouped by folder: `{folder: [{path, name, folder, mtime}]}`. |\n| `read_memory` | R | `path` (string, required) | Markdown body, frontmatter, tags and backlinks of one note. |\n| `create_memory` | W | `title` (string, required), `folder` (string, default `Memory`; `Root` or empty for the top level), `content` (string; default is a stub with `created` frontmatter and a heading) | Creates `<folder>/<title>.md` and returns `{ok, path}`. |\n| `save_memory` | W | `path` (string, required), `content` (string, required) | Replaces the whole note. |\n| `patch_memory` | W | `path` (string, required), `ops` (array, required) | Partial edits. Each op is an object: `{op:"append", text}`, `{op:"prepend", text}`, `{op:"replace", find, with}`, `{op:"set_field", field, value}`, `{op:"add_tag", tag}`, `{op:"remove_tag", tag}`. |\n| `delete_memory` | W | `path` (string, required) | Deletes a note (recoverable from git history). |\n| `move_memory` | W | `path` (string, required), `folder` (string, required) | Moves a note into another folder. Wikilinks resolve by note name, so they keep working. |\n| `rename_memory` | W | `path` (string, required), `new_name` (string, required) | Renames a note in its folder. |\n\n### Search (`search`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_stats` | R | none | Counts of notes, links and folders. |\n| `search_memory` | R | `q` (string, required; `query` is accepted as an alias), `limit` (integer, default 12) | Search titles and bodies. Supports `tag:x` and `#x`. |\n\n### Query (`query`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `query_memory` | R | `folder`, `tags`, `author`, `type`, `status` (strings), `limit` (integer, default 50) | Filter notes by frontmatter. |\n| `find_similar` | R | `path` (string, required), `limit` (integer, default 8) | Notes most similar to one note (shared tags and words). |\n| `suggest_links` | R | `path` (string, required), `limit` (integer, default 8) | Similar notes not yet linked from this one. |\n| `list_tags` | R | none | Every tag with its usage count. |\n| `rename_tag` | W | `old` (string, required), `new` (string, required) | Renames a tag across the vault. |\n| `merge_tag` | W | `a` (string, required), `b` (string, required) | Merges tag `a` into tag `b` across every note. |\n\n### Tags (`tag`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_tags` | R | `path` (string; not in the advertised schema) | Every tag with its count, or the tags of one note when `path` is given. |\n| `search_by_tag` | R | `tag` (string, required), `limit` (integer, default 50; not in the advertised schema) | Every note carrying a tag. |\n| `add_tags` | W | `path` (string, required), `tags` (string, required, comma-separated) | Adds tags to a note. A leading `#` is stripped. |\n| `remove_tags` | W | `path` (string, required), `tags` (string, required, comma-separated) | Removes tags from a note. |\n| `set_tags` | W | `path` (string, required), `tags` (string, required, comma-separated) | Replaces a note\'s tag list. |\n\n### Folders (`folder`, `ops`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `list_folders` | R | none | `{count, folders: [{name, count, color}]}`. |\n| `create_folder` | W | `name` (string, required) | Creates a folder. |\n| `rename_folder` | W | `folder` (string, required), `name` (string, required, one segment) | Renames a folder in place. Notes, sub folders, color and icon move along. |\n| `move_folder` | W | `folder` (string, required), `into` (string; empty or `Root` = top level) | Moves a folder with everything in it. |\n| `move_folder_contents` | W | `folder` (string, required), `into` (string; empty = top level) | Moves everything inside a folder into another folder, then removes the empty folder. Name clashes get a `-N` suffix. |\n| `delete_folder` | W | `folder` (string, required) | Deletes a folder. Its notes move to Root. |\n| `folder_stats` | R | `folder` (string, required) | Note count and metadata for one folder. |\n| `get_folder_meta` | R | `folder` (string) | Color, icon and description of one folder, or of every folder. |\n| `set_folder_meta` | W | `folder` (string, required), `color`, `icon`, `desc` (strings) | Sets folder display metadata. A field sent as an empty string is cleared. |\n\n### Graph (`graph`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_graph` | R | none | Whole graph: `{nodes: [{id, path, folder, color, degree, tags, mtime}], links: [{source, target}]}`. |\n| `get_neighbors` | R | `path` (string, required), `depth` (integer, default 1) | Notes within N hops. |\n| `get_subgraph` | R | `path` (string, required), `depth` (integer, default 1), `max_nodes` (integer, default 60) | Subgraph around one note. |\n| `find_path` | R | `source` (string, required), `target` (string, required) | Shortest wikilink path between two notes. |\n| `get_hubs` | R | `limit` (integer, default 10) | Most connected notes. |\n| `get_isolated` | R | none | Notes with no links in or out. |\n| `link_stats` | R | `path` (string, required) | Outgoing, incoming and unresolved links of one note. |\n| `broken_links` | R | none | Wikilinks pointing at notes that do not exist. |\n\n### Versioning (`version`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_history` | R | `path` (string, required), `limit` (integer, default 20) | Git history of a note. A single entry is returned as an object, several as an array. |\n| `get_note_at` | R | `path` (string, required), `rev` (string, required) | `{ok, path, rev, content}` at a revision. |\n| `diff` | R | `path` (string, required), `rev_a` (string, required), `rev_b` (string) | Diff between two revisions, or `rev_a` against the working tree. |\n| `restore_memory` | W | `path` (string, required), `rev` (string, required) | Restores a note to a revision. |\n| `snapshot` | W | `label` (string, required) | Tags the whole vault (git tag). |\n| `soft_delete` | W | `path` (string, required) | Moves a note to `.Trash`. |\n| `restore_trash` | W | `name` (string, required), `into` (string, default `Root`) | Restores a note from `.Trash` into a folder. |\n\n### Bulk writes (`write`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `batch_create` | W | `notes` (array, required) of `{title, folder (default Root), content}` | Creates many notes in one call. |\n| `duplicate_memory` | W | `path` (string, required) | Copies a note as `<name>-copy` in the same folder. |\n| `merge_memory` | W | `paths` (array of strings, required), `into` (string, required) | Merges several notes into one target note. |\n| `template_create` | W | `template` (string, required), `title` (string, required), `folder` (string, default `Root`), `variables` (object) | Creates a note from a file in `Templates/` with `{{var}}` substitution. |\n| `bulk_replace` | W | `find` (string, required), `replace` (string, required), `folder` (string), `regex` (boolean, default false), `dry_run` (boolean, default false) | Find and replace across notes. Needs `write` even with `dry_run`. |\n| `bulk_delete` | W | `paths` (array of strings), `folder` (string) | Deletes many notes by list or by folder. |\n\n### Collaboration (`collab`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `lock_node` | W | `path` (string, required), `owner` (string, default the caller), `ttl` (integer seconds, default 300) | Soft lock on a note. |\n| `release_lock` | W | `path` (string, required), `owner` (string, default the caller) | Releases a lock. |\n| `get_locks` | R | none | Active locks. |\n| `mention_agent` | W | `agent` (string, required), `path` (string, required), `message` (string) | Writes `> @agent: message` into a note. |\n| `get_assignments` | R | `agent` (string) | Notes with `assigned_to` in their frontmatter. |\n\n### Activity and health (`ops`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_events` | R | `since` (number, unix time), `folder`, `actor` (strings), `limit` (integer, default 50) | Recent note created, updated and deleted events. |\n| `presence` | R | `window` (integer seconds, default 300) | Agents active within the window. |\n| `get_logs` | R | `range` (string, default `1d`; also `7d`, `today`, `yesterday`), `actor` (string), `limit` (integer, default 100) | Activity log for a period. |\n| `search_logs` | R | `q` (string, required), `range` (string, default `7d`), `actor` (string), `limit` (integer, default 100) | Keyword search in the activity log. |\n| `digest` | R | `folder` (string), `since` (number) | Event counts per actor and per type. |\n| `healthcheck` | R | none | Note count, broken links, orphans and git status. |\n| `stale_detection` | R | `days` (integer, default 30) | Notes untouched for more than N days. |\n\n### Identity (`identity`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `set_my_name` | W | `name` (string, required) | Sets the display alias shown in the activity feed and log. |\n| `set_my_color` | W | `color` (string, required; `#rrggbb`, or `""` to reset) | Sets the calling API key\'s display color. Fails for browser sessions. |\n| `list_actors` | R | none | `{me, aliases}`: the caller and every known alias. |\n\n### Import and export (`interop`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `export_memory` | W | `paths` (array of strings, required; notes or folders), `out_path` (string) | Writes a zip of the given paths to the server\'s exchange folder and returns `{ok, path, name, bytes}`, where `path` and `name` are the zip\'s file name. `out_path` is a plain file name ending in `.zip` (letters, digits, `.`, `_`, `-`, at most 120 characters); the default is `memora-export-<time>.zip`. |\n| `import_memory` | W | `zip_path` (string, required), `overwrite` (boolean, default false) | Imports notes from a zip in the exchange folder, by the file name `export_memory` returned. |\n\nThe exchange folder is `memora-exchange` in the server\'s temporary directory.\nTools never read or write anywhere else on the server\'s disk.\n\n### Checks, to-dos and pins (`ux`)\n\n| Tool | | Arguments | Purpose |\n|---|---|---|---|\n| `get_todos` | R | `path` (string) | Open checklist items (`- [ ]`) in one note or the whole vault. |\n| `follow_ups` | R | none | Notes whose status is still awaiting action. |\n| `validate_memory` | R | `path` (string, required) | Checks frontmatter, created date, tags and links of a note. |\n| `list_pins` | R | none | The owner\'s pinned notes and folders in sidebar order: `{count, pins:[{kind, path, position, missing}]}`. `missing` is true when the path no longer exists (renamed or deleted outside Memora). |\n| `pin` | W | `path` (string, required), `kind` (`note` or `folder`; default: what the path is on disk), `position` (integer from 0; default: the end) | Pins an existing note or folder, or moves its pin. A note path may leave out `.md`. At most 200 pins. Returns the list. |\n| `unpin` | W | `path` (string, required), `kind` | Removes a pin; the note or folder is not touched. Returns the list with `removed`. |\n\nPins are shared by every browser of the owner (`/api/pins`). They follow their note or\nfolder through renames and moves done by Memora (over MCP or HTTP, including notes inside\na moved folder) and are removed when the item is deleted or moved to the trash; deleting a\nfolder removes every pin under it. A key whose privacy rules hide a path neither lists\nnor changes its pin, and `position` counts only the pins the key can see.\n\n### Admin tools (`admin`)\n\nListed and callable only for keys with the `admin` scope (and for browser\nsessions). They are not part of the switchable catalog: global tool switches and\na key\'s tool list do not apply to them, and they do not need `write`.\n\n| Tool | Arguments | Purpose |\n|---|---|---|\n| `admin_list_tools` | none | `{tools: [{name, category, description, enabled}]}` for every catalog tool. |\n| `admin_set_tool` | `name` (string, required), `enabled` (boolean, required) | Switches a catalog tool on or off for every key. Returns `{ok, name, enabled}`. |\n| `privacy_list` | `path` (string), `kind` (`node` or `folder`) | Without `path`: every privacy rule. With `path`: that note or folder\'s own rule, the folder rules it inherits, and which agents can see it. |\n| `privacy_set` | `path` (string, required), `agents` (array of key ids or names, required; a comma-separated string also works), `kind` (`node` or `folder`), `mode` (`deny` or `allow_only`, default `deny`) | Replaces the rule on a path. `deny` hides it from the listed agents; `allow_only` hides it from every other agent, including keys created later. `deny` with no agents removes the rule. A node rule follows its note through renames and moves. |\n| `privacy_clear` | `path` (string, required), `kind` (`node` or `folder`) | Removes the path\'s own rule. Rules on parent folders still apply. |\n\nWhen `kind` is omitted it is taken from the path on disk: a folder if a folder\nexists there, otherwise a note.\n\n## Identity and tracking\n\nEvery tool call is published to the web UI\'s realtime activity stream as an\n`ai_activity` start and end pair, named after the API key (or the signed-in\nuser), with the note paths involved. Calls are also counted per key: the Keys\npage and `GET /api/keys` show each key\'s `uses`, `last_ip`, and the tools it has\ncalled recently. `initialize` registers the connection under the key\'s name\n(`GET /api/aliases`). `set_my_name` changes the alias shown in the activity\nfeed and log, and `set_my_color` changes the key\'s color in the UI. See\n[API.md](API.md) for the HTTP endpoints.\n',nD='# HTTP API\n\nThe `memora` binary serves the HTTP API, the MCP endpoint, the OAuth endpoints,\nthe web UI, and the WebSocket on one port. This document lists the HTTP endpoints.\n\n## Authentication\n\nThe Auth column in the tables below uses these levels:\n\n- None: reachable without credentials.\n- Session: requires the `memora_sess` cookie set by a successful login.\n- Key (`scope`): an API key sent as `Authorization: Bearer <key>` or `X-API-Key: <key>`\n that carries the named scope.\n- Session or key (`scope`): either of the above.\n- Session only: an API key is not enough. API keys get `401` (or `403` where noted).\n- +CSRF: the same-origin check described below applies.\n\n### API key scopes\n\nA key carries any of the scopes `mcp`, `read`, `write`, and `admin`. New keys get\n`mcp`, `read`, and `write` unless other scopes are requested. The scope a route\nneeds is decided by its path and method:\n\n| Scope | Routes |\n|---|---|\n| `mcp` | `/mcp` |\n| `admin` | `/api/tools`, `/api/keys` and `/api/keys/*`, `/api/access` and `/api/access/*`, `/api/logs/settings`, `/api/oauth/clients` and `/api/oauth/clients/*`, `/api/privacy` and `/api/privacy/*` |\n| `read` | Every other `GET` or `HEAD` under `/api/` |\n| `write` | Every other method under `/api/` |\n\nA key without the needed scope gets `403 {error, required_scope}`. A missing key\ngets `401`; for `/mcp` the `401` carries a `WWW-Authenticate` header,\n`Bearer resource_metadata="<base>/.well-known/oauth-protected-resource"`, so OAuth\ncapable clients can start sign-in. An invalid key gets `401` and is logged; an\nIP that keeps presenting invalid keys is put on a cooldown (`429`).\n\n`/api/auth/*` never accepts an API key: without a valid session it answers `401`.\n\nAPI keys see the vault through their privacy rules (see [Privacy](#privacy)):\nnotes and folders hidden from a key behave as if they do not exist. A browser\nsession sees everything.\n\n### CSRF\n\nWrite endpoints that accept a session check the request origin whenever a\nsession cookie is present: `Origin` (or, without it, `Referer`) must match the\nrequest `Host` (or an `X-Forwarded-Host` sent by a trusted proxy), and\n`Sec-Fetch-Site: cross-site` is refused. A failed check is\n`403 {"error":"origin mismatch"}`. Requests without a session cookie (API-key\nclients) pass, since a browser cannot attach an API key on its own.\n\nThe public auth forms (`/api/auth/login`, `/api/auth/verify`,\n`/api/auth/bootstrap`, `/api/auth/reset`) also refuse a foreign or `null`\n`Origin` when no cookie exists yet. A request with neither `Origin` nor\n`Referer` (curl, the CLI) passes.\n\n### Locked instance\n\nWhile the instance is LOCKED, `/api/*` and `/mcp` answer\n`423 {error, locked: true, hint}` except for `/api/auth/state`, `/api/auth/verify`,\n`/api/auth/login`, `/api/auth/logout`, `/api/auth/bootstrap`, and\n`/api/auth/reset`. Other pages redirect to `/login?locked=1`; static assets,\n`/login`, `/logout`, `/healthz`, and `/favicon.ico` are still served.\n`/api/auth/login` itself answers `423` while locked.\n\n### Vault not configured\n\nUntil a vault folder is configured, `/mcp` and every `/api/*` route except\n`/api/auth/*`, `/api/settings*`, `/api/config`, `/api/keys*`, `/api/tools`,\n`/api/access*`, and `/api/ui/*` answer\n`409 {"error":"vault not configured", "needs_vault":true}`.\n\n### Limits and other gates\n\n- Requests for a host outside the configured domain list get a bare `404`.\n- Access rules (see `/api/access`) can block a caller:\n `403 {"error":"access denied by stack rule", ip}`.\n- Per-IP rate limits answer `429` with a `Retry-After` header and\n `{error, limited, cooldown, retry_after}`. Login, code check, setup, reset, profile,\n password, and username changes have a stricter limit and a cooldown after\n repeated failed attempts. Requests from the machine itself and `/healthz` are\n not limited.\n- A request that takes longer than 30 seconds is answered with `408`.\n- A password hashing pool that is busy answers `503` with `Retry-After: 2`.\n\nResponses are JSON unless stated otherwise. Errors are `{"error": "..."}`. Vault\nerrors map to `404` for not-found (including paths hidden from the caller) and\n`400` for bad input.\n\n## Health and discovery\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/healthz` | None | `{ok, server}` for unauthenticated callers from other machines. A signed-in browser or a caller on the same machine gets `{ok, server, version, vault_configured, vault, armed, locked, base_url, base_url_configured}`. |\n| GET | `/.well-known/mcp.json` | None | The MCP discovery card: `{name, version, description, mcp, auth, capabilities, tools, resources}`. `tools` lists the full catalog with `enabled` per tool. |\n| GET | `/tools` | None | An HTML rendering of the tool catalog. A signed-in browser gets the app shell instead. |\n| POST | `/mcp` | Key (`mcp`), or Session (+CSRF) | MCP over streamable HTTP (JSON-RPC in, JSON-RPC out). See [MCP.md](MCP.md). A session has full access; a key is limited by its tool grant. Notifications get `202` with no body. Malformed JSON is `400` with a JSON-RPC error. Other methods get `405` with `Allow: POST`. |\n\n## Auth\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/auth/state` | None | `{bootstrap, realm, min_password_len, gateway, armed, locked, setup_hint, ready, checks:{vault, state}, code_required, cooldown, vault_configured}`. Adds `signed_out` (`password_changed` or `signed_out_remotely`) when the browser\'s session was ended on purpose, and `mode`, `expires_in`, `ttl` while a setup or reset window is open. |\n| POST | `/api/auth/verify` | None (+CSRF) | Checks the setup code shown on the server before the setup or reset form is shown. Body: `{code}`. Returns `{ok, mode, expires_in, user}`. `403` when no window is open or the instance is not ready. A wrong code closes the window and voids the code: `403 {error, burned:true}`. |\n| POST | `/api/auth/login` | None (+CSRF) | `{ok, user, expires_in, redirect}` and sets the session cookie. Body: `{username, password}`. `400` when a field is missing, `401` on bad credentials, `403` if the account is disabled, `423` if locked, `429` during a cooldown. |\n| POST | `/api/auth/logout` | None (+CSRF) | `{ok:true}`. Ends the session named by the cookie, if any, and clears the cookie. |\n| POST | `/api/auth/bootstrap` | None (+CSRF) | Creates the owner account. Body: `{code, username, password}`. Returns `{ok, user, redirect, persisted}` and sets a session cookie. The username is stored lowercase. `400` for an invalid username or password length; `403` unless a window is open, the code is right, the instance is ready, and no account exists. |\n| POST | `/api/auth/reset` | None (+CSRF) | Sets a new password for the single account, and may rename it. Body: `{code, username, password}`. Returns `{ok, user, persisted}`. Signs out every session. `400` for invalid input; `403` unless a window is open, the code is right, and an account exists. |\n| POST | `/api/auth/profile` | Session only (+CSRF) | With `password` in the body, changes the password exactly like `POST /api/settings/password` (body `{current, password, confirm}`). Otherwise sets `display_name` (at most 48 characters) and returns `{ok, changed, persisted, user, password_changed:false}`; with no `display_name` it returns `{ok, changed:false}`. |\n| GET | `/api/auth/me` | Session only | `{authenticated, user, enabled, expires_in}`. `401` without a session. |\n| GET | `/api/auth/events` | Session only | Recent entries of the security activity log, newest first: `{events:[{at, event, ip, user, detail, actor, actor_kind, actor_id}], count}`. `user` is the stored actor (`key:<id>` for API-key calls); `actor` is the display name (the key\'s current name, falling back to its id; the username for the browser), `actor_kind` is `agent` or `user` (null when there is no actor). Query: `limit` (default 200, max 2000), `q`. |\n\n## Pages\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/login` | None | The sign-in page. A signed-in browser is redirected to `/` unless the instance is locked or the query has `oauth` (the OAuth consent card). |\n| any | `/logout` | None | Ends the session, clears the cookie, and redirects to `/login`. A cross-site request only clears the cookie. |\n| GET | `/`, `/index.html` | Session | The web app shell. Without a session: `302` to `/login`. `503` when the UI assets are not installed. |\n| GET | App routes (see below) | Session | The same app shell as `/`. Without a session: `302` to `/login?r=<path>`, so sign-in returns to the page. |\n\nApp routes are the web app\'s client-side pages: `/brain`, `/nodes`, `/graph`,\n`/canvas`, `/tags`, `/activity`, `/agents`, `/access`, `/settings`,\n`/overview`, `/welcome`, the older names `/home`, `/vault`, `/logs`, `/keys`,\nand `/node/` or `/node/<percent-encoded vault path>`. The path is never used to\nread a file; a path holding NUL or another control character (raw or\npercent-encoded) is `400`. `/tools` is an app route for a signed-in browser and\nthe public tool catalog otherwise.\n\nHTML pages are sent with `Cache-Control: no-cache, no-store, must-revalidate`\nand a per-response CSP nonce.\n\nAny other `GET` that asks for HTML (`Accept: text/html`), is outside `/api/`,\n`/mcp`, `/oauth`, and `/.well-known`, and has no file extension in its last\nsegment gets the app shell (which shows its "page not found" view). Every other\nunmatched request is `404 {"error":"not found"}`.\n\n## Static assets\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/assets/{name}` | None | Static UI assets (whitelisted filenames only, else `404`). |\n| GET | `/app.js`, `/app.css`, `/login.css` | None | The UI bundle and styles. Revalidated on every load (`Cache-Control: no-cache`, ETag). |\n| GET | `/favicon.svg` | None | The icon. |\n| GET | `/favicon.ico` | None | `204` with no body. |\n| GET | `/manifest.webmanifest`, `/sw.js`, `/robots.txt`, `/offline.html`, `/icon-192.png`, `/icon-512.png`, `/icon-maskable-512.png`, `/apple-touch-icon.png` | None | PWA files and `robots.txt`. Images and the manifest are cached for 5 minutes; code is revalidated on every load. |\n\n## Vault\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/tree` | Session or key (`read`) | Notes grouped by folder. |\n| GET | `/api/note` | Session or key (`read`) | `{path, name, content, html, tags, frontmatter, backlinks, size, mtime}`. Query: `path` (`400` when empty). |\n| GET | `/api/vault/file` | Session or key (`read`) | The raw bytes of one image file in the vault (PNG, JPEG, GIF, WebP, AVIF, BMP, ICO; never SVG). Query: `path` (vault-relative). The file content must match its type. At most 10 MiB (`413`). Sent with an `ETag` (`304` on `If-None-Match`), `Cache-Control: private, max-age=300`, and a sandbox CSP. `400` invalid path, `403` path not allowed, `404` not found, `415` not an image. |\n| GET | `/api/folder-meta` | Session or key (`read`) | Folder metadata keyed by folder name. Query: `folder` (optional). |\n| POST | `/api/save` | Session or key (`write`, +CSRF) | `{ok, path}`. Body: `{path, content}`. Overwrites the note. |\n| POST | `/api/create` | Session or key (`write`, +CSRF) | `{ok, path}`. Body: `{title, folder?, content?}`. |\n| POST | `/api/rename` | Session or key (`write`, +CSRF) | `{ok, path}` with the new path. Body: `{path, name}`. |\n| POST | `/api/move` | Session or key (`write`, +CSRF) | `{ok, path}` with the new path. Body: `{path, folder?}`. |\n| POST | `/api/delete` | Session or key (`write`, +CSRF) | `{ok:true}`. Body: `{path}`. |\n| POST | `/api/folder` | Session or key (`write`, +CSRF) | `{ok, path}`. Body: `{name}`. |\n| POST | `/api/folder/rename` | Session or key (`write`, +CSRF) | `{ok, from, to, notes}`. Body: `{folder, name}`. |\n| POST | `/api/folder/move` | Session or key (`write`, +CSRF) | Moves a folder and everything in it. `{ok, from, to, notes}`. Body: `{folder, into}`; `into` empty or `Root` means the top level. |\n| POST | `/api/folder/move-contents` | Session or key (`write`, +CSRF) | Moves everything inside a folder into another one, then removes the emptied folder. Name clashes get a `-N` suffix. `{ok, from, to, moved}`. Body: `{folder, into}`; `into` empty or `Root` means the top level. |\n| POST | `/api/delete-folder` | Session or key (`write`, +CSRF) | Deletes a folder and moves its notes to the top level. `{ok, deleted_folder, moved_to_root}` where `moved_to_root` lists the new note paths. Body: `{folder}`. |\n| POST | `/api/folder-meta` | Session or key (`write`, +CSRF) | `{ok, folder}`. Body: `{folder, color?, icon?, desc?}`. |\n\nThe three folder operations also publish a `folder_changed` realtime event so\nopen browsers reload their tree.\n\n## Search and graph\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/search` | Session or key (`read`) | `{q, count, hits:[{path, name, folder, score, snippet}]}`, at most 20 hits. Query: `q`. Supports `tag:x` and `#x`. |\n| GET | `/api/stats` | Session or key (`read`) | `{notes, links, folders}`. |\n| GET | `/api/graph` | Session or key (`read`) | `{nodes:[{id, path, folder, color, degree, tags}], links:[{source, target}]}`. `tags` holds inline `#tags` plus frontmatter `tags` (as the note view reports them). Realtime `node_*` events\' `node` payload carries `tags` too. |\n| GET | `/api/aliases` | Session or key (`read`) | `{aliases:[{alias, key_id, key_name, first_seen, last_seen, connections, actor, actor_kind}]}`: one record per API key that sent MCP `initialize`, kept in memory until the server restarts. `key_name` and `actor` are the key\'s current name (fallback: the id). |\n| GET | `/api/actors` | Session or key (`read`) | `{actors:[{actor, alias, display, events, tools, last_ip, last_ts, seen_minutes_ago}], count}`. `seen_minutes_ago` is `-1` when the actor has no events. |\n\n## Privacy\n\nPrivacy rules hide notes or folders from chosen agents (API keys). A rule has a\n`kind` (`node` or `folder`), a `path`, a `mode` (`deny`: hidden from the listed\nkeys; `allow_only`: hidden from every key except the listed ones), and a list\nof keys. Folder rules apply to everything inside the folder.\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/privacy` | Session or key (`admin`) | `{count, rules:[{id, kind, path, mode, keys:[{id, name, color}], created_at, updated_at}], agents:[{id, name, color, enabled}]}`. |\n| GET | `/api/privacy/path` | Session or key (`admin`) | The privacy state of one path: `{path, kind, own, own_rules, inherited, agents:[{id, name, color, enabled, can_see, hidden_by}], private}`. `own` is `{mode, keys}` or `null`. Query: `path`, `kind` (optional; defaults to `folder` when the path is a folder on disk, else `node`). |\n| PUT | `/api/privacy/path` | Session or key (`admin`, +CSRF) | Replaces the rule on a path. Body: `{path, kind?, mode, keys}`. `mode` defaults to `deny`; `keys` is a list of key ids (or unique key names). `deny` with no keys removes the rule. Returns the same shape as `GET`. |\n| DELETE | `/api/privacy/path` | Session or key (`admin`, +CSRF) | Removes the rule on a path. Query: `path`, `kind` (optional). Returns the same shape as `GET`. |\n\nChanges are written to the activity log and publish a `privacy_changed`\nrealtime event.\n\n## API keys, tools, and access\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/keys` | Session or key (`admin`) | `{count, keys:[{id, name, enabled, scopes, tools, prefix, created, color, revealable, uses, last_ip, used_tools}]}`. `tools` is `"*"` or a list of tool names; `revealable` says whether the secret can be shown again; `used_tools` lists recently used tools and routes. |\n| POST | `/api/keys` | Session or key (`admin`, +CSRF) | Creates a key. Body: `{name?, tools?, scopes?, color?}`. `tools` is `"*"` or a list of tool names; `scopes` a list of scope names (an empty list means the defaults). Returns `{ok, id, key, name, prefix, persisted, color, tools, scopes}`. The raw `key` is returned once. `400` for an unknown tool or scope. |\n| POST | `/api/keys/roll` | Session or key (`admin`, +CSRF) | New secret for an existing id. Body: `{id}`. Returns `{ok, id, key, prefix, persisted}`. `404` for an unknown id. |\n| POST | `/api/keys/reveal` | Session only (+CSRF) | Shows the secret of a key created or rolled from the dashboard again. Body: `{id, current}` where `current` is the owner\'s password. Returns `{ok, id, key}`. `403` for a wrong password; `429` after 5 wrong passwords (5 minute pause); `404 {error:"not_stored", message}` when the secret is not stored (for example keys created by the CLI or by OAuth). |\n| POST | `/api/keys/update` | Session or key (`admin`, +CSRF) | Body: `{id, name?, enabled?, tools?, scopes?, color?}`. `color` as `""` or `null` clears it. Returns `{ok, id, name, enabled, color, tools, scopes, persisted}`. `400` for an unknown tool or scope, `404` for an unknown id. |\n| POST | `/api/keys/delete` | Session or key (`admin`, +CSRF) | `{ok, id, persisted}`. Moves the key to the trash. Body: `{id}`. |\n| POST | `/api/keys/restore` | Session or key (`admin`, +CSRF) | `{ok, id, persisted}`. Restores a deleted key. Body: `{id}`. `404` when no deleted key has that id. |\n| GET | `/api/tools` | Session or key (`admin`) | `{tools:[{name, category, description, enabled}]}`: the MCP tool catalog with the global on/off switch of each tool. |\n| POST | `/api/tools` | Session or key (`admin`, +CSRF) | Switches a tool on or off for every caller. Body: `{name, enabled}`. Returns `{ok, name, enabled}`. `400` for an unknown tool. |\n| GET | `/api/access` | Session or key (`admin`) | `{default_allow, rules, count}`. |\n| POST | `/api/access/test` | Session or key (`admin`) | `{action, would_lock_out_caller}` for the given address or domain. Body: `{ip?, domain?}`. |\n| POST | `/api/access/rules` | Session or key (`admin`, +CSRF) | `{ok, count, persisted}`. Body: `{op, kind, value, action}`. `op` is `add` (default) or `remove`. `kind` is `ip`, `range`, `cidr`, `domain`, or `all`; `value` is required unless `kind` is `all`. `action` is `allow` or `block` (default `block`). `remove` deletes every rule matching the given `kind` and `value`; `404` when none match. |\n| GET | `/api/config` | Session or key (`read`) | `{realm, min_password_len, session_ttl, vault, version, gateway, update}`. `update` is the cached release check: `{current, latest, available, url, checked_at, state}`, `state` one of `ok`, `none` (no release published), `error`, `disabled`, `pending`. |\n\n## Settings\n\nAll settings endpoints need a signed-in browser.\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/settings` | Session only | `{user, vault_configured, vault, vault_suggested, vault_writable, stats, min_password_len, expires_in, session_ttl, session_max_age, state_dir}`. `stats` is `{notes, links, folders}` or `null` without a vault. |\n| POST | `/api/settings/password` | Session only (+CSRF) | Body: `{current, password, confirm}`. Returns `{ok, user, password_changed, revoked_sessions, persisted}`. Every other session is signed out. `400` for a short, mismatched, or unchanged password; `403` for a wrong current password (counts toward the login cooldown). |\n| POST | `/api/settings/username` | Session only (+CSRF) | Renames the account. Body: `{username, current}`. Returns `{ok, user, changed}` (plus `persisted` when changed). The username is stored lowercase. Sessions stay signed in. `400` for an invalid username, `403` for a wrong password. |\n| POST | `/api/settings/vault` | Session only (+CSRF) | Sets the vault folder and switches the running server to it. Body: `{path, create?}`. `path` must be absolute, without `..`, writable, not a system folder, and not overlap the state folder; with `create` a missing folder is created (its parent must exist). Returns `{ok, vault, created, stats}`. `400` with a message when the folder is refused. |\n| GET | `/api/settings/sessions` | Session only | `{sessions:[{id, current, source, alias, ip, user_agent, created_at, last_seen, expires_in}], count}`: live browser sessions. API keys are not sessions and never appear here. |\n| POST | `/api/settings/sessions/revoke` | Session only (+CSRF) | Signs other browsers out. Body: `{id}` or `{others:true}`. Returns `{ok, revoked}`. `400` for the current session (use logout), `404` when the session has already ended. |\n| POST | `/api/settings/sessions/rename` | Session only (+CSRF) | Names a device. Body: `{id, alias}`; an empty alias clears it. Returns `{ok, alias}`. |\n| GET | `/api/settings/sessions/activity` | Session only | `{events, count, ip, since}`: activity log entries from that session\'s IP address since it signed in, API-key entries left out, newest first, at most 200. Query: `id`. |\n\nSession `id` values are the short ids returned by `GET /api/settings/sessions`\n(a unique prefix also works). An ambiguous or malformed id is `400`.\n\n## OAuth\n\nMemora is an OAuth 2.1 authorization server for remote MCP clients. Only the\nauthorization code flow with PKCE (`S256`) is supported. The access token is a\nnew API key named after the client, with the default scopes (`mcp`, `read`,\n`write`) and every tool; it appears on the Agents page like any other key and\nis revoked by deleting or disabling that key. URLs in the metadata use\n`MEMORA_BASE_URL` when it is set, else the scheme and host of the request.\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/.well-known/oauth-protected-resource`, `/.well-known/oauth-protected-resource/mcp` | None | Protected resource metadata (RFC 9728): `{resource, authorization_servers, bearer_methods_supported, scopes_supported, resource_name}`. |\n| GET | `/.well-known/oauth-authorization-server`, `/.well-known/oauth-authorization-server/mcp`, `/.well-known/openid-configuration` | None | Authorization server metadata (RFC 8414): `issuer`, the authorization, token, and registration endpoints, supported response types (`code`), grant types (`authorization_code`, `refresh_token`), PKCE methods (`S256`), token endpoint auth methods, `scopes_supported` (`mcp`), and `client_id_metadata_document_supported: true`. |\n| POST | `/oauth/register` | None | Dynamic client registration (RFC 7591). Body: `{redirect_uris, client_name?}`. `redirect_uris` holds 1 to 10 URIs, each HTTPS or plain HTTP on `localhost`, `127.0.0.1`, or `[::1]`, without a fragment. Returns `201 {client_id, client_name, redirect_uris, client_id_issued_at, token_endpoint_auth_method, grant_types, response_types}`. `400 {error, error_description}` for invalid metadata. |\n| GET | `/oauth/authorize` | None | `302` to `/login?oauth=1&<query>`, where the sign-in page shows a consent card (after sign-in when needed). |\n| POST | `/oauth/token` | None | Form-encoded or JSON body. `grant_type=authorization_code` with `code`, `code_verifier`, `client_id` (or HTTP Basic), and optional `redirect_uri`; or `grant_type=refresh_token` with `refresh_token` and optional `client_id`. Returns `{access_token, token_type:"Bearer", refresh_token, scope:"mcp"}`. Codes are single use and expire after 10 minutes. A refresh gives the same key a new secret and a new refresh token. Errors are `400 {error, error_description}` (`invalid_request`, `invalid_grant`, `unsupported_grant_type`). |\n| GET | `/api/oauth/request` | None | What the consent card shows for an authorization request. Query: the `/oauth/authorize` query. Returns `{ok:true, client:{id, name, kind}, redirect_host, signed_in, user}` or `{ok:false, error, error_description, redirect}`. |\n| POST | `/api/oauth/approve` | Session only (+CSRF) | Body: `{query, allow}` where `query` is the authorization request query. Returns `{ok:true, redirect}`: the client\'s redirect URI with a `code` when `allow` is `true`, else with `error=access_denied`. An invalid request returns `{ok:false, error, error_description, redirect}`. `401` without a session. |\n| GET | `/api/oauth/clients` | Session or key (`admin`) | `{clients:[{client_id, name, redirect_uris, kind, created_at, fetched_at}], connections:[{key_id, client_id}]}`. `kind` is `dcr` (registered), `cimd` (metadata document), or `manual` (added by the owner). |\n| POST | `/api/oauth/clients` | Session or key (`admin`, +CSRF) | Registers a client by hand. Body: `{name?, redirect_uris}`. Returns `{ok, client}`. `400` for invalid redirect URIs. |\n| POST | `/api/oauth/clients/delete` | Session or key (`admin`, +CSRF) | Forgets a client and its refresh tokens. Body: `{client_id}`. Returns `{ok, deleted}`. Keys issued to the client stay until they are deleted. |\n\nA `client_id` may also be an HTTPS URL of a client metadata document. The\nserver fetches it (public addresses only, no redirects, at most 64 KiB), checks\nthat its `client_id` matches the URL, and caches it for 24 hours.\n\n## Logs and activity\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/logs` | Session or key (`read`) | `{range, count, events}`, newest first, each event with a local `time`. Query: `range` (for example `1d`, `7d`, `today`, `yesterday`, `all`; default `1d`), `days` (used when `range` is absent, at most 7), `since` and `until` (unix seconds; override `range`), `limit` (default 400, max 2000), `actor`, `q`. |\n| GET | `/api/logs/settings` | Session or key (`admin`) | `{max_mb, max_days, stats:{bytes, lines, oldest, newest, max_bytes, max_days}}` for the vault event log. |\n| POST | `/api/logs/settings` | Session or key (`admin`, +CSRF) | Body: `{max_mb?, max_days?}` (1 to 512 MB; 0 to 3650 days, 0 meaning no age limit). Returns the same shape as `GET`. The log is trimmed to the new limits at once. `400` for out-of-range values. |\n| GET | `/api/events` | Session or key (`read`) | `{events, count}`: the vault event log (`.events.jsonl`), oldest first, the newest `limit` entries. Query: `since` (unix seconds), `folder`, `actor` (the key name for agents), `limit` (default 100, max 2000). |\n\n### Realtime\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/ws` | Session only | WebSocket upgrade. The `Origin` must be same-origin (`403` otherwise). `503` when too many clients are connected. |\n| POST | `/_bus` | Loopback only | Publishes a JSON object (at most 64 KiB) into the event stream. Returns `{ok:true}`. `403` for callers that are not on the same machine or that come through a proxy (any forwarding header), `400` for a body that is not a JSON object, `413` for a body or event that is too large. |\n\nOn connect the server sends a `hello` event with the client count, replays the\nlast 40 stored events (each marked `replay: true`), then streams live events.\nWhen a client leaves, the others get a `presence` event with the new count.\nMessages from the client are ignored; the server pings every 30 seconds and\ncloses a connection that has been silent for 75 seconds.\n\n### `ai_activity` events\n\nEvery MCP `tools/call` publishes a `start` and an `end` event sharing `call_id`:\n\n```json\n{"type":"ai_activity","phase":"start","call_id":"c1a2b3c4d5e6-0","actor":"research-bot",\n "actor_kind":"agent","actor_id":"k_1a2b3c4d","action":"read_memory","label":"Plan/Index.md",\n "paths":["Plan/Index.md"],"_ts":1760600000.12}\n{"type":"ai_activity","phase":"end","call_id":"c1a2b3c4d5e6-0","actor":"research-bot",\n "actor_kind":"agent","actor_id":"k_1a2b3c4d","action":"read_memory","label":"Plan/Index.md",\n "paths":["Plan/Index.md"],"ok":true,"ms":2,"_ts":1760600000.12}\n```\n\n- `actor`: the API key\'s name (fallback: key id) with `actor_kind: "agent"`; for a\n browser session the username with `actor_kind: "user"`. `actor_id` is the key id (or\n the username). Node events (`node_created`, ...) from the call carry the same `actor`.\n- `action`: the tool name.\n- `paths`: vault-relative note paths from the arguments (`path`, `paths`, `from`, `to`,\n `old_path`, `new_path`, `into` of `merge_memory`, `source`/`target` of `find_path`)\n plus note paths found in the result (search hits, the created or moved note), at\n most 20, each at most 512 bytes (longer paths are dropped). Whole-vault overviews\n (`get_graph`, `list_memory`, logs, ...) add no result paths.\n- Read-only tools publish `start` after running (so it carries the result paths),\n immediately followed by `end`; mutating tools publish `start` before running and `end`\n after, with the result paths added.\n- `end` adds `ok`, `ms`, and on failure `error` (at most 200 characters). `label` is at\n most 160 characters. `_ts` is the publish time in unix seconds. `end` events are\n realtime only: they are not written to `.events.jsonl` or the replay buffer.\n\n## UI layout\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/ui/layout/{name}` | Session only | `{name, data, updated_at}`; `data` and `updated_at` are `null` if never saved. |\n| PUT | `/api/ui/layout/{name}` | Session only (+CSRF) | `{ok:true, updated_at}`. Body: `{data: <any JSON>}`. |\n\n`name` is `[a-z0-9_-]{1,40}` (else `400`). API keys get `403`. `data` is stored as\nserialized JSON of at most 512 KiB (`413` above); the request body limit is 600 KiB.\nLayouts are stored in the `ui_layout` table of `memora.db`. The web UI uses them for\n`canvas` (card positions and frames) and `graph` (pinned positions).\n\n## Pins\n\nThe owner\'s pinned notes and folders (the sidebar\'s Pinned list), shared by every\nbrowser and device of the instance.\n\n| Method | Path | Auth | Returns |\n|---|---|---|---|\n| GET | `/api/pins` | Session only | `{count, pins:[{kind, path, position, missing}]}` in display order. |\n| PUT | `/api/pins` | Session only (+CSRF) | Same as GET. Body: `{pins:[{kind, path}]}`, the whole ordered list (reorder, remove). |\n| POST | `/api/pins/pin` | Session only (+CSRF) | Same as GET. Body: `{kind, path, position?}`. Pins an existing note or folder at `position` (default: the end), or moves its pin there; `404` if it does not exist. |\n| POST | `/api/pins/unpin` | Session only (+CSRF) | Same as GET plus `removed`. Body: `{kind, path}`. |\n\n`kind` is `note` or `folder`. `path` is vault-relative as the tree shows it (notes end in\n`.md`): absolute paths, `..`, empty or hidden segments, `\\`, control characters and paths\nover 1024 characters get `400`, as do more than 200 pins. API keys get `403` (agents use\nthe MCP tools `list_pins`, `pin` and `unpin`). Bodies are limited to 256 KiB for `PUT`\nand 8 KiB for `pin`/`unpin` (`413`). `missing` is true when the path no longer exists,\nfor example after a rename outside Memora; such a pin is kept until it is removed.\n\nRenames, moves and deletes done by Memora (HTTP or MCP) rewrite or drop pins in the same\ndatabase transaction, including pins on notes and folders inside a moved folder;\nmoving an item to the trash or deleting it removes its pin, and deleting a folder\nremoves every pin under it. Every change publishes a `pins_changed` realtime event with\nno other data; open browsers reload the list. Pins are stored in the `pin` table of\n`memora.db`.\n\n## Status codes\n\n| Code | Meaning |\n|---|---|\n| 200 | Success. |\n| 201 | OAuth client registered. |\n| 202 | MCP notification accepted. |\n| 204 | `/favicon.ico`. |\n| 302 | Redirect (pages to `/login` without a session, `/login` to `/` when signed in, logout to `/login`, locked instance to `/login?locked=1`, `/oauth/authorize` to the consent page). |\n| 304 | Not modified (`/api/vault/file`, static assets). |\n| 400 | Bad request, for example a missing required field or an invalid value. |\n| 401 | Missing or invalid credentials, or a session-only endpoint called without a session. |\n| 403 | Blocked by an access rule, a CSRF origin mismatch, a missing key scope, a wrong password or setup code, or an endpoint that needs an open setup or reset window. |\n| 404 | Note, key, session, rule, or route not found; also any request for a host outside the domain list. |\n| 405 | `/mcp` called with a method other than `POST`. |\n| 408 | The request took longer than 30 seconds. |\n| 409 | No vault configured (`needs_vault: true`), or a state conflict. |\n| 413 | Body, layout, image, or event too large. |\n| 415 | `/api/vault/file` path is not an image. |\n| 423 | Instance is LOCKED. |\n| 429 | Rate limit or failed-attempt cooldown (`Retry-After` header). |\n| 500 | Internal error, for example the state database failed. |\n| 503 | UI assets are not installed, the password hashing pool is busy, or too many realtime clients. |\n',iD=`# Deployment
9732
9740
 
9733
9741
  This guide covers health checks, running Memora behind a reverse proxy, in a
9734
9742
  container, and under systemd, first-run and recovery, backups, and upgrades.
@@ -10103,6 +10111,31 @@ All notable changes to this project are documented in this file.
10103
10111
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
10104
10112
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
10105
10113
 
10114
+ ## [1.3.2] - 2026-10-20
10115
+
10116
+ ### Added
10117
+
10118
+ - \`memora-cli start\`, \`stop\` (\`--force\`), \`restart\` and \`uninstall\`, and
10119
+ \`/start\`, \`/shutdown\` (alias \`/stop\`), \`/restart\` and \`/uninstall\` in the
10120
+ console. They detect how the install runs: a systemd service is driven
10121
+ with \`systemctl\`; an npm, release zip or source install runs the server in
10122
+ the background with \`memora.pid\` and \`memora.log\` in the state folder;
10123
+ inside Docker the console prints the host commands.
10124
+ - Uninstall explains what it removes, then offers a checklist (space to
10125
+ select) to also delete the settings and accounts and the vault. Both are
10126
+ kept by default; deleting the vault needs its folder name typed, a final
10127
+ database backup is offered before the state goes, and system folders, the
10128
+ home folder and the program folder are never deleted. Without a terminal
10129
+ it needs \`--yes\` and only deletes what \`--delete-config\` and
10130
+ \`--delete-vault\` say.
10131
+ - \`/guide\` gains a "Run and manage the server" step; \`memora-cli docs manage\`
10132
+ covers it per install.
10133
+
10134
+ ### Changed
10135
+
10136
+ - The install guide's introduction names Windows and the npm and zip
10137
+ installs and leads with \`memora-cli setup\`.
10138
+
10106
10139
  ## [1.3.1] - 2026-10-20
10107
10140
 
10108
10141
  ### Added
@@ -10371,6 +10404,7 @@ First public release.
10371
10404
  - Docker image, Docker Compose file and an installer script with checksum
10372
10405
  verification.
10373
10406
 
10407
+ [1.3.2]: https://github.com/Codrihub/memora/releases/tag/v1.3.2
10374
10408
  [1.3.1]: https://github.com/Codrihub/memora/releases/tag/v1.3.1
10375
10409
  [1.3.0]: https://github.com/Codrihub/memora/releases/tag/v1.3.0
10376
10410
  [1.2.3]: https://github.com/Codrihub/memora/releases/tag/v1.2.3