@pix3/cli 1.6.0 → 1.6.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/LICENSE +201 -201
- package/README.md +788 -754
- package/dist/index.js +208 -203
- package/dist/runtime-types.json +1 -1
- package/dist/smoke/prebuilt/{chunk-J2SJVMDO.mjs → chunk-7MZGPAUK.mjs} +1 -1
- package/dist/smoke/prebuilt/chunk-7WOFGLW3.mjs +239 -0
- package/dist/smoke/prebuilt/runtime.mjs +1 -1
- package/dist/smoke/prebuilt/smoke-worker.mjs +1 -1
- package/dist/smoke/prebuilt/tree-defaults.mjs +1 -1
- package/dist/validate/prebuilt/bundle-main.js +13 -13
- package/dist/validate/prebuilt/chunk-HKG6YI6Y.js +239 -0
- package/dist/validate/prebuilt/runtime.js +1 -1
- package/kit/files/.claude/skills/pix3-nodes/SKILL.md +210 -210
- package/kit/files/.claude/skills/pix3-nodes/reference.md +32 -24
- package/kit/files/.claude/skills/pix3-scene-format/SKILL.md +238 -235
- package/kit/files/.claude/skills/pix3-scene-format/reference.md +28 -28
- package/kit/files/.claude/skills/pix3-scripts/SKILL.md +285 -281
- package/kit/files/.claude/skills/pix3-scripts/reference.md +69 -52
- package/kit/files/.claude/skills/pix3-verify/SKILL.md +298 -256
- package/kit/files/.claude/skills/pix3-verify/reference.md +21 -21
- package/kit/files/AGENTS.md +203 -203
- package/kit/files/CLAUDE.md +1 -1
- package/kit/kit.json +2 -2
- package/package.json +54 -54
- package/templates/empty-2d/files/README.md +20 -20
- package/templates/empty-2d/files/scenes/main.pix3scene +68 -68
- package/templates/empty-2d/template.yaml +7 -7
- package/templates/empty-3d/files/README.md +20 -20
- package/templates/empty-3d/files/scenes/main.pix3scene +108 -108
- package/templates/empty-3d/template.yaml +7 -7
- package/templates/idea-blank/files/README.md +22 -22
- package/templates/idea-blank/files/scenes/main.pix3scene +37 -37
- package/templates/idea-blank/template.yaml +10 -10
- package/templates/minigame-2d/files/README.md +44 -44
- package/templates/minigame-2d/files/design/tests/reachability.json +1 -1
- package/templates/minigame-2d/files/design/tests/routines/mute-music.json +44 -44
- package/templates/minigame-2d/files/scenes/main.pix3scene +84 -84
- package/templates/minigame-2d/files/scenes/menu.pix3scene +118 -118
- package/templates/minigame-2d/files/scenes/ui/settings-window.pix3scene +138 -138
- package/templates/minigame-2d/files/scripts/GameFlow.ts +133 -133
- package/templates/minigame-2d/files/scripts/MenuFlow.ts +217 -217
- package/templates/minigame-2d/files/scripts/SettingsWindow.ts +198 -198
- package/templates/minigame-2d/template.yaml +10 -10
- package/templates/playable-2d/files/README.md +30 -30
- package/templates/playable-2d/files/design/recipe.md +83 -83
- package/templates/playable-2d/files/design/tests/reachability.json +4 -4
- package/templates/playable-2d/files/design/tests/routines/intro-to-cta.json +32 -32
- package/templates/playable-2d/files/scenes/main.pix3scene +111 -111
- package/templates/playable-2d/files/scenes/ui/end-screen.pix3scene +91 -91
- package/templates/playable-2d/files/scenes/ui/intro.pix3scene +65 -65
- package/templates/playable-2d/files/scripts/GameFlow.ts +256 -256
- package/templates/playable-2d/template.yaml +9 -9
- package/templates/playable-3d/files/README.md +32 -32
- package/templates/playable-3d/files/design/recipe.md +127 -127
- package/templates/playable-3d/files/design/tests/reachability.json +4 -4
- package/templates/playable-3d/files/design/tests/routines/intro-to-cta.json +32 -32
- package/templates/playable-3d/files/scenes/main.pix3scene +230 -230
- package/templates/playable-3d/files/scenes/ui/end-screen.pix3scene +91 -91
- package/templates/playable-3d/files/scenes/ui/intro.pix3scene +65 -65
- package/templates/playable-3d/files/scripts/GameFlow.ts +309 -309
- package/templates/playable-3d/files/scripts/GameRules.ts +290 -290
- package/templates/playable-3d/files/scripts/ScoreHud.ts +113 -113
- package/templates/playable-3d/template.yaml +9 -9
- package/templates/recipe-arena-2d/files/README.md +48 -48
- package/templates/recipe-arena-2d/files/design/recipe.md +127 -127
- package/templates/recipe-arena-2d/files/scenes/main.pix3scene +292 -292
- package/templates/recipe-arena-2d/files/scenes/menu.pix3scene +100 -100
- package/templates/recipe-arena-2d/files/scenes/prefabs/hazard.pix3scene +42 -42
- package/templates/recipe-arena-2d/files/scenes/prefabs/pickup.pix3scene +45 -45
- package/templates/recipe-arena-2d/files/scenes/ui/result.pix3scene +85 -85
- package/templates/recipe-arena-2d/files/scripts/GameRules.ts +368 -368
- package/templates/recipe-arena-2d/files/scripts/MenuFlow.ts +106 -106
- package/templates/recipe-arena-2d/files/scripts/PlayerController.ts +151 -151
- package/templates/recipe-arena-2d/files/scripts/ScoreHud.ts +94 -94
- package/templates/recipe-arena-2d/files/scripts/Spawner.ts +214 -214
- package/templates/recipe-arena-2d/files/scripts/TouchRules.ts +174 -174
- package/templates/recipe-arena-2d/template.yaml +10 -10
- package/templates/recipe-blank-2d/files/README.md +61 -61
- package/templates/recipe-blank-2d/files/design/recipe.md +148 -148
- package/templates/recipe-blank-2d/files/design/tests/reachability.json +4 -4
- package/templates/recipe-blank-2d/files/design/tests/routines/restart.json +27 -27
- package/templates/recipe-blank-2d/files/scenes/main.pix3scene +224 -224
- package/templates/recipe-blank-2d/files/scenes/ui/result.pix3scene +85 -85
- package/templates/recipe-blank-2d/files/scripts/GameRules.ts +350 -350
- package/templates/recipe-blank-2d/files/scripts/ScoreHud.ts +110 -110
- package/templates/recipe-blank-2d/template.yaml +10 -10
- package/templates/recipe-bouncer-2d/files/README.md +81 -81
- package/templates/recipe-bouncer-2d/files/design/recipe.md +146 -146
- package/templates/recipe-bouncer-2d/files/scenes/main.pix3scene +615 -615
- package/templates/recipe-bouncer-2d/files/scenes/menu.pix3scene +191 -191
- package/templates/recipe-bouncer-2d/files/scenes/ui/result.pix3scene +87 -87
- package/templates/recipe-bouncer-2d/files/scripts/BallBody.ts +298 -298
- package/templates/recipe-bouncer-2d/files/scripts/GameRules.ts +377 -377
- package/templates/recipe-bouncer-2d/files/scripts/MenuFlow.ts +109 -109
- package/templates/recipe-bouncer-2d/files/scripts/PaddleController.ts +112 -112
- package/templates/recipe-bouncer-2d/files/scripts/ScoreHud.ts +94 -94
- package/templates/recipe-bouncer-2d/files/scripts/TouchRules.ts +263 -263
- package/templates/recipe-bouncer-2d/files/scripts/ball-collision.ts +307 -307
- package/templates/recipe-bouncer-2d/template.yaml +10 -10
- package/templates/recipe-grid-3d/files/README.md +22 -22
- package/templates/recipe-grid-3d/files/design/recipe.md +110 -110
- package/templates/recipe-grid-3d/files/scenes/main.pix3scene +169 -169
- package/templates/recipe-grid-3d/files/scenes/menu.pix3scene +100 -100
- package/templates/recipe-grid-3d/files/scenes/ui/result.pix3scene +105 -105
- package/templates/recipe-grid-3d/files/scripts/GridBoard.ts +319 -319
- package/templates/recipe-grid-3d/files/scripts/GridRules.ts +278 -278
- package/templates/recipe-grid-3d/files/scripts/MenuFlow.ts +106 -106
- package/templates/recipe-grid-3d/files/scripts/ScoreHud.ts +94 -94
- package/templates/recipe-grid-3d/template.yaml +10 -10
- package/templates/recipe-tapper-2d/files/README.md +39 -39
- package/templates/recipe-tapper-2d/files/design/recipe.md +132 -132
- package/templates/recipe-tapper-2d/files/design/tests/reachability.json +4 -4
- package/templates/recipe-tapper-2d/files/design/tests/routines/terminal-retry.json +23 -23
- package/templates/recipe-tapper-2d/files/scenes/main.pix3scene +269 -269
- package/templates/recipe-tapper-2d/files/scenes/menu.pix3scene +100 -100
- package/templates/recipe-tapper-2d/files/scenes/prefabs/hazard.pix3scene +42 -42
- package/templates/recipe-tapper-2d/files/scenes/prefabs/target.pix3scene +45 -45
- package/templates/recipe-tapper-2d/files/scenes/ui/result.pix3scene +85 -85
- package/templates/recipe-tapper-2d/files/scripts/GameRules.ts +368 -368
- package/templates/recipe-tapper-2d/files/scripts/MenuFlow.ts +106 -106
- package/templates/recipe-tapper-2d/files/scripts/ScoreHud.ts +94 -94
- package/templates/recipe-tapper-2d/files/scripts/Spawner.ts +214 -214
- package/templates/recipe-tapper-2d/files/scripts/TouchRules.ts +192 -192
- package/templates/recipe-tapper-2d/template.yaml +10 -10
- package/dist/smoke/prebuilt/chunk-OJXQXIIQ.mjs +0 -239
- package/dist/validate/prebuilt/chunk-BS2OZM7U.js +0 -239
|
@@ -1,239 +0,0 @@
|
|
|
1
|
-
import { createRequire as __pix3CreateRequire } from 'node:module'; const require = __pix3CreateRequire(import.meta.url);
|
|
2
|
-
import{$f as gm,Aa as jr,Ad as Bi,Ae as Mt,Ba as $p,Bd as $r,Bf as mm,Bg as Sm,Da as El,Dd as L,Ee as Jr,Eg as Zo,Gd as Kr,Ge as Ll,He as cm,Id as em,Ie as um,Jf as Fl,Kd as lt,Kg as vm,Lb as Xp,Lc as se,Lf as $o,Lg as wm,Ma as Kp,Mb as Qp,Nf as Ko,Ob as Jp,Of as _l,Pb as Il,Pd as qo,Rd as tm,Sf as fm,Td as J,Tf as zl,Ud as rm,Vd as le,Wd as Vl,Xb as Zp,Xd as Ol,Yb as Go,Yd as Ho,Zb as Ri,Zf as Zr,a as Uo,b as C,be as R,bg as ye,c as lw,ce as B,cg as Xo,d as _p,de as im,df as z,dg as Qo,ee as nm,eg as me,fc as Pe,fg as Jo,gc as Ge,ge as om,gf as Yo,gg as ym,hd as E,he as qe,id as I,ie as Xr,if as dm,jd as _,je as Vi,kd as S,lg as ei,lh as xm,m as zp,md as Rl,ne as Ct,oe as sm,of as hm,p as Up,pd as Bl,pe as Qr,pg as bm,qe as jo,qf as sr,r as xe,re as am,rf as Ve,sa as Wo,se as lm,t as st,ta as qp,u as at,ua as Hp,v as Wp,va as Ii,vf as pm,w as Gp,wa as jp,xd as ae,ya as Yp,yd as Yr}from"./chunk-6ACT6FNV.js";var H=C(de=>{"use strict";var Du=Symbol.for("yaml.alias"),Kf=Symbol.for("yaml.document"),Fs=Symbol.for("yaml.map"),Xf=Symbol.for("yaml.pair"),Nu=Symbol.for("yaml.scalar"),_s=Symbol.for("yaml.seq"),xt=Symbol.for("yaml.node.type"),$x=n=>!!n&&typeof n=="object"&&n[xt]===Du,Kx=n=>!!n&&typeof n=="object"&&n[xt]===Kf,Xx=n=>!!n&&typeof n=="object"&&n[xt]===Fs,Qx=n=>!!n&&typeof n=="object"&&n[xt]===Xf,Qf=n=>!!n&&typeof n=="object"&&n[xt]===Nu,Jx=n=>!!n&&typeof n=="object"&&n[xt]===_s;function Jf(n){if(n&&typeof n=="object")switch(n[xt]){case Fs:case _s:return!0}return!1}function Zx(n){if(n&&typeof n=="object")switch(n[xt]){case Du:case Fs:case Nu:case _s:return!0}return!1}var e0=n=>(Qf(n)||Jf(n))&&!!n.anchor;de.ALIAS=Du;de.DOC=Kf;de.MAP=Fs;de.NODE_TYPE=xt;de.PAIR=Xf;de.SCALAR=Nu;de.SEQ=_s;de.hasAnchor=e0;de.isAlias=$x;de.isCollection=Jf;de.isDocument=Kx;de.isMap=Xx;de.isNode=Zx;de.isPair=Qx;de.isScalar=Qf;de.isSeq=Jx});var dn=C(Eu=>{"use strict";var ue=H(),be=Symbol("break visit"),Zf=Symbol("skip children"),tt=Symbol("remove node");function zs(n,e){let t=eg(e);ue.isDocument(n)?hi(null,n.contents,t,Object.freeze([n]))===tt&&(n.contents=null):hi(null,n,t,Object.freeze([]))}zs.BREAK=be;zs.SKIP=Zf;zs.REMOVE=tt;function hi(n,e,t,r){let i=tg(n,e,t,r);if(ue.isNode(i)||ue.isPair(i))return rg(n,r,i),hi(n,i,t,r);if(typeof i!="symbol"){if(ue.isCollection(e)){r=Object.freeze(r.concat(e));for(let o=0;o<e.items.length;++o){let s=hi(o,e.items[o],t,r);if(typeof s=="number")o=s-1;else{if(s===be)return be;s===tt&&(e.items.splice(o,1),o-=1)}}}else if(ue.isPair(e)){r=Object.freeze(r.concat(e));let o=hi("key",e.key,t,r);if(o===be)return be;o===tt&&(e.key=null);let s=hi("value",e.value,t,r);if(s===be)return be;s===tt&&(e.value=null)}}return i}async function Us(n,e){let t=eg(e);ue.isDocument(n)?await pi(null,n.contents,t,Object.freeze([n]))===tt&&(n.contents=null):await pi(null,n,t,Object.freeze([]))}Us.BREAK=be;Us.SKIP=Zf;Us.REMOVE=tt;async function pi(n,e,t,r){let i=await tg(n,e,t,r);if(ue.isNode(i)||ue.isPair(i))return rg(n,r,i),pi(n,i,t,r);if(typeof i!="symbol"){if(ue.isCollection(e)){r=Object.freeze(r.concat(e));for(let o=0;o<e.items.length;++o){let s=await pi(o,e.items[o],t,r);if(typeof s=="number")o=s-1;else{if(s===be)return be;s===tt&&(e.items.splice(o,1),o-=1)}}}else if(ue.isPair(e)){r=Object.freeze(r.concat(e));let o=await pi("key",e.key,t,r);if(o===be)return be;o===tt&&(e.key=null);let s=await pi("value",e.value,t,r);if(s===be)return be;s===tt&&(e.value=null)}}return i}function eg(n){return typeof n=="object"&&(n.Collection||n.Node||n.Value)?Object.assign({Alias:n.Node,Map:n.Node,Scalar:n.Node,Seq:n.Node},n.Value&&{Map:n.Value,Scalar:n.Value,Seq:n.Value},n.Collection&&{Map:n.Collection,Seq:n.Collection},n):n}function tg(n,e,t,r){if(typeof t=="function")return t(n,e,r);if(ue.isMap(e))return t.Map?.(n,e,r);if(ue.isSeq(e))return t.Seq?.(n,e,r);if(ue.isPair(e))return t.Pair?.(n,e,r);if(ue.isScalar(e))return t.Scalar?.(n,e,r);if(ue.isAlias(e))return t.Alias?.(n,e,r)}function rg(n,e,t){let r=e[e.length-1];if(ue.isCollection(r))r.items[n]=t;else if(ue.isPair(r))n==="key"?r.key=t:r.value=t;else if(ue.isDocument(r))r.contents=t;else{let i=ue.isAlias(r)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}Eu.visit=zs;Eu.visitAsync=Us});var Iu=C(ng=>{"use strict";var ig=H(),t0=dn(),r0={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},i0=n=>n.replace(/[!,[\]{}]/g,e=>r0[e]),hn=class n{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},n.defaultYaml,e),this.tags=Object.assign({},n.defaultTags,t)}clone(){let e=new n(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new n(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:n.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},n.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:n.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},n.defaultTags),this.atNextDocument=!1);let r=e.trim().split(/[ \t]+/),i=r.shift();switch(i){case"%TAG":{if(r.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),r.length<2))return!1;let[o,s]=r;return this.tags[o]=s,!0}case"%YAML":{if(this.yaml.explicit=!0,r.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[o]=r;if(o==="1.1"||o==="1.2")return this.yaml.version=o,!0;{let s=/^\d+\.\d+$/.test(o);return t(6,`Unsupported YAML version ${o}`,s),!1}}default:return t(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let s=e.slice(2,-1);return s==="!"||s==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),s)}let[,r,i]=e.match(/^(.*!)([^!]*)$/s);i||t(`The ${e} tag has no suffix`);let o=this.tags[r];if(o)try{return o+decodeURIComponent(i)}catch(s){return t(String(s)),null}return r==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,r]of Object.entries(this.tags))if(e.startsWith(r))return t+i0(e.substring(r.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],r=Object.entries(this.tags),i;if(e&&r.length>0&&ig.isNode(e.contents)){let o={};t0.visit(e.contents,(s,a)=>{ig.isNode(a)&&a.tag&&(o[a.tag]=!0)}),i=Object.keys(o)}else i=[];for(let[o,s]of r)o==="!!"&&s==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(s)))&&t.push(`%TAG ${o} ${s}`);return t.join(`
|
|
3
|
-
`)}};hn.defaultYaml={explicit:!1,version:"1.2"};hn.defaultTags={"!!":"tag:yaml.org,2002:"};ng.Directives=hn});var Ws=C(pn=>{"use strict";var og=H(),n0=dn();function o0(n){if(/[\x00-\x19\s,[\]{}]/.test(n)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(n)}`;throw new Error(t)}return!0}function sg(n){let e=new Set;return n0.visit(n,{Value(t,r){r.anchor&&e.add(r.anchor)}}),e}function ag(n,e){for(let t=1;;++t){let r=`${n}${t}`;if(!e.has(r))return r}}function s0(n,e){let t=[],r=new Map,i=null;return{onAnchor:o=>{t.push(o),i??(i=sg(n));let s=ag(e,i);return i.add(s),s},setAnchors:()=>{for(let o of t){let s=r.get(o);if(typeof s=="object"&&s.anchor&&(og.isScalar(s.node)||og.isCollection(s.node)))s.node.anchor=s.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=o,a}}},sourceObjects:r}}pn.anchorIsValid=o0;pn.anchorNames=sg;pn.createNodeAnchors=s0;pn.findNewAnchor=ag});var Ru=C(lg=>{"use strict";function mn(n,e,t,r){if(r&&typeof r=="object")if(Array.isArray(r))for(let i=0,o=r.length;i<o;++i){let s=r[i],a=mn(n,r,String(i),s);a===void 0?delete r[i]:a!==s&&(r[i]=a)}else if(r instanceof Map)for(let i of Array.from(r.keys())){let o=r.get(i),s=mn(n,r,i,o);s===void 0?r.delete(i):s!==o&&r.set(i,s)}else if(r instanceof Set)for(let i of Array.from(r)){let o=mn(n,r,i,i);o===void 0?r.delete(i):o!==i&&(r.delete(i),r.add(o))}else for(let[i,o]of Object.entries(r)){let s=mn(n,r,i,o);s===void 0?delete r[i]:s!==o&&(r[i]=s)}return n.call(e,t,r)}lg.applyReviver=mn});var Ut=C(ug=>{"use strict";var a0=H();function cg(n,e,t){if(Array.isArray(n))return n.map((r,i)=>cg(r,String(i),t));if(n&&typeof n.toJSON=="function"){if(!t||!a0.hasAnchor(n))return n.toJSON(e,t);let r={aliasCount:0,count:1,res:void 0};t.anchors.set(n,r),t.onCreate=o=>{r.res=o,delete t.onCreate};let i=n.toJSON(e,t);return t.onCreate&&t.onCreate(i),i}return typeof n=="bigint"&&!t?.keep?Number(n):n}ug.toJS=cg});var Gs=C(hg=>{"use strict";var l0=Ru(),dg=H(),c0=Ut(),Bu=class{constructor(e){Object.defineProperty(this,dg.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:r,onAnchor:i,reviver:o}={}){if(!dg.isDocument(e))throw new TypeError("A document argument is required");let s={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},a=c0.toJS(this,"",s);if(typeof i=="function")for(let{count:l,res:c}of s.anchors.values())i(c,l);return typeof o=="function"?l0.applyReviver(o,{"":a},"",a):a}};hg.NodeBase=Bu});var fn=C(pg=>{"use strict";var u0=Ws(),d0=dn(),mi=H(),h0=Gs(),p0=Ut(),Vu=class extends h0.NodeBase{constructor(e){super(mi.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if(t?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let r;t?.aliasResolveCache?r=t.aliasResolveCache:(r=[],d0.visit(e,{Node:(o,s)=>{(mi.isAlias(s)||mi.hasAnchor(s))&&r.push(s)}}),t&&(t.aliasResolveCache=r));let i;for(let o of r){if(o===this)break;o.anchor===this.source&&(i=o)}return i}toJSON(e,t){if(!t)return{source:this.source};let{anchors:r,doc:i,maxAliasCount:o}=t,s=this.resolve(i,t);if(!s){let l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let a=r.get(s);if(a||(p0.toJS(s,null,t),a=r.get(s)),a?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(o>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=qs(i,s,r)),a.count*a.aliasCount>o)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return a.res}toString(e,t,r){let i=`*${this.source}`;if(e){if(u0.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let o=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(o)}if(e.implicitKey)return`${i} `}return i}};function qs(n,e,t){if(mi.isAlias(e)){let r=e.resolve(n),i=t&&r&&t.get(r);return i?i.count*i.aliasCount:0}else if(mi.isCollection(e)){let r=0;for(let i of e.items){let o=qs(n,i,t);o>r&&(r=o)}return r}else if(mi.isPair(e)){let r=qs(n,e.key,t),i=qs(n,e.value,t);return Math.max(r,i)}return 1}pg.Alias=Vu});var oe=C(Ou=>{"use strict";var m0=H(),f0=Gs(),g0=Ut(),y0=n=>!n||typeof n!="function"&&typeof n!="object",Wt=class extends f0.NodeBase{constructor(e){super(m0.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:g0.toJS(this.value,e,t)}toString(){return String(this.value)}};Wt.BLOCK_FOLDED="BLOCK_FOLDED";Wt.BLOCK_LITERAL="BLOCK_LITERAL";Wt.PLAIN="PLAIN";Wt.QUOTE_DOUBLE="QUOTE_DOUBLE";Wt.QUOTE_SINGLE="QUOTE_SINGLE";Ou.Scalar=Wt;Ou.isScalarValue=y0});var gn=C(fg=>{"use strict";var b0=fn(),Cr=H(),mg=oe(),S0="tag:yaml.org,2002:";function v0(n,e,t){if(e){let r=t.filter(o=>o.tag===e),i=r.find(o=>!o.format)??r[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return t.find(r=>r.identify?.(n)&&!r.format)}function w0(n,e,t){if(Cr.isDocument(n)&&(n=n.contents),Cr.isNode(n))return n;if(Cr.isPair(n)){let d=t.schema[Cr.MAP].createNode?.(t.schema,null,t);return d.items.push(n),d}(n instanceof String||n instanceof Number||n instanceof Boolean||typeof BigInt<"u"&&n instanceof BigInt)&&(n=n.valueOf());let{aliasDuplicateObjects:r,onAnchor:i,onTagObj:o,schema:s,sourceObjects:a}=t,l;if(r&&n&&typeof n=="object"){if(l=a.get(n),l)return l.anchor??(l.anchor=i(n)),new b0.Alias(l.anchor);l={anchor:null,node:null},a.set(n,l)}e?.startsWith("!!")&&(e=S0+e.slice(2));let c=v0(n,e,s.tags);if(!c){if(n&&typeof n.toJSON=="function"&&(n=n.toJSON()),!n||typeof n!="object"){let d=new mg.Scalar(n);return l&&(l.node=d),d}c=n instanceof Map?s[Cr.MAP]:Symbol.iterator in Object(n)?s[Cr.SEQ]:s[Cr.MAP]}o&&(o(c),delete t.onTagObj);let u=c?.createNode?c.createNode(t.schema,n,t):typeof c?.nodeClass?.from=="function"?c.nodeClass.from(t.schema,n,t):new mg.Scalar(n);return e?u.tag=e:c.default||(u.tag=c.tag),l&&(l.node=u),u}fg.createNode=w0});var js=C(Hs=>{"use strict";var x0=gn(),rt=H(),P0=Gs();function Lu(n,e,t){let r=t;for(let i=e.length-1;i>=0;--i){let o=e[i];if(typeof o=="number"&&Number.isInteger(o)&&o>=0){let s=[];s[o]=r,r=s}else r=new Map([[o,r]])}return x0.createNode(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:n,sourceObjects:new Map})}var gg=n=>n==null||typeof n=="object"&&!!n[Symbol.iterator]().next().done,Fu=class extends P0.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(r=>rt.isNode(r)||rt.isPair(r)?r.clone(e):r),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(gg(e))this.add(t);else{let[r,...i]=e,o=this.get(r,!0);if(rt.isCollection(o))o.addIn(i,t);else if(o===void 0&&this.schema)this.set(r,Lu(this.schema,i,t));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}}deleteIn(e){let[t,...r]=e;if(r.length===0)return this.delete(t);let i=this.get(t,!0);if(rt.isCollection(i))return i.deleteIn(r);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){let[r,...i]=e,o=this.get(r,!0);return i.length===0?!t&&rt.isScalar(o)?o.value:o:rt.isCollection(o)?o.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!rt.isPair(t))return!1;let r=t.value;return r==null||e&&rt.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[t,...r]=e;if(r.length===0)return this.has(t);let i=this.get(t,!0);return rt.isCollection(i)?i.hasIn(r):!1}setIn(e,t){let[r,...i]=e;if(i.length===0)this.set(r,t);else{let o=this.get(r,!0);if(rt.isCollection(o))o.setIn(i,t);else if(o===void 0&&this.schema)this.set(r,Lu(this.schema,i,t));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${i}`)}}};Hs.Collection=Fu;Hs.collectionFromPath=Lu;Hs.isEmptyPath=gg});var yn=C(Ys=>{"use strict";var k0=n=>n.replace(/^(?!$)(?: $)?/gm,"#");function _u(n,e){return/^\n+$/.test(n)?n.substring(1):e?n.replace(/^(?! *$)/gm,e):n}var A0=(n,e,t)=>n.endsWith(`
|
|
4
|
-
`)?_u(t,e):t.includes(`
|
|
5
|
-
`)?`
|
|
6
|
-
`+_u(t,e):(n.endsWith(" ")?"":" ")+t;Ys.indentComment=_u;Ys.lineComment=A0;Ys.stringifyComment=k0});var bg=C(bn=>{"use strict";var T0="flow",zu="block",$s="quoted";function C0(n,e,t="flow",{indentAtStart:r,lineWidth:i=80,minContentWidth:o=20,onFold:s,onOverflow:a}={}){if(!i||i<0)return n;i<o&&(o=0);let l=Math.max(1+o,1+i-e.length);if(n.length<=l)return n;let c=[],u={},d=i-e.length;typeof r=="number"&&(r>i-Math.max(2,o)?c.push(0):d=i-r);let h,p,f=!1,m=-1,g=-1,y=-1;t===zu&&(m=yg(n,m,e.length),m!==-1&&(d=m+l));for(let v;v=n[m+=1];){if(t===$s&&v==="\\"){switch(g=m,n[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}y=m}if(v===`
|
|
7
|
-
`)t===zu&&(m=yg(n,m,e.length)),d=m+e.length+l,h=void 0;else{if(v===" "&&p&&p!==" "&&p!==`
|
|
8
|
-
`&&p!==" "){let w=n[m+1];w&&w!==" "&&w!==`
|
|
9
|
-
`&&w!==" "&&(h=m)}if(m>=d)if(h)c.push(h),d=h+l,h=void 0;else if(t===$s){for(;p===" "||p===" ";)p=v,v=n[m+=1],f=!0;let w=m>y+1?m-2:g-1;if(u[w])return n;c.push(w),u[w]=!0,d=w+l,h=void 0}else f=!0}p=v}if(f&&a&&a(),c.length===0)return n;s&&s();let b=n.slice(0,c[0]);for(let v=0;v<c.length;++v){let w=c[v],k=c[v+1]||n.length;w===0?b=`
|
|
10
|
-
${e}${n.slice(0,k)}`:(t===$s&&u[w]&&(b+=`${n[w]}\\`),b+=`
|
|
11
|
-
${e}${n.slice(w+1,k)}`)}return b}function yg(n,e,t){let r=e,i=e+1,o=n[i];for(;o===" "||o===" ";)if(e<i+t)o=n[++e];else{do o=n[++e];while(o&&o!==`
|
|
12
|
-
`);r=e,i=e+1,o=n[i]}return r}bn.FOLD_BLOCK=zu;bn.FOLD_FLOW=T0;bn.FOLD_QUOTED=$s;bn.foldFlowLines=C0});var vn=C(Sg=>{"use strict";var Ue=oe(),Gt=bg(),Xs=(n,e)=>({indentAtStart:e?n.indent.length:n.indentAtStart,lineWidth:n.options.lineWidth,minContentWidth:n.options.minContentWidth}),Qs=n=>/^(%|---|\.\.\.)/m.test(n);function M0(n,e,t){if(!e||e<0)return!1;let r=e-t,i=n.length;if(i<=r)return!1;for(let o=0,s=0;o<i;++o)if(n[o]===`
|
|
13
|
-
`){if(o-s>r)return!0;if(s=o+1,i-s<=r)return!1}return!0}function Sn(n,e){let t=JSON.stringify(n);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:r}=e,i=e.options.doubleQuotedMinMultiLineLength,o=e.indent||(Qs(n)?" ":""),s="",a=0;for(let l=0,c=t[l];c;c=t[++l])if(c===" "&&t[l+1]==="\\"&&t[l+2]==="n"&&(s+=t.slice(a,l)+"\\ ",l+=1,a=l,c="\\"),c==="\\")switch(t[l+1]){case"u":{s+=t.slice(a,l);let u=t.substr(l+2,4);switch(u){case"0000":s+="\\0";break;case"0007":s+="\\a";break;case"000b":s+="\\v";break;case"001b":s+="\\e";break;case"0085":s+="\\N";break;case"00a0":s+="\\_";break;case"2028":s+="\\L";break;case"2029":s+="\\P";break;default:u.substr(0,2)==="00"?s+="\\x"+u.substr(2):s+=t.substr(l,6)}l+=5,a=l+1}break;case"n":if(r||t[l+2]==='"'||t.length<i)l+=1;else{for(s+=t.slice(a,l)+`
|
|
14
|
-
|
|
15
|
-
`;t[l+2]==="\\"&&t[l+3]==="n"&&t[l+4]!=='"';)s+=`
|
|
16
|
-
`,l+=2;s+=o,t[l+2]===" "&&(s+="\\"),l+=1,a=l+1}break;default:l+=1}return s=a?s+t.slice(a):t,r?s:Gt.foldFlowLines(s,o,Gt.FOLD_QUOTED,Xs(e,!1))}function Uu(n,e){if(e.options.singleQuote===!1||e.implicitKey&&n.includes(`
|
|
17
|
-
`)||/[ \t]\n|\n[ \t]/.test(n))return Sn(n,e);let t=e.indent||(Qs(n)?" ":""),r="'"+n.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
18
|
-
${t}`)+"'";return e.implicitKey?r:Gt.foldFlowLines(r,t,Gt.FOLD_FLOW,Xs(e,!1))}function fi(n,e){let{singleQuote:t}=e.options,r;if(t===!1)r=Sn;else{let i=n.includes('"'),o=n.includes("'");i&&!o?r=Uu:o&&!i?r=Sn:r=t?Uu:Sn}return r(n,e)}var Wu;try{Wu=new RegExp(`(^|(?<!
|
|
19
|
-
))
|
|
20
|
-
+(?!
|
|
21
|
-
|$)`,"g")}catch{Wu=/\n+(?!\n|$)/g}function Ks({comment:n,type:e,value:t},r,i,o){let{blockQuote:s,commentString:a,lineWidth:l}=r.options;if(!s||/\n[\t ]+$/.test(t))return fi(t,r);let c=r.indent||(r.forceBlockIndent||Qs(t)?" ":""),u=s==="literal"?!0:s==="folded"||e===Ue.Scalar.BLOCK_FOLDED?!1:e===Ue.Scalar.BLOCK_LITERAL?!0:!M0(t,l,c.length);if(!t)return u?`|
|
|
22
|
-
`:`>
|
|
23
|
-
`;let d,h;for(h=t.length;h>0;--h){let k=t[h-1];if(k!==`
|
|
24
|
-
`&&k!==" "&&k!==" ")break}let p=t.substring(h),f=p.indexOf(`
|
|
25
|
-
`);f===-1?d="-":t===p||f!==p.length-1?(d="+",o&&o()):d="",p&&(t=t.slice(0,-p.length),p[p.length-1]===`
|
|
26
|
-
`&&(p=p.slice(0,-1)),p=p.replace(Wu,`$&${c}`));let m=!1,g,y=-1;for(g=0;g<t.length;++g){let k=t[g];if(k===" ")m=!0;else if(k===`
|
|
27
|
-
`)y=g;else break}let b=t.substring(0,y<g?y+1:g);b&&(t=t.substring(b.length),b=b.replace(/\n+/g,`$&${c}`));let w=(m?c?"2":"1":"")+d;if(n&&(w+=" "+a(n.replace(/ ?[\r\n]+/g," ")),i&&i()),!u){let k=t.replace(/\n+/g,`
|
|
28
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${c}`),T=!1,N=Xs(r,!0);s!=="folded"&&e!==Ue.Scalar.BLOCK_FOLDED&&(N.onOverflow=()=>{T=!0});let A=Gt.foldFlowLines(`${b}${k}${p}`,c,Gt.FOLD_BLOCK,N);if(!T)return`>${w}
|
|
29
|
-
${c}${A}`}return t=t.replace(/\n+/g,`$&${c}`),`|${w}
|
|
30
|
-
${c}${b}${t}${p}`}function D0(n,e,t,r){let{type:i,value:o}=n,{actualString:s,implicitKey:a,indent:l,indentStep:c,inFlow:u}=e;if(a&&o.includes(`
|
|
31
|
-
`)||u&&/[[\]{},]/.test(o))return fi(o,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(o))return a||u||!o.includes(`
|
|
32
|
-
`)?fi(o,e):Ks(n,e,t,r);if(!a&&!u&&i!==Ue.Scalar.PLAIN&&o.includes(`
|
|
33
|
-
`))return Ks(n,e,t,r);if(Qs(o)){if(l==="")return e.forceBlockIndent=!0,Ks(n,e,t,r);if(a&&l===c)return fi(o,e)}let d=o.replace(/\n+/g,`$&
|
|
34
|
-
${l}`);if(s){let h=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(d),{compat:p,tags:f}=e.doc.schema;if(f.some(h)||p?.some(h))return fi(o,e)}return a?d:Gt.foldFlowLines(d,l,Gt.FOLD_FLOW,Xs(e,!1))}function N0(n,e,t,r){let{implicitKey:i,inFlow:o}=e,s=typeof n.value=="string"?n:Object.assign({},n,{value:String(n.value)}),{type:a}=n;a!==Ue.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(s.value)&&(a=Ue.Scalar.QUOTE_DOUBLE);let l=u=>{switch(u){case Ue.Scalar.BLOCK_FOLDED:case Ue.Scalar.BLOCK_LITERAL:return i||o?fi(s.value,e):Ks(s,e,t,r);case Ue.Scalar.QUOTE_DOUBLE:return Sn(s.value,e);case Ue.Scalar.QUOTE_SINGLE:return Uu(s.value,e);case Ue.Scalar.PLAIN:return D0(s,e,t,r);default:return null}},c=l(a);if(c===null){let{defaultKeyType:u,defaultStringType:d}=e.options,h=i&&u||d;if(c=l(h),c===null)throw new Error(`Unsupported default string type ${h}`)}return c}Sg.stringifyString=N0});var wn=C(Gu=>{"use strict";var E0=Ws(),qt=H(),I0=yn(),R0=vn();function B0(n,e){let t=Object.assign({blockQuote:!0,commentString:I0.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},n.schema.toStringOptions,e),r;switch(t.collectionStyle){case"block":r=!1;break;case"flow":r=!0;break;default:r=null}return{anchors:new Set,doc:n,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:r,options:t}}function V0(n,e){if(e.tag){let i=n.filter(o=>o.tag===e.tag);if(i.length>0)return i.find(o=>o.format===e.format)??i[0]}let t,r;if(qt.isScalar(e)){r=e.value;let i=n.filter(o=>o.identify?.(r));if(i.length>1){let o=i.filter(s=>s.test);o.length>0&&(i=o)}t=i.find(o=>o.format===e.format)??i.find(o=>!o.format)}else r=e,t=n.find(i=>i.nodeClass&&r instanceof i.nodeClass);if(!t){let i=r?.constructor?.name??(r===null?"null":typeof r);throw new Error(`Tag not resolved for ${i} value`)}return t}function O0(n,e,{anchors:t,doc:r}){if(!r.directives)return"";let i=[],o=(qt.isScalar(n)||qt.isCollection(n))&&n.anchor;o&&E0.anchorIsValid(o)&&(t.add(o),i.push(`&${o}`));let s=n.tag??(e.default?null:e.tag);return s&&i.push(r.directives.tagString(s)),i.join(" ")}function L0(n,e,t,r){if(qt.isPair(n))return n.toString(e,t,r);if(qt.isAlias(n)){if(e.doc.directives)return n.toString(e);if(e.resolvedAliases?.has(n))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(n):e.resolvedAliases=new Set([n]),n=n.resolve(e.doc)}let i,o=qt.isNode(n)?n:e.doc.createNode(n,{onTagObj:l=>i=l});i??(i=V0(e.doc.schema.tags,o));let s=O0(o,i,e);s.length>0&&(e.indentAtStart=(e.indentAtStart??0)+s.length+1);let a=typeof i.stringify=="function"?i.stringify(o,e,t,r):qt.isScalar(o)?R0.stringifyString(o,e,t,r):o.toString(e,t,r);return s?qt.isScalar(o)||a[0]==="{"||a[0]==="["?`${s} ${a}`:`${s}
|
|
35
|
-
${e.indent}${a}`:a}Gu.createStringifyContext=B0;Gu.stringify=L0});var Pg=C(xg=>{"use strict";var Pt=H(),vg=oe(),wg=wn(),xn=yn();function F0({key:n,value:e},t,r,i){let{allNullValues:o,doc:s,indent:a,indentStep:l,options:{commentString:c,indentSeq:u,simpleKeys:d}}=t,h=Pt.isNode(n)&&n.comment||null;if(d){if(h)throw new Error("With simple keys, key nodes cannot have comments");if(Pt.isCollection(n)||!Pt.isNode(n)&&typeof n=="object"){let N="With simple keys, collection cannot be used as a key value";throw new Error(N)}}let p=!d&&(!n||h&&e==null&&!t.inFlow||Pt.isCollection(n)||(Pt.isScalar(n)?n.type===vg.Scalar.BLOCK_FOLDED||n.type===vg.Scalar.BLOCK_LITERAL:typeof n=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(d||!o),indent:a+l});let f=!1,m=!1,g=wg.stringify(n,t,()=>f=!0,()=>m=!0);if(!p&&!t.inFlow&&g.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(t.inFlow){if(o||e==null)return f&&r&&r(),g===""?"?":p?`? ${g}`:g}else if(o&&!d||e==null&&p)return g=`? ${g}`,h&&!f?g+=xn.lineComment(g,t.indent,c(h)):m&&i&&i(),g;f&&(h=null),p?(h&&(g+=xn.lineComment(g,t.indent,c(h))),g=`? ${g}
|
|
36
|
-
${a}:`):(g=`${g}:`,h&&(g+=xn.lineComment(g,t.indent,c(h))));let y,b,v;Pt.isNode(e)?(y=!!e.spaceBefore,b=e.commentBefore,v=e.comment):(y=!1,b=null,v=null,e&&typeof e=="object"&&(e=s.createNode(e))),t.implicitKey=!1,!p&&!h&&Pt.isScalar(e)&&(t.indentAtStart=g.length+1),m=!1,!u&&l.length>=2&&!t.inFlow&&!p&&Pt.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let w=!1,k=wg.stringify(e,t,()=>w=!0,()=>m=!0),T=" ";if(h||y||b){if(T=y?`
|
|
37
|
-
`:"",b){let N=c(b);T+=`
|
|
38
|
-
${xn.indentComment(N,t.indent)}`}k===""&&!t.inFlow?T===`
|
|
39
|
-
`&&v&&(T=`
|
|
40
|
-
|
|
41
|
-
`):T+=`
|
|
42
|
-
${t.indent}`}else if(!p&&Pt.isCollection(e)){let N=k[0],A=k.indexOf(`
|
|
43
|
-
`),F=A!==-1,Z=t.inFlow??e.flow??e.items.length===0;if(F||!Z){let ne=!1;if(F&&(N==="&"||N==="!")){let re=k.indexOf(" ");N==="&"&&re!==-1&&re<A&&k[re+1]==="!"&&(re=k.indexOf(" ",re+1)),(re===-1||A<re)&&(ne=!0)}ne||(T=`
|
|
44
|
-
${t.indent}`)}}else(k===""||k[0]===`
|
|
45
|
-
`)&&(T="");return g+=T+k,t.inFlow?w&&r&&r():v&&!w?g+=xn.lineComment(g,t.indent,c(v)):m&&i&&i(),g}xg.stringifyPair=F0});var Hu=C(qu=>{"use strict";var kg=Uo("process");function _0(n,...e){n==="debug"&&console.log(...e)}function z0(n,e){(n==="debug"||n==="warn")&&(typeof kg.emitWarning=="function"?kg.emitWarning(e):console.warn(e))}qu.debug=_0;qu.warn=z0});var ra=C(ta=>{"use strict";var ea=H(),Ag=oe(),Js="<<",Zs={identify:n=>n===Js||typeof n=="symbol"&&n.description===Js,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Ag.Scalar(Symbol(Js)),{addToJSMap:Tg}),stringify:()=>Js},U0=(n,e)=>(Zs.identify(e)||ea.isScalar(e)&&(!e.type||e.type===Ag.Scalar.PLAIN)&&Zs.identify(e.value))&&n?.doc.schema.tags.some(t=>t.tag===Zs.tag&&t.default);function Tg(n,e,t){let r=Cg(n,t);if(ea.isSeq(r))for(let i of r.items)ju(n,e,i);else if(Array.isArray(r))for(let i of r)ju(n,e,i);else ju(n,e,r)}function ju(n,e,t){let r=Cg(n,t);if(!ea.isMap(r))throw new Error("Merge sources must be maps or map aliases");let i=r.toJSON(null,n,Map);for(let[o,s]of i)e instanceof Map?e.has(o)||e.set(o,s):e instanceof Set?e.add(o):Object.prototype.hasOwnProperty.call(e,o)||Object.defineProperty(e,o,{value:s,writable:!0,enumerable:!0,configurable:!0});return e}function Cg(n,e){return n&&ea.isAlias(e)?e.resolve(n.doc,n):e}ta.addMergeToJSMap=Tg;ta.isMergeKey=U0;ta.merge=Zs});var $u=C(Ng=>{"use strict";var W0=Hu(),Mg=ra(),G0=wn(),Dg=H(),Yu=Ut();function q0(n,e,{key:t,value:r}){if(Dg.isNode(t)&&t.addToJSMap)t.addToJSMap(n,e,r);else if(Mg.isMergeKey(n,t))Mg.addMergeToJSMap(n,e,r);else{let i=Yu.toJS(t,"",n);if(e instanceof Map)e.set(i,Yu.toJS(r,i,n));else if(e instanceof Set)e.add(i);else{let o=H0(t,i,n),s=Yu.toJS(r,o,n);o in e?Object.defineProperty(e,o,{value:s,writable:!0,enumerable:!0,configurable:!0}):e[o]=s}}return e}function H0(n,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(Dg.isNode(n)&&t?.doc){let r=G0.createStringifyContext(t.doc,{});r.anchors=new Set;for(let o of t.anchors.keys())r.anchors.add(o.anchor);r.inFlow=!0,r.inStringifyKey=!0;let i=n.toString(r);if(!t.mapKeyWarned){let o=JSON.stringify(i);o.length>40&&(o=o.substring(0,36)+'..."'),W0.warn(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${o}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return i}return JSON.stringify(e)}Ng.addPairToJSMap=q0});var Ht=C(Ku=>{"use strict";var Eg=gn(),j0=Pg(),Y0=$u(),ia=H();function $0(n,e,t){let r=Eg.createNode(n,void 0,t),i=Eg.createNode(e,void 0,t);return new na(r,i)}var na=class n{constructor(e,t=null){Object.defineProperty(this,ia.NODE_TYPE,{value:ia.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:r}=this;return ia.isNode(t)&&(t=t.clone(e)),ia.isNode(r)&&(r=r.clone(e)),new n(t,r)}toJSON(e,t){let r=t?.mapAsMap?new Map:{};return Y0.addPairToJSMap(t,r,this)}toString(e,t,r){return e?.doc?j0.stringifyPair(this,e,t,r):JSON.stringify(this)}};Ku.Pair=na;Ku.createPair=$0});var Xu=C(Rg=>{"use strict";var Mr=H(),Ig=wn(),oa=yn();function K0(n,e,t){return(e.inFlow??n.flow?Q0:X0)(n,e,t)}function X0({comment:n,items:e},t,{blockItemPrefix:r,flowChars:i,itemIndent:o,onChompKeep:s,onComment:a}){let{indent:l,options:{commentString:c}}=t,u=Object.assign({},t,{indent:o,type:null}),d=!1,h=[];for(let f=0;f<e.length;++f){let m=e[f],g=null;if(Mr.isNode(m))!d&&m.spaceBefore&&h.push(""),sa(t,h,m.commentBefore,d),m.comment&&(g=m.comment);else if(Mr.isPair(m)){let b=Mr.isNode(m.key)?m.key:null;b&&(!d&&b.spaceBefore&&h.push(""),sa(t,h,b.commentBefore,d))}d=!1;let y=Ig.stringify(m,u,()=>g=null,()=>d=!0);g&&(y+=oa.lineComment(y,o,c(g))),d&&g&&(d=!1),h.push(r+y)}let p;if(h.length===0)p=i.start+i.end;else{p=h[0];for(let f=1;f<h.length;++f){let m=h[f];p+=m?`
|
|
46
|
-
${l}${m}`:`
|
|
47
|
-
`}}return n?(p+=`
|
|
48
|
-
`+oa.indentComment(c(n),l),a&&a()):d&&s&&s(),p}function Q0({items:n},e,{flowChars:t,itemIndent:r}){let{indent:i,indentStep:o,flowCollectionPadding:s,options:{commentString:a}}=e;r+=o;let l=Object.assign({},e,{indent:r,inFlow:!0,type:null}),c=!1,u=0,d=[];for(let f=0;f<n.length;++f){let m=n[f],g=null;if(Mr.isNode(m))m.spaceBefore&&d.push(""),sa(e,d,m.commentBefore,!1),m.comment&&(g=m.comment);else if(Mr.isPair(m)){let b=Mr.isNode(m.key)?m.key:null;b&&(b.spaceBefore&&d.push(""),sa(e,d,b.commentBefore,!1),b.comment&&(c=!0));let v=Mr.isNode(m.value)?m.value:null;v?(v.comment&&(g=v.comment),v.commentBefore&&(c=!0)):m.value==null&&b?.comment&&(g=b.comment)}g&&(c=!0);let y=Ig.stringify(m,l,()=>g=null);c||(c=d.length>u||y.includes(`
|
|
49
|
-
`)),f<n.length-1?y+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(c||(c=d.reduce((b,v)=>b+v.length+2,2)+(y.length+2)>e.options.lineWidth)),c&&(y+=",")),g&&(y+=oa.lineComment(y,r,a(g))),d.push(y),u=d.length}let{start:h,end:p}=t;if(d.length===0)return h+p;if(!c){let f=d.reduce((m,g)=>m+g.length+2,2);c=e.options.lineWidth>0&&f>e.options.lineWidth}if(c){let f=h;for(let m of d)f+=m?`
|
|
50
|
-
${o}${i}${m}`:`
|
|
51
|
-
`;return`${f}
|
|
52
|
-
${i}${p}`}else return`${h}${s}${d.join(" ")}${s}${p}`}function sa({indent:n,options:{commentString:e}},t,r,i){if(r&&i&&(r=r.replace(/^\n+/,"")),r){let o=oa.indentComment(e(r),n);t.push(o.trimStart())}}Rg.stringifyCollection=K0});var Yt=C(Ju=>{"use strict";var J0=Xu(),Z0=$u(),eP=js(),jt=H(),aa=Ht(),tP=oe();function Pn(n,e){let t=jt.isScalar(e)?e.value:e;for(let r of n)if(jt.isPair(r)&&(r.key===e||r.key===t||jt.isScalar(r.key)&&r.key.value===t))return r}var Qu=class extends eP.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(jt.MAP,e),this.items=[]}static from(e,t,r){let{keepUndefined:i,replacer:o}=r,s=new this(e),a=(l,c)=>{if(typeof o=="function")c=o.call(t,l,c);else if(Array.isArray(o)&&!o.includes(l))return;(c!==void 0||i)&&s.items.push(aa.createPair(l,c,r))};if(t instanceof Map)for(let[l,c]of t)a(l,c);else if(t&&typeof t=="object")for(let l of Object.keys(t))a(l,t[l]);return typeof e.sortMapEntries=="function"&&s.items.sort(e.sortMapEntries),s}add(e,t){let r;jt.isPair(e)?r=e:!e||typeof e!="object"||!("key"in e)?r=new aa.Pair(e,e?.value):r=new aa.Pair(e.key,e.value);let i=Pn(this.items,r.key),o=this.schema?.sortMapEntries;if(i){if(!t)throw new Error(`Key ${r.key} already set`);jt.isScalar(i.value)&&tP.isScalarValue(r.value)?i.value.value=r.value:i.value=r.value}else if(o){let s=this.items.findIndex(a=>o(r,a)<0);s===-1?this.items.push(r):this.items.splice(s,0,r)}else this.items.push(r)}delete(e){let t=Pn(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let i=Pn(this.items,e)?.value;return(!t&&jt.isScalar(i)?i.value:i)??void 0}has(e){return!!Pn(this.items,e)}set(e,t){this.add(new aa.Pair(e,t),!0)}toJSON(e,t,r){let i=r?new r:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(i);for(let o of this.items)Z0.addPairToJSMap(t,i,o);return i}toString(e,t,r){if(!e)return JSON.stringify(this);for(let i of this.items)if(!jt.isPair(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),J0.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:r,onComment:t})}};Ju.YAMLMap=Qu;Ju.findPair=Pn});var gi=C(Vg=>{"use strict";var rP=H(),Bg=Yt(),iP={collection:"map",default:!0,nodeClass:Bg.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(n,e){return rP.isMap(n)||e("Expected a mapping for this tag"),n},createNode:(n,e,t)=>Bg.YAMLMap.from(n,e,t)};Vg.map=iP});var $t=C(Og=>{"use strict";var nP=gn(),oP=Xu(),sP=js(),ca=H(),aP=oe(),lP=Ut(),Zu=class extends sP.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(ca.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=la(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let r=la(e);if(typeof r!="number")return;let i=this.items[r];return!t&&ca.isScalar(i)?i.value:i}has(e){let t=la(e);return typeof t=="number"&&t<this.items.length}set(e,t){let r=la(e);if(typeof r!="number")throw new Error(`Expected a valid index, not ${e}.`);let i=this.items[r];ca.isScalar(i)&&aP.isScalarValue(t)?i.value=t:this.items[r]=t}toJSON(e,t){let r=[];t?.onCreate&&t.onCreate(r);let i=0;for(let o of this.items)r.push(lP.toJS(o,String(i++),t));return r}toString(e,t,r){return e?oP.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:r,onComment:t}):JSON.stringify(this)}static from(e,t,r){let{replacer:i}=r,o=new this(e);if(t&&Symbol.iterator in Object(t)){let s=0;for(let a of t){if(typeof i=="function"){let l=t instanceof Set?a:String(s++);a=i.call(t,l,a)}o.items.push(nP.createNode(a,void 0,r))}}return o}};function la(n){let e=ca.isScalar(n)?n.value:n;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}Og.YAMLSeq=Zu});var yi=C(Fg=>{"use strict";var cP=H(),Lg=$t(),uP={collection:"seq",default:!0,nodeClass:Lg.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(n,e){return cP.isSeq(n)||e("Expected a sequence for this tag"),n},createNode:(n,e,t)=>Lg.YAMLSeq.from(n,e,t)};Fg.seq=uP});var kn=C(_g=>{"use strict";var dP=vn(),hP={identify:n=>typeof n=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:n=>n,stringify(n,e,t,r){return e=Object.assign({actualString:!0},e),dP.stringifyString(n,e,t,r)}};_g.string=hP});var ua=C(Wg=>{"use strict";var zg=oe(),Ug={identify:n=>n==null,createNode:()=>new zg.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new zg.Scalar(null),stringify:({source:n},e)=>typeof n=="string"&&Ug.test.test(n)?n:e.options.nullStr};Wg.nullTag=Ug});var ed=C(qg=>{"use strict";var pP=oe(),Gg={identify:n=>typeof n=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:n=>new pP.Scalar(n[0]==="t"||n[0]==="T"),stringify({source:n,value:e},t){if(n&&Gg.test.test(n)){let r=n[0]==="t"||n[0]==="T";if(e===r)return n}return e?t.options.trueStr:t.options.falseStr}};qg.boolTag=Gg});var bi=C(Hg=>{"use strict";function mP({format:n,minFractionDigits:e,tag:t,value:r}){if(typeof r=="bigint")return String(r);let i=typeof r=="number"?r:Number(r);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let o=Object.is(r,-0)?"-0":JSON.stringify(r);if(!n&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^-?\d/.test(o)&&!o.includes("e")){let s=o.indexOf(".");s<0&&(s=o.length,o+=".");let a=e-(o.length-s-1);for(;a-- >0;)o+="0"}return o}Hg.stringifyNumber=mP});var rd=C(da=>{"use strict";var fP=oe(),td=bi(),gP={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:n=>n.slice(-3).toLowerCase()==="nan"?NaN:n[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:td.stringifyNumber},yP={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:n=>parseFloat(n),stringify(n){let e=Number(n.value);return isFinite(e)?e.toExponential():td.stringifyNumber(n)}},bP={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(n){let e=new fP.Scalar(parseFloat(n)),t=n.indexOf(".");return t!==-1&&n[n.length-1]==="0"&&(e.minFractionDigits=n.length-t-1),e},stringify:td.stringifyNumber};da.float=bP;da.floatExp=yP;da.floatNaN=gP});var nd=C(pa=>{"use strict";var jg=bi(),ha=n=>typeof n=="bigint"||Number.isInteger(n),id=(n,e,t,{intAsBigInt:r})=>r?BigInt(n):parseInt(n.substring(e),t);function Yg(n,e,t){let{value:r}=n;return ha(r)&&r>=0?t+r.toString(e):jg.stringifyNumber(n)}var SP={identify:n=>ha(n)&&n>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(n,e,t)=>id(n,2,8,t),stringify:n=>Yg(n,8,"0o")},vP={identify:ha,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(n,e,t)=>id(n,0,10,t),stringify:jg.stringifyNumber},wP={identify:n=>ha(n)&&n>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(n,e,t)=>id(n,2,16,t),stringify:n=>Yg(n,16,"0x")};pa.int=vP;pa.intHex=wP;pa.intOct=SP});var Kg=C($g=>{"use strict";var xP=gi(),PP=ua(),kP=yi(),AP=kn(),TP=ed(),od=rd(),sd=nd(),CP=[xP.map,kP.seq,AP.string,PP.nullTag,TP.boolTag,sd.intOct,sd.int,sd.intHex,od.floatNaN,od.floatExp,od.float];$g.schema=CP});var Jg=C(Qg=>{"use strict";var MP=oe(),DP=gi(),NP=yi();function Xg(n){return typeof n=="bigint"||Number.isInteger(n)}var ma=({value:n})=>JSON.stringify(n),EP=[{identify:n=>typeof n=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:n=>n,stringify:ma},{identify:n=>n==null,createNode:()=>new MP.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:ma},{identify:n=>typeof n=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:n=>n==="true",stringify:ma},{identify:Xg,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(n,e,{intAsBigInt:t})=>t?BigInt(n):parseInt(n,10),stringify:({value:n})=>Xg(n)?n.toString():JSON.stringify(n)},{identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:n=>parseFloat(n),stringify:ma}],IP={default:!0,tag:"",test:/^/,resolve(n,e){return e(`Unresolved plain scalar ${JSON.stringify(n)}`),n}},RP=[DP.map,NP.seq].concat(EP,IP);Qg.schema=RP});var ld=C(Zg=>{"use strict";var An=Uo("buffer"),ad=oe(),BP=vn(),VP={identify:n=>n instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(n,e){if(typeof An.Buffer=="function")return An.Buffer.from(n,"base64");if(typeof atob=="function"){let t=atob(n.replace(/[\n\r]/g,"")),r=new Uint8Array(t.length);for(let i=0;i<t.length;++i)r[i]=t.charCodeAt(i);return r}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),n},stringify({comment:n,type:e,value:t},r,i,o){if(!t)return"";let s=t,a;if(typeof An.Buffer=="function")a=s instanceof An.Buffer?s.toString("base64"):An.Buffer.from(s.buffer).toString("base64");else if(typeof btoa=="function"){let l="";for(let c=0;c<s.length;++c)l+=String.fromCharCode(s[c]);a=btoa(l)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=ad.Scalar.BLOCK_LITERAL),e!==ad.Scalar.QUOTE_DOUBLE){let l=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),c=Math.ceil(a.length/l),u=new Array(c);for(let d=0,h=0;d<c;++d,h+=l)u[d]=a.substr(h,l);a=u.join(e===ad.Scalar.BLOCK_LITERAL?`
|
|
53
|
-
`:" ")}return BP.stringifyString({comment:n,type:e,value:a},r,i,o)}};Zg.binary=VP});var ya=C(ga=>{"use strict";var fa=H(),cd=Ht(),OP=oe(),LP=$t();function ey(n,e){if(fa.isSeq(n))for(let t=0;t<n.items.length;++t){let r=n.items[t];if(!fa.isPair(r)){if(fa.isMap(r)){r.items.length>1&&e("Each pair must have its own sequence indicator");let i=r.items[0]||new cd.Pair(new OP.Scalar(null));if(r.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${r.commentBefore}
|
|
54
|
-
${i.key.commentBefore}`:r.commentBefore),r.comment){let o=i.value??i.key;o.comment=o.comment?`${r.comment}
|
|
55
|
-
${o.comment}`:r.comment}r=i}n.items[t]=fa.isPair(r)?r:new cd.Pair(r)}}else e("Expected a sequence for this tag");return n}function ty(n,e,t){let{replacer:r}=t,i=new LP.YAMLSeq(n);i.tag="tag:yaml.org,2002:pairs";let o=0;if(e&&Symbol.iterator in Object(e))for(let s of e){typeof r=="function"&&(s=r.call(e,String(o++),s));let a,l;if(Array.isArray(s))if(s.length===2)a=s[0],l=s[1];else throw new TypeError(`Expected [key, value] tuple: ${s}`);else if(s&&s instanceof Object){let c=Object.keys(s);if(c.length===1)a=c[0],l=s[a];else throw new TypeError(`Expected tuple with one key, not ${c.length} keys`)}else a=s;i.items.push(cd.createPair(a,l,t))}return i}var FP={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ey,createNode:ty};ga.createPairs=ty;ga.pairs=FP;ga.resolvePairs=ey});var hd=C(dd=>{"use strict";var ry=H(),ud=Ut(),Tn=Yt(),_P=$t(),iy=ya(),Dr=class n extends _P.YAMLSeq{constructor(){super(),this.add=Tn.YAMLMap.prototype.add.bind(this),this.delete=Tn.YAMLMap.prototype.delete.bind(this),this.get=Tn.YAMLMap.prototype.get.bind(this),this.has=Tn.YAMLMap.prototype.has.bind(this),this.set=Tn.YAMLMap.prototype.set.bind(this),this.tag=n.tag}toJSON(e,t){if(!t)return super.toJSON(e);let r=new Map;t?.onCreate&&t.onCreate(r);for(let i of this.items){let o,s;if(ry.isPair(i)?(o=ud.toJS(i.key,"",t),s=ud.toJS(i.value,o,t)):o=ud.toJS(i,"",t),r.has(o))throw new Error("Ordered maps must not include duplicate keys");r.set(o,s)}return r}static from(e,t,r){let i=iy.createPairs(e,t,r),o=new this;return o.items=i.items,o}};Dr.tag="tag:yaml.org,2002:omap";var zP={collection:"seq",identify:n=>n instanceof Map,nodeClass:Dr,default:!1,tag:"tag:yaml.org,2002:omap",resolve(n,e){let t=iy.resolvePairs(n,e),r=[];for(let{key:i}of t.items)ry.isScalar(i)&&(r.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):r.push(i.value));return Object.assign(new Dr,t)},createNode:(n,e,t)=>Dr.from(n,e,t)};dd.YAMLOMap=Dr;dd.omap=zP});var ly=C(pd=>{"use strict";var ny=oe();function oy({value:n,source:e},t){return e&&(n?sy:ay).test.test(e)?e:n?t.options.trueStr:t.options.falseStr}var sy={identify:n=>n===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new ny.Scalar(!0),stringify:oy},ay={identify:n=>n===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new ny.Scalar(!1),stringify:oy};pd.falseTag=ay;pd.trueTag=sy});var cy=C(ba=>{"use strict";var UP=oe(),md=bi(),WP={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:n=>n.slice(-3).toLowerCase()==="nan"?NaN:n[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:md.stringifyNumber},GP={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:n=>parseFloat(n.replace(/_/g,"")),stringify(n){let e=Number(n.value);return isFinite(e)?e.toExponential():md.stringifyNumber(n)}},qP={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(n){let e=new UP.Scalar(parseFloat(n.replace(/_/g,""))),t=n.indexOf(".");if(t!==-1){let r=n.substring(t+1).replace(/_/g,"");r[r.length-1]==="0"&&(e.minFractionDigits=r.length)}return e},stringify:md.stringifyNumber};ba.float=qP;ba.floatExp=GP;ba.floatNaN=WP});var dy=C(Mn=>{"use strict";var uy=bi(),Cn=n=>typeof n=="bigint"||Number.isInteger(n);function Sa(n,e,t,{intAsBigInt:r}){let i=n[0];if((i==="-"||i==="+")&&(e+=1),n=n.substring(e).replace(/_/g,""),r){switch(t){case 2:n=`0b${n}`;break;case 8:n=`0o${n}`;break;case 16:n=`0x${n}`;break}let s=BigInt(n);return i==="-"?BigInt(-1)*s:s}let o=parseInt(n,t);return i==="-"?-1*o:o}function fd(n,e,t){let{value:r}=n;if(Cn(r)){let i=r.toString(e);return r<0?"-"+t+i.substr(1):t+i}return uy.stringifyNumber(n)}var HP={identify:Cn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(n,e,t)=>Sa(n,2,2,t),stringify:n=>fd(n,2,"0b")},jP={identify:Cn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(n,e,t)=>Sa(n,1,8,t),stringify:n=>fd(n,8,"0")},YP={identify:Cn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(n,e,t)=>Sa(n,0,10,t),stringify:uy.stringifyNumber},$P={identify:Cn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(n,e,t)=>Sa(n,2,16,t),stringify:n=>fd(n,16,"0x")};Mn.int=YP;Mn.intBin=HP;Mn.intHex=$P;Mn.intOct=jP});var yd=C(gd=>{"use strict";var xa=H(),va=Ht(),wa=Yt(),Nr=class n extends wa.YAMLMap{constructor(e){super(e),this.tag=n.tag}add(e){let t;xa.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new va.Pair(e.key,null):t=new va.Pair(e,null),wa.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let r=wa.findPair(this.items,e);return!t&&xa.isPair(r)?xa.isScalar(r.key)?r.key.value:r.key:r}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let r=wa.findPair(this.items,e);r&&!t?this.items.splice(this.items.indexOf(r),1):!r&&t&&this.items.push(new va.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,r);throw new Error("Set items must all have null values")}static from(e,t,r){let{replacer:i}=r,o=new this(e);if(t&&Symbol.iterator in Object(t))for(let s of t)typeof i=="function"&&(s=i.call(t,s,s)),o.items.push(va.createPair(s,null,r));return o}};Nr.tag="tag:yaml.org,2002:set";var KP={collection:"map",identify:n=>n instanceof Set,nodeClass:Nr,default:!1,tag:"tag:yaml.org,2002:set",createNode:(n,e,t)=>Nr.from(n,e,t),resolve(n,e){if(xa.isMap(n)){if(n.hasAllNullValues(!0))return Object.assign(new Nr,n);e("Set items must all have null values")}else e("Expected a mapping for this tag");return n}};gd.YAMLSet=Nr;gd.set=KP});var Sd=C(Pa=>{"use strict";var XP=bi();function bd(n,e){let t=n[0],r=t==="-"||t==="+"?n.substring(1):n,i=s=>e?BigInt(s):Number(s),o=r.replace(/_/g,"").split(":").reduce((s,a)=>s*i(60)+i(a),i(0));return t==="-"?i(-1)*o:o}function hy(n){let{value:e}=n,t=s=>s;if(typeof e=="bigint")t=s=>BigInt(s);else if(isNaN(e)||!isFinite(e))return XP.stringifyNumber(n);let r="";e<0&&(r="-",e*=t(-1));let i=t(60),o=[e%i];return e<60?o.unshift(0):(e=(e-o[0])/i,o.unshift(e%i),e>=60&&(e=(e-o[0])/i,o.unshift(e))),r+o.map(s=>String(s).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var QP={identify:n=>typeof n=="bigint"||Number.isInteger(n),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(n,e,{intAsBigInt:t})=>bd(n,t),stringify:hy},JP={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:n=>bd(n,!1),stringify:hy},py={identify:n=>n instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(n){let e=n.match(py.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,r,i,o,s,a]=e.map(Number),l=e[7]?Number((e[7]+"00").substr(1,3)):0,c=Date.UTC(t,r-1,i,o||0,s||0,a||0,l),u=e[8];if(u&&u!=="Z"){let d=bd(u,!1);Math.abs(d)<30&&(d*=60),c-=6e4*d}return new Date(c)},stringify:({value:n})=>n?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Pa.floatTime=JP;Pa.intTime=QP;Pa.timestamp=py});var gy=C(fy=>{"use strict";var ZP=gi(),ek=ua(),tk=yi(),rk=kn(),ik=ld(),my=ly(),vd=cy(),ka=dy(),nk=ra(),ok=hd(),sk=ya(),ak=yd(),wd=Sd(),lk=[ZP.map,tk.seq,rk.string,ek.nullTag,my.trueTag,my.falseTag,ka.intBin,ka.intOct,ka.int,ka.intHex,vd.floatNaN,vd.floatExp,vd.float,ik.binary,nk.merge,ok.omap,sk.pairs,ak.set,wd.intTime,wd.floatTime,wd.timestamp];fy.schema=lk});var Ty=C(kd=>{"use strict";var vy=gi(),ck=ua(),wy=yi(),uk=kn(),dk=ed(),xd=rd(),Pd=nd(),hk=Kg(),pk=Jg(),xy=ld(),Dn=ra(),Py=hd(),ky=ya(),yy=gy(),Ay=yd(),Aa=Sd(),by=new Map([["core",hk.schema],["failsafe",[vy.map,wy.seq,uk.string]],["json",pk.schema],["yaml11",yy.schema],["yaml-1.1",yy.schema]]),Sy={binary:xy.binary,bool:dk.boolTag,float:xd.float,floatExp:xd.floatExp,floatNaN:xd.floatNaN,floatTime:Aa.floatTime,int:Pd.int,intHex:Pd.intHex,intOct:Pd.intOct,intTime:Aa.intTime,map:vy.map,merge:Dn.merge,null:ck.nullTag,omap:Py.omap,pairs:ky.pairs,seq:wy.seq,set:Ay.set,timestamp:Aa.timestamp},mk={"tag:yaml.org,2002:binary":xy.binary,"tag:yaml.org,2002:merge":Dn.merge,"tag:yaml.org,2002:omap":Py.omap,"tag:yaml.org,2002:pairs":ky.pairs,"tag:yaml.org,2002:set":Ay.set,"tag:yaml.org,2002:timestamp":Aa.timestamp};function fk(n,e,t){let r=by.get(e);if(r&&!n)return t&&!r.includes(Dn.merge)?r.concat(Dn.merge):r.slice();let i=r;if(!i)if(Array.isArray(n))i=[];else{let o=Array.from(by.keys()).filter(s=>s!=="yaml11").map(s=>JSON.stringify(s)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${o} or define customTags array`)}if(Array.isArray(n))for(let o of n)i=i.concat(o);else typeof n=="function"&&(i=n(i.slice()));return t&&(i=i.concat(Dn.merge)),i.reduce((o,s)=>{let a=typeof s=="string"?Sy[s]:s;if(!a){let l=JSON.stringify(s),c=Object.keys(Sy).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${c}`)}return o.includes(a)||o.push(a),o},[])}kd.coreKnownTags=mk;kd.getTags=fk});var Cd=C(Cy=>{"use strict";var Ad=H(),gk=gi(),yk=yi(),bk=kn(),Ta=Ty(),Sk=(n,e)=>n.key<e.key?-1:n.key>e.key?1:0,Td=class n{constructor({compat:e,customTags:t,merge:r,resolveKnownTags:i,schema:o,sortMapEntries:s,toStringDefaults:a}){this.compat=Array.isArray(e)?Ta.getTags(e,"compat"):e?Ta.getTags(null,e):null,this.name=typeof o=="string"&&o||"core",this.knownTags=i?Ta.coreKnownTags:{},this.tags=Ta.getTags(t,this.name,r),this.toStringOptions=a??null,Object.defineProperty(this,Ad.MAP,{value:gk.map}),Object.defineProperty(this,Ad.SCALAR,{value:bk.string}),Object.defineProperty(this,Ad.SEQ,{value:yk.seq}),this.sortMapEntries=typeof s=="function"?s:s===!0?Sk:null}clone(){let e=Object.create(n.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Cy.Schema=Td});var Dy=C(My=>{"use strict";var vk=H(),Md=wn(),Nn=yn();function wk(n,e){let t=[],r=e.directives===!0;if(e.directives!==!1&&n.directives){let l=n.directives.toString(n);l?(t.push(l),r=!0):n.directives.docStart&&(r=!0)}r&&t.push("---");let i=Md.createStringifyContext(n,e),{commentString:o}=i.options;if(n.commentBefore){t.length!==1&&t.unshift("");let l=o(n.commentBefore);t.unshift(Nn.indentComment(l,""))}let s=!1,a=null;if(n.contents){if(vk.isNode(n.contents)){if(n.contents.spaceBefore&&r&&t.push(""),n.contents.commentBefore){let u=o(n.contents.commentBefore);t.push(Nn.indentComment(u,""))}i.forceBlockIndent=!!n.comment,a=n.contents.comment}let l=a?void 0:()=>s=!0,c=Md.stringify(n.contents,i,()=>a=null,l);a&&(c+=Nn.lineComment(c,"",o(a))),(c[0]==="|"||c[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${c}`:t.push(c)}else t.push(Md.stringify(n.contents,i));if(n.directives?.docEnd)if(n.comment){let l=o(n.comment);l.includes(`
|
|
56
|
-
`)?(t.push("..."),t.push(Nn.indentComment(l,""))):t.push(`... ${l}`)}else t.push("...");else{let l=n.comment;l&&s&&(l=l.replace(/^\n+/,"")),l&&((!s||a)&&t[t.length-1]!==""&&t.push(""),t.push(Nn.indentComment(o(l),"")))}return t.join(`
|
|
57
|
-
`)+`
|
|
58
|
-
`}My.stringifyDocument=wk});var En=C(Ny=>{"use strict";var xk=fn(),Si=js(),Ie=H(),Pk=Ht(),kk=Ut(),Ak=Cd(),Tk=Dy(),Dd=Ws(),Ck=Ru(),Mk=gn(),Nd=Iu(),Ed=class n{constructor(e,t,r){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Ie.NODE_TYPE,{value:Ie.DOC});let i=null;typeof t=="function"||Array.isArray(t)?i=t:r===void 0&&t&&(r=t,t=void 0);let o=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},r);this.options=o;let{version:s}=o;r?._directives?(this.directives=r._directives.atDocument(),this.directives.yaml.explicit&&(s=this.directives.yaml.version)):this.directives=new Nd.Directives({version:s}),this.setSchema(s,r),this.contents=e===void 0?null:this.createNode(e,i,r)}clone(){let e=Object.create(n.prototype,{[Ie.NODE_TYPE]:{value:Ie.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=Ie.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){vi(this.contents)&&this.contents.add(e)}addIn(e,t){vi(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let r=Dd.anchorNames(this);e.anchor=!t||r.has(t)?Dd.findNewAnchor(t||"a",r):t}return new xk.Alias(e.anchor)}createNode(e,t,r){let i;if(typeof t=="function")e=t.call({"":e},"",e),i=t;else if(Array.isArray(t)){let g=b=>typeof b=="number"||b instanceof String||b instanceof Number,y=t.filter(g).map(String);y.length>0&&(t=t.concat(y)),i=t}else r===void 0&&t&&(r=t,t=void 0);let{aliasDuplicateObjects:o,anchorPrefix:s,flow:a,keepUndefined:l,onTagObj:c,tag:u}=r??{},{onAnchor:d,setAnchors:h,sourceObjects:p}=Dd.createNodeAnchors(this,s||"a"),f={aliasDuplicateObjects:o??!0,keepUndefined:l??!1,onAnchor:d,onTagObj:c,replacer:i,schema:this.schema,sourceObjects:p},m=Mk.createNode(e,u,f);return a&&Ie.isCollection(m)&&(m.flow=!0),h(),m}createPair(e,t,r={}){let i=this.createNode(e,null,r),o=this.createNode(t,null,r);return new Pk.Pair(i,o)}delete(e){return vi(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Si.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):vi(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return Ie.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Si.isEmptyPath(e)?!t&&Ie.isScalar(this.contents)?this.contents.value:this.contents:Ie.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return Ie.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return Si.isEmptyPath(e)?this.contents!==void 0:Ie.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Si.collectionFromPath(this.schema,[e],t):vi(this.contents)&&this.contents.set(e,t)}setIn(e,t){Si.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=Si.collectionFromPath(this.schema,Array.from(e),t):vi(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let r;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Nd.Directives({version:"1.1"}),r={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Nd.Directives({version:e}),r={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,r=null;break;default:{let i=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(r)this.schema=new Ak.Schema(Object.assign(r,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:r,maxAliasCount:i,onAnchor:o,reviver:s}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:r===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},l=kk.toJS(this.contents,t??"",a);if(typeof o=="function")for(let{count:c,res:u}of a.anchors.values())o(u,c);return typeof s=="function"?Ck.applyReviver(s,{"":l},"",l):l}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return Tk.stringifyDocument(this,e)}};function vi(n){if(Ie.isCollection(n))return!0;throw new Error("Expected a YAML collection as document contents")}Ny.Document=Ed});var Bn=C(Rn=>{"use strict";var In=class extends Error{constructor(e,t,r,i){super(),this.name=e,this.code=r,this.message=i,this.pos=t}},Id=class extends In{constructor(e,t,r){super("YAMLParseError",e,t,r)}},Rd=class extends In{constructor(e,t,r){super("YAMLWarning",e,t,r)}},Dk=(n,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:r,col:i}=t.linePos[0];t.message+=` at line ${r}, column ${i}`;let o=i-1,s=n.substring(e.lineStarts[r-1],e.lineStarts[r]).replace(/[\n\r]+$/,"");if(o>=60&&s.length>80){let a=Math.min(o-39,s.length-79);s="\u2026"+s.substring(a),o-=a-1}if(s.length>80&&(s=s.substring(0,79)+"\u2026"),r>1&&/^ *$/.test(s.substring(0,o))){let a=n.substring(e.lineStarts[r-2],e.lineStarts[r-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
|
|
59
|
-
`),s=a+s}if(/[^ ]/.test(s)){let a=1,l=t.linePos[1];l?.line===r&&l.col>i&&(a=Math.max(1,Math.min(l.col-i,80-o)));let c=" ".repeat(o)+"^".repeat(a);t.message+=`:
|
|
60
|
-
|
|
61
|
-
${s}
|
|
62
|
-
${c}
|
|
63
|
-
`}};Rn.YAMLError=In;Rn.YAMLParseError=Id;Rn.YAMLWarning=Rd;Rn.prettifyError=Dk});var Vn=C(Ey=>{"use strict";function Nk(n,{flow:e,indicator:t,next:r,offset:i,onError:o,parentIndent:s,startOnNewline:a}){let l=!1,c=a,u=a,d="",h="",p=!1,f=!1,m=null,g=null,y=null,b=null,v=null,w=null,k=null;for(let A of n)switch(f&&(A.type!=="space"&&A.type!=="newline"&&A.type!=="comma"&&o(A.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),f=!1),m&&(c&&A.type!=="comment"&&A.type!=="newline"&&o(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),A.type){case"space":!e&&(t!=="doc-start"||r?.type!=="flow-collection")&&A.source.includes(" ")&&(m=A),u=!0;break;case"comment":{u||o(A,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let F=A.source.substring(1)||" ";d?d+=h+F:d=F,h="",c=!1;break}case"newline":c?d?d+=A.source:(!w||t!=="seq-item-ind")&&(l=!0):h+=A.source,c=!0,p=!0,(g||y)&&(b=A),u=!0;break;case"anchor":g&&o(A,"MULTIPLE_ANCHORS","A node can have at most one anchor"),A.source.endsWith(":")&&o(A.offset+A.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=A,k??(k=A.offset),c=!1,u=!1,f=!0;break;case"tag":{y&&o(A,"MULTIPLE_TAGS","A node can have at most one tag"),y=A,k??(k=A.offset),c=!1,u=!1,f=!0;break}case t:(g||y)&&o(A,"BAD_PROP_ORDER",`Anchors and tags must be after the ${A.source} indicator`),w&&o(A,"UNEXPECTED_TOKEN",`Unexpected ${A.source} in ${e??"collection"}`),w=A,c=t==="seq-item-ind"||t==="explicit-key-ind",u=!1;break;case"comma":if(e){v&&o(A,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),v=A,c=!1,u=!1;break}default:o(A,"UNEXPECTED_TOKEN",`Unexpected ${A.type} token`),c=!1,u=!1}let T=n[n.length-1],N=T?T.offset+T.source.length:i;return f&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&o(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(c&&m.indent<=s||r?.type==="block-map"||r?.type==="block-seq")&&o(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:v,found:w,spaceBefore:l,comment:d,hasNewline:p,anchor:g,tag:y,newlineAfterProp:b,end:N,start:k??N}}Ey.resolveProps=Nk});var Ca=C(Iy=>{"use strict";function Bd(n){if(!n)return null;switch(n.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(n.source.includes(`
|
|
64
|
-
`))return!0;if(n.end){for(let e of n.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of n.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(Bd(e.key)||Bd(e.value))return!0}return!1;default:return!0}}Iy.containsNewline=Bd});var Vd=C(Ry=>{"use strict";var Ek=Ca();function Ik(n,e,t){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===n&&(r.source==="]"||r.source==="}")&&Ek.containsNewline(e)&&t(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Ry.flowIndentCheck=Ik});var Od=C(Vy=>{"use strict";var By=H();function Rk(n,e,t){let{uniqueKeys:r}=n.options;if(r===!1)return!1;let i=typeof r=="function"?r:(o,s)=>o===s||By.isScalar(o)&&By.isScalar(s)&&o.value===s.value;return e.some(o=>i(o.key,t))}Vy.mapIncludes=Rk});var Uy=C(zy=>{"use strict";var Oy=Ht(),Bk=Yt(),Ly=Vn(),Vk=Ca(),Fy=Vd(),Ok=Od(),_y="All mapping items must start at the same column";function Lk({composeNode:n,composeEmptyNode:e},t,r,i,o){let s=o?.nodeClass??Bk.YAMLMap,a=new s(t.schema);t.atRoot&&(t.atRoot=!1);let l=r.offset,c=null;for(let u of r.items){let{start:d,key:h,sep:p,value:f}=u,m=Ly.resolveProps(d,{indicator:"explicit-key-ind",next:h??p?.[0],offset:l,onError:i,parentIndent:r.indent,startOnNewline:!0}),g=!m.found;if(g){if(h&&(h.type==="block-seq"?i(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in h&&h.indent!==r.indent&&i(l,"BAD_INDENT",_y)),!m.anchor&&!m.tag&&!p){c=m.end,m.comment&&(a.comment?a.comment+=`
|
|
65
|
-
`+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||Vk.containsNewline(h))&&i(h??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==r.indent&&i(l,"BAD_INDENT",_y);t.atKey=!0;let y=m.end,b=h?n(t,h,m,i):e(t,y,d,null,m,i);t.schema.compat&&Fy.flowIndentCheck(r.indent,h,i),t.atKey=!1,Ok.mapIncludes(t,a.items,b)&&i(y,"DUPLICATE_KEY","Map keys must be unique");let v=Ly.resolveProps(p??[],{indicator:"map-value-ind",next:f,offset:b.range[2],onError:i,parentIndent:r.indent,startOnNewline:!h||h.type==="block-scalar"});if(l=v.end,v.found){g&&(f?.type==="block-map"&&!v.hasNewline&&i(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&m.start<v.found.offset-1024&&i(b.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let w=f?n(t,f,v,i):e(t,l,p,null,v,i);t.schema.compat&&Fy.flowIndentCheck(r.indent,f,i),l=w.range[2];let k=new Oy.Pair(b,w);t.options.keepSourceTokens&&(k.srcToken=u),a.items.push(k)}else{g&&i(b.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),v.comment&&(b.comment?b.comment+=`
|
|
66
|
-
`+v.comment:b.comment=v.comment);let w=new Oy.Pair(b);t.options.keepSourceTokens&&(w.srcToken=u),a.items.push(w)}}return c&&c<l&&i(c,"IMPOSSIBLE","Map comment with trailing content"),a.range=[r.offset,l,c??l],a}zy.resolveBlockMap=Lk});var Gy=C(Wy=>{"use strict";var Fk=$t(),_k=Vn(),zk=Vd();function Uk({composeNode:n,composeEmptyNode:e},t,r,i,o){let s=o?.nodeClass??Fk.YAMLSeq,a=new s(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let l=r.offset,c=null;for(let{start:u,value:d}of r.items){let h=_k.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:l,onError:i,parentIndent:r.indent,startOnNewline:!0});if(!h.found)if(h.anchor||h.tag||d)d?.type==="block-seq"?i(h.end,"BAD_INDENT","All sequence items must start at the same column"):i(l,"MISSING_CHAR","Sequence item without - indicator");else{c=h.end,h.comment&&(a.comment=h.comment);continue}let p=d?n(t,d,h,i):e(t,h.end,u,null,h,i);t.schema.compat&&zk.flowIndentCheck(r.indent,d,i),l=p.range[2],a.items.push(p)}return a.range=[r.offset,l,c??l],a}Wy.resolveBlockSeq=Uk});var wi=C(qy=>{"use strict";function Wk(n,e,t,r){let i="";if(n){let o=!1,s="";for(let a of n){let{source:l,type:c}=a;switch(c){case"space":o=!0;break;case"comment":{t&&!o&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=l.substring(1)||" ";i?i+=s+u:i=u,s="";break}case"newline":i&&(s+=l),o=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}e+=l.length}}return{comment:i,offset:e}}qy.resolveEnd=Wk});var $y=C(Yy=>{"use strict";var Gk=H(),qk=Ht(),Hy=Yt(),Hk=$t(),jk=wi(),jy=Vn(),Yk=Ca(),$k=Od(),Ld="Block collections are not allowed within flow collections",Fd=n=>n&&(n.type==="block-map"||n.type==="block-seq");function Kk({composeNode:n,composeEmptyNode:e},t,r,i,o){let s=r.start.source==="{",a=s?"flow map":"flow sequence",l=o?.nodeClass??(s?Hy.YAMLMap:Hk.YAMLSeq),c=new l(t.schema);c.flow=!0;let u=t.atRoot;u&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let d=r.offset+r.start.source.length;for(let g=0;g<r.items.length;++g){let y=r.items[g],{start:b,key:v,sep:w,value:k}=y,T=jy.resolveProps(b,{flow:a,indicator:"explicit-key-ind",next:v??w?.[0],offset:d,onError:i,parentIndent:r.indent,startOnNewline:!1});if(!T.found){if(!T.anchor&&!T.tag&&!w&&!k){g===0&&T.comma?i(T.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):g<r.items.length-1&&i(T.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),T.comment&&(c.comment?c.comment+=`
|
|
67
|
-
`+T.comment:c.comment=T.comment),d=T.end;continue}!s&&t.options.strict&&Yk.containsNewline(v)&&i(v,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(g===0)T.comma&&i(T.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(T.comma||i(T.start,"MISSING_CHAR",`Missing , between ${a} items`),T.comment){let N="";e:for(let A of b)switch(A.type){case"comma":case"space":break;case"comment":N=A.source.substring(1);break e;default:break e}if(N){let A=c.items[c.items.length-1];Gk.isPair(A)&&(A=A.value??A.key),A.comment?A.comment+=`
|
|
68
|
-
`+N:A.comment=N,T.comment=T.comment.substring(N.length+1)}}if(!s&&!w&&!T.found){let N=k?n(t,k,T,i):e(t,T.end,w,null,T,i);c.items.push(N),d=N.range[2],Fd(k)&&i(N.range,"BLOCK_IN_FLOW",Ld)}else{t.atKey=!0;let N=T.end,A=v?n(t,v,T,i):e(t,N,b,null,T,i);Fd(v)&&i(A.range,"BLOCK_IN_FLOW",Ld),t.atKey=!1;let F=jy.resolveProps(w??[],{flow:a,indicator:"map-value-ind",next:k,offset:A.range[2],onError:i,parentIndent:r.indent,startOnNewline:!1});if(F.found){if(!s&&!T.found&&t.options.strict){if(w)for(let re of w){if(re===F.found)break;if(re.type==="newline"){i(re,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}T.start<F.found.offset-1024&&i(F.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else k&&("source"in k&&k.source?.[0]===":"?i(k,"MISSING_CHAR",`Missing space after : in ${a}`):i(F.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let Z=k?n(t,k,F,i):F.found?e(t,F.end,w,null,F,i):null;Z?Fd(k)&&i(Z.range,"BLOCK_IN_FLOW",Ld):F.comment&&(A.comment?A.comment+=`
|
|
69
|
-
`+F.comment:A.comment=F.comment);let ne=new qk.Pair(A,Z);if(t.options.keepSourceTokens&&(ne.srcToken=y),s){let re=c;$k.mapIncludes(t,re.items,A)&&i(N,"DUPLICATE_KEY","Map keys must be unique"),re.items.push(ne)}else{let re=new Hy.YAMLMap(t.schema);re.flow=!0,re.items.push(ne);let Be=(Z??A).range;re.range=[A.range[0],Be[1],Be[2]],c.items.push(re)}d=Z?Z.range[2]:F.end}}let h=s?"}":"]",[p,...f]=r.end,m=d;if(p?.source===h)m=p.offset+p.source.length;else{let g=a[0].toUpperCase()+a.substring(1),y=u?`${g} must end with a ${h}`:`${g} in block collection must be sufficiently indented and end with a ${h}`;i(d,u?"MISSING_CHAR":"BAD_INDENT",y),p&&p.source.length!==1&&f.unshift(p)}if(f.length>0){let g=jk.resolveEnd(f,m,t.options.strict,i);g.comment&&(c.comment?c.comment+=`
|
|
70
|
-
`+g.comment:c.comment=g.comment),c.range=[r.offset,m,g.offset]}else c.range=[r.offset,m,m];return c}Yy.resolveFlowCollection=Kk});var Xy=C(Ky=>{"use strict";var Xk=H(),Qk=oe(),Jk=Yt(),Zk=$t(),eA=Uy(),tA=Gy(),rA=$y();function _d(n,e,t,r,i,o){let s=t.type==="block-map"?eA.resolveBlockMap(n,e,t,r,o):t.type==="block-seq"?tA.resolveBlockSeq(n,e,t,r,o):rA.resolveFlowCollection(n,e,t,r,o),a=s.constructor;return i==="!"||i===a.tagName?(s.tag=a.tagName,s):(i&&(s.tag=i),s)}function iA(n,e,t,r,i){let o=r.tag,s=o?e.directives.tagName(o.source,h=>i(o,"TAG_RESOLVE_FAILED",h)):null;if(t.type==="block-seq"){let{anchor:h,newlineAfterProp:p}=r,f=h&&o?h.offset>o.offset?h:o:h??o;f&&(!p||p.offset<f.offset)&&i(f,"MISSING_CHAR","Missing newline after block sequence props")}let a=t.type==="block-map"?"map":t.type==="block-seq"?"seq":t.start.source==="{"?"map":"seq";if(!o||!s||s==="!"||s===Jk.YAMLMap.tagName&&a==="map"||s===Zk.YAMLSeq.tagName&&a==="seq")return _d(n,e,t,i,s);let l=e.schema.tags.find(h=>h.tag===s&&h.collection===a);if(!l){let h=e.schema.knownTags[s];if(h?.collection===a)e.schema.tags.push(Object.assign({},h,{default:!1})),l=h;else return h?i(o,"BAD_COLLECTION_TYPE",`${h.tag} used for ${a} collection, but expects ${h.collection??"scalar"}`,!0):i(o,"TAG_RESOLVE_FAILED",`Unresolved tag: ${s}`,!0),_d(n,e,t,i,s)}let c=_d(n,e,t,i,s,l),u=l.resolve?.(c,h=>i(o,"TAG_RESOLVE_FAILED",h),e.options)??c,d=Xk.isNode(u)?u:new Qk.Scalar(u);return d.range=c.range,d.tag=s,l?.format&&(d.format=l.format),d}Ky.composeCollection=iA});var Ud=C(Qy=>{"use strict";var zd=oe();function nA(n,e,t){let r=e.offset,i=oA(e,n.options.strict,t);if(!i)return{value:"",type:null,comment:"",range:[r,r,r]};let o=i.mode===">"?zd.Scalar.BLOCK_FOLDED:zd.Scalar.BLOCK_LITERAL,s=e.source?sA(e.source):[],a=s.length;for(let m=s.length-1;m>=0;--m){let g=s[m][1];if(g===""||g==="\r")a=m;else break}if(a===0){let m=i.chomp==="+"&&s.length>0?`
|
|
71
|
-
`.repeat(Math.max(1,s.length-1)):"",g=r+i.length;return e.source&&(g+=e.source.length),{value:m,type:o,comment:i.comment,range:[r,g,g]}}let l=e.indent+i.indent,c=e.offset+i.length,u=0;for(let m=0;m<a;++m){let[g,y]=s[m];if(y===""||y==="\r")i.indent===0&&g.length>l&&(l=g.length);else{g.length<l&&t(c+g.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),i.indent===0&&(l=g.length),u=m,l===0&&!n.atRoot&&t(c,"BAD_INDENT","Block scalar values in collections must be indented");break}c+=g.length+y.length+1}for(let m=s.length-1;m>=a;--m)s[m][0].length>l&&(a=m+1);let d="",h="",p=!1;for(let m=0;m<u;++m)d+=s[m][0].slice(l)+`
|
|
72
|
-
`;for(let m=u;m<a;++m){let[g,y]=s[m];c+=g.length+y.length+1;let b=y[y.length-1]==="\r";if(b&&(y=y.slice(0,-1)),y&&g.length<l){let w=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;t(c-y.length-(b?2:1),"BAD_INDENT",w),g=""}o===zd.Scalar.BLOCK_LITERAL?(d+=h+g.slice(l)+y,h=`
|
|
73
|
-
`):g.length>l||y[0]===" "?(h===" "?h=`
|
|
74
|
-
`:!p&&h===`
|
|
75
|
-
`&&(h=`
|
|
76
|
-
|
|
77
|
-
`),d+=h+g.slice(l)+y,h=`
|
|
78
|
-
`,p=!0):y===""?h===`
|
|
79
|
-
`?d+=`
|
|
80
|
-
`:h=`
|
|
81
|
-
`:(d+=h+y,h=" ",p=!1)}switch(i.chomp){case"-":break;case"+":for(let m=a;m<s.length;++m)d+=`
|
|
82
|
-
`+s[m][0].slice(l);d[d.length-1]!==`
|
|
83
|
-
`&&(d+=`
|
|
84
|
-
`);break;default:d+=`
|
|
85
|
-
`}let f=r+i.length+e.source.length;return{value:d,type:o,comment:i.comment,range:[r,f,f]}}function oA({offset:n,props:e},t,r){if(e[0].type!=="block-scalar-header")return r(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:i}=e[0],o=i[0],s=0,a="",l=-1;for(let h=1;h<i.length;++h){let p=i[h];if(!a&&(p==="-"||p==="+"))a=p;else{let f=Number(p);!s&&f?s=f:l===-1&&(l=n+h)}}l!==-1&&r(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let c=!1,u="",d=i.length;for(let h=1;h<e.length;++h){let p=e[h];switch(p.type){case"space":c=!0;case"newline":d+=p.source.length;break;case"comment":t&&!c&&r(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=p.source.length,u=p.source.substring(1);break;case"error":r(p,"UNEXPECTED_TOKEN",p.message),d+=p.source.length;break;default:{let f=`Unexpected token in block scalar header: ${p.type}`;r(p,"UNEXPECTED_TOKEN",f);let m=p.source;m&&typeof m=="string"&&(d+=m.length)}}}return{mode:o,indent:s,chomp:a,comment:u,length:d}}function sA(n){let e=n.split(/\n( *)/),t=e[0],r=t.match(/^( *)/),o=[r?.[1]?[r[1],t.slice(r[1].length)]:["",t]];for(let s=1;s<e.length;s+=2)o.push([e[s],e[s+1]]);return o}Qy.resolveBlockScalar=nA});var Gd=C(Zy=>{"use strict";var Wd=oe(),aA=wi();function lA(n,e,t){let{offset:r,type:i,source:o,end:s}=n,a,l,c=(h,p,f)=>t(r+h,p,f);switch(i){case"scalar":a=Wd.Scalar.PLAIN,l=cA(o,c);break;case"single-quoted-scalar":a=Wd.Scalar.QUOTE_SINGLE,l=uA(o,c);break;case"double-quoted-scalar":a=Wd.Scalar.QUOTE_DOUBLE,l=dA(o,c);break;default:return t(n,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[r,r+o.length,r+o.length]}}let u=r+o.length,d=aA.resolveEnd(s,u,e,t);return{value:l,type:a,comment:d.comment,range:[r,u,d.offset]}}function cA(n,e){let t="";switch(n[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${n[0]}`;break}case"@":case"`":{t=`reserved character ${n[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),Jy(n)}function uA(n,e){return(n[n.length-1]!=="'"||n.length===1)&&e(n.length,"MISSING_CHAR","Missing closing 'quote"),Jy(n.slice(1,-1)).replace(/''/g,"'")}function Jy(n){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
86
|
-
`,"sy"),t=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
87
|
-
`,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,t=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=e.exec(n);if(!r)return n;let i=r[1],o=" ",s=e.lastIndex;for(t.lastIndex=s;r=t.exec(n);)r[1]===""?o===`
|
|
88
|
-
`?i+=o:o=`
|
|
89
|
-
`:(i+=o+r[1],o=" "),s=t.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=s,r=a.exec(n),i+o+(r?.[1]??"")}function dA(n,e){let t="";for(let r=1;r<n.length-1;++r){let i=n[r];if(!(i==="\r"&&n[r+1]===`
|
|
90
|
-
`))if(i===`
|
|
91
|
-
`){let{fold:o,offset:s}=hA(n,r);t+=o,r=s}else if(i==="\\"){let o=n[++r],s=pA[o];if(s)t+=s;else if(o===`
|
|
92
|
-
`)for(o=n[r+1];o===" "||o===" ";)o=n[++r+1];else if(o==="\r"&&n[r+1]===`
|
|
93
|
-
`)for(o=n[++r+1];o===" "||o===" ";)o=n[++r+1];else if(o==="x"||o==="u"||o==="U"){let a=o==="x"?2:o==="u"?4:8;t+=mA(n,r+1,a,e),r+=a}else{let a=n.substr(r-1,2);e(r-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),t+=a}}else if(i===" "||i===" "){let o=r,s=n[r+1];for(;s===" "||s===" ";)s=n[++r+1];s!==`
|
|
94
|
-
`&&!(s==="\r"&&n[r+2]===`
|
|
95
|
-
`)&&(t+=r>o?n.slice(o,r+1):i)}else t+=i}return(n[n.length-1]!=='"'||n.length===1)&&e(n.length,"MISSING_CHAR",'Missing closing "quote'),t}function hA(n,e){let t="",r=n[e+1];for(;(r===" "||r===" "||r===`
|
|
96
|
-
`||r==="\r")&&!(r==="\r"&&n[e+2]!==`
|
|
97
|
-
`);)r===`
|
|
98
|
-
`&&(t+=`
|
|
99
|
-
`),e+=1,r=n[e+1];return t||(t=" "),{fold:t,offset:e}}var pA={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
100
|
-
`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function mA(n,e,t,r){let i=n.substr(e,t),s=i.length===t&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(s)}catch{let a=n.substr(e-2,t+2);return r(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}Zy.resolveFlowScalar=lA});var rb=C(tb=>{"use strict";var Er=H(),eb=oe(),fA=Ud(),gA=Gd();function yA(n,e,t,r){let{value:i,type:o,comment:s,range:a}=e.type==="block-scalar"?fA.resolveBlockScalar(n,e,r):gA.resolveFlowScalar(e,n.options.strict,r),l=t?n.directives.tagName(t.source,d=>r(t,"TAG_RESOLVE_FAILED",d)):null,c;n.options.stringKeys&&n.atKey?c=n.schema[Er.SCALAR]:l?c=bA(n.schema,i,l,t,r):e.type==="scalar"?c=SA(n,i,e,r):c=n.schema[Er.SCALAR];let u;try{let d=c.resolve(i,h=>r(t??e,"TAG_RESOLVE_FAILED",h),n.options);u=Er.isScalar(d)?d:new eb.Scalar(d)}catch(d){let h=d instanceof Error?d.message:String(d);r(t??e,"TAG_RESOLVE_FAILED",h),u=new eb.Scalar(i)}return u.range=a,u.source=i,o&&(u.type=o),l&&(u.tag=l),c.format&&(u.format=c.format),s&&(u.comment=s),u}function bA(n,e,t,r,i){if(t==="!")return n[Er.SCALAR];let o=[];for(let a of n.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)o.push(a);else return a;for(let a of o)if(a.test?.test(e))return a;let s=n.knownTags[t];return s&&!s.collection?(n.tags.push(Object.assign({},s,{default:!1,test:void 0})),s):(i(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),n[Er.SCALAR])}function SA({atKey:n,directives:e,schema:t},r,i,o){let s=t.tags.find(a=>(a.default===!0||n&&a.default==="key")&&a.test?.test(r))||t[Er.SCALAR];if(t.compat){let a=t.compat.find(l=>l.default&&l.test?.test(r))??t[Er.SCALAR];if(s.tag!==a.tag){let l=e.tagString(s.tag),c=e.tagString(a.tag),u=`Value may be parsed as either ${l} or ${c}`;o(i,"TAG_RESOLVE_FAILED",u,!0)}}return s}tb.composeScalar=yA});var nb=C(ib=>{"use strict";function vA(n,e,t){if(e){t??(t=e.length);for(let r=t-1;r>=0;--r){let i=e[r];switch(i.type){case"space":case"comment":case"newline":n-=i.source.length;continue}for(i=e[++r];i?.type==="space";)n+=i.source.length,i=e[++r];break}}return n}ib.emptyScalarPosition=vA});var ab=C(Hd=>{"use strict";var wA=fn(),xA=H(),PA=Xy(),ob=rb(),kA=wi(),AA=nb(),TA={composeNode:sb,composeEmptyNode:qd};function sb(n,e,t,r){let i=n.atKey,{spaceBefore:o,comment:s,anchor:a,tag:l}=t,c,u=!0;switch(e.type){case"alias":c=CA(n,e,r),(a||l)&&r(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":c=ob.composeScalar(n,e,l,r),a&&(c.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{c=PA.composeCollection(TA,n,e,t,r),a&&(c.anchor=a.source.substring(1))}catch(d){let h=d instanceof Error?d.message:String(d);r(e,"RESOURCE_EXHAUSTION",h)}break;default:{let d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;r(e,"UNEXPECTED_TOKEN",d),u=!1}}return c??(c=qd(n,e.offset,void 0,null,t,r)),a&&c.anchor===""&&r(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&n.options.stringKeys&&(!xA.isScalar(c)||typeof c.value!="string"||c.tag&&c.tag!=="tag:yaml.org,2002:str")&&r(l??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),o&&(c.spaceBefore=!0),s&&(e.type==="scalar"&&e.source===""?c.comment=s:c.commentBefore=s),n.options.keepSourceTokens&&u&&(c.srcToken=e),c}function qd(n,e,t,r,{spaceBefore:i,comment:o,anchor:s,tag:a,end:l},c){let u={type:"scalar",offset:AA.emptyScalarPosition(e,t,r),indent:-1,source:""},d=ob.composeScalar(n,u,a,c);return s&&(d.anchor=s.source.substring(1),d.anchor===""&&c(s,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(d.spaceBefore=!0),o&&(d.comment=o,d.range[2]=l),d}function CA({options:n},{offset:e,source:t,end:r},i){let o=new wA.Alias(t.substring(1));o.source===""&&i(e,"BAD_ALIAS","Alias cannot be an empty string"),o.source.endsWith(":")&&i(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let s=e+t.length,a=kA.resolveEnd(r,s,n.strict,i);return o.range=[e,s,a.offset],a.comment&&(o.comment=a.comment),o}Hd.composeEmptyNode=qd;Hd.composeNode=sb});var ub=C(cb=>{"use strict";var MA=En(),lb=ab(),DA=wi(),NA=Vn();function EA(n,e,{offset:t,start:r,value:i,end:o},s){let a=Object.assign({_directives:e},n),l=new MA.Document(void 0,a),c={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},u=NA.resolveProps(r,{indicator:"doc-start",next:i??o?.[0],offset:t,onError:s,parentIndent:0,startOnNewline:!0});u.found&&(l.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!u.hasNewline&&s(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=i?lb.composeNode(c,i,u,s):lb.composeEmptyNode(c,u.end,r,null,u,s);let d=l.contents.range[2],h=DA.resolveEnd(o,d,!1,s);return h.comment&&(l.comment=h.comment),l.range=[t,d,h.offset],l}cb.composeDoc=EA});var Yd=C(pb=>{"use strict";var IA=Uo("process"),RA=Iu(),BA=En(),On=Bn(),db=H(),VA=ub(),OA=wi();function Ln(n){if(typeof n=="number")return[n,n+1];if(Array.isArray(n))return n.length===2?n:[n[0],n[1]];let{offset:e,source:t}=n;return[e,e+(typeof t=="string"?t.length:1)]}function hb(n){let e="",t=!1,r=!1;for(let i=0;i<n.length;++i){let o=n[i];switch(o[0]){case"#":e+=(e===""?"":r?`
|
|
101
|
-
|
|
102
|
-
`:`
|
|
103
|
-
`)+(o.substring(1)||" "),t=!0,r=!1;break;case"%":n[i+1]?.[0]!=="#"&&(i+=1),t=!1;break;default:t||(r=!0),t=!1}}return{comment:e,afterEmptyLine:r}}var jd=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,r,i,o)=>{let s=Ln(t);o?this.warnings.push(new On.YAMLWarning(s,r,i)):this.errors.push(new On.YAMLParseError(s,r,i))},this.directives=new RA.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:r,afterEmptyLine:i}=hb(this.prelude);if(r){let o=e.contents;if(t)e.comment=e.comment?`${e.comment}
|
|
104
|
-
${r}`:r;else if(i||e.directives.docStart||!o)e.commentBefore=r;else if(db.isCollection(o)&&!o.flow&&o.items.length>0){let s=o.items[0];db.isPair(s)&&(s=s.key);let a=s.commentBefore;s.commentBefore=a?`${r}
|
|
105
|
-
${a}`:r}else{let s=o.commentBefore;o.commentBefore=s?`${r}
|
|
106
|
-
${s}`:r}}if(t){for(let o=0;o<this.errors.length;++o)e.errors.push(this.errors[o]);for(let o=0;o<this.warnings.length;++o)e.warnings.push(this.warnings[o])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:hb(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,r=-1){for(let i of e)yield*this.next(i);yield*this.end(t,r)}*next(e){switch(IA.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(t,r,i)=>{let o=Ln(e);o[0]+=t,this.onError(o,"BAD_DIRECTIVE",r,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=VA.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,r=new On.YAMLParseError(Ln(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(r):this.doc.errors.push(r);break}case"doc-end":{if(!this.doc){let r="Unexpected doc-end without preceding document";this.errors.push(new On.YAMLParseError(Ln(e),"UNEXPECTED_TOKEN",r));break}this.doc.directives.docEnd=!0;let t=OA.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let r=this.doc.comment;this.doc.comment=r?`${r}
|
|
107
|
-
${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new On.YAMLParseError(Ln(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let r=Object.assign({_directives:this.directives},this.options),i=new BA.Document(void 0,r);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),i.range=[0,t,t],this.decorate(i,!1),yield i}}};pb.Composer=jd});var gb=C(Ma=>{"use strict";var LA=Ud(),FA=Gd(),_A=Bn(),mb=vn();function zA(n,e=!0,t){if(n){let r=(i,o,s)=>{let a=typeof i=="number"?i:Array.isArray(i)?i[0]:i.offset;if(t)t(a,o,s);else throw new _A.YAMLParseError([a,a+1],o,s)};switch(n.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return FA.resolveFlowScalar(n,e,r);case"block-scalar":return LA.resolveBlockScalar({options:{strict:e}},n,r)}}return null}function UA(n,e){let{implicitKey:t=!1,indent:r,inFlow:i=!1,offset:o=-1,type:s="PLAIN"}=e,a=mb.stringifyString({type:s,value:n},{implicitKey:t,indent:r>0?" ".repeat(r):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),l=e.end??[{type:"newline",offset:-1,indent:r,source:`
|
|
108
|
-
`}];switch(a[0]){case"|":case">":{let c=a.indexOf(`
|
|
109
|
-
`),u=a.substring(0,c),d=a.substring(c+1)+`
|
|
110
|
-
`,h=[{type:"block-scalar-header",offset:o,indent:r,source:u}];return fb(h,l)||h.push({type:"newline",offset:-1,indent:r,source:`
|
|
111
|
-
`}),{type:"block-scalar",offset:o,indent:r,props:h,source:d}}case'"':return{type:"double-quoted-scalar",offset:o,indent:r,source:a,end:l};case"'":return{type:"single-quoted-scalar",offset:o,indent:r,source:a,end:l};default:return{type:"scalar",offset:o,indent:r,source:a,end:l}}}function WA(n,e,t={}){let{afterKey:r=!1,implicitKey:i=!1,inFlow:o=!1,type:s}=t,a="indent"in n?n.indent:null;if(r&&typeof a=="number"&&(a+=2),!s)switch(n.type){case"single-quoted-scalar":s="QUOTE_SINGLE";break;case"double-quoted-scalar":s="QUOTE_DOUBLE";break;case"block-scalar":{let c=n.props[0];if(c.type!=="block-scalar-header")throw new Error("Invalid block scalar header");s=c.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:s="PLAIN"}let l=mb.stringifyString({type:s,value:e},{implicitKey:i||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:o,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":GA(n,l);break;case'"':$d(n,l,"double-quoted-scalar");break;case"'":$d(n,l,"single-quoted-scalar");break;default:$d(n,l,"scalar")}}function GA(n,e){let t=e.indexOf(`
|
|
112
|
-
`),r=e.substring(0,t),i=e.substring(t+1)+`
|
|
113
|
-
`;if(n.type==="block-scalar"){let o=n.props[0];if(o.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o.source=r,n.source=i}else{let{offset:o}=n,s="indent"in n?n.indent:-1,a=[{type:"block-scalar-header",offset:o,indent:s,source:r}];fb(a,"end"in n?n.end:void 0)||a.push({type:"newline",offset:-1,indent:s,source:`
|
|
114
|
-
`});for(let l of Object.keys(n))l!=="type"&&l!=="offset"&&delete n[l];Object.assign(n,{type:"block-scalar",indent:s,props:a,source:i})}}function fb(n,e){if(e)for(let t of e)switch(t.type){case"space":case"comment":n.push(t);break;case"newline":return n.push(t),!0}return!1}function $d(n,e,t){switch(n.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":n.type=t,n.source=e;break;case"block-scalar":{let r=n.props.slice(1),i=e.length;n.props[0].type==="block-scalar-header"&&(i-=n.props[0].source.length);for(let o of r)o.offset+=i;delete n.props,Object.assign(n,{type:t,source:e,end:r});break}case"block-map":case"block-seq":{let i={type:"newline",offset:n.offset+e.length,indent:n.indent,source:`
|
|
115
|
-
`};delete n.items,Object.assign(n,{type:t,source:e,end:[i]});break}default:{let r="indent"in n?n.indent:-1,i="end"in n&&Array.isArray(n.end)?n.end.filter(o=>o.type==="space"||o.type==="comment"||o.type==="newline"):[];for(let o of Object.keys(n))o!=="type"&&o!=="offset"&&delete n[o];Object.assign(n,{type:t,indent:r,source:e,end:i})}}}Ma.createScalarToken=UA;Ma.resolveAsScalar=zA;Ma.setScalarValue=WA});var bb=C(yb=>{"use strict";var qA=n=>"type"in n?Na(n):Da(n);function Na(n){switch(n.type){case"block-scalar":{let e="";for(let t of n.props)e+=Na(t);return e+n.source}case"block-map":case"block-seq":{let e="";for(let t of n.items)e+=Da(t);return e}case"flow-collection":{let e=n.start.source;for(let t of n.items)e+=Da(t);for(let t of n.end)e+=t.source;return e}case"document":{let e=Da(n);if(n.end)for(let t of n.end)e+=t.source;return e}default:{let e=n.source;if("end"in n&&n.end)for(let t of n.end)e+=t.source;return e}}}function Da({start:n,key:e,sep:t,value:r}){let i="";for(let o of n)i+=o.source;if(e&&(i+=Na(e)),t)for(let o of t)i+=o.source;return r&&(i+=Na(r)),i}yb.stringify=qA});var xb=C(wb=>{"use strict";var Kd=Symbol("break visit"),HA=Symbol("skip children"),Sb=Symbol("remove item");function Ir(n,e){"type"in n&&n.type==="document"&&(n={start:n.start,value:n.value}),vb(Object.freeze([]),n,e)}Ir.BREAK=Kd;Ir.SKIP=HA;Ir.REMOVE=Sb;Ir.itemAtPath=(n,e)=>{let t=n;for(let[r,i]of e){let o=t?.[r];if(o&&"items"in o)t=o.items[i];else return}return t};Ir.parentCollection=(n,e)=>{let t=Ir.itemAtPath(n,e.slice(0,-1)),r=e[e.length-1][0],i=t?.[r];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function vb(n,e,t){let r=t(e,n);if(typeof r=="symbol")return r;for(let i of["key","value"]){let o=e[i];if(o&&"items"in o){for(let s=0;s<o.items.length;++s){let a=vb(Object.freeze(n.concat([[i,s]])),o.items[s],t);if(typeof a=="number")s=a-1;else{if(a===Kd)return Kd;a===Sb&&(o.items.splice(s,1),s-=1)}}typeof r=="function"&&i==="key"&&(r=r(e,n))}}return typeof r=="function"?r(e,n):r}wb.visit=Ir});var Ea=C(Se=>{"use strict";var Xd=gb(),jA=bb(),YA=xb(),Qd="\uFEFF",Jd="",Zd="",eh="",$A=n=>!!n&&"items"in n,KA=n=>!!n&&(n.type==="scalar"||n.type==="single-quoted-scalar"||n.type==="double-quoted-scalar"||n.type==="block-scalar");function XA(n){switch(n){case Qd:return"<BOM>";case Jd:return"<DOC>";case Zd:return"<FLOW_END>";case eh:return"<SCALAR>";default:return JSON.stringify(n)}}function QA(n){switch(n){case Qd:return"byte-order-mark";case Jd:return"doc-mode";case Zd:return"flow-error-end";case eh:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
116
|
-
`:case`\r
|
|
117
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(n[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Se.createScalarToken=Xd.createScalarToken;Se.resolveAsScalar=Xd.resolveAsScalar;Se.setScalarValue=Xd.setScalarValue;Se.stringify=jA.stringify;Se.visit=YA.visit;Se.BOM=Qd;Se.DOCUMENT=Jd;Se.FLOW_END=Zd;Se.SCALAR=eh;Se.isCollection=$A;Se.isScalar=KA;Se.prettyToken=XA;Se.tokenType=QA});var ih=C(kb=>{"use strict";var Fn=Ea();function We(n){switch(n){case void 0:case" ":case`
|
|
118
|
-
`:case"\r":case" ":return!0;default:return!1}}var Pb=new Set("0123456789ABCDEFabcdef"),JA=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Ia=new Set(",[]{}"),ZA=new Set(` ,[]{}
|
|
119
|
-
\r `),th=n=>!n||ZA.has(n),rh=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let r=this.next??"stream";for(;r&&(t||this.hasChars(1));)r=yield*this.parseNext(r)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===`
|
|
120
|
-
`?!0:t==="\r"?this.buffer[e+1]===`
|
|
121
|
-
`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let r=0;for(;t===" ";)t=this.buffer[++r+e];if(t==="\r"){let i=this.buffer[r+e+1];if(i===`
|
|
122
|
-
`||!i&&!this.atEnd)return e+r+1}return t===`
|
|
123
|
-
`||r>=this.indentNext||!t&&!this.atEnd?e+r:-1}if(t==="-"||t==="."){let r=this.buffer.substr(e,3);if((r==="---"||r==="...")&&We(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
|
|
124
|
-
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===Fn.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let t=e.length,r=e.indexOf("#");for(;r!==-1;){let o=e[r-1];if(o===" "||o===" "){t=r-1;break}else r=e.indexOf("#",r+1)}for(;;){let o=e[t-1];if(o===" "||o===" ")t-=1;else break}let i=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-i),this.pushNewline(),"stream"}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),"stream"}return yield Fn.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let t=this.peek(3);if((t==="---"||t==="...")&&We(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,t==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!We(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&We(t)){let r=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=r,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(th),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,r=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=r=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let i=this.getLine();if(i===null)return this.setNext("flow");if((r!==-1&&r<this.indentNext&&i[0]!=="#"||r===0&&(i.startsWith("---")||i.startsWith("..."))&&We(i[3]))&&!(r===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}")))return this.flowLevel=0,yield Fn.FLOW_END,yield*this.parseLineStart();let o=0;for(;i[o]===",";)o+=yield*this.pushCount(1),o+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(o+=yield*this.pushIndicators(),i[o]){case void 0:return"flow";case"#":return yield*this.pushCount(i.length-o),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(th),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let s=this.charAt(1);if(this.flowKey||We(s)||s===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;t!==-1&&this.buffer[t+1]==="'";)t=this.buffer.indexOf("'",t+2);else for(;t!==-1;){let o=0;for(;this.buffer[t-1-o]==="\\";)o+=1;if(o%2===0)break;t=this.buffer.indexOf('"',t+1)}let r=this.buffer.substring(0,t),i=r.indexOf(`
|
|
125
|
-
`,this.pos);if(i!==-1){for(;i!==-1;){let o=this.continueScalar(i+1);if(o===-1)break;i=r.indexOf(`
|
|
126
|
-
`,o)}i!==-1&&(t=i-(r[i-1]==="\r"?2:1))}if(t===-1){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t==="+")this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>We(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,r;e:for(let o=this.pos;r=this.buffer[o];++o)switch(r){case" ":t+=1;break;case`
|
|
127
|
-
`:e=o,t=0;break;case"\r":{let s=this.buffer[o+1];if(!s&&!this.atEnd)return this.setNext("block-scalar");if(s===`
|
|
128
|
-
`)break}default:break e}if(!r&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=t:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let o=this.continueScalar(e+1);if(o===-1)break;e=this.buffer.indexOf(`
|
|
129
|
-
`,o)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let i=e+1;for(r=this.buffer[i];r===" ";)r=this.buffer[++i];if(r===" "){for(;r===" "||r===" "||r==="\r"||r===`
|
|
130
|
-
`;)r=this.buffer[++i];e=i-1}else if(!this.blockScalarKeep)do{let o=e-1,s=this.buffer[o];s==="\r"&&(s=this.buffer[--o]);let a=o;for(;s===" ";)s=this.buffer[--o];if(s===`
|
|
131
|
-
`&&o>=this.pos&&o+1+t>a)e=o;else break}while(!0);return yield Fn.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,r=this.pos-1,i;for(;i=this.buffer[++r];)if(i===":"){let o=this.buffer[r+1];if(We(o)||e&&Ia.has(o))break;t=r}else if(We(i)){let o=this.buffer[r+1];if(i==="\r"&&(o===`
|
|
132
|
-
`?(r+=1,i=`
|
|
133
|
-
`,o=this.buffer[r+1]):t=r),o==="#"||e&&Ia.has(o))break;if(i===`
|
|
134
|
-
`){let s=this.continueScalar(r+1);if(s===-1)break;r=Math.max(r,s-2)}}else{if(e&&Ia.has(i))break;t=r}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield Fn.SCALAR,yield*this.pushToIndex(t+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let r=this.buffer.slice(this.pos,e);return r?(yield r,this.pos+=r.length,r.length):(t&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(th),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let t=this.flowLevel>0,r=this.charAt(1);if(We(r)||t&&Ia.has(r)){t?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];for(;!We(t)&&t!==">";)t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];for(;t;)if(JA.has(t))t=this.buffer[++e];else if(t==="%"&&Pb.has(this.buffer[e+1])&&Pb.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
|
|
135
|
-
`?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
|
|
136
|
-
`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,r;do r=this.buffer[++t];while(r===" "||e&&r===" ");let i=t-this.pos;return i>0&&(yield this.buffer.substr(this.pos,i),this.pos=t),i}*pushUntil(e){let t=this.pos,r=this.buffer[t];for(;!e(r);)r=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};kb.Lexer=rh});var oh=C(Ab=>{"use strict";var nh=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,r=this.lineStarts.length;for(;t<r;){let o=t+r>>1;this.lineStarts[o]<e?t=o+1:r=o}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let i=this.lineStarts[t-1];return{line:t,col:e-i+1}}}};Ab.LineCounter=nh});var ah=C(Nb=>{"use strict";var eT=Uo("process"),Tb=Ea(),tT=ih();function Kt(n,e){for(let t=0;t<n.length;++t)if(n[t].type===e)return!0;return!1}function Cb(n){for(let e=0;e<n.length;++e)switch(n[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function Db(n){switch(n?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Ra(n){switch(n.type){case"document":return n.start;case"block-map":{let e=n.items[n.items.length-1];return e.sep??e.start}case"block-seq":return n.items[n.items.length-1].start;default:return[]}}function xi(n){if(n.length===0)return[];let e=n.length;e:for(;--e>=0;)switch(n[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;n[++e]?.type==="space";);return n.splice(e,n.length)}function Ba(n,e){if(e.length<1e5)Array.prototype.push.apply(n,e);else for(let t=0;t<e.length;++t)n.push(e[t])}function Mb(n){if(n.start.type==="flow-seq-start")for(let e of n.items)e.sep&&!e.value&&!Kt(e.start,"explicit-key-ind")&&!Kt(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Db(e.value)?e.value.end?Ba(e.value.end,e.sep):e.value.end=e.sep:Ba(e.start,e.sep),delete e.sep)}var sh=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new tT.Lexer,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let r of this.lexer.lex(e,t))yield*this.next(r);t||(yield*this.end())}*next(e){if(this.source=e,eT.env.LOG_TOKENS&&console.log("|",Tb.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=Tb.tokenType(e);if(t)if(t==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=t,yield*this.step(),t){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let r=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:r,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{let r=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in r?r.indent:0:t.type==="flow-collection"&&r.type==="document"&&(t.indent=0),t.type==="flow-collection"&&Mb(t),r.type){case"document":r.value=t;break;case"block-scalar":r.props.push(t);break;case"block-map":{let i=r.items[r.items.length-1];if(i.value){r.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(i.sep)i.value=t;else{Object.assign(i,{key:t,sep:[]}),this.onKeyLine=!i.explicitKey;return}break}case"block-seq":{let i=r.items[r.items.length-1];i.value?r.items.push({start:[],value:t}):i.value=t;break}case"flow-collection":{let i=r.items[r.items.length-1];!i||i.value?r.items.push({start:[],key:t,sep:[]}):i.sep?i.value=t:Object.assign(i,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((r.type==="document"||r.type==="block-map"||r.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){let i=t.items[t.items.length-1];i&&!i.sep&&!i.value&&i.start.length>0&&Cb(i.start)===-1&&(t.indent===0||i.start.every(o=>o.type!=="comment"||o.indent<t.indent))&&(r.type==="document"?r.end=i.start:r.items.push({start:i.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{Cb(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);t?this.stack.push(t):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let t=Ra(this.peek(2)),r=xi(t),i;e.end?(i=e.end,i.push(this.sourceToken),delete e.end):i=[this.sourceToken];let o={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:r,key:e,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=o}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let t=this.source.indexOf(`
|
|
137
|
-
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
138
|
-
`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let r="end"in t.value?t.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){Ba(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let r=!this.onKeyLine&&this.indent===e.indent,i=r&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",o=[];if(i&&t.sep&&!t.value){let s=[];for(let a=0;a<t.sep.length;++a){let l=t.sep[a];switch(l.type){case"newline":s.push(a);break;case"space":break;case"comment":l.indent>e.indent&&(s.length=0);break;default:s.length=0}}s.length>=2&&(o=t.sep.splice(s[1]))}switch(this.type){case"anchor":case"tag":i||t.value?(o.push(this.sourceToken),e.items.push({start:o}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):i||t.value?(o.push(this.sourceToken),e.items.push({start:o,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Kt(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(Db(t.key)&&!Kt(t.sep,"newline")){let s=xi(t.start),a=t.key,l=t.sep;l.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:a,sep:l}]})}else o.length>0?t.sep=t.sep.concat(o,this.sourceToken):t.sep.push(this.sourceToken);else if(Kt(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let s=xi(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||i?e.items.push({start:o,key:null,sep:[this.sourceToken]}):Kt(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let s=this.flowScalar(this.type);i||t.value?(e.items.push({start:o,key:s,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(s):(Object.assign(t,{key:s,sep:[]}),this.onKeyLine=!0);return}default:{let s=this.startBlockValue(e);if(s){if(s.type==="block-seq"){if(!t.explicitKey&&t.sep&&!Kt(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&e.items.push({start:o});this.stack.push(s);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let r="end"in t.value?t.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){Ba(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||Kt(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let r=this.startBlockValue(e);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:i,sep:[]}):t.sep?this.stack.push(i):Object.assign(t,{key:i,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let r=this.startBlockValue(e);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===e.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let i=Ra(r),o=xi(i);Mb(e);let s=e.end.splice(1,e.end.length);s.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:o,key:e,sep:s}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
|
|
139
|
-
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
140
|
-
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=Ra(e),r=xi(t);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=Ra(e),r=xi(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Nb.Parser=sh});var Vb=C(zn=>{"use strict";var Eb=Yd(),rT=En(),_n=Bn(),iT=Hu(),nT=H(),oT=oh(),Ib=ah();function Rb(n){let e=n.prettyErrors!==!1;return{lineCounter:n.lineCounter||e&&new oT.LineCounter||null,prettyErrors:e}}function sT(n,e={}){let{lineCounter:t,prettyErrors:r}=Rb(e),i=new Ib.Parser(t?.addNewLine),o=new Eb.Composer(e),s=Array.from(o.compose(i.parse(n)));if(r&&t)for(let a of s)a.errors.forEach(_n.prettifyError(n,t)),a.warnings.forEach(_n.prettifyError(n,t));return s.length>0?s:Object.assign([],{empty:!0},o.streamInfo())}function Bb(n,e={}){let{lineCounter:t,prettyErrors:r}=Rb(e),i=new Ib.Parser(t?.addNewLine),o=new Eb.Composer(e),s=null;for(let a of o.compose(i.parse(n),!0,n.length))if(!s)s=a;else if(s.options.logLevel!=="silent"){s.errors.push(new _n.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&t&&(s.errors.forEach(_n.prettifyError(n,t)),s.warnings.forEach(_n.prettifyError(n,t))),s}function aT(n,e,t){let r;typeof e=="function"?r=e:t===void 0&&e&&typeof e=="object"&&(t=e);let i=Bb(n,t);if(!i)return null;if(i.warnings.forEach(o=>iT.warn(i.options.logLevel,o)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:r},t))}function lT(n,e,t){let r=null;if(typeof e=="function"||Array.isArray(e)?r=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){let i=Math.round(t);t=i<1?void 0:i>8?{indent:8}:{indent:i}}if(n===void 0){let{keepUndefined:i}=t??e??{};if(!i)return}return nT.isDocument(n)&&!r?n.toString(t):new rT.Document(n,r,t).toString(t)}zn.parse=aT;zn.parseAllDocuments=sT;zn.parseDocument=Bb;zn.stringify=lT});var ch=C($=>{"use strict";var cT=Yd(),uT=En(),dT=Cd(),lh=Bn(),hT=fn(),Xt=H(),pT=Ht(),mT=oe(),fT=Yt(),gT=$t(),yT=Ea(),bT=ih(),ST=oh(),vT=ah(),Va=Vb(),Ob=dn();$.Composer=cT.Composer;$.Document=uT.Document;$.Schema=dT.Schema;$.YAMLError=lh.YAMLError;$.YAMLParseError=lh.YAMLParseError;$.YAMLWarning=lh.YAMLWarning;$.Alias=hT.Alias;$.isAlias=Xt.isAlias;$.isCollection=Xt.isCollection;$.isDocument=Xt.isDocument;$.isMap=Xt.isMap;$.isNode=Xt.isNode;$.isPair=Xt.isPair;$.isScalar=Xt.isScalar;$.isSeq=Xt.isSeq;$.Pair=pT.Pair;$.Scalar=mT.Scalar;$.YAMLMap=fT.YAMLMap;$.YAMLSeq=gT.YAMLSeq;$.CST=yT;$.Lexer=bT.Lexer;$.LineCounter=ST.LineCounter;$.Parser=vT.Parser;$.parse=Va.parse;$.parseAllDocuments=Va.parseAllDocuments;$.parseDocument=Va.parseDocument;$.stringify=Va.stringify;$.visit=Ob.visit;$.visitAsync=Ob.visitAsync});var Ul=class{baseUrl;embeddedResources;audioBuffers=new Map;constructor(e="/",t={}){this.baseUrl=e.endsWith("/")?e:`${e}/`,this.embeddedResources=new Map;for(let[r,i]of Object.entries(t)){let o=this.normalizeEmbeddedPath(r);this.embeddedResources.set(o,i)}}normalize(e){let t=this.getScheme(e);if(t==="res"){let r=e.substring(6);return this.buildUrl(r)}return t==="http"||t==="https"||t==="blob"||t==="data"?e:this.buildUrl(e)}get hasEmbeddedResources(){return this.embeddedResources.size>0}hasEmbeddedResource(e){return this.getEmbeddedEntry(e)!==null}getAudioBuffer(e){return this.audioBuffers.get(e)}setAudioBuffer(e,t){this.audioBuffers.set(e,t)}async readText(e){let t=this.getEmbeddedEntry(e);if(t){let i=this.decodeBase64ToBytes(t.base64);return new TextDecoder().decode(i)}let r=this.normalize(e);return await this.fetchText(r)}async readBlob(e){let t=this.getEmbeddedEntry(e);if(t){let i=this.decodeBase64ToBytes(t.base64),o=new Uint8Array(i.byteLength);return o.set(i),new Blob([o],{type:t.mimeType??"application/octet-stream"})}let r=this.normalize(e);return await this.fetchBlob(r)}async fetchText(e){let t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status} while fetching ${e}`);return await t.text()}async fetchBlob(e){let t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status} while fetching blob from ${e}`);return await t.blob()}getScheme(e){let t=/^([a-z]+[a-z0-9+.-]*):\/\//i.exec(e.trim());return t?t[1].toLowerCase():""}buildUrl(e){let t=e.replace(/^\/+/,"");return`${this.baseUrl}${t}`}getEmbeddedEntry(e){let t=this.toEmbeddedPath(e);return t?this.embeddedResources.get(t)??null:null}toEmbeddedPath(e){let t=this.getScheme(e);return t==="res"?this.normalizeEmbeddedPath(e.substring(6)):t?null:this.normalizeEmbeddedPath(e)}normalizeEmbeddedPath(e){return e.replace(/\\/g,"/").replace(/^\/+/,"")}decodeBase64ToBytes(e){let t=atob(e),r=new Uint8Array(t.length);for(let i=0;i<t.length;i+=1)r[i]=t.charCodeAt(i);return r}};var Oi="__PIX3_GAME_DEBUG__";function cw(n){let e=globalThis;return e[Oi]=n,()=>{e[Oi]===n&&delete e[Oi]}}function uw(){return globalThis[Oi]??null}var Wl="__PIX3_RUNTIME_SCENE__";function es(n){let e=globalThis;e[Wl]=n??void 0}function dw(){return globalThis[Wl]??null}var Gl="__PIX3_RUNTIME_PROPERTY_SINK__";function ts(n){let e=globalThis;e[Gl]=n??void 0}function hw(){return globalThis[Gl]??null}var Li="__PIX3_PHYSICS_DEBUG__";function pw(n){let e=globalThis;return e[Li]=n??void 0,()=>{e[Li]===n&&delete e[Li]}}function ql(){return globalThis[Li]??null}var Hl="__PIX3_PHYSICS_DEBUG_ENABLED__";function mw(n){let e=globalThis;e[Hl]=n}function zi(){return globalThis[Hl]===!0}var jl="__PIX3_DIRECTION_AXES_ENABLED__";function fw(n){let e=globalThis;e[jl]=n}function Yl(){return globalThis[jl]===!0}var Pm="test:";function gw(n){return n?.startsWith(Pm)===!0}var Fi="__PIX3_SCRIPT_ERROR_SINK__";function yw(n){let e=globalThis;return e[Fi]=n??void 0,()=>{e[Fi]===n&&delete e[Fi]}}function km(){return globalThis[Fi]??null}var _i="__PIX3_SIGNAL_EMIT_SINK__";function bw(n){let e=globalThis;return e[_i]=n??void 0,()=>{e[_i]===n&&delete e[_i]}}function Am(){return globalThis[_i]??null}function $l(n){let e=Am();if(e)try{e(n)}catch{}}function Dt(n){let e=km();if(e)try{e(n)}catch{}}function Nt(n){return n instanceof Error?{message:`${n.name}: ${n.message}`,stack:n.stack}:{message:String(n)}}var Me=new z(1,1);var ti=new WeakMap,Kl=n=>typeof n=="object"&&n!==null||typeof n=="function";function Tm(n,e){if(!Kl(n))return;let t=ti.get(n);t||(t=new Set,ti.set(n,t)),t.add(e)}function rs(n,e){if(!Kl(n))return;let t=ti.get(n);t&&(t.delete(e),t.size===0&&ti.delete(n))}function ar(n){if(!Kl(n))return;let e=ti.get(n);if(e){ti.delete(n);for(let t of e)try{t.host.disconnect(t.signal,n,t.method)}catch(r){console.error("[signals] Failed to disconnect a detached target",{signal:t.signal,error:r})}}}var V=class n extends Bi{nodeId;type;name;properties;metadata;_instancePath;isContainer=!0;components=[];pendingComponents=[];groups=new Set;_selfVisible=!0;hiddenByEditor=!1;_signals=new Map;_disposed=!1;get isDisposed(){return this._disposed}_input;_scene;constructor(e){super(),this.nodeId=e.id,this.uuid=e.id,this.type=e.type??"Group",this.name=e.name??this.type,this.properties={...e.properties??{}},this.metadata={...e.metadata??{}},this._instancePath=e.instancePath??null;for(let t of e.groups??[])typeof t=="string"&&t.trim().length>0&&this.groups.add(t.trim());this.properties.visible!==void 0&&(this.visible=!!this.properties.visible),this.properties.locked!==void 0&&(this.userData.locked=!!this.properties.locked),this.userData={...this.userData,nodeId:this.nodeId,metadata:this.metadata,properties:this.properties}}get instancePath(){return this._instancePath}setInstancePath(e){this._instancePath=e}get input(){return this._input}set input(e){this._input=e;for(let t of this.children)t instanceof n&&(t.input=e);for(let t of this.components)t.input=e}get scene(){return this._scene}set scene(e){this._scene=e;for(let t of this.children)t instanceof n&&(t.scene=e);for(let t of this.components)t.scene=e}get parentNode(){return this.parent instanceof n?this.parent:null}adoptChild(e){if(e===this)throw new Error("Cannot adopt node as its own child.");this.add(e),this._input&&(e.input=this._input),this._scene&&(e.scene=this._scene)}disownChild(e){this.remove(e)}findById(e){if(this.nodeId===e)return this;for(let t of this.children){let r=t instanceof n?t.findById(e):null;if(r)return r}return null}findByName(e){if(this.name===e)return this;for(let t of this.children){let r=t instanceof n?t.findByName(e):null;if(r)return r}return null}getChildByName(e){for(let t of this.children)if(t instanceof n&&t.name===e)return t;return null}findByPath(e){let t=e.split("/").map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0)return null;let r=this;for(let i of t)if(r=r?r.getChildByName(i):null,!r)return null;return r}findNode(e){return e.includes("/")?this.findByPath(e):this.findById(e)??this.findByName(e)}addComponent(e){if(this.components.includes(e)){console.warn(`[NodeBase] Component ${e.id} is already attached to node ${this.nodeId}`);return}e.node=this,this._input&&(e.input=this._input),this._scene&&(e.scene=this._scene),this.components.push(e);let t=e.onAttach;t&&this.runComponentHook(e,"attach",()=>t.call(e,this));let r=this.components.some(o=>o._started),i=e.onStart;r&&e.enabled&&i&&(this.runComponentHook(e,"start",()=>i.call(e)),e._started=!0)}runComponentHook(e,t,r){try{return r(),!0}catch(i){e.enabled=!1;let{message:o,stack:s}=Nt(i);return console.error(`[NodeBase] Script "${e.type}" threw in ${t} on node "${this.name}" (disabled):`,i),Dt({phase:t,message:o,stack:s,nodeId:this.nodeId,nodeName:this.name,componentType:e.type,componentId:e.id}),!1}}getComponent(e){let t=this.components.find(r=>r instanceof e);return t||null}removeComponent(e){let t=this.components.indexOf(e);if(t===-1){console.warn(`[NodeBase] Component ${e.id} is not attached to node ${this.nodeId}`);return}e.onDetach&&e.onDetach(),ar(e),e.resetStartedState&&e.resetStartedState(),e.node=null,this.components.splice(t,1)}isVisibleInTree(){let e=this;for(;e;){if(!e.visible)return!1;e=e.parent}return!0}get authoredVisible(){return this._selfVisible}tick(e){for(let t of this.components){if(!t.enabled)continue;let r=t.onStart;if(!t._started&&r){let o=this.runComponentHook(t,"start",()=>r.call(t));if(t._started=!0,!o)continue}let i=t.onUpdate;t.enabled&&i&&this.runComponentHook(t,"update",()=>i.call(t,e))}for(let t of this.children)t instanceof n&&t.tick(e)}signal(e){!e||!e.trim()||this._signals.has(e)||this._signals.set(e,new Set)}emit(e,...t){let r=this._signals.get(e);if($l({nodeId:this.nodeId,nodeName:this.name,signal:e,listenerCount:r?.size??0,args:t}),!(!r||r.size===0))for(let i of r)try{i.method.call(i.target,...t)}catch(o){console.error("[NodeBase] Signal listener failed",{nodeId:this.nodeId,signal:e,error:o})}}connect(e,t,r){if(!e||!e.trim()||typeof r!="function")return;let i=this._signals.get(e)??new Set;for(let s of i)if(s.target===t&&s.method===r)return;let o={target:t,method:r,host:this,signal:e};i.add(o),this._signals.set(e,i),Tm(t,o)}disconnect(e,t,r){let i=this._signals.get(e);if(i){for(let o of i)o.target===t&&o.method===r&&(i.delete(o),rs(t,o));i.size===0&&this._signals.delete(e)}}disconnectAll(e){if(!e){for(let r of this._signals.values())this.unregisterLinks(r);this._signals.clear();return}let t=this._signals.get(e);t&&this.unregisterLinks(t),this._signals.delete(e)}disconnectAllFromTarget(e){for(let[t,r]of this._signals.entries()){for(let i of r)i.target===e&&(r.delete(i),rs(e,i));r.size===0&&this._signals.delete(t)}}unregisterLinks(e){for(let t of e)rs(t.target,t)}addToGroup(e){let t=e.trim();if(!t)return!1;let r=this.groups.size;return this.groups.add(t),this.groups.size!==r}removeFromGroup(e){return this.groups.delete(e.trim())}isInGroup(e){return this.groups.has(e.trim())}static freeQueue=[];_freeQueued=!1;queueFree(){this._disposed||this._freeQueued||(this._freeQueued=!0,n.freeQueue.push(this))}static flushFreeQueue(){if(n.freeQueue.length===0)return;let e=n.freeQueue.splice(0,n.freeQueue.length);for(let t of e)t._freeQueued=!1,!t._disposed&&(t.detachComponentsDeep(),t.dispose())}detachComponentsDeep(){for(;this.components.length>0;)this.removeComponent(this.components[this.components.length-1]);for(let e of[...this.children])e instanceof n&&e.detachComponentsDeep()}dispose(){if(!this._disposed){this._disposed=!0;for(let e of[...this.children])e instanceof n&&e.dispose();for(let e of this.components)ar(e),e.node=null;this.components.length=0,this.disconnectAll(),this.disposeResources(),this.removeFromParent()}}disposeResources(){let e=this.children;for(let t of e)t instanceof n||t.traverse(r=>{if(r instanceof n)return;let i=r.geometry;i&&i!==Me&&i.dispose?.();let o=r.material;if(Array.isArray(o))for(let s of o)s?.dispose?.();else o?.dispose?.()})}static getPropertySchema(){return{nodeType:"NodeBase",properties:[{name:"id",type:"string",ui:{label:"Node ID",description:"Unique identifier for this node",group:"Base",readOnly:!0},getValue:e=>e.nodeId,setValue:()=>{}},{name:"name",type:"string",ui:{label:"Name",description:"Display name for this node",group:"Base"},getValue:e=>e.name,setValue:(e,t)=>{e.name=String(t)}},{name:"type",type:"string",ui:{label:"Type",description:"Node type",group:"Base",readOnly:!0},getValue:e=>e.type,setValue:()=>{}},{name:"groups",type:"object",ui:{label:"Groups",description:"Node groups used for runtime querying and call-group operations",group:"Base",hidden:!0},getValue:e=>Array.from(e.groups),setValue:(e,t)=>{let r=Array.isArray(t)?t.filter(o=>typeof o=="string"):[],i=e;i.groups.clear();for(let o of r){let s=o.trim();s&&i.groups.add(s)}}},{name:"visible",type:"boolean",ui:{label:"Visible",description:"Whether the node is visible in the viewport",group:"Editor"},getValue:e=>e.authoredVisible,setValue:(e,t)=>{let r=e,i=!!t;r.visible=i,r.properties.visible=i}},{name:"initiallyVisible",type:"boolean",ui:{label:"Initially Visible",description:"Whether the node starts visible when entering play mode",group:"Base"},getValue:e=>{let t=e;return typeof t.properties.initiallyVisible=="boolean"?t.properties.initiallyVisible:t.visible},setValue:(e,t)=>{let r=e;r.properties.initiallyVisible=!!t}},{name:"locked",type:"boolean",ui:{label:"Locked",description:"Whether the node is locked and cannot be selected in the viewport",group:"Editor"},getValue:e=>!!e.userData.locked,setValue:(e,t)=>{let r=e,i=!!t;r.userData.locked=i,r.properties.locked=i}},{name:"editorOnly",type:"boolean",ui:{label:"Editor Only",description:"Annotation node (label, guide): visible while authoring, stripped from play mode and exported games",group:"Editor"},getValue:e=>e.properties.editorOnly===!0,setValue:(e,t)=>{e.properties.editorOnly=!!t}}],groups:{Base:{label:"Base Properties",description:"Core node properties",expanded:!0},Editor:{label:"Editor",description:"Editor and play-mode defaults",expanded:!0}}}}};Object.defineProperty(V.prototype,"visible",{configurable:!0,enumerable:!0,get(){return this._selfVisible&&!this.hiddenByEditor},set(n){this._selfVisible=n,this.properties!==void 0&&(this.properties.visible=n)}});var U=class n extends V{_opacity;visibleOpacity;opacityMaterials=new Set;visibilityFade=null;constructor(e,t="Node3D"){super({...e,type:t}),e.position&&this.position.copy(e.position),e.rotation?this.rotation.copy(e.rotation):this.rotation.set(0,0,0),this.rotation.order=e.rotationOrder??this.rotation.order,e.scale&&this.scale.copy(e.scale),this._opacity=n.clampOpacity(e.opacity??1),this.visibleOpacity=this._opacity>0?this._opacity:1}get opacity(){return this._opacity}set opacity(e){let t=n.clampOpacity(e);this._opacity!==t&&(this._opacity=t,!this.visibilityFade&&t>0&&(this.visibleOpacity=t),this.applyOpacityToMaterials())}hide(e=0,t){let r=n.toNonNegativeSeconds(e);if(this.opacity>0&&(this.visibleOpacity=this.opacity),r===0){this.visibilityFade=null,this.opacity=0,this.setVisibleState(!1),t?.();return}this.setVisibleState(!0),this.visibilityFade={from:this.opacity,to:0,duration:r,elapsed:0,hideAfterComplete:!0,onComplete:t}}show(e=0,t){let r=n.toNonNegativeSeconds(e),i=this.visibleOpacity>0?this.visibleOpacity:1;if(this.setVisibleState(!0),r===0){this.visibilityFade=null,this.opacity=i,t?.();return}this.visibilityFade={from:this.opacity,to:i,duration:r,elapsed:0,hideAfterComplete:!1,onComplete:t}}tick(e){if(super.tick(e),!this.visibilityFade)return;let t=this.visibilityFade;t.elapsed=Math.min(t.duration,t.elapsed+Math.max(0,e));let r=t.duration>0?t.elapsed/t.duration:1;this.opacity=t.from+(t.to-t.from)*r,!(t.elapsed<t.duration)&&(this.opacity=t.to,this.visibilityFade=null,t.hideAfterComplete&&this.setVisibleState(!1),t.onComplete?.())}registerOpacityMaterial(e,t){t!==void 0?e.userData.__pix3BaseOpacity=n.clampOpacity(t):typeof e.userData.__pix3BaseOpacity!="number"&&(e.userData.__pix3BaseOpacity=n.clampOpacity(e.opacity)),e.userData.__pix3OriginalTransparent===void 0&&(e.userData.__pix3OriginalTransparent=e.transparent),this.opacityMaterials.add(e),this.applyOpacityToMaterial(e)}applyOpacityToMaterials(){for(let e of this.opacityMaterials)this.applyOpacityToMaterial(e)}applyOpacityToMaterial(e){let t=e.userData.__pix3BaseOpacity,r=typeof t=="number"?n.clampOpacity(t):n.clampOpacity(e.opacity);e.opacity=r*this._opacity;let i=e.userData.__pix3OriginalTransparent;e.transparent=!!i||e.opacity<1,e.needsUpdate=!0}setVisibleState(e){this.visible=e,this.properties.visible=e}static clampOpacity(e){let t=Number.isFinite(e)?e:1;return Math.max(0,Math.min(1,t))}static toNonNegativeSeconds(e){return Number.isFinite(e)?Math.max(0,e):0}get treeColor(){return"#fe9ebeff"}get treeIcon(){return"box"}static getPropertySchema(){let e=V.getPropertySchema();return{nodeType:"Node3D",extends:"NodeBase",properties:[...e.properties,{name:"position",type:"vector3",ui:{label:"Position",group:"Transform",step:.01,precision:2},getValue:t=>{let r=t;return{x:r.position.x,y:r.position.y,z:r.position.z}},setValue:(t,r)=>{let i=t,o=r;i.position.x=o.x,i.position.y=o.y,i.position.z=o.z}},{name:"rotation",type:"euler",ui:{label:"Rotation",description:"Pitch (X), Yaw (Y), Roll (Z)",group:"Transform",step:.1,precision:1,unit:"\xB0"},getValue:t=>{let r=t;return{x:r.rotation.x*(180/Math.PI),y:r.rotation.y*(180/Math.PI),z:r.rotation.z*(180/Math.PI)}},setValue:(t,r)=>{let i=t,o=r;i.rotation.x=o.x*(Math.PI/180),i.rotation.y=o.y*(Math.PI/180),i.rotation.z=o.z*(Math.PI/180)}},{name:"scale",type:"vector3",ui:{label:"Scale",group:"Transform",step:.01,precision:2,min:0},getValue:t=>{let r=t;return{x:r.scale.x,y:r.scale.y,z:r.scale.z}},setValue:(t,r)=>{let i=t,o=r;i.scale.x=o.x,i.scale.y=o.y,i.scale.z=o.z}}],groups:{...e.groups,Transform:{label:"Transform",description:"3D position, rotation, and scale",expanded:!0}}}}};var Mm=Symbol("pix3.reactiveSchemaProperties"),Dm=Symbol("pix3.reactiveSchemaPropertiesInFlight"),Nm=(n,e)=>{let t=Object.getOwnPropertyDescriptor(n,e);return t!==void 0&&t.writable===!0&&!("get"in t)};function Em(n,e){let{name:t,setValue:r}=e,i=Object.getOwnPropertyDescriptor(n,t);if(i===void 0)return"skipped-missing";if(!Nm(n,t))return"skipped-accessor";let o=i.value,s=!1,a=n;return Object.defineProperty(n,t,{configurable:!0,enumerable:i.enumerable,get:()=>o,set(l){let c=a[Dm]??=new Set;if(c.has(t)){o=l,s=!0;return}c.add(t),s=!1;try{r(n,l),!s&&(o===null||typeof o!="object")&&(o=e.getValue(n))}finally{c.delete(t)}}}),"installed"}var Cm=new WeakMap,Sw=n=>{if(typeof n!="function")return n;let e=Cm.get(n);if(e)return e;let t=n();return Cm.set(n,t),t};function G(n,e){let t=Sw(e),r=n,i=r[Mm]??=new Set,o=[];for(let s of t.properties)i.has(s.name)&&!Nm(n,s.name)||Em(n,s)==="installed"&&(i.add(s.name),o.push(s.name));return o}function vw(n){return n[Mm]??new Set}function ri(n,e,t){let r=n,i=r[Dm]??=new Set,o=i.has(e);i.add(e);try{n[e]=t}finally{o||i.delete(e)}}var ct=class n extends U{src;castShadow;receiveShadow;animations=[];mixer=null;currentAction=null;activeAnimation=null;initialAnimation;_isPlaying;_isLoop;hasAttemptedInitialAnimation=!1;constructor(e){super(e,"MeshInstance"),this.src=e.src??null,this.castShadow=e.castShadow??!0,this.receiveShadow=e.receiveShadow??!0,this.initialAnimation=e.initialAnimation??null,this._isPlaying=e.isPlaying??!0,this._isLoop=e.isLoop??!0,G(this,n.getPropertySchema)}get isPlaying(){return this._isPlaying}set isPlaying(e){let t=!!e;this._isPlaying!==t&&(this._isPlaying=t,this.currentAction&&(this.currentAction.paused=!t,t&&this.currentAction.play()),t&&!this.currentAction&&(this.hasAttemptedInitialAnimation=!1))}get isLoop(){return this._isLoop}set isLoop(e){let t=!!e;this._isLoop!==t&&(this._isLoop=t,this.currentAction&&this.applyLoopMode(this.currentAction))}playAnimation(e,t){this.isPlaying=!0,this.setAnimation(e,t)}setAnimation(e,t){let r=this.animations.find(i=>i.name===e);if(!r){console.warn(`[MeshInstance] Animation '${e}' not found on node ${this.nodeId}`);return}this.mixer||(this.mixer=new Zo(this)),this.currentAction&&this.currentAction.stop(),this.currentAction=this.mixer.clipAction(r),this.applyLoopMode(this.currentAction,t),this.currentAction.reset().play(),this.mixer.update(0),this.currentAction.paused=!this._isPlaying,this.activeAnimation=e,this.hasAttemptedInitialAnimation=!0}showDefaultPose(){if(this.animations.length===0){this.mixer&&this.mixer.stopAllAction(),this.currentAction=null,this.activeAnimation=null,this.hasAttemptedInitialAnimation=!1;return}let t=(this.initialAnimation?this.animations.find(i=>i.name===this.initialAnimation):null)??this.animations[0];this.mixer||(this.mixer=new Zo(this)),this.currentAction&&this.currentAction.stop();let r=this.mixer.clipAction(t);r.reset().play(),this.mixer.update(0),r.paused=!0,this.currentAction=r,this.activeAnimation=t.name,this.hasAttemptedInitialAnimation=!1}tick(e){super.tick(e),this.playInitialAnimationIfNeeded(),this.mixer&&this._isPlaying&&this.mixer.update(e)}playInitialAnimationIfNeeded(){if(this.hasAttemptedInitialAnimation||this.animations.length===0)return;let e=this.initialAnimation?this.animations.find(r=>r.name===this.initialAnimation):null;this.initialAnimation&&!e&&console.warn(`[MeshInstance] Initial animation '${this.initialAnimation}' not found on node ${this.nodeId}. Falling back to first clip.`);let t=e??this.animations[0];this.setAnimation(t.name)}applyLoopMode(e,t){if(t!==void 0?t:this._isLoop){e.setLoop(Qp,1/0),e.clampWhenFinished=!1;return}e.setLoop(Xp,1),e.clampWhenFinished=!0}static getPropertySchema(){let e=U.getPropertySchema();return{nodeType:"MeshInstance",extends:"Node3D",properties:[...e.properties,{name:"isPlaying",type:"boolean",ui:{label:"IsPlaying",description:"Whether animation starts and keeps advancing at runtime",group:"Animation"},getValue:t=>t.isPlaying,setValue:(t,r)=>{let i=t;i.isPlaying=!!r}},{name:"isLoop",type:"boolean",ui:{label:"IsLoop",description:"Whether animation repeats after reaching the end",group:"Animation"},getValue:t=>t.isLoop,setValue:(t,r)=>{let i=t;i.isLoop=!!r}},{name:"initialAnimation",type:"string",ui:{label:"Initial Animation",description:"Clip name to auto-play on scene start (uses first clip when empty)",group:"Animation"},getValue:t=>t.initialAnimation??"",setValue:(t,r)=>{let i=t,o=typeof r=="string"?r.trim():"";i.initialAnimation=o.length>0?o:null,i.showDefaultPose()}},{name:"castShadow",type:"boolean",ui:{label:"Cast Shadow",description:"Whether this mesh casts shadows in the scene",group:"Rendering"},getValue:t=>t.castShadow,setValue:(t,r)=>{let i=t,o=!!r;i.castShadow=o,n.applyShadowPropertiesToChildren(i,o,i.receiveShadow)}},{name:"receiveShadow",type:"boolean",ui:{label:"Receive Shadow",description:"Whether this mesh receives shadows from other objects",group:"Rendering"},getValue:t=>t.receiveShadow,setValue:(t,r)=>{let i=t,o=!!r;i.receiveShadow=o,n.applyShadowPropertiesToChildren(i,i.castShadow,o)}}],groups:{...e.groups,Animation:{label:"Animation",description:"Animation playback properties",expanded:!0},Rendering:{label:"Rendering",description:"Shadow and rendering properties",expanded:!0}}}}static applyShadowPropertiesToChildren(e,t,r){e instanceof B&&(e.castShadow=t,e.receiveShadow=r);for(let i of e.children)n.applyShadowPropertiesToChildren(i,t,r)}applyLoadedShadowProperties(){n.applyShadowPropertiesToChildren(this,this.castShadow,this.receiveShadow)}};function Ql(n,e){return e?e.texturePath.trim().length>0?e.texturePath.trim():n?.texturePath?.trim()??"":""}function Jl(n){return!!n?.texturePath?.trim()}function ww(n){let e=typeof n=="object"&&n!==null?n:{},t=typeof e.x=="number"?e.x:.5,r=typeof e.y=="number"?e.y:.5;return{x:t,y:r}}function Xl(n){let e=typeof n=="object"&&n!==null?n:{},t=typeof e.x=="number"?e.x:0,r=typeof e.y=="number"?e.y:0;return{x:t,y:r}}function He(n,e=0){return typeof n=="number"&&Number.isFinite(n)?n:e}function xw(n){let e=typeof n=="object"&&n!==null?n:{};return{x:He(e.x),y:He(e.y),width:Math.max(0,He(e.width)),height:Math.max(0,He(e.height))}}function Pw(n){return Xl(n)}function kw(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){let r=typeof t=="object"&&t!==null?t:{},i=typeof r.signal=="string"?r.signal.trim():"";if(i.length===0)continue;let o=typeof r.args=="string"?r.args:"";e.push({signal:i,args:o})}return e}function Aw(n){if(!Array.isArray(n))return[];let e=[],t=new Set;for(let r of n){let i=typeof r=="object"&&r!==null?r:{},o=typeof i.name=="string"?i.name.trim():"";if(o.length===0||t.has(o))continue;t.add(o);let s=He(i.angle);e.push({name:o,x:He(i.x,.5),y:He(i.y,.5),...s!==0?{angle:s}:{}})}return e}function Tw(n,e){let t=typeof n=="object"&&n!==null?n:null,r=Math.max(0,He(t?.width)),i=Math.max(0,He(t?.height));return r>0&&i>0?{width:r,height:i}:{width:e.width,height:e.height}}function Cw(n){return n==="ping-pong"?"ping-pong":"normal"}function Mw(n){let e=typeof n=="object"&&n!==null?n:{},t=typeof e.textureIndex=="number"?Math.max(0,Math.floor(e.textureIndex)):0,r=xw(e.boundingBox);return{textureIndex:t,offset:Xl(e.offset),repeat:Xl(e.repeat),durationMultiplier:Math.max(.001,He(e.durationMultiplier,1)),anchor:ww(e.anchor),texturePath:typeof e.texturePath=="string"?e.texturePath.trim():"",boundingBox:r,collisionPolygon:Array.isArray(e.collisionPolygon)?(e.collisionPolygon??[]).map(Pw):[],events:kw(e.events),sourceSize:Tw(e.sourceSize,r),points:Aw(e.points)}}function Zl(n,e){return!n?.points||e.length===0?null:n.points.find(t=>t.name===e)??null}function ec(n){let e=[],t=new Set;for(let r of n?.frames??[])for(let i of r.points??[])t.has(i.name)||(t.add(i.name),e.push(i.name));return e}function Dw(n,e){let t=typeof n=="object"&&n!==null?n:{},r=Array.isArray(t.frames)?t.frames??[]:[];return{name:typeof t.name=="string"&&t.name.trim().length>0?t.name.trim():`clip-${e+1}`,frames:r.map(Mw),fps:typeof t.fps=="number"&&Number.isFinite(t.fps)&&t.fps>0?t.fps:12,loop:typeof t.loop=="boolean"?t.loop:!0,playbackMode:Cw(t.playbackMode)}}function tc(n){let e=typeof n=="object"&&n!==null?n:{},t=Array.isArray(e.clips)?e.clips??[]:[];return{version:typeof e.version=="string"&&e.version.trim().length>0?e.version.trim():"1.0.0",texturePath:typeof e.texturePath=="string"?e.texturePath.trim():"",clips:t.map(Dw)}}function rc(n,e){return!n||n.clips.length===0?null:e?n.clips.find(t=>t.name===e)??n.clips[0]??null:n.clips[0]??null}var Im=["linear","nearest"],Rm="__PIX3_PROJECT_TEXTURE_FILTERING__",Nw="linear";function ic(n){let e=typeof n=="string"?n.toLowerCase():"";return Im.includes(e)?e:Nw}function Ew(n){globalThis[Rm]=ic(n)}function nc(){return ic(globalThis[Rm])}function Y(n){let e=nc()==="nearest"?Ii:jr;n.colorSpace===Pe&&n.generateMipmaps===!1&&n.minFilter===e&&n.magFilter===e||(n.colorSpace=Pe,n.generateMipmaps=!1,n.minFilter=e,n.magFilter=e,n.needsUpdate=!0)}var is=n=>typeof n=="number"&&Number.isFinite(n),ns=n=>Math.min(1,Math.max(0,n));function oc(n){if(!n||!is(n.x)||!is(n.y)||!is(n.width)||!is(n.height))return null;let e=ns(n.width),t=ns(n.height);return e<=0||t<=0?null:{x:ns(n.x),y:ns(n.y),width:e,height:t}}function lr(n,e){e?(n.offset.set(e.x,e.y),n.repeat.set(e.width,e.height)):(n.offset.set(0,0),n.repeat.set(1,1))}function Ui(n,e){return n?e?{x:n.x+e.x*n.width,y:n.y+e.y*n.height,width:e.width*n.width,height:e.height*n.height}:n:e}function Iw(n,e){return n===e?!0:!n||!e?!1:n.x===e.x&&n.y===e.y&&n.width===e.width&&n.height===e.height}var Rw="pix3atlas://",Bw="pix3AtlasRegion",Vw="pix3AtlasSize";function Wi(n){return n?n.userData.pix3AtlasRegion??null:null}function Gi(n){return n?n.userData.pix3AtlasSize??null:null}function sc(n,e,t){let r=n.userData;r.pix3AtlasRegion=e,r.pix3AtlasSize=t}function ac(n,e){let t=n.userData,r=e.userData;t.pix3AtlasRegion&&(r.pix3AtlasRegion=t.pix3AtlasRegion),t.pix3AtlasSize&&(r.pix3AtlasSize=t.pix3AtlasSize)}function lc(n,e){let t=new Map(n.sheets.map(i=>[i.id,i])),r=new Map;for(let[i,o]of Object.entries(n.frames)){let s=t.get(o.sheet);if(!s)continue;let a=s.width,l=s.height;r.set(i,{sheetPath:e(o.sheet),region:{x:o.x/a,y:1-(o.y+o.h)/l,width:o.w/a,height:o.h/l},pixelWidth:o.w,pixelHeight:o.h})}return{resolve(i){return r.get(i)??null}}}var ii=null,qi=null;function Ow(n){ii!==n&&(ii=n,qi=null)}function Lw(){return ii!==null}function cc(){if(!ii)return Promise.reject(new Error('[Spine] No Spine runtime registered. Install `@esotericsoftware/spine-threejs` (~4.3) and call `setSpineModuleLoader(() => import("@esotericsoftware/spine-threejs"))` during startup before using SpineSkeleton2D.'));if(!qi){let n=ii;qi=n().catch(e=>{throw ii===n&&(qi=null),e})}return qi}function ni(n){return`${n.skeletonPath}|${n.atlasPath}|${n.texturePath??""}`}function Bm(n,e){let t=e.trim().replace(/^\.\//,"");if(/^[a-z]+[a-z0-9+.-]*:\/\//i.test(t)||t.startsWith("/"))return t;let r=n.lastIndexOf("/");return r<0?t:`${n.slice(0,r+1)}${t}`}var Fw=/\.(png|jpg|jpeg|webp|ktx2|basis|bmp)$/i;function _w(n){let e=[],t=!0;for(let r of n.split(/\r?\n/)){if(r.trim().length===0){t=!0;continue}if(t){let i=r.trim();Fw.test(i)&&e.push(i),t=!1}}return e}function zw(n){return n.trim().toLowerCase().endsWith(".skel")}function uc(n){return n instanceof Error?n.message:String(n)}async function dc(n,e){let t=await cc(),{skeletonPath:r,atlasPath:i}=e,o=await n.readText(i),s;try{s=new t.TextureAtlas(o)}catch(d){throw new Error(`[Spine] Failed to parse atlas ${i}: ${uc(d)}`)}let a=[],l=[],c=s.pages.length===1&&e.texturePath?e.texturePath:null;try{for(let d of s.pages){let h=c??Bm(i,d.name);a.push(h);let p=await n.readBlob(h),f=await createImageBitmap(p),m=new t.ThreeJsTexture(f,d.pma);l.push(m),d.setTexture(m),Y(m.texture)}}catch(d){for(let h of l)h.dispose();throw new Error(`[Spine] Failed to load atlas pages for ${i}: ${uc(d)}`)}let u;try{let d=new t.AtlasAttachmentLoader(s);if(zw(r)){let p=await(await n.readBlob(r)).arrayBuffer();u=new t.SkeletonBinary(d).readSkeletonData(new Uint8Array(p))}else{let h=await n.readText(r);u=new t.SkeletonJson(d).readSkeletonData(h)}}catch(d){for(let h of l)h.dispose();throw new Error(`[Spine] Failed to read skeleton ${r} (atlas ${i}): ${uc(d)}. Check that the skeleton was exported from a Spine version matching the installed @esotericsoftware/spine-threejs release.`)}return{key:ni(e),spine:t,skeletonData:u,atlas:s,pagePaths:a,dispose:()=>{s.dispose()}}}function hc(n,e){if(e===Zp)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),n;if(e===Ri||e===Go){let t=n.getIndex();if(t===null){let s=[],a=n.getAttribute("position");if(a!==void 0){for(let l=0;l<a.count;l++)s.push(l);n.setIndex(s),t=n.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),n}let r=t.count-2,i=[];if(e===Ri)for(let s=1;s<=r;s++)i.push(t.getX(0)),i.push(t.getX(s)),i.push(t.getX(s+1));else for(let s=0;s<r;s++)s%2===0?(i.push(t.getX(s)),i.push(t.getX(s+1)),i.push(t.getX(s+2))):(i.push(t.getX(s+2)),i.push(t.getX(s+1)),i.push(t.getX(s)));i.length/3!==r&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");let o=n.clone();return o.setIndex(i),o.clearGroups(),o}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),n}function Vm(n){let e=new Map,t=new Map,r=n.clone();return Om(n,r,function(i,o){e.set(o,i),t.set(i,o)}),r.traverse(function(i){if(!i.isSkinnedMesh)return;let o=i,s=e.get(i),a=s.skeleton.bones;o.skeleton=s.skeleton.clone(),o.bindMatrix.copy(s.bindMatrix),o.skeleton.bones=a.map(function(l){return t.get(l)}),o.bind(o.skeleton,o.bindMatrix)}),r}function Om(n,e,t){t(n,e);for(let r=0;r<n.children.length;r++)Om(n.children[r],e.children[r],t)}var os=class extends fm{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new Sc(t)}),this.register(function(t){return new vc(t)}),this.register(function(t){return new Dc(t)}),this.register(function(t){return new Nc(t)}),this.register(function(t){return new Ec(t)}),this.register(function(t){return new xc(t)}),this.register(function(t){return new Pc(t)}),this.register(function(t){return new kc(t)}),this.register(function(t){return new Ac(t)}),this.register(function(t){return new bc(t)}),this.register(function(t){return new Tc(t)}),this.register(function(t){return new wc(t)}),this.register(function(t){return new Mc(t)}),this.register(function(t){return new Cc(t)}),this.register(function(t){return new gc(t)}),this.register(function(t){return new ss(t,W.EXT_MESHOPT_COMPRESSION)}),this.register(function(t){return new ss(t,W.KHR_MESHOPT_COMPRESSION)}),this.register(function(t){return new Ic(t)})}load(e,t,r,i){let o=this,s;if(this.resourcePath!=="")s=this.resourcePath;else if(this.path!==""){let c=ei.extractUrlBase(e);s=ei.resolveURL(c,this.path)}else s=ei.extractUrlBase(e);this.manager.itemStart(e);let a=function(c){i?i(c):console.error(c),o.manager.itemError(e),o.manager.itemEnd(e)},l=new zl(this.manager);l.setPath(this.path),l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setWithCredentials(this.withCredentials),l.load(e,function(c){try{o.parse(c,s,function(u){t(u),o.manager.itemEnd(e)},a)}catch(u){a(u)}},r,a)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,r,i){let o,s={},a={},l=new TextDecoder;if(typeof e=="string")o=JSON.parse(e);else if(e instanceof ArrayBuffer)if(l.decode(new Uint8Array(e,0,4))===Um){try{s[W.KHR_BINARY_GLTF]=new Rc(e)}catch(d){i&&i(d);return}o=JSON.parse(s[W.KHR_BINARY_GLTF].content)}else o=JSON.parse(l.decode(e));else o=e;if(o.asset===void 0||o.asset.version[0]<2){i&&i(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}let c=new zc(o,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let u=0;u<this.pluginCallbacks.length;u++){let d=this.pluginCallbacks[u](c);d.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),a[d.name]=d,s[d.name]=!0}if(o.extensionsUsed)for(let u=0;u<o.extensionsUsed.length;++u){let d=o.extensionsUsed[u],h=o.extensionsRequired||[];switch(d){case W.KHR_MATERIALS_UNLIT:s[d]=new yc;break;case W.KHR_DRACO_MESH_COMPRESSION:s[d]=new Bc(o,this.dracoLoader);break;case W.KHR_TEXTURE_TRANSFORM:s[d]=new Vc;break;case W.KHR_MESH_QUANTIZATION:s[d]=new Oc;break;default:h.indexOf(d)>=0&&a[d]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+d+'".')}}c.setExtensions(s),c.setPlugins(a),c.parse(r,i)}parseAsync(e,t){let r=this;return new Promise(function(i,o){r.parse(e,t,i,o)})}};function Uw(){let n={};return{get:function(e){return n[e]},add:function(e,t){n[e]=t},remove:function(e){delete n[e]},removeAll:function(){n={}}}}function ie(n,e,t){let r=n.json.materials[e];return r.extensions&&r.extensions[t]?r.extensions[t]:null}var W={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",KHR_MESHOPT_COMPRESSION:"KHR_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"},gc=class{constructor(e){this.parser=e,this.name=W.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let e=this.parser,t=this.parser.json.nodes||[];for(let r=0,i=t.length;r<i;r++){let o=t[r];o.extensions&&o.extensions[this.name]&&o.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,o.extensions[this.name].light)}}_loadLight(e){let t=this.parser,r="light:"+e,i=t.cache.get(r);if(i)return i;let o=t.json,l=((o.extensions&&o.extensions[this.name]||{}).lights||[])[e],c,u=new L(16777215);l.color!==void 0&&u.setRGB(l.color[0],l.color[1],l.color[2],Ge);let d=l.range!==void 0?l.range:0;switch(l.type){case"directional":c=new Jo(u),c.target.position.set(0,0,-1),c.add(c.target);break;case"point":c=new Qo(u),c.distance=d;break;case"spot":c=new Xo(u),c.distance=d,l.spot=l.spot||{},l.spot.innerConeAngle=l.spot.innerConeAngle!==void 0?l.spot.innerConeAngle:0,l.spot.outerConeAngle=l.spot.outerConeAngle!==void 0?l.spot.outerConeAngle:Math.PI/4,c.angle=l.spot.outerConeAngle,c.penumbra=1-l.spot.innerConeAngle/l.spot.outerConeAngle,c.target.position.set(0,0,-1),c.add(c.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+l.type)}return c.position.set(0,0,0),je(c,l),l.intensity!==void 0&&(c.intensity=l.intensity),c.name=t.createUniqueName(l.name||"light_"+e),i=Promise.resolve(c),t.cache.add(r,i),i}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){let t=this,r=this.parser,o=r.json.nodes[e],a=(o.extensions&&o.extensions[this.name]||{}).light;return a===void 0?null:this._loadLight(a).then(function(l){return r._getNodeRef(t.cache,a,l)})}},yc=class{constructor(){this.name=W.KHR_MATERIALS_UNLIT}getMaterialType(){return R}extendParams(e,t,r){let i=[];e.color=new L(1,1,1),e.opacity=1;let o=t.pbrMetallicRoughness;if(o){if(Array.isArray(o.baseColorFactor)){let s=o.baseColorFactor;e.color.setRGB(s[0],s[1],s[2],Ge),e.opacity=s[3]}o.baseColorTexture!==void 0&&i.push(r.assignTexture(e,"map",o.baseColorTexture,Pe))}return Promise.all(i)}},bc=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){let r=ie(this.parser,e,this.name);return r===null||r.emissiveStrength!==void 0&&(t.emissiveIntensity=r.emissiveStrength),Promise.resolve()}},Sc=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){return ie(this.parser,e,this.name)!==null?Ve:null}extendMaterialParams(e,t){let r=ie(this.parser,e,this.name);if(r===null)return Promise.resolve();let i=[];if(r.clearcoatFactor!==void 0&&(t.clearcoat=r.clearcoatFactor),r.clearcoatTexture!==void 0&&i.push(this.parser.assignTexture(t,"clearcoatMap",r.clearcoatTexture)),r.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=r.clearcoatRoughnessFactor),r.clearcoatRoughnessTexture!==void 0&&i.push(this.parser.assignTexture(t,"clearcoatRoughnessMap",r.clearcoatRoughnessTexture)),r.clearcoatNormalTexture!==void 0&&(i.push(this.parser.assignTexture(t,"clearcoatNormalMap",r.clearcoatNormalTexture)),r.clearcoatNormalTexture.scale!==void 0)){let o=r.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new I(o,o)}return Promise.all(i)}},vc=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_DISPERSION}getMaterialType(e){return ie(this.parser,e,this.name)!==null?Ve:null}extendMaterialParams(e,t){let r=ie(this.parser,e,this.name);return r===null||(t.dispersion=r.dispersion!==void 0?r.dispersion:0),Promise.resolve()}},wc=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){return ie(this.parser,e,this.name)!==null?Ve:null}extendMaterialParams(e,t){let r=ie(this.parser,e,this.name);if(r===null)return Promise.resolve();let i=[];return r.iridescenceFactor!==void 0&&(t.iridescence=r.iridescenceFactor),r.iridescenceTexture!==void 0&&i.push(this.parser.assignTexture(t,"iridescenceMap",r.iridescenceTexture)),r.iridescenceIor!==void 0&&(t.iridescenceIOR=r.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),r.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=r.iridescenceThicknessMinimum),r.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=r.iridescenceThicknessMaximum),r.iridescenceThicknessTexture!==void 0&&i.push(this.parser.assignTexture(t,"iridescenceThicknessMap",r.iridescenceThicknessTexture)),Promise.all(i)}},xc=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_SHEEN}getMaterialType(e){return ie(this.parser,e,this.name)!==null?Ve:null}extendMaterialParams(e,t){let r=ie(this.parser,e,this.name);if(r===null)return Promise.resolve();let i=[];if(t.sheenColor=new L(0,0,0),t.sheenRoughness=0,t.sheen=1,r.sheenColorFactor!==void 0){let o=r.sheenColorFactor;t.sheenColor.setRGB(o[0],o[1],o[2],Ge)}return r.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=r.sheenRoughnessFactor),r.sheenColorTexture!==void 0&&i.push(this.parser.assignTexture(t,"sheenColorMap",r.sheenColorTexture,Pe)),r.sheenRoughnessTexture!==void 0&&i.push(this.parser.assignTexture(t,"sheenRoughnessMap",r.sheenRoughnessTexture)),Promise.all(i)}},Pc=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){return ie(this.parser,e,this.name)!==null?Ve:null}extendMaterialParams(e,t){let r=ie(this.parser,e,this.name);if(r===null)return Promise.resolve();let i=[];return r.transmissionFactor!==void 0&&(t.transmission=r.transmissionFactor),r.transmissionTexture!==void 0&&i.push(this.parser.assignTexture(t,"transmissionMap",r.transmissionTexture)),Promise.all(i)}},kc=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_VOLUME}getMaterialType(e){return ie(this.parser,e,this.name)!==null?Ve:null}extendMaterialParams(e,t){let r=ie(this.parser,e,this.name);if(r===null)return Promise.resolve();let i=[];t.thickness=r.thicknessFactor!==void 0?r.thicknessFactor:0,r.thicknessTexture!==void 0&&i.push(this.parser.assignTexture(t,"thicknessMap",r.thicknessTexture)),t.attenuationDistance=r.attenuationDistance||1/0;let o=r.attenuationColor||[1,1,1];return t.attenuationColor=new L().setRGB(o[0],o[1],o[2],Ge),Promise.all(i)}},Ac=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_IOR}getMaterialType(e){return ie(this.parser,e,this.name)!==null?Ve:null}extendMaterialParams(e,t){let r=ie(this.parser,e,this.name);return r===null||(t.ior=r.ior!==void 0?r.ior:1.5),Promise.resolve()}},Tc=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_SPECULAR}getMaterialType(e){return ie(this.parser,e,this.name)!==null?Ve:null}extendMaterialParams(e,t){let r=ie(this.parser,e,this.name);if(r===null)return Promise.resolve();let i=[];t.specularIntensity=r.specularFactor!==void 0?r.specularFactor:1,r.specularTexture!==void 0&&i.push(this.parser.assignTexture(t,"specularIntensityMap",r.specularTexture));let o=r.specularColorFactor||[1,1,1];return t.specularColor=new L().setRGB(o[0],o[1],o[2],Ge),r.specularColorTexture!==void 0&&i.push(this.parser.assignTexture(t,"specularColorMap",r.specularColorTexture,Pe)),Promise.all(i)}},Cc=class{constructor(e){this.parser=e,this.name=W.EXT_MATERIALS_BUMP}getMaterialType(e){return ie(this.parser,e,this.name)!==null?Ve:null}extendMaterialParams(e,t){let r=ie(this.parser,e,this.name);if(r===null)return Promise.resolve();let i=[];return t.bumpScale=r.bumpFactor!==void 0?r.bumpFactor:1,r.bumpTexture!==void 0&&i.push(this.parser.assignTexture(t,"bumpMap",r.bumpTexture)),Promise.all(i)}},Mc=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){return ie(this.parser,e,this.name)!==null?Ve:null}extendMaterialParams(e,t){let r=ie(this.parser,e,this.name);if(r===null)return Promise.resolve();let i=[];return r.anisotropyStrength!==void 0&&(t.anisotropy=r.anisotropyStrength),r.anisotropyRotation!==void 0&&(t.anisotropyRotation=r.anisotropyRotation),r.anisotropyTexture!==void 0&&i.push(this.parser.assignTexture(t,"anisotropyMap",r.anisotropyTexture)),Promise.all(i)}},Dc=class{constructor(e){this.parser=e,this.name=W.KHR_TEXTURE_BASISU}loadTexture(e){let t=this.parser,r=t.json,i=r.textures[e];if(!i.extensions||!i.extensions[this.name])return null;let o=i.extensions[this.name],s=t.options.ktx2Loader;if(!s){if(r.extensionsRequired&&r.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,o.source,s)}},Nc=class{constructor(e){this.parser=e,this.name=W.EXT_TEXTURE_WEBP}loadTexture(e){let t=this.name,r=this.parser,i=r.json,o=i.textures[e];if(!o.extensions||!o.extensions[t])return null;let s=o.extensions[t],a=i.images[s.source],l=r.textureLoader;if(a.uri){let c=r.options.manager.getHandler(a.uri);c!==null&&(l=c)}return r.loadTextureImage(e,s.source,l)}},Ec=class{constructor(e){this.parser=e,this.name=W.EXT_TEXTURE_AVIF}loadTexture(e){let t=this.name,r=this.parser,i=r.json,o=i.textures[e];if(!o.extensions||!o.extensions[t])return null;let s=o.extensions[t],a=i.images[s.source],l=r.textureLoader;if(a.uri){let c=r.options.manager.getHandler(a.uri);c!==null&&(l=c)}return r.loadTextureImage(e,s.source,l)}},ss=class{constructor(e,t){this.name=t,this.parser=e}loadBufferView(e){let t=this.parser.json,r=t.bufferViews[e];if(r.extensions&&r.extensions[this.name]){let i=r.extensions[this.name],o=this.parser.getDependency("buffer",i.buffer),s=this.parser.options.meshoptDecoder;if(!s||!s.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return o.then(function(a){let l=i.byteOffset||0,c=i.byteLength||0,u=i.count,d=i.byteStride,h=new Uint8Array(a,l,c);return s.decodeGltfBufferAsync?s.decodeGltfBufferAsync(u,d,h,i.mode,i.filter).then(function(p){return p.buffer}):s.ready.then(function(){let p=new ArrayBuffer(u*d);return s.decodeGltfBuffer(new Uint8Array(p),u,d,h,i.mode,i.filter),p})})}else return null}},Ic=class{constructor(e){this.name=W.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){let t=this.parser.json,r=t.nodes[e];if(!r.extensions||!r.extensions[this.name]||r.mesh===void 0)return null;let i=t.meshes[r.mesh];for(let c of i.primitives)if(c.mode!==De.TRIANGLES&&c.mode!==De.TRIANGLE_STRIP&&c.mode!==De.TRIANGLE_FAN&&c.mode!==void 0)return null;let s=r.extensions[this.name].attributes,a=[],l={};for(let c in s)a.push(this.parser.getDependency("accessor",s[c]).then(u=>(l[c]=u,l[c])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(c=>{let u=c.pop(),d=u.isGroup?u.children:[u],h=c[0].count,p=[];for(let f of d){let m=new ae,g=new S,y=new _,b=new S(1,1,1),v=new Xr(f.geometry,f.material,h);for(let w=0;w<h;w++)l.TRANSLATION&&g.fromBufferAttribute(l.TRANSLATION,w),l.ROTATION&&y.fromBufferAttribute(l.ROTATION,w),l.SCALE&&b.fromBufferAttribute(l.SCALE,w),v.setMatrixAt(w,m.compose(g,y,b));for(let w in l)if(w==="_COLOR_0"){let k=l[w];v.instanceColor=new qe(k.array,k.itemSize,k.normalized)}else w!=="TRANSLATION"&&w!=="ROTATION"&&w!=="SCALE"&&f.geometry.setAttribute(w,l[w]);Bi.prototype.copy.call(v,f),this.parser.assignFinalMaterial(v),p.push(v)}return u.isGroup?(u.clear(),u.add(...p),u):p[0]}))}},Um="glTF",Hi=12,Lm={JSON:1313821514,BIN:5130562},Rc=class{constructor(e){this.name=W.KHR_BINARY_GLTF,this.content=null,this.body=null;let t=new DataView(e,0,Hi),r=new TextDecoder;if(this.header={magic:r.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==Um)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");let i=this.header.length-Hi,o=new DataView(e,Hi),s=0;for(;s<i;){let a=o.getUint32(s,!0);s+=4;let l=o.getUint32(s,!0);if(s+=4,l===Lm.JSON){let c=new Uint8Array(e,Hi+s,a);this.content=r.decode(c)}else if(l===Lm.BIN){let c=Hi+s;this.body=e.slice(c,c+a)}s+=a}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}},Bc=class{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=W.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){let r=this.json,i=this.dracoLoader,o=e.extensions[this.name].bufferView,s=e.extensions[this.name].attributes,a={},l={},c={};for(let u in s){let d=Fc[u]||u.toLowerCase();a[d]=s[u]}for(let u in e.attributes){let d=Fc[u]||u.toLowerCase();if(s[u]!==void 0){let h=r.accessors[e.attributes[u]],p=oi[h.componentType];c[d]=p.name,l[d]=h.normalized===!0}}return t.getDependency("bufferView",o).then(function(u){return new Promise(function(d,h){i.decodeDracoFile(u,function(p){for(let f in p.attributes){let m=p.attributes[f],g=l[f];g!==void 0&&(m.normalized=g)}d(p)},a,c,Ge,h)})})}},Vc=class{constructor(){this.name=W.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}},Oc=class{constructor(){this.name=W.KHR_MESH_QUANTIZATION}},as=class extends mm{constructor(e,t,r,i){super(e,t,r,i)}copySampleValue_(e){let t=this.resultBuffer,r=this.sampleValues,i=this.valueSize,o=e*i*3+i;for(let s=0;s!==i;s++)t[s]=r[o+s];return t}interpolate_(e,t,r,i){let o=this.resultBuffer,s=this.sampleValues,a=this.valueSize,l=a*2,c=a*3,u=i-t,d=(r-t)/u,h=d*d,p=h*d,f=e*c,m=f-c,g=-2*p+3*h,y=p-h,b=1-g,v=y-h+d;for(let w=0;w!==a;w++){let k=s[m+w+a],T=s[m+w+l]*u,N=s[f+w+a],A=s[f+w]*u;o[w]=b*k+v*T+g*N+y*A}return o}},Ww=new _,Lc=class extends as{interpolate_(e,t,r,i){let o=super.interpolate_(e,t,r,i);return Ww.fromArray(o).normalize().toArray(o),o}},De={FLOAT:5126,FLOAT_MAT3:35675,FLOAT_MAT4:35676,FLOAT_VEC2:35664,FLOAT_VEC3:35665,FLOAT_VEC4:35666,LINEAR:9729,REPEAT:10497,SAMPLER_2D:35678,POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6,UNSIGNED_BYTE:5121,UNSIGNED_SHORT:5123},oi={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},Fm={9728:Ii,9729:jr,9984:jp,9985:$p,9986:Yp,9987:El},_m={33071:qp,33648:Hp,10497:Wo},pc={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Fc={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},Et={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},Gw={CUBICSPLINE:void 0,LINEAR:Il,STEP:Jp},mc={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function qw(n){return n.DefaultMaterial===void 0&&(n.DefaultMaterial=new sr({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:Up})),n.DefaultMaterial}function cr(n,e,t){for(let r in t.extensions)n[r]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[r]=t.extensions[r])}function je(n,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(n.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function Hw(n,e,t){let r=!1,i=!1,o=!1;for(let c=0,u=e.length;c<u;c++){let d=e[c];if(d.POSITION!==void 0&&(r=!0),d.NORMAL!==void 0&&(i=!0),d.COLOR_0!==void 0&&(o=!0),r&&i&&o)break}if(!r&&!i&&!o)return Promise.resolve(n);let s=[],a=[],l=[];for(let c=0,u=e.length;c<u;c++){let d=e[c];if(r){let h=d.POSITION!==void 0?t.getDependency("accessor",d.POSITION):n.attributes.position;s.push(h)}if(i){let h=d.NORMAL!==void 0?t.getDependency("accessor",d.NORMAL):n.attributes.normal;a.push(h)}if(o){let h=d.COLOR_0!==void 0?t.getDependency("accessor",d.COLOR_0):n.attributes.color;l.push(h)}}return Promise.all([Promise.all(s),Promise.all(a),Promise.all(l)]).then(function(c){let u=c[0],d=c[1],h=c[2];return r&&(n.morphAttributes.position=u),i&&(n.morphAttributes.normal=d),o&&(n.morphAttributes.color=h),n.morphTargetsRelative=!0,n})}function jw(n,e){if(n.updateMorphTargets(),e.weights!==void 0)for(let t=0,r=e.weights.length;t<r;t++)n.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){let t=e.extras.targetNames;if(n.morphTargetInfluences.length===t.length){n.morphTargetDictionary={};for(let r=0,i=t.length;r<i;r++)n.morphTargetDictionary[t[r]]=r}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function Yw(n){let e,t=n.extensions&&n.extensions[W.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+fc(t.attributes):e=n.indices+":"+fc(n.attributes)+":"+n.mode,n.targets!==void 0)for(let r=0,i=n.targets.length;r<i;r++)e+=":"+fc(n.targets[r]);return e}function fc(n){let e="",t=Object.keys(n).sort();for(let r=0,i=t.length;r<i;r++)e+=t[r]+":"+n[t[r]]+";";return e}function _c(n){switch(n){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function $w(n){return n.search(/\.jpe?g($|\?)/i)>0||n.search(/^data\:image\/jpeg/)===0?"image/jpeg":n.search(/\.webp($|\?)/i)>0||n.search(/^data\:image\/webp/)===0?"image/webp":n.search(/\.ktx2($|\?)/i)>0||n.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}var Kw=new ae,zc=class{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new Uw,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let r=!1,i=-1,o=!1,s=-1;if(typeof navigator<"u"&&typeof navigator.userAgent<"u"){let a=navigator.userAgent;r=/^((?!chrome|android).)*safari/i.test(a)===!0;let l=a.match(/Version\/(\d+)/);i=r&&l?parseInt(l[1],10):-1,o=a.indexOf("Firefox")>-1,s=o?a.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||r&&i<17||o&&s<98?this.textureLoader=new Zr(this.options.manager):this.textureLoader=new bm(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new zl(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){let r=this,i=this.json,o=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(s){return s._markDefs&&s._markDefs()}),Promise.all(this._invokeAll(function(s){return s.beforeRoot&&s.beforeRoot()})).then(function(){return Promise.all([r.getDependencies("scene"),r.getDependencies("animation"),r.getDependencies("camera")])}).then(function(s){let a={scene:s[0][i.scene||0],scenes:s[0],animations:s[1],cameras:s[2],asset:i.asset,parser:r,userData:{}};return cr(o,a,i),je(a,i),Promise.all(r._invokeAll(function(l){return l.afterRoot&&l.afterRoot(a)})).then(function(){for(let l of a.scenes)l.updateMatrixWorld();e(a)})}).catch(t)}_markDefs(){let e=this.json.nodes||[],t=this.json.skins||[],r=this.json.meshes||[];for(let i=0,o=t.length;i<o;i++){let s=t[i].joints;for(let a=0,l=s.length;a<l;a++)e[s[a]].isBone=!0}for(let i=0,o=e.length;i<o;i++){let s=e[i];s.mesh!==void 0&&(this._addNodeRef(this.meshCache,s.mesh),s.skin!==void 0&&(r[s.mesh].isSkinnedMesh=!0)),s.camera!==void 0&&this._addNodeRef(this.cameraCache,s.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,r){if(e.refs[t]<=1)return r;let i=r.clone(),o=(s,a)=>{let l=this.associations.get(s);l!=null&&this.associations.set(a,l);for(let[c,u]of s.children.entries())o(u,a.children[c])};return o(r,i),i.name+="_instance_"+e.uses[t]++,i}_invokeOne(e){let t=Object.values(this.plugins);t.push(this);for(let r=0;r<t.length;r++){let i=e(t[r]);if(i)return i}return null}_invokeAll(e){let t=Object.values(this.plugins);t.unshift(this);let r=[];for(let i=0;i<t.length;i++){let o=e(t[i]);o&&r.push(o)}return r}getDependency(e,t){let r=e+":"+t,i=this.cache.get(r);if(!i){switch(e){case"scene":i=this.loadScene(t);break;case"node":i=this._invokeOne(function(o){return o.loadNode&&o.loadNode(t)});break;case"mesh":i=this._invokeOne(function(o){return o.loadMesh&&o.loadMesh(t)});break;case"accessor":i=this.loadAccessor(t);break;case"bufferView":i=this._invokeOne(function(o){return o.loadBufferView&&o.loadBufferView(t)});break;case"buffer":i=this.loadBuffer(t);break;case"material":i=this._invokeOne(function(o){return o.loadMaterial&&o.loadMaterial(t)});break;case"texture":i=this._invokeOne(function(o){return o.loadTexture&&o.loadTexture(t)});break;case"skin":i=this.loadSkin(t);break;case"animation":i=this._invokeOne(function(o){return o.loadAnimation&&o.loadAnimation(t)});break;case"camera":i=this.loadCamera(t);break;default:if(i=this._invokeOne(function(o){return o!=this&&o.getDependency&&o.getDependency(e,t)}),!i)throw new Error("Unknown type: "+e);break}this.cache.add(r,i)}return i}getDependencies(e){let t=this.cache.get(e);if(!t){let r=this,i=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(i.map(function(o,s){return r.getDependency(e,s)})),this.cache.add(e,t)}return t}loadBuffer(e){let t=this.json.buffers[e],r=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[W.KHR_BINARY_GLTF].body);let i=this.options;return new Promise(function(o,s){r.load(ei.resolveURL(t.uri,i.path),o,void 0,function(){s(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){let t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(r){let i=t.byteLength||0,o=t.byteOffset||0;return r.slice(o,o+i)})}loadAccessor(e){let t=this,r=this.json,i=this.json.accessors[e];if(i.bufferView===void 0&&i.sparse===void 0){let s=pc[i.type],a=oi[i.componentType],l=i.normalized===!0,c=new a(i.count*s);return Promise.resolve(new lt(c,s,l))}let o=[];return i.bufferView!==void 0?o.push(this.getDependency("bufferView",i.bufferView)):o.push(null),i.sparse!==void 0&&(o.push(this.getDependency("bufferView",i.sparse.indices.bufferView)),o.push(this.getDependency("bufferView",i.sparse.values.bufferView))),Promise.all(o).then(function(s){let a=s[0],l=pc[i.type],c=oi[i.componentType],u=c.BYTES_PER_ELEMENT,d=u*l,h=i.byteOffset||0,p=i.bufferView!==void 0?r.bufferViews[i.bufferView].byteStride:void 0,f=i.normalized===!0,m,g;if(p&&p!==d){let y=Math.floor(h/p),b="InterleavedBuffer:"+i.bufferView+":"+i.componentType+":"+y+":"+i.count,v=t.cache.get(b);v||(m=new c(a,y*p,i.count*p/u),v=new Vl(m,p/u),t.cache.add(b,v)),g=new Ol(v,l,h%p/u,f)}else a===null?m=new c(i.count*l):m=new c(a,h,i.count*l),g=new lt(m,l,f);if(i.sparse!==void 0){let y=pc.SCALAR,b=oi[i.sparse.indices.componentType],v=i.sparse.indices.byteOffset||0,w=i.sparse.values.byteOffset||0,k=new b(s[1],v,i.sparse.count*y),T=new c(s[2],w,i.sparse.count*l);a!==null&&(g=new lt(g.array.slice(),g.itemSize,g.normalized)),g.normalized=!1;for(let N=0,A=k.length;N<A;N++){let F=k[N];if(g.setX(F,T[N*l]),l>=2&&g.setY(F,T[N*l+1]),l>=3&&g.setZ(F,T[N*l+2]),l>=4&&g.setW(F,T[N*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}g.normalized=f}return g})}loadTexture(e){let t=this.json,r=this.options,o=t.textures[e].source,s=t.images[o],a=this.textureLoader;if(s.uri){let l=r.manager.getHandler(s.uri);l!==null&&(a=l)}return this.loadTextureImage(e,o,a)}loadTextureImage(e,t,r){let i=this,o=this.json,s=o.textures[e],a=o.images[t],l=(a.uri||a.bufferView)+":"+s.sampler;if(this.textureCache[l])return this.textureCache[l];let c=this.loadImageSource(t,r).then(function(u){u.flipY=!1,u.name=s.name||a.name||"",u.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(u.name=a.uri);let h=(o.samplers||{})[s.sampler]||{};return u.magFilter=Fm[h.magFilter]||jr,u.minFilter=Fm[h.minFilter]||El,u.wrapS=_m[h.wrapS]||Wo,u.wrapT=_m[h.wrapT]||Wo,u.generateMipmaps=!u.isCompressedTexture&&u.minFilter!==Ii&&u.minFilter!==jr,i.associations.set(u,{textures:e}),u}).catch(function(){return null});return this.textureCache[l]=c,c}loadImageSource(e,t){let r=this,i=this.json,o=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(d=>d.clone());let s=i.images[e],a=self.URL||self.webkitURL,l=s.uri||"",c=!1;if(s.bufferView!==void 0)l=r.getDependency("bufferView",s.bufferView).then(function(d){c=!0;let h=new Blob([d],{type:s.mimeType});return l=a.createObjectURL(h),l});else if(s.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");let u=Promise.resolve(l).then(function(d){return new Promise(function(h,p){let f=h;t.isImageBitmapLoader===!0&&(f=function(m){let g=new Bl(m);g.needsUpdate=!0,h(g)}),t.load(ei.resolveURL(d,o.path),f,void 0,p)})}).then(function(d){return c===!0&&a.revokeObjectURL(l),je(d,s),d.userData.mimeType=s.mimeType||$w(s.uri),d}).catch(function(d){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),d});return this.sourceCache[e]=u,u}assignTexture(e,t,r,i){let o=this;return this.getDependency("texture",r.index).then(function(s){if(!s)return null;if(r.texCoord!==void 0&&r.texCoord>0&&(s=s.clone(),s.channel=r.texCoord),o.extensions[W.KHR_TEXTURE_TRANSFORM]){let a=r.extensions!==void 0?r.extensions[W.KHR_TEXTURE_TRANSFORM]:void 0;if(a){let l=o.associations.get(s);s=o.extensions[W.KHR_TEXTURE_TRANSFORM].extendTexture(s,a),o.associations.set(s,l)}}return i!==void 0&&(s.colorSpace=i),e[t]=s,s})}assignFinalMaterial(e){let t=e.geometry,r=e.material,i=t.attributes.tangent===void 0,o=t.attributes.color!==void 0,s=t.attributes.normal===void 0;if(e.isPoints){let a="PointsMaterial:"+r.uuid,l=this.cache.get(a);l||(l=new am,Ho.prototype.copy.call(l,r),l.color.copy(r.color),l.map=r.map,l.sizeAttenuation=!1,this.cache.add(a,l)),r=l}else if(e.isLine){let a="LineBasicMaterial:"+r.uuid,l=this.cache.get(a);l||(l=new Ct,Ho.prototype.copy.call(l,r),l.color.copy(r.color),l.map=r.map,this.cache.add(a,l)),r=l}if(i||o||s){let a="ClonedMaterial:"+r.uuid+":";i&&(a+="derivative-tangents:"),o&&(a+="vertex-colors:"),s&&(a+="flat-shading:");let l=this.cache.get(a);l||(l=r.clone(),o&&(l.vertexColors=!0),s&&(l.flatShading=!0),i&&(l.normalScale&&(l.normalScale.y*=-1),l.clearcoatNormalScale&&(l.clearcoatNormalScale.y*=-1)),this.cache.add(a,l),this.associations.set(l,this.associations.get(r))),r=l}e.material=r}getMaterialType(){return sr}loadMaterial(e){let t=this,r=this.json,i=this.extensions,o=r.materials[e],s,a={},l=o.extensions||{},c=[];if(l[W.KHR_MATERIALS_UNLIT]){let d=i[W.KHR_MATERIALS_UNLIT];s=d.getMaterialType(),c.push(d.extendParams(a,o,t))}else{let d=o.pbrMetallicRoughness||{};if(a.color=new L(1,1,1),a.opacity=1,Array.isArray(d.baseColorFactor)){let h=d.baseColorFactor;a.color.setRGB(h[0],h[1],h[2],Ge),a.opacity=h[3]}d.baseColorTexture!==void 0&&c.push(t.assignTexture(a,"map",d.baseColorTexture,Pe)),a.metalness=d.metallicFactor!==void 0?d.metallicFactor:1,a.roughness=d.roughnessFactor!==void 0?d.roughnessFactor:1,d.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(a,"metalnessMap",d.metallicRoughnessTexture)),c.push(t.assignTexture(a,"roughnessMap",d.metallicRoughnessTexture))),s=this._invokeOne(function(h){return h.getMaterialType&&h.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(h){return h.extendMaterialParams&&h.extendMaterialParams(e,a)})))}o.doubleSided===!0&&(a.side=xe);let u=o.alphaMode||mc.OPAQUE;if(u===mc.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,u===mc.MASK&&(a.alphaTest=o.alphaCutoff!==void 0?o.alphaCutoff:.5)),o.normalTexture!==void 0&&s!==R&&(c.push(t.assignTexture(a,"normalMap",o.normalTexture)),a.normalScale=new I(1,1),o.normalTexture.scale!==void 0)){let d=o.normalTexture.scale;a.normalScale.set(d,d)}if(o.occlusionTexture!==void 0&&s!==R&&(c.push(t.assignTexture(a,"aoMap",o.occlusionTexture)),o.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=o.occlusionTexture.strength)),o.emissiveFactor!==void 0&&s!==R){let d=o.emissiveFactor;a.emissive=new L().setRGB(d[0],d[1],d[2],Ge)}return o.emissiveTexture!==void 0&&s!==R&&c.push(t.assignTexture(a,"emissiveMap",o.emissiveTexture,Pe)),Promise.all(c).then(function(){let d=new s(a);return o.name&&(d.name=o.name),je(d,o),t.associations.set(d,{materials:e}),o.extensions&&cr(i,d,o),d})}createUniqueName(e){let t=Sm.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){let t=this,r=this.extensions,i=this.primitiveCache;function o(a){return r[W.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,t).then(function(l){return zm(l,a,t)})}let s=[];for(let a=0,l=e.length;a<l;a++){let c=e[a],u=Yw(c),d=i[u];if(d)s.push(d.promise);else{let h;c.extensions&&c.extensions[W.KHR_DRACO_MESH_COMPRESSION]?h=o(c):h=zm(new le,c,t),i[u]={primitive:c,promise:h},s.push(h)}}return Promise.all(s)}loadMesh(e){let t=this,r=this.json,i=this.extensions,o=r.meshes[e],s=o.primitives,a=[];for(let l=0,c=s.length;l<c;l++){let u=s[l].material===void 0?qw(this.cache):this.getDependency("material",s[l].material);a.push(u)}return a.push(t.loadGeometries(s)),Promise.all(a).then(function(l){let c=l.slice(0,l.length-1),u=l[l.length-1],d=[];for(let p=0,f=u.length;p<f;p++){let m=u[p],g=s[p],y,b=c[p];if(g.mode===De.TRIANGLES||g.mode===De.TRIANGLE_STRIP||g.mode===De.TRIANGLE_FAN||g.mode===void 0)y=o.isSkinnedMesh===!0?new im(m,b):new B(m,b),y.isSkinnedMesh===!0&&y.normalizeSkinWeights(),g.mode===De.TRIANGLE_STRIP?y.geometry=hc(y.geometry,Go):g.mode===De.TRIANGLE_FAN&&(y.geometry=hc(y.geometry,Ri));else if(g.mode===De.LINES)y=new Qr(m,b);else if(g.mode===De.LINE_STRIP)y=new sm(m,b);else if(g.mode===De.LINE_LOOP)y=new jo(m,b);else if(g.mode===De.POINTS)y=new lm(m,b);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+g.mode);Object.keys(y.geometry.morphAttributes).length>0&&jw(y,o),y.name=t.createUniqueName(o.name||"mesh_"+e),je(y,o),g.extensions&&cr(i,y,g),t.assignFinalMaterial(y),d.push(y)}for(let p=0,f=d.length;p<f;p++)t.associations.set(d[p],{meshes:e,primitives:p});if(d.length===1)return o.extensions&&cr(i,d[0],o),d[0];let h=new $r;o.extensions&&cr(i,h,o),t.associations.set(h,{meshes:e});for(let p=0,f=d.length;p<f;p++)h.add(d[p]);return h})}loadCamera(e){let t,r=this.json.cameras[e],i=r[r.type];if(!i){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return r.type==="perspective"?t=new ye(E.radToDeg(i.yfov),i.aspectRatio||1,i.znear||1,i.zfar||2e6):r.type==="orthographic"&&(t=new me(-i.xmag,i.xmag,i.ymag,-i.ymag,i.znear,i.zfar)),r.name&&(t.name=this.createUniqueName(r.name)),je(t,r),Promise.resolve(t)}loadSkin(e){let t=this.json.skins[e],r=[];for(let i=0,o=t.joints.length;i<o;i++)r.push(this._loadNodeShallow(t.joints[i]));return t.inverseBindMatrices!==void 0?r.push(this.getDependency("accessor",t.inverseBindMatrices)):r.push(null),Promise.all(r).then(function(i){let o=i.pop(),s=i,a=[],l=[];for(let c=0,u=s.length;c<u;c++){let d=s[c];if(d){a.push(d);let h=new ae;o!==null&&h.fromArray(o.array,c*16),l.push(h)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[c])}return new om(a,l)})}loadAnimation(e){let t=this.json,r=this,i=t.animations[e],o=i.name?i.name:"animation_"+e,s=[],a=[],l=[],c=[],u=[];for(let d=0,h=i.channels.length;d<h;d++){let p=i.channels[d],f=i.samplers[p.sampler],m=p.target,g=m.node,y=i.parameters!==void 0?i.parameters[f.input]:f.input,b=i.parameters!==void 0?i.parameters[f.output]:f.output;m.node!==void 0&&(s.push(this.getDependency("node",g)),a.push(this.getDependency("accessor",y)),l.push(this.getDependency("accessor",b)),c.push(f),u.push(m))}return Promise.all([Promise.all(s),Promise.all(a),Promise.all(l),Promise.all(c),Promise.all(u)]).then(function(d){let h=d[0],p=d[1],f=d[2],m=d[3],g=d[4],y=[];for(let v=0,w=h.length;v<w;v++){let k=h[v],T=p[v],N=f[v],A=m[v],F=g[v];if(k===void 0)continue;k.updateMatrix&&k.updateMatrix();let Z=r._createAnimationTracks(k,T,N,A,F);if(Z)for(let ne=0;ne<Z.length;ne++)y.push(Z[ne])}let b=new _l(o,void 0,y);return je(b,i),b})}createNodeMesh(e){let t=this.json,r=this,i=t.nodes[e];return i.mesh===void 0?null:r.getDependency("mesh",i.mesh).then(function(o){let s=r._getNodeRef(r.meshCache,i.mesh,o);return i.weights!==void 0&&s.traverse(function(a){if(a.isMesh)for(let l=0,c=i.weights.length;l<c;l++)a.morphTargetInfluences[l]=i.weights[l]}),s})}loadNode(e){let t=this.json,r=this,i=t.nodes[e],o=r._loadNodeShallow(e),s=[],a=i.children||[];for(let c=0,u=a.length;c<u;c++)s.push(r.getDependency("node",a[c]));let l=i.skin===void 0?Promise.resolve(null):r.getDependency("skin",i.skin);return Promise.all([o,Promise.all(s),l]).then(function(c){let u=c[0],d=c[1],h=c[2];h!==null&&u.traverse(function(p){p.isSkinnedMesh&&p.bind(h,Kw)});for(let p=0,f=d.length;p<f;p++)u.add(d[p]);if(u.userData.pivot!==void 0&&d.length>0){let p=u.userData.pivot,f=d[0];u.pivot=new S().fromArray(p),u.position.x-=p[0],u.position.y-=p[1],u.position.z-=p[2],f.position.set(0,0,0),delete u.userData.pivot}return u})}_loadNodeShallow(e){let t=this.json,r=this.extensions,i=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];let o=t.nodes[e],s=o.name?i.createUniqueName(o.name):"",a=[],l=i._invokeOne(function(c){return c.createNodeMesh&&c.createNodeMesh(e)});return l&&a.push(l),o.camera!==void 0&&a.push(i.getDependency("camera",o.camera).then(function(c){return i._getNodeRef(i.cameraCache,o.camera,c)})),i._invokeAll(function(c){return c.createNodeAttachment&&c.createNodeAttachment(e)}).forEach(function(c){a.push(c)}),this.nodeCache[e]=Promise.all(a).then(function(c){let u;if(o.isBone===!0?u=new nm:c.length>1?u=new $r:c.length===1?u=c[0]:u=new Bi,u!==c[0])for(let d=0,h=c.length;d<h;d++)u.add(c[d]);if(o.name&&(u.userData.name=o.name,u.name=s),je(u,o),o.extensions&&cr(r,u,o),o.matrix!==void 0){let d=new ae;d.fromArray(o.matrix),u.applyMatrix4(d)}else o.translation!==void 0&&u.position.fromArray(o.translation),o.rotation!==void 0&&u.quaternion.fromArray(o.rotation),o.scale!==void 0&&u.scale.fromArray(o.scale);if(!i.associations.has(u))i.associations.set(u,{});else if(o.mesh!==void 0&&i.meshCache.refs[o.mesh]>1){let d=i.associations.get(u);i.associations.set(u,{...d})}return i.associations.get(u).nodes=e,u}),this.nodeCache[e]}loadScene(e){let t=this.extensions,r=this.json.scenes[e],i=this,o=new $r;r.name&&(o.name=i.createUniqueName(r.name)),je(o,r),r.extensions&&cr(t,o,r);let s=r.nodes||[],a=[];for(let l=0,c=s.length;l<c;l++)a.push(i.getDependency("node",s[l]));return Promise.all(a).then(function(l){for(let u=0,d=l.length;u<d;u++){let h=l[u];h.parent!==null?o.add(Vm(h)):o.add(h)}let c=u=>{let d=new Map;for(let[h,p]of i.associations)(h instanceof Ho||h instanceof Bl)&&d.set(h,p);return u.traverse(h=>{let p=i.associations.get(h);p!=null&&d.set(h,p)}),d};return i.associations=c(o),o})}_createAnimationTracks(e,t,r,i,o){let s=[],a=e.name?e.name:e.uuid,l=[];Et[o.path]===Et.weights?e.traverse(function(h){h.morphTargetInfluences&&l.push(h.name?h.name:h.uuid)}):l.push(a);let c;switch(Et[o.path]){case Et.weights:c=Fl;break;case Et.rotation:c=$o;break;case Et.translation:case Et.scale:c=Ko;break;default:r.itemSize===1?c=Fl:c=Ko;break}let u=i.interpolation!==void 0?Gw[i.interpolation]:Il,d=this._getArrayFromAccessor(r);for(let h=0,p=l.length;h<p;h++){let f=new c(l[h]+"."+Et[o.path],t.array,d,u);i.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(f),s.push(f)}return s}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){let r=_c(t.constructor),i=new Float32Array(t.length);for(let o=0,s=t.length;o<s;o++)i[o]=t[o]*r;t=i}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(r){let i=this instanceof $o?Lc:as;return new i(this.times,this.values,this.getValueSize()/3,r)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}};function Xw(n,e,t){let r=e.attributes,i=new em;if(r.POSITION!==void 0){let a=t.json.accessors[r.POSITION],l=a.min,c=a.max;if(l!==void 0&&c!==void 0){if(i.set(new S(l[0],l[1],l[2]),new S(c[0],c[1],c[2])),a.normalized){let u=_c(oi[a.componentType]);i.min.multiplyScalar(u),i.max.multiplyScalar(u)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;let o=e.targets;if(o!==void 0){let a=new S,l=new S;for(let c=0,u=o.length;c<u;c++){let d=o[c];if(d.POSITION!==void 0){let h=t.json.accessors[d.POSITION],p=h.min,f=h.max;if(p!==void 0&&f!==void 0){if(l.setX(Math.max(Math.abs(p[0]),Math.abs(f[0]))),l.setY(Math.max(Math.abs(p[1]),Math.abs(f[1]))),l.setZ(Math.max(Math.abs(p[2]),Math.abs(f[2]))),h.normalized){let m=_c(oi[h.componentType]);l.multiplyScalar(m)}a.max(l)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}i.expandByVector(a)}n.boundingBox=i;let s=new rm;i.getCenter(s.center),s.radius=i.min.distanceTo(i.max)/2,n.boundingSphere=s}function zm(n,e,t){let r=e.attributes,i=[];function o(s,a){return t.getDependency("accessor",s).then(function(l){n.setAttribute(a,l)})}for(let s in r){let a=Fc[s]||s.toLowerCase();a in n.attributes||i.push(o(r[s],a))}if(e.indices!==void 0&&!n.index){let s=t.getDependency("accessor",e.indices).then(function(a){n.setIndex(a)});i.push(s)}return Rl.workingColorSpace!==Ge&&"COLOR_0"in r&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${Rl.workingColorSpace}" not supported.`),je(n,e),Xw(n,e,t),Promise.all(i).then(function(){return e.targets!==void 0?Hw(n,e.targets,t):n})}var Uc=class{resources;audioService;textureLoader;textureCache=new Map;textureLoadInFlight=new Map;animationResourceCache=new Map;animationResourceLoadInFlight=new Map;audioLoadInFlight=new Map;audioMetadataCache=new Map;spineAssetCache=new Map;spineAssetLoadInFlight=new Map;atlasResolver=null;constructor(e,t){this.resources=e,this.audioService=t,this.textureLoader=new Zr}trackInFlight(e,t,r){e.set(t,r);let i=()=>{e.get(t)===r&&e.delete(t)};return r.then(i,i),r}getResourceManager(){return this.resources}setAtlasResolver(e){this.atlasResolver=e}seedTexture(e,t){this.textureCache.set(e,t)}evictTexture(e){this.textureCache.delete(e)}getAudioMetadata(e){let t=this.audioMetadataCache.get(e);return t?{...t}:null}async loadAsset(e,t,r){let i=this.getExtension(e);switch(i){case"glb":case"gltf":return this.loadGltfAsMeshInstance(e,t,r);case"png":case"jpg":case"jpeg":case"webp":throw new Error(`[AssetLoader] Generic image node creation not yet implemented. Use loadTexture. Path: ${e}`);case"mp3":case"ogg":case"wav":throw await this.loadAudio(e),new Error(`[AssetLoader] Audio assets are not node assets. Use loadAudio() instead. Path: ${e}`);case"pix3anim":throw await this.loadAnimationResource(e),new Error(`[AssetLoader] Animation assets are metadata assets. Use loadAnimationResource() instead. Path: ${e}`);default:throw new Error(`[AssetLoader] Unsupported asset type: ${i}`)}}async loadAudio(e){if(!this.audioService)throw new Error("[AssetLoader] AudioService is required to decode audio assets.");let t=this.audioService,r=this.resources.getAudioBuffer(e);if(r)return r;let i=this.audioLoadInFlight.get(e);if(i)return i;let o=(async()=>{try{let s,a=0;if(e.startsWith("res://")){let c=await this.resources.readBlob(e);a=c.size,s=await c.arrayBuffer()}else try{let c=this.resources.normalize(e),u=await fetch(c);if(!u.ok)throw new Error(`HTTP ${u.status} while fetching ${c}`);if((u.headers.get("content-type")??"").includes("text/html"))throw new Error(`Unexpected HTML response for audio at ${c}`);s=await u.arrayBuffer();let h=Number(u.headers.get("content-length"));a=Number.isFinite(h)&&h>0?h:s.byteLength}catch{let c=await this.resources.readBlob(e);a=c.size,s=await c.arrayBuffer()}let l=await t.decodeAudioData(s);return this.audioMetadataCache.set(e,{resourcePath:e,sizeBytes:Math.max(0,Math.round(a||s.byteLength))}),this.resources.setAudioBuffer(e,l),l}catch(s){throw console.error(`[AssetLoader] Failed to load audio: ${e}`,s),s}})();return this.trackInFlight(this.audioLoadInFlight,e,o)}async loadTexture(e,t){let r=this.textureCache.get(e);if(r)return r;let i=this.textureLoadInFlight.get(e);if(i)return i;if(t?.atlas!==!1&&this.atlasResolver){let s=this.atlasResolver.resolve(e);if(s)return this.trackInFlight(this.textureLoadInFlight,e,this.buildAtlasView(e,s))}let o=(async()=>{let s,a=!1;if(e.startsWith("res://"))try{let l=await this.resources.readBlob(e);s=URL.createObjectURL(l),a=!0}catch(l){throw console.error(`[AssetLoader] Failed to read blob for ${e}:`,l),l}else s=this.resources.normalize(e);return new Promise((l,c)=>{this.textureLoader.load(s,u=>{a&&URL.revokeObjectURL(s),this.textureCache.set(e,u),l(u)},void 0,u=>{console.error(`[AssetLoader] Failed to load texture: ${s}`,u),a&&URL.revokeObjectURL(s),c(u)})})})();return this.trackInFlight(this.textureLoadInFlight,e,o)}async buildAtlasView(e,t){let i=(await this.loadTexture(t.sheetPath,{atlas:!1})).clone();return Y(i),lr(i,t.region),sc(i,t.region,{width:t.pixelWidth,height:t.pixelHeight}),this.textureCache.set(e,i),i}async loadAnimationResource(e){let t=this.animationResourceCache.get(e);if(t)return t;let r=this.animationResourceLoadInFlight.get(e);if(r)return r;let i=(async()=>{let o=await this.resources.readText(e),s;try{s=JSON.parse(o)}catch(l){throw new Error(`[AssetLoader] Failed to parse animation resource ${e}: ${l instanceof Error?l.message:String(l)}`)}let a=tc(s);return this.animationResourceCache.set(e,a),a})();return this.trackInFlight(this.animationResourceLoadInFlight,e,i)}async loadSpineAsset(e){let t=ni(e),r=this.spineAssetCache.get(t);if(r)return r;let i=this.spineAssetLoadInFlight.get(t);if(i)return i;let o=(async()=>{try{let s=await dc(this.resources,e);return this.spineAssetCache.set(t,s),s}finally{this.spineAssetLoadInFlight.delete(t)}})();return this.spineAssetLoadInFlight.set(t,o),o}getCachedSpineAsset(e){return this.spineAssetCache.get(ni(e))??null}evictSpineAsset(e){let t=ni(e),r=this.spineAssetCache.get(t);r&&(this.spineAssetCache.delete(t),r.dispose())}async loadInstancingModel(e){let t=await this.loadGltf(e),r=this.findFirstMesh(t.scene);if(!r)throw new Error(`[AssetLoader] No mesh found in model: ${e}`);return{geometry:r.geometry.clone(),material:Array.isArray(r.material)?r.material.map(i=>i.clone()):r.material.clone(),scene:t.scene}}async loadGltfAsMeshInstance(e,t,r){try{let i=await this.loadGltf(e),o=i.animations.map(c=>c.clone()),s=t||crypto.randomUUID(),a=r||"mesh",l=new ct({id:s,name:a,src:e});return l.add(i.scene),l.animations=o,{node:l}}catch(i){throw console.error(`[AssetLoader] Failed to load GLTF: ${e}`,i),new Error(`Failed to load asset: ${i instanceof Error?i.message:String(i)}`)}}async loadGltf(e){let r=await(await this.resources.readBlob(e)).arrayBuffer(),i=new os;return new Promise((o,s)=>{i.parse(r,"",a=>o(a),a=>s(a))})}findFirstMesh(e){let t=null;return e.traverse(r=>{t||!(r instanceof B)||(t=r)}),t}getExtension(e){let t=e.match(/\.([a-z0-9]+)$/i);return t?t[1].toLowerCase():""}};var ut=["master","music","sfx"];function Wm(n){return typeof n!="number"||!Number.isFinite(n)?0:Math.min(1,Math.max(0,n))}var Wc=class n{static LOWPASS_OPEN_HZ=2e4;context=null;buses=new Map;snapshots=new Map;activeSnapshotName="default";activePlaybacks=new Set;activePlaybackEntries=new Map;nextPlaybackId=0;activePlaybackRevision=0;wantsAudible=!0;pageActive=!0;pausedByHost=!1;unlockedByGesture=!1;unlockFromPointerDown=()=>{this.unlock()};unlockFromKeydown=()=>{this.unlock()};handleContextStateChange=()=>{this.reconcileContextState()};constructor(){let e=window,t=window.AudioContext??e.webkitAudioContext;if(!t){console.warn("[AudioService] Web Audio API is not supported in this environment.");return}try{this.context=new t;let r=this.createBus(this.context.destination),i=this.createBus(r.input),o=this.createBus(r.input);this.buses.set("master",r),this.buses.set("music",i),this.buses.set("sfx",o)}catch(r){this.context=null,this.buses.clear(),console.warn("[AudioService] Failed to initialize AudioContext:",r);return}this.snapshots.set("default",{name:"default"}),this.snapshots.set("muffled",{name:"muffled",lowpassHz:{master:700},volumeScale:{master:.85}}),window.addEventListener("pointerdown",this.unlockFromPointerDown),window.addEventListener("keydown",this.unlockFromKeydown),window.addEventListener("blur",this.handleActivityChange),window.addEventListener("focus",this.handleActivityChange),window.addEventListener("pageshow",this.handleActivityChange),window.addEventListener("pagehide",this.handleActivityChange),document.addEventListener("visibilitychange",this.handleActivityChange),this.context.addEventListener?.("statechange",this.handleContextStateChange),this.handleActivityChange()}setVolume(e){this.setBusVolume("master",e,.03)}mute(){this.setVolume(0)}unmute(){this.setVolume(1)}setBusVolume(e,t,r=.05){let i=this.buses.get(e);!i||!this.context||(i.userVolume=Math.max(0,Number.isFinite(t)?t:1),this.applyBusGain(e,Math.max(.001,r/3)))}getBusVolume(e){return this.buses.get(e)?.userVolume??1}applyBusGain(e,t){let r=this.buses.get(e);if(!r||!this.context)return;let i=this.snapshots.get(this.activeSnapshotName)?.volumeScale?.[e]??1;r.input.gain.setTargetAtTime(r.userVolume*i,this.context.currentTime,t)}applySnapshot(e,t){let r=this.snapshots.get(e);if(!r||!this.context){r||console.warn(`[AudioService] Unknown snapshot "${e}".`);return}this.activeSnapshotName=e;let i=Math.max(.001,t?.timeConstantSec??.08);for(let o of ut)this.applyBusGain(o,i),this.buses.get(o)?.filter?.frequency.setTargetAtTime(r.lowpassHz?.[o]??n.LOWPASS_OPEN_HZ,this.context.currentTime,i)}resetSnapshot(e){this.applySnapshot("default",e)}registerSnapshot(e){if(!e||typeof e.name!="string"||e.name.length===0){console.warn("[AudioService] registerSnapshot requires a non-empty name.");return}this.snapshots.set(e.name,e)}getActiveSnapshotName(){return this.activeSnapshotName}resetBuses(){for(let e of ut){let t=this.buses.get(e);t&&(t.userVolume=1)}this.applySnapshot("default",{timeConstantSec:.01})}createBus(e){let t=this.context,r=t.createGain(),i=null;return typeof t.createBiquadFilter=="function"?(i=t.createBiquadFilter(),i.type="lowpass",i.frequency.value=n.LOWPASS_OPEN_HZ,i.Q.value=.7071,r.connect(i),i.connect(e)):r.connect(e),{input:r,filter:i,userVolume:1}}getBusInput(e){return this.buses.get(e??"sfx")?.input??this.buses.get("master").input}handleActivityChange=()=>{let e=document.visibilityState==="visible",t=typeof document.hasFocus=="function"?document.hasFocus():!0;this.pageActive=e&&t,this.updateWantsAudible()};setPaused(e){this.pausedByHost!==e&&(this.pausedByHost=e,this.updateWantsAudible())}updateWantsAudible(){this.wantsAudible=this.pageActive&&!this.pausedByHost,this.reconcileContextState()}reconcileContextState(){let e=this.context;if(e){if(e.state==="running"&&(this.unlockedByGesture=!0),!this.wantsAudible){e.state==="running"&&e.suspend().catch(()=>{});return}e.state==="suspended"&&this.unlockedByGesture&&e.resume().catch(t=>{console.warn("[AudioService] Failed to resume AudioContext:",t)})}}unlock(){this.context&&(this.unlockedByGesture=!0,this.reconcileContextState())}stopAll(){let e=Array.from(this.activePlaybacks);this.activePlaybacks.clear(),this.activePlaybackEntries.clear(),this.activePlaybackRevision++;for(let t of e)try{t.stop()}catch{}}play(e,t){if(!this.context||this.buses.size===0)return console.warn("[AudioService] Cannot play audio: AudioContext is unavailable."),{stop:()=>{},ended:Promise.resolve()};this.context.state==="suspended"&&this.wantsAudible&&console.warn("[AudioService] Attempting to play audio while context is suspended. It might not be audible until user interaction.");let r=t?.loop??!1;if(!r&&!this.wantsAudible&&this.context.state!=="running")return{stop:()=>{},ended:Promise.resolve()};let i=this.context.createBufferSource();i.buffer=e,i.loop=r;let o=Wm(t?.pitchVariation),s=Wm(t?.volumeVariation),a=o>0?1+(Math.random()*2-1)*o:1,l=s>0?1+(Math.random()*2-1)*s:1,c=Math.max(.01,(t?.playbackRate??1)*a);i.playbackRate.value=c;let u=this.context.createGain(),d=Math.max(0,(t?.volume??1)*l);u.gain.value=d;let h=u,p=null,f=typeof t?.pan=="number"?Math.max(-1,Math.min(1,t.pan)):null;f!==null&&typeof this.context.createStereoPanner=="function"&&(p=this.context.createStereoPanner(),p.pan.value=f,u.connect(p),h=p);let m=t?.bus??"sfx";i.connect(u),h.connect(this.getBusInput(m));let g,y=new Promise(F=>{g=F}),b=!1,v=()=>{b||(b=!0,this.activePlaybacks.delete(w),this.activePlaybackEntries.delete(w),this.activePlaybackRevision++,i.disconnect(),u.disconnect(),p?.disconnect(),g())},w={stop:()=>{try{i.stop()}catch{}finally{v()}},ended:y};i.onended=v;let k=this.normalizeResourcePath(t?.resourcePath),T=this.normalizePositiveNumber(e.duration),N=this.normalizePositiveNumber(e.numberOfChannels),A=this.normalizePositiveNumber(e.sampleRate);return this.activePlaybacks.add(w),this.activePlaybackEntries.set(w,{id:this.createPlaybackId(),label:this.normalizePlaybackLabel(t?.label,k),resourcePath:k,startedAtMs:this.readNowMs(),loop:i.loop,volume:d,playbackRate:c,pan:f,bus:m,durationSeconds:T,channelCount:N,sampleRate:A,bitrateKbps:this.computeBitrateKbps(T,t?.sizeBytes)}),this.activePlaybackRevision++,i.start(),w}getActivePlaybackRevision(){return this.activePlaybackRevision}getActivePlaybackSnapshot(e=this.readNowMs()){let t=Number.isFinite(e)?e:this.readNowMs();return[...this.activePlaybackEntries.values()].map(r=>({...r,elapsedMs:Math.max(0,t-r.startedAtMs)})).sort((r,i)=>i.startedAtMs-r.startedAtMs||r.label.localeCompare(i.label)||r.id.localeCompare(i.id))}getSampleRate(){return this.context?.sampleRate??null}createBuffer(e,t=1){if(!this.context)return null;try{return this.context.createBuffer(Math.max(1,Math.floor(t)),Math.max(1,Math.floor(e)),this.context.sampleRate)}catch(r){return console.warn("[AudioService] Failed to allocate an AudioBuffer:",r),null}}async decodeAudioData(e){if(!this.context)throw new Error("AudioContext is unavailable.");return this.context.decodeAudioData(e)}dispose(){window.removeEventListener("pointerdown",this.unlockFromPointerDown),window.removeEventListener("keydown",this.unlockFromKeydown),window.removeEventListener("blur",this.handleActivityChange),window.removeEventListener("focus",this.handleActivityChange),window.removeEventListener("pageshow",this.handleActivityChange),window.removeEventListener("pagehide",this.handleActivityChange),document.removeEventListener("visibilitychange",this.handleActivityChange),this.context?.removeEventListener?.("statechange",this.handleContextStateChange),this.stopAll(),this.context?.close(),this.context=null,this.buses.clear(),this.wantsAudible=!0,this.pageActive=!0,this.pausedByHost=!1,this.unlockedByGesture=!1}createPlaybackId(){return this.nextPlaybackId+=1,`playback-${this.nextPlaybackId}`}normalizePlaybackLabel(e,t){let r=typeof e=="string"?e.trim():"";return r.length>0?r:this.extractFileName(t)??"Unknown"}normalizeResourcePath(e){let t=typeof e=="string"?e.trim():"";return t.length>0?t:null}extractFileName(e){if(!e)return null;let r=(e.split(/[?#]/,1)[0]??e).split(/[\\/]/).filter(Boolean);return r.length>0?r[r.length-1]??null:null}normalizePositiveNumber(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?null:e}computeBitrateKbps(e,t){return typeof e!="number"||!Number.isFinite(e)||e<=0||typeof t!="number"||!Number.isFinite(t)||t<=0?null:t*8/e/1e3}readNowMs(){let e=globalThis.performance?.now?.();return typeof e=="number"&&Number.isFinite(e)?e:Date.now()}};var Gc=class{components=new Map;constructor(){}registerComponent(e){this.components.has(e.id)&&console.warn(`[ScriptRegistry] Component "${e.id}" is already registered. Overwriting.`),this.components.set(e.id,e)}unregisterComponent(e){return this.components.delete(e)}getComponentType(e){return this.components.get(e)}getAllComponentTypes(){return Array.from(this.components.values())}createComponent(e,t,r={}){let i=this.components.get(e);if(!i)return r.expectRegistered!==!1&&console.error(`[ScriptRegistry] Component type "${e}" not found in registry.`),null;try{return new i.componentClass(t,e)}catch(o){return console.error(`[ScriptRegistry] Failed to instantiate component "${e}":`,o),null}}getComponentPropertySchema(e){let t=this.components.get(e);return t?t.componentClass.getPropertySchema():null}searchComponents(e){let t=e.toLowerCase();return this.getAllComponentTypes().filter(r=>r.displayName.toLowerCase().includes(t)||r.description.toLowerCase().includes(t)||r.keywords.some(i=>i.toLowerCase().includes(t)))}dispose(){this.components.clear()}};var O=class{id;type;node=null;enabled=!0;config={};_started=!1;input;scene;constructor(e,t){this.id=e,this.type=t}static getPropertySchema(){return{nodeType:"Script",properties:[],groups:{}}}findNode(e){if(this.scene)return this.scene.findNode(e);let t=this.node;for(;t?.parentNode;)t=t.parentNode;return t?.findNode(e)??null}getNode(e){let t=this.findNode(e);if(!t)throw new Error(`[${this.type}] getNode("${e}"): node not found in scene`);return t}onDetach(){ar(this)}resetStartedState(){this._started=!1}};function Qw(n){return typeof n=="object"&&n!==null&&"id"in n&&"type"in n&&"enabled"in n&&"config"in n}var cs=new Set,qc=n=>`${n.family}|${n.weight??400}|${n.style??"normal"}|${n.path}`,ji=n=>`${n.family} ${n.weight??400}${n.style==="italic"?" italic":""}`,ls=new Map;function Jw(){cs.clear(),ls.clear()}function Zw(n){return cs.has(qc(n))}async function Hc(n,e,t=5e3){let r={loaded:[],failed:[]};return!n||n.length===0||typeof document>"u"||!document.fonts||typeof FontFace>"u"||await Promise.all(n.map(async i=>{let o=qc(i);if(cs.has(o))return;let s=ls.get(o);s||(s=ex(i,e,t).finally(()=>ls.delete(o)),ls.set(o,s));let a=await s;a.ok?r.loaded.push(ji(i)):r.failed.push({face:ji(i),reason:a.reason})})),r}async function ex(n,e,t){try{let r=n.path.startsWith("res://")?n.path:`res://${n.path}`,o=await(await e.readBlob(r)).arrayBuffer(),s=new FontFace(n.family,o,{weight:String(n.weight??400),style:n.style??"normal",...n.unicodeRange?{unicodeRange:n.unicodeRange}:{}}),a=await tx(s.load(),t,ji(n));return document.fonts.add(a),cs.add(qc(n)),{ok:!0}}catch(r){let i=r instanceof Error?r.message:String(r);return console.warn(`[ProjectFontLoader] ${ji(n)} (${n.path}) could not be loaded; captions in that family fall back to a system face: ${i}`),{ok:!1,reason:i}}}function tx(n,e,t){return!Number.isFinite(e)||e<=0?n:new Promise((r,i)=>{let o=setTimeout(()=>i(new Error(`${t}: timed out after ${e}ms`)),e);n.then(s=>{clearTimeout(o),r(s)},s=>{clearTimeout(o),i(s instanceof Error?s:new Error(String(s)))})})}function Gm(n,e){let t=n.getComponentPropertySchema(e);if(!t)return null;if(!Array.isArray(t.properties))return console.warn(`[SceneLoader] Component "${e}" has a malformed property schema: getPropertySchema() must return an object with a "properties" array. Skipping config application for this component.`),null;let r=t.properties,i=[];for(let o of r){if(o&&typeof o.setValue=="function"&&typeof o.name=="string"){i.push(o);continue}let s=o&&typeof o.name=="string"?`"${o.name}"`:"(unnamed)";console.warn(`[SceneLoader] Component "${e}" has a malformed property definition ${s}: each property must expose a setValue(node, value) function. Skipping this property.`)}return i}function qm(n,e,t){let r=e.id||`${t}-${e.type}-${Date.now()}`,i=n.createComponent(e.type,r,{expectRegistered:!1});if(!i)return null;i.enabled=e.enabled??!0;let o=e.config??{};i.config={...i.config,...o};let s=Gm(n,e.type);if(s)for(let a of s)o[a.name]!==void 0&&a.setValue(i,o[a.name]);return i}function us(n,e,t){if(e)for(let r of e){let i=qm(t,r,n.nodeId);if(i){n.addComponent(i);continue}n.pendingComponents.push({...r,config:{...r.config??{}}}),console.warn(`[SceneLoader] Component type "${r.type}" is not registered yet \u2014 kept as pending on node "${n.nodeId}". It will attach once the type registers, and is preserved on save.`)}}var rx=n=>Array.isArray(n?.pendingComponents);function jc(n,e){let t=0,r=[...n];for(;r.length>0;){let i=r.pop();if(!i)continue;for(let s of i.children)rx(s)&&r.push(s);if(i.pendingComponents.length===0)continue;let o=[];for(let s of i.pendingComponents){let a=qm(e,s,i.nodeId);a?(i.addComponent(a),t+=1):o.push(s)}i.pendingComponents.length=0,i.pendingComponents.push(...o)}return t}function Yi(n){let e=n.components.map(t=>({id:t.id,type:t.type,enabled:t.enabled,config:t.config&&Object.keys(t.config).length>0?t.config:{}}));for(let t of n.pendingComponents)e.push({...t,config:{...t.config??{}}});return e}function ke(n){let e=n.constructor,t=typeof e.getPropertySchema=="function"?e.getPropertySchema():{nodeType:"Unknown",properties:[]},r=n.getInstancePropertySchema?.();if(!r||r.properties.length===0)return t;let i=new Map(r.properties.map(a=>[a.name,a])),o=t.properties.map(a=>i.get(a.name)??a),s=new Set(t.properties.map(a=>a.name));for(let a of r.properties)s.has(a.name)||o.push(a);return{...t,properties:o,groups:{...t.groups,...r.groups}}}function ix(n){let e=new Map;for(let t of n.properties){let r=t.ui?.group||"General";e.has(r)||e.set(r,[]),e.get(r).push(t)}return e}function It(n,e){return n.properties.find(t=>t.name===e)}function nx(n,e){let t=e.getValue(n);if(e.type==="number"){let r=Number(t);if(isNaN(r))return"0";let i=e.ui?.precision??2;return parseFloat(r.toFixed(i)).toString()}return e.type==="boolean"?String(t===!0):e.type==="vector2"||e.type==="vector3"||e.type==="vector4"||e.type==="euler"||e.type==="object"?JSON.stringify(t):String(t??"")}function Hm(n,e){if(n.validation?.validate){let r=n.validation.validate(e);if(r===!1)return{isValid:!1,error:"Invalid value"};if(typeof r=="string")return{isValid:!1,error:r}}let t=e;return n.validation?.transform&&(t=n.validation.transform(e)),{isValid:!0,transformedValue:t}}function si(n,e,t){let r=Hm(e,t);if(!r.isValid)return{success:!1,error:r.error};try{return e.setValue(n,r.transformedValue),{success:!0}}catch(i){return{success:!1,error:String(i)}}}var jm=["normal","additive","multiply","subtract"],Yc={Normal:"normal",Additive:"additive",Multiply:"multiply",Subtract:"subtract"},ox={normal:st,additive:at,multiply:Gp,subtract:Wp};function $i(n){return typeof n=="string"&&jm.includes(n)?n:"normal"}function Ym(n){return ox[n]??st}function Ki(n,e){let t=Ym(e),r=n.transparent||e!=="normal";n.blending===t&&n.transparent===r||(n.blending=t,n.transparent=r,n.needsUpdate=!0)}var Xi=4096,M=class n extends V{static scratchUnproject=new S;isCanvasLayer=!1;_opacity;_computedOpacity;_blendMode;_zIndex;_zAsRelative;_layoutEnabled;_flow;_horizontalAlign;_verticalAlign;authoredLayoutPosition=new I;authoredLayoutSize=new I;tmpPointerWorld=new I;hasAuthoredLayoutSize=!1;opacityMaterials=new Set;visibleOpacity;visibilityFade=null;constructor(e,t="Node2D"){super({...e,type:t}),this.layers.set(1);let r=e.position??new I(0,0);this.position.set(r.x,r.y,0);let i=e.scale??new I(1,1);this.scale.set(i.x,i.y,1);let o=e.rotation??0,s=E.degToRad(o);this.rotation.set(0,0,s);let a=n.normalizeLayout(e.layout);this._flow=n.normalizeFlow(e.flow),this._layoutEnabled=a.enabled,this._horizontalAlign=a.horizontalAlign,this._verticalAlign=a.verticalAlign,this.authoredLayoutPosition.set(r.x,r.y);let l=n.readInitialLayoutSize(e);l&&(this.authoredLayoutSize.copy(l),this.hasAuthoredLayoutSize=!0),this._opacity=n.clampOpacity(e.opacity??1),this._computedOpacity=this._opacity,this.visibleOpacity=this._opacity>0?this._opacity:1,(e.opacity!==void 0||typeof this.properties.opacity=="number")&&(this.properties.opacity=this._opacity),this._blendMode=$i(e.blendMode??this.properties.blendMode),this.syncBlendModeProperty(),this._zIndex=n.clampZIndex(e.zIndex??this.properties.zIndex),this._zAsRelative=typeof e.zAsRelative=="boolean"?e.zAsRelative:typeof this.properties.zAsRelative=="boolean"?this.properties.zAsRelative:!0,this.syncZOrderProperties(),this.syncLayoutProperties()}get opacity(){return this._opacity}set opacity(e){let t=n.clampOpacity(e);this._opacity!==t&&(this._opacity=t,this.properties.opacity=t,!this.visibilityFade&&t>0&&(this.visibleOpacity=t),this.refreshComputedOpacityRecursive())}get computedOpacity(){return this._computedOpacity}get blendMode(){return this._blendMode}set blendMode(e){let t=$i(e);this._blendMode!==t&&(this._blendMode=t,this.syncBlendModeProperty(),this.refreshBlendMode())}refreshBlendMode(){for(let e of this.opacityMaterials)Ki(e,this._blendMode),this.applyOpacityToMaterial(e)}syncBlendModeProperty(){this._blendMode!=="normal"?this.properties.blendMode=this._blendMode:delete this.properties.blendMode}get zIndex(){return this._zIndex}set zIndex(e){let t=n.clampZIndex(e);this._zIndex!==t&&(this._zIndex=t,this.syncZOrderProperties())}get zAsRelative(){return this._zAsRelative}set zAsRelative(e){let t=!!e;this._zAsRelative!==t&&(this._zAsRelative=t,this.syncZOrderProperties())}get effectiveZIndex(){if(!this._zAsRelative)return this._zIndex;let e=this.parent;return e instanceof n?e.effectiveZIndex+this._zIndex:this._zIndex}get layoutEnabled(){return this._layoutEnabled}set layoutEnabled(e){let t=!!e;this._layoutEnabled!==t&&(this.captureAuthoredLayoutRectFromCurrent(),this._layoutEnabled=t,this.syncLayoutProperties())}get horizontalAlign(){return this._horizontalAlign}set horizontalAlign(e){let t=n.normalizeHorizontalAlign(e);this._horizontalAlign!==t&&(this._horizontalAlign=t,this.syncLayoutProperties())}get verticalAlign(){return this._verticalAlign}set verticalAlign(e){let t=n.normalizeVerticalAlign(e);this._verticalAlign!==t&&(this._verticalAlign=t,this.syncLayoutProperties())}getLayoutConfig(){return{enabled:this._layoutEnabled,horizontalAlign:this._horizontalAlign,verticalAlign:this._verticalAlign}}setLayoutConfig(e){let t=n.normalizeLayout(e);this.captureAuthoredLayoutRectFromCurrent(),this._layoutEnabled=t.enabled,this._horizontalAlign=t.horizontalAlign,this._verticalAlign=t.verticalAlign,this.syncLayoutProperties()}captureAuthoredLayoutRectFromCurrent(){this.authoredLayoutPosition.set(this.position.x,this.position.y);let e=this.getCurrentLayoutSize();e.width>0&&e.height>0&&(this.authoredLayoutSize.set(e.width,e.height),this.hasAuthoredLayoutSize=!0)}getAuthoredLayoutPosition(){return{x:this.authoredLayoutPosition.x,y:this.authoredLayoutPosition.y}}setAuthoredLayoutPosition(e,t){this.authoredLayoutPosition.set(e,t)}getAuthoredLayoutSize(){return this.ensureAuthoredLayoutSize(),{width:this.authoredLayoutSize.x,height:this.authoredLayoutSize.y}}setAuthoredLayoutSize(e,t){this.authoredLayoutSize.set(Math.max(0,e),Math.max(0,t)),this.hasAuthoredLayoutSize=!0}getPointerWorldPosition(e=this.tmpPointerWorld){let t=this.input;return t?this.screenPointToWorld(t.pointerPosition.x,t.pointerPosition.y,e):null}screenPointToWorld(e,t,r=this.tmpPointerWorld){let i=this.input;if(!i)return null;let o=Math.max(1,i.width),s=Math.max(1,i.height),a=this.scene?.getUICamera();if(a&&!this.isInOverlayBand()){let d=e/o*2-1,h=-(t/s*2-1);return n.scratchUnproject.set(d,h,0).unproject(a),r.set(n.scratchUnproject.x,n.scratchUnproject.y),r}let l=this.scene?.getLogicalCameraSize(),c=l&&Number.isFinite(l.width)&&l.width>0?l.width:o,u=l&&Number.isFinite(l.height)&&l.height>0?l.height:s;return r.set(e/o*c-c/2,u/2-t/s*u),r}isInOverlayBand(){let e=this;for(;e;){if(e.isCanvasLayer)return!0;e=e.parent instanceof n?e.parent:null}return!1}get flow(){return this._flow}setFlow(e){this._flow=n.normalizeFlow(e??void 0),this._flow.enabled&&this.applyFlowLayout()}static normalizeFlow(e){return{enabled:e?.enabled===!0,direction:e?.direction==="horizontal"?"horizontal":"vertical",gap:Number.isFinite(e?.gap)?Math.max(0,Number(e?.gap)):0,paddingX:Number.isFinite(e?.paddingX)?Math.max(0,Number(e?.paddingX)):0,paddingY:Number.isFinite(e?.paddingY)?Math.max(0,Number(e?.paddingY)):0,align:e?.align==="center"||e?.align==="end"?e.align:"start",autoSize:e?.autoSize===!0}}applyFlowLayout(){if(!this._flow.enabled)return;let e=this._flow,t=this.getCurrentLayoutSize(),r=this.children.filter(l=>l instanceof n&&l.visible);if(r.length===0)return;let i=e.direction==="vertical",o=i?t.width:t.height,s=i?e.paddingX:e.paddingY,a=i?e.paddingY:e.paddingX;for(let l of r){let c=l.getCurrentLayoutSize(),u=i?c.height:c.width,d=i?c.width:c.height,h=l.layoutEnabled,p;h?p=i?l.position.x:l.position.y:e.align==="center"?p=0:e.align==="end"?p=o/2-s-d/2:p=-o/2+s+d/2;let f=i?t.height/2-a-u/2:-t.width/2+a+u/2,m=l.getAuthoredLayoutPosition();i?(l.position.set(p,f,l.position.z),l.setAuthoredLayoutPosition(h?m.x:p,f)):(l.position.set(f,p,l.position.z),l.setAuthoredLayoutPosition(f,h?m.y:p)),a+=u+e.gap}if(e.autoSize){let l=a-e.gap+(i?e.paddingY:e.paddingX),c=i?{width:t.width,height:Math.max(l,0)}:{width:Math.max(l,0),height:t.height};this.setLayoutSizeIfPossible(c),(c.height!==t.height||c.width!==t.width)&&this.applyFlowLayout()}}setLayoutSizeIfPossible(e){let t=this;typeof t.width=="number"&&typeof t.height=="number"&&(t.width=e.width,t.height=e.height),this.authoredLayoutSize.set(e.width,e.height)}serializeFlow(){if(this._flow.enabled)return{enabled:!0,direction:this._flow.direction,gap:this._flow.gap,paddingX:this._flow.paddingX,paddingY:this._flow.paddingY,align:this._flow.align,autoSize:this._flow.autoSize}}applyAnchoredLayoutRecursive(e,t){this._layoutEnabled&&this.applyAnchoredLayout(e,t),this.applyFlowLayout();let r=this.getCurrentLayoutSize(),i=this.getAuthoredLayoutSize();this._flow.enabled&&(i=this._flow.direction==="vertical"?{width:i.width,height:r.height}:{width:r.width,height:i.height});for(let o of this.children)o instanceof n&&o.applyAnchoredLayoutRecursive(r,i)}reflowAnchoredChildren(){let e=this.getCurrentLayoutSize(),t=this.getAuthoredLayoutSize();for(let r of this.children)r instanceof n&&r.applyAnchoredLayoutRecursive(e,t)}getCurrentLayoutSize(){let e=this.readCurrentLayoutSize();return e||(this.hasAuthoredLayoutSize?{width:this.authoredLayoutSize.x,height:this.authoredLayoutSize.y}:{width:0,height:0})}serializeLayout(){if(this._layoutEnabled)return{enabled:!0,horizontalAlign:this._horizontalAlign,verticalAlign:this._verticalAlign}}hide(e=0,t){let r=n.toNonNegativeSeconds(e);if(this.opacity>0&&(this.visibleOpacity=this.opacity),r===0){this.visibilityFade=null,this.opacity=0,this.setVisibleState(!1),t?.();return}this.setVisibleState(!0),this.visibilityFade={from:this.opacity,to:0,duration:r,elapsed:0,hideAfterComplete:!0,onComplete:t}}show(e=0,t){let r=n.toNonNegativeSeconds(e),i=this.visibleOpacity>0?this.visibleOpacity:1;if(this.setVisibleState(!0),r===0){this.visibilityFade=null,this.opacity=i,t?.();return}this.visibilityFade={from:this.opacity,to:i,duration:r,elapsed:0,hideAfterComplete:!1,onComplete:t}}tick(e){if(super.tick(e),!this.visibilityFade)return;let t=this.visibilityFade;t.elapsed=Math.min(t.duration,t.elapsed+Math.max(0,e));let r=t.duration>0?t.elapsed/t.duration:1,i=t.from+(t.to-t.from)*r;if(this.opacity=i,!(t.elapsed<t.duration)){if(this.opacity=t.to,this.visibilityFade=null,t.hideAfterComplete){this.setVisibleState(!1),t.onComplete?.();return}this.setVisibleState(!0),t.onComplete?.()}}registerOpacityMaterial(e,t){t!==void 0?e.userData.__pix3BaseOpacity=n.clampOpacity(t):typeof e.userData.__pix3BaseOpacity!="number"&&(e.userData.__pix3BaseOpacity=n.clampOpacity(e.opacity)),e.userData.__pix3OriginalTransparent===void 0&&(e.userData.__pix3OriginalTransparent=e.transparent),this.opacityMaterials.add(e),Ki(e,this._blendMode),this.applyOpacityToMaterial(e)}setOpacityMaterialBase(e,t){e.userData.__pix3BaseOpacity=n.clampOpacity(t),e.userData.__pix3OriginalTransparent===void 0&&(e.userData.__pix3OriginalTransparent=e.transparent),this.opacityMaterials.add(e),Ki(e,this._blendMode),this.applyOpacityToMaterial(e)}applyOpacityToMaterial(e){let t=e.userData.__pix3BaseOpacity,r=typeof t=="number"?n.clampOpacity(t):n.clampOpacity(e.opacity);e.opacity=r*this._computedOpacity;let i=e.userData.__pix3OriginalTransparent;e.transparent=i||e.opacity<1||this._blendMode!=="normal",e.needsUpdate=!0}refreshOpacity(){this.refreshComputedOpacityRecursive()}getParentComputedOpacity(){return this.parent instanceof n?this.parent.computedOpacity:1}refreshComputedOpacityRecursive(){this._computedOpacity=this._opacity*this.getParentComputedOpacity();for(let e of this.opacityMaterials)this.applyOpacityToMaterial(e);for(let e of this.children)e instanceof n&&e.refreshComputedOpacityRecursive()}static clampOpacity(e){let t=Number.isFinite(e)?e:1;return Math.max(0,Math.min(1,t))}static normalizeLayout(e){return{enabled:!!e?.enabled,horizontalAlign:n.normalizeHorizontalAlign(e?.horizontalAlign),verticalAlign:n.normalizeVerticalAlign(e?.verticalAlign)}}static normalizeHorizontalAlign(e){switch(e){case"left":case"right":case"stretch":return e;default:return"center"}}static normalizeVerticalAlign(e){switch(e){case"top":case"bottom":case"stretch":return e;default:return"center"}}static readInitialLayoutSize(e){let t=e,r=n.toFiniteNumber(t.width),i=n.toFiniteNumber(t.height);if(r!==void 0&&i!==void 0)return new I(Math.max(0,r),Math.max(0,i));let o=n.toFiniteNumber(t.size);if(o!==void 0)return new I(Math.max(0,o),Math.max(0,o));let s=n.toFiniteNumber(t.radius);return s!==void 0?new I(Math.max(0,s*2),Math.max(0,s*2)):null}static toFiniteNumber(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}static toNonNegativeSeconds(e){return Number.isFinite(e)?Math.max(0,e):0}setVisibleState(e){this.visible=e,this.properties.visible=e}ensureAuthoredLayoutSize(){if(this.hasAuthoredLayoutSize)return;let e=this.readCurrentLayoutSize();e&&(this.authoredLayoutSize.set(e.width,e.height),this.hasAuthoredLayoutSize=!0)}readCurrentLayoutSize(){let e=this,t=n.toFiniteNumber(e.width),r=n.toFiniteNumber(e.height);if(t!==void 0&&r!==void 0)return{width:Math.max(0,t),height:Math.max(0,r)};let i=n.toFiniteNumber(e.size);if(i!==void 0){let s=Math.max(0,i);return{width:s,height:s}}let o=n.toFiniteNumber(e.radius);if(o!==void 0){let s=Math.max(0,o*2);return{width:s,height:s}}return null}applyAnchoredLayout(e,t){this.ensureAuthoredLayoutSize();let r=this.getAuthoredLayoutSize(),i=this.normalizeReferenceSize(t??e),o=this.normalizeReferenceSize(e),s=this.resolveHorizontalLayout(o.width,i.width,this.authoredLayoutPosition.x,r.width),a=this.resolveVerticalLayout(o.height,i.height,this.authoredLayoutPosition.y,r.height);this.position.set(s.center,a.center,this.position.z),this.applyCurrentLayoutSize(s.size,a.size)}normalizeReferenceSize(e){return{width:Math.max(1,e.width||0),height:Math.max(1,e.height||0)}}resolveHorizontalLayout(e,t,r,i){let o=Math.max(0,i),s=r-o/2,a=r+o/2,l=s+t/2,c=t/2-a;switch(this._horizontalAlign){case"left":return{center:-e/2+l+o/2,size:o};case"right":return{center:e/2-c-o/2,size:o};case"stretch":{let u=-e/2+l,d=e/2-c,h=Math.max(1,d-u);return{center:(u+d)/2,size:h}}default:return{center:r,size:o}}}resolveVerticalLayout(e,t,r,i){let o=Math.max(0,i),s=r-o/2,a=r+o/2,l=s+t/2,c=t/2-a;switch(this._verticalAlign){case"bottom":return{center:-e/2+l+o/2,size:o};case"top":return{center:e/2-c-o/2,size:o};case"stretch":{let u=-e/2+l,d=e/2-c,h=Math.max(1,d-u);return{center:(d+u)/2,size:h}}default:return{center:r,size:o}}}applyCurrentLayoutSize(e,t){let r=ke(this),i=It(r,"width"),o=It(r,"height");if(i&&o){si(this,i,e),si(this,o,t);return}let s=It(r,"size");if(s){si(this,s,Math.max(e,t));return}let a=It(r,"radius");a&&si(this,a,Math.min(e,t)/2)}static clampZIndex(e){let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?Math.max(-Xi,Math.min(Xi,Math.round(t))):0}syncZOrderProperties(){this._zIndex!==0?this.properties.zIndex=this._zIndex:delete this.properties.zIndex,this._zAsRelative?delete this.properties.zAsRelative:this.properties.zAsRelative=!1}syncLayoutProperties(){if(!this._layoutEnabled){delete this.properties.layout;return}this.properties.layout={enabled:!0,horizontalAlign:this._horizontalAlign,verticalAlign:this._verticalAlign}}add(...e){super.add(...e);for(let t of e)t.traverse(r=>{r.layers.set(1)}),t instanceof n&&t.refreshComputedOpacityRecursive();return this}static getPropertySchema(){let e=V.getPropertySchema();return{nodeType:"Node2D",extends:"NodeBase",properties:[...e.properties,{name:"position",type:"vector2",ui:{label:"Position",group:"Transform",step:.01,precision:2},getValue:t=>{let r=t;return{x:r.position.x,y:r.position.y}},setValue:(t,r)=>{let i=t,o=r;i.position.x=o.x,i.position.y=o.y,i.setAuthoredLayoutPosition(o.x,o.y)}},{name:"rotation",type:"number",ui:{label:"Rotation",description:"Z-axis rotation",group:"Transform",step:.1,precision:1,unit:"\xB0"},getValue:t=>t.rotation.z*(180/Math.PI),setValue:(t,r)=>{let i=t;i.rotation.z=Number(r)*(Math.PI/180)}},{name:"scale",type:"vector2",ui:{label:"Scale",group:"Transform",step:.01,precision:2,min:0},getValue:t=>{let r=t;return{x:r.scale.x,y:r.scale.y}},setValue:(t,r)=>{let i=t,o=r;i.scale.x=o.x,i.scale.y=o.y}},{name:"opacity",type:"number",ui:{label:"Opacity",description:"Local opacity multiplier inherited by child 2D nodes",group:"Style",step:.01,precision:2,min:0,max:1},getValue:t=>t.opacity,setValue:(t,r)=>{t.opacity=Number(r)}},{name:"blendMode",type:"select",ui:{label:"Blend Mode",description:"How this node's own visuals combine with what is behind them. Not inherited by child nodes; a non-normal mode opts the node out of 2D batching",group:"Style",options:Yc},getValue:t=>t.blendMode,setValue:(t,r)=>{t.blendMode=$i(r)}},{name:"zIndex",type:"number",ui:{label:"Z Index",description:"Draw-order override for the 2D pass. Higher draws on top; ties keep scene-tree order",group:"Ordering",step:1,precision:0,min:-Xi,max:Xi},getValue:t=>t.zIndex,setValue:(t,r)=>{t.zIndex=Number(r)}},{name:"zAsRelative",type:"boolean",ui:{label:"Z Relative",description:"Add Z Index to the parent's effective z instead of using it as absolute",group:"Ordering"},getValue:t=>t.zAsRelative,setValue:(t,r)=>{t.zAsRelative=!!r}},{name:"flowEnabled",type:"boolean",ui:{label:"Flow",description:"Stack this container\u2019s children in tree order. Anchors place ONE node against its parent; a flow decides where each child in a column or a row begins.",group:"Flow"},getValue:t=>t.flow.enabled,setValue:(t,r)=>{let i=t;i.setFlow({...i.flow,enabled:!!r})}},{name:"flowDirection",type:"select",ui:{label:"Direction",group:"Flow",options:["vertical","horizontal"]},getValue:t=>t.flow.direction,setValue:(t,r)=>{let i=t,o=r==="horizontal"?"horizontal":"vertical";i.setFlow({...i.flow,direction:o})}},{name:"flowGap",type:"number",ui:{label:"Gap",group:"Flow",min:0,max:400,step:1},getValue:t=>t.flow.gap,setValue:(t,r)=>{let i=t;i.setFlow({...i.flow,gap:Number(r)})}},{name:"flowPaddingX",type:"number",ui:{label:"Padding X",group:"Flow",min:0,max:400,step:1},getValue:t=>t.flow.paddingX,setValue:(t,r)=>{let i=t;i.setFlow({...i.flow,paddingX:Number(r)})}},{name:"flowPaddingY",type:"number",ui:{label:"Padding Y",group:"Flow",min:0,max:400,step:1},getValue:t=>t.flow.paddingY,setValue:(t,r)=>{let i=t;i.setFlow({...i.flow,paddingY:Number(r)})}},{name:"flowAlign",type:"select",ui:{label:"Cross Axis",group:"Flow",options:["start","center","end"],description:"Where each child sits on the axis the flow does NOT own"},getValue:t=>t.flow.align,setValue:(t,r)=>{let i=t,o=r==="center"||r==="end"?r:"start";i.setFlow({...i.flow,align:o})}},{name:"flowAutoSize",type:"boolean",ui:{label:"Auto Size",group:"Flow",description:"Grow the container along the flow axis so the last child fits"},getValue:t=>t.flow.autoSize,setValue:(t,r)=>{let i=t;i.setFlow({...i.flow,autoSize:!!r})}},{name:"layoutEnabled",type:"boolean",ui:{label:"Anchors",description:"Enable anchor-based layout for this 2D node",group:"Anchors"},getValue:t=>t.layoutEnabled,setValue:(t,r)=>{t.layoutEnabled=!!r}},{name:"horizontalAlign",type:"select",ui:{label:"Horizontal",description:"Horizontal anchor mode",group:"Anchors",options:["left","center","right","stretch"],readOnly:t=>!(t instanceof n)||!t.layoutEnabled},getValue:t=>t.horizontalAlign,setValue:(t,r)=>{t.horizontalAlign=r}},{name:"verticalAlign",type:"select",ui:{label:"Vertical",description:"Vertical anchor mode",group:"Anchors",options:["top","center","bottom","stretch"],readOnly:t=>!(t instanceof n)||!t.layoutEnabled},getValue:t=>t.verticalAlign,setValue:(t,r)=>{t.verticalAlign=r}}],groups:{...e.groups,Transform:{label:"Transform",description:"2D position, rotation, and scale",expanded:!0},Style:{label:"Style",description:"2D visual styling properties",expanded:!1},Ordering:{label:"Ordering",description:"Draw order within the 2D pass",expanded:!1},Anchors:{label:"Anchors",description:"Anchor-based layout relative to the containing frame",expanded:!1},Flow:{label:"Flow",description:"Stack this container\u2019s children along one axis, in tree order",expanded:!1}}}}};function x(n,e,t){return{name:n,type:e,...t}}function ds(n,e){if(n==="number"&&typeof e=="string"){let t=e.trim();if(t==="")return e;let r=Number(t);return Number.isFinite(r)?r:e}if(n==="boolean"&&typeof e=="string"){let t=e.trim().toLowerCase();return t==="true"?!0:t==="false"?!1:e}return n==="string"&&(typeof e=="number"||typeof e=="boolean")?String(e):e}function sx(n,e,t){return{[n]:{label:e,...t}}}function ce(n,e){return{nodeType:e.nodeType,extends:e.extends||n.nodeType,properties:[...n.properties,...e.properties],groups:{...n.groups,...e.groups}}}function hs(n,e){return(n.targets??["standard"]).includes(e)}var ax={id:"core:dissolve",key:"dissolve",displayName:"Dissolve",description:"Noise-thresholded discard with a glowing edge. Animate Amount 0\u21921 to dissolve away.",category:"Surface",keywords:["dissolve","disintegrate","erode","discard","burn"],define:"PIX3_FX_DISSOLVE",targets:["standard"],fragmentPars:`
|
|
141
|
-
uniform float uPix3DissolveAmount;
|
|
142
|
-
uniform float uPix3DissolveScale;
|
|
143
|
-
uniform float uPix3DissolveEdgeWidth;
|
|
144
|
-
uniform vec3 uPix3DissolveEdgeColor;
|
|
145
|
-
float pix3Hash(vec2 p){ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453123); }
|
|
146
|
-
float pix3Noise(vec2 p){
|
|
147
|
-
vec2 i = floor(p); vec2 f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f);
|
|
148
|
-
return mix(mix(pix3Hash(i), pix3Hash(i + vec2(1.0, 0.0)), u.x),
|
|
149
|
-
mix(pix3Hash(i + vec2(0.0, 1.0)), pix3Hash(i + vec2(1.0, 1.0)), u.x), u.y);
|
|
150
|
-
}`,chunks:[{stage:"fragment",anchor:"emissivemap_fragment",position:"after",glsl:`
|
|
151
|
-
float pix3N = pix3Noise(vPix3Uv * uPix3DissolveScale)
|
|
152
|
-
- uPix3DissolveAmount * (1.0 + uPix3DissolveEdgeWidth);
|
|
153
|
-
if (pix3N < 0.0) discard;
|
|
154
|
-
totalEmissiveRadiance += uPix3DissolveEdgeColor
|
|
155
|
-
* (1.0 - smoothstep(0.0, max(uPix3DissolveEdgeWidth, 1e-4), pix3N));`}],params:[{key:"amount",type:"number",default:0,uniform:"uPix3DissolveAmount",ui:{label:"Amount",min:0,max:1,step:.01,precision:2,slider:!0}},{key:"scale",type:"number",default:8,uniform:"uPix3DissolveScale",ui:{label:"Noise Scale",min:.1,max:64,step:.1,precision:2}},{key:"edgeWidth",type:"number",default:.05,uniform:"uPix3DissolveEdgeWidth",ui:{label:"Edge Width",min:0,max:.5,step:.005,precision:3}},{key:"edgeColor",type:"color",default:"#ffae42",uniform:"uPix3DissolveEdgeColor",ui:{label:"Edge Color"}}],createUniforms:()=>({uPix3DissolveAmount:{value:0},uPix3DissolveScale:{value:8},uPix3DissolveEdgeWidth:{value:.05},uPix3DissolveEdgeColor:{value:new L("#ffae42")}})},lx={id:"core:rim",key:"rim",displayName:"Rim Light",description:"Fresnel-based emissive rim glow, strongest at grazing angles.",category:"Surface",keywords:["rim","fresnel","glow","outline","edge"],define:"PIX3_FX_RIM",targets:["standard"],fragmentPars:`
|
|
156
|
-
uniform vec3 uPix3RimColor;
|
|
157
|
-
uniform float uPix3RimIntensity;
|
|
158
|
-
uniform float uPix3RimPower;`,chunks:[{stage:"fragment",anchor:"emissivemap_fragment",position:"after",glsl:`
|
|
159
|
-
float pix3Fr = pow(1.0 - saturate(dot(normalize(vViewPosition), normal)), uPix3RimPower);
|
|
160
|
-
totalEmissiveRadiance += uPix3RimColor * pix3Fr * uPix3RimIntensity;`}],params:[{key:"color",type:"color",default:"#ffffff",uniform:"uPix3RimColor",ui:{label:"Color"}},{key:"intensity",type:"number",default:1,uniform:"uPix3RimIntensity",ui:{label:"Intensity",min:0,max:5,step:.05,precision:2,slider:!0}},{key:"power",type:"number",default:2,uniform:"uPix3RimPower",ui:{label:"Power",min:.5,max:8,step:.1,precision:2}}],createUniforms:()=>({uPix3RimColor:{value:new L("#ffffff")},uPix3RimIntensity:{value:1},uPix3RimPower:{value:2}})},cx={id:"core:uv-scroll",key:"uvScroll",displayName:"UV Scroll",description:"Scrolls the albedo map over time (play-mode only). Requires an Albedo Map.",category:"Texture",keywords:["uv","scroll","flow","conveyor","panner","texture"],define:"PIX3_FX_UVSCROLL",targets:["standard","basic"],vertexPars:"uniform vec2 uPix3UvOffset;",chunks:[{stage:"vertex",anchor:"uv_vertex",position:"after",glsl:`
|
|
161
|
-
#if defined( USE_MAP )
|
|
162
|
-
vMapUv += uPix3UvOffset;
|
|
163
|
-
#endif`}],params:[{key:"speed",type:"vector2",default:{x:.1,y:0},ui:{label:"Speed",step:.01,precision:2,unit:"uv/s"}}],createUniforms:()=>({uPix3UvOffset:{value:new I}}),onTick:(n,e)=>{let t=n.uniforms.uPix3UvOffset?.value,r=n.params.speed;!t||!r||(t.x=(t.x+r.x*e)%1,t.y=(t.y+r.y*e)%1)}},ux={id:"core:flash",key:"flash",displayName:"Flash Tint",description:"Blends the final lit colour toward a flat colour \u2014 a hit / damage flash.",category:"Color",keywords:["flash","tint","hit","damage","blink"],define:"PIX3_FX_FLASH",targets:["standard","basic"],fragmentPars:`
|
|
164
|
-
uniform vec3 uPix3FlashColor;
|
|
165
|
-
uniform float uPix3FlashAmount;`,chunks:[{stage:"fragment",anchor:"opaque_fragment",position:"before",glsl:`
|
|
166
|
-
outgoingLight = mix(outgoingLight, uPix3FlashColor, saturate(uPix3FlashAmount));`}],params:[{key:"color",type:"color",default:"#ffffff",uniform:"uPix3FlashColor",ui:{label:"Color"}},{key:"amount",type:"number",default:0,uniform:"uPix3FlashAmount",ui:{label:"Amount",min:0,max:1,step:.01,precision:2,slider:!0}}],createUniforms:()=>({uPix3FlashColor:{value:new L("#ffffff")},uPix3FlashAmount:{value:0}})},dx={id:"core:adjust",key:"adjust",displayName:"Adjust (Brightness/Contrast/Saturation)",description:"Brightness, contrast and saturation grade on the base color.",category:"Color",keywords:["adjust","brightness","contrast","saturation","darken","lighten","hover","grade","hsl"],define:"PIX3_FX_ADJUST",targets:["basic","standard"],fragmentPars:`
|
|
167
|
-
uniform float uPix3AdjustSaturation;
|
|
168
|
-
uniform float uPix3AdjustContrast;
|
|
169
|
-
uniform float uPix3AdjustBrightness;`,chunks:[{stage:"fragment",anchor:"color_fragment",position:"after",glsl:`
|
|
170
|
-
float pix3AdjL = dot(diffuseColor.rgb, vec3(0.2126, 0.7152, 0.0722));
|
|
171
|
-
diffuseColor.rgb = mix(vec3(pix3AdjL), diffuseColor.rgb, uPix3AdjustSaturation);
|
|
172
|
-
diffuseColor.rgb = (diffuseColor.rgb - 0.5) * uPix3AdjustContrast + 0.5;
|
|
173
|
-
diffuseColor.rgb *= uPix3AdjustBrightness;`}],params:[{key:"saturation",type:"number",default:1,uniform:"uPix3AdjustSaturation",ui:{label:"Saturation",min:0,max:2,step:.01,precision:2,slider:!0}},{key:"contrast",type:"number",default:1,uniform:"uPix3AdjustContrast",ui:{label:"Contrast",min:0,max:2,step:.01,precision:2,slider:!0}},{key:"brightness",type:"number",default:1,uniform:"uPix3AdjustBrightness",ui:{label:"Brightness",min:0,max:2,step:.01,precision:2,slider:!0}}],createUniforms:()=>({uPix3AdjustSaturation:{value:1},uPix3AdjustContrast:{value:1},uPix3AdjustBrightness:{value:1}})},hx={id:"core:grayscale",key:"grayscale",displayName:"Grayscale",description:"Desaturates the base color toward its luminance.",category:"Color",keywords:["grayscale","greyscale","desaturate","mono","monochrome","black","white"],define:"PIX3_FX_GRAYSCALE",targets:["basic","standard"],fragmentPars:`
|
|
174
|
-
uniform float uPix3GrayAmount;`,chunks:[{stage:"fragment",anchor:"color_fragment",position:"after",glsl:`
|
|
175
|
-
float pix3GrayL = dot(diffuseColor.rgb, vec3(0.2126, 0.7152, 0.0722));
|
|
176
|
-
diffuseColor.rgb = mix(diffuseColor.rgb, vec3(pix3GrayL), uPix3GrayAmount);`}],params:[{key:"amount",type:"number",default:1,uniform:"uPix3GrayAmount",ui:{label:"Amount",min:0,max:1,step:.01,precision:2,slider:!0}}],createUniforms:()=>({uPix3GrayAmount:{value:1}})},px={id:"core:tint",key:"tint",displayName:"Tint",description:"Multiplies the base color by a tint color.",category:"Color",keywords:["tint","color","colour","multiply","recolor","colorize","hue"],define:"PIX3_FX_TINT",targets:["basic","standard"],fragmentPars:`
|
|
177
|
-
uniform vec3 uPix3TintColor;
|
|
178
|
-
uniform float uPix3TintAmount;`,chunks:[{stage:"fragment",anchor:"color_fragment",position:"after",glsl:`
|
|
179
|
-
diffuseColor.rgb = mix(diffuseColor.rgb, diffuseColor.rgb * uPix3TintColor, saturate(uPix3TintAmount));`}],params:[{key:"color",type:"color",default:"#ffffff",uniform:"uPix3TintColor",ui:{label:"Color"}},{key:"amount",type:"number",default:1,uniform:"uPix3TintAmount",ui:{label:"Amount",min:0,max:1,step:.01,precision:2,slider:!0}}],createUniforms:()=>({uPix3TintColor:{value:new L("#ffffff")},uPix3TintAmount:{value:1}})},ps=[ax,lx,cx,ux,dx,hx,px];var Qi=new Map,$m=!1,ms=/^[a-zA-Z][a-zA-Z0-9]*$/;function Km(){if(!$m){$m=!0;for(let n of ps)Xm(n)}}function Xm(n){if(!ms.test(n.key))throw new Error(`[ShaderEffectRegistry] invalid effect key "${n.key}" (must match ${ms})`);for(let e of n.params)if(!ms.test(e.key))throw new Error(`[ShaderEffectRegistry] effect "${n.id}" has invalid param key "${e.key}" (must match ${ms})`);if(Qi.has(n.id))throw new Error(`[ShaderEffectRegistry] duplicate effect id "${n.id}"`);for(let e of Qi.values())if(e.key===n.key)throw new Error(`[ShaderEffectRegistry] effect key "${n.key}" already used by "${e.id}"`);Qi.set(n.id,n)}function fs(n){return Km(),Qi.get(n)}function mx(){return Km(),[...Qi.values()]}var gs={uv_vertex:"#include <uv_vertex>",emissivemap_fragment:"#include <emissivemap_fragment>",opaque_fragment:"#include <opaque_fragment>",color_fragment:"#include <color_fragment>"};function Qm(n,e){return n.map(t=>e==="vertex"?t.info.vertexPars:t.info.fragmentPars).filter(t=>!!t).join(`
|
|
180
|
-
`)}function ys(n,e,t){let r=[];for(let i of n)for(let o of i.info.chunks)o.stage===e&&o.anchor===t&&r.push(`#ifdef ${i.info.define}
|
|
181
|
-
${o.glsl}
|
|
182
|
-
#endif`);return r.join(`
|
|
183
|
-
`)}function $c(n,e,t){return t?n.replace(e,`${e}
|
|
184
|
-
${t}`):n}function fx(n,e,t){return t?n.replace(e,`${t}
|
|
185
|
-
${e}`):n}function Kc(n,e,t){if(e.length===0)return;Object.assign(n.uniforms,t);let r=Qm(e,"vertex");n.vertexShader=`varying vec2 vPix3Uv;
|
|
186
|
-
${r?r+`
|
|
187
|
-
`:""}${n.vertexShader}`,n.vertexShader=$c(n.vertexShader,gs.uv_vertex,`vPix3Uv = uv;
|
|
188
|
-
${ys(e,"vertex","uv_vertex")}`);let i=Qm(e,"fragment");n.fragmentShader=`varying vec2 vPix3Uv;
|
|
189
|
-
${i?i+`
|
|
190
|
-
`:""}${n.fragmentShader}`,n.fragmentShader=$c(n.fragmentShader,gs.color_fragment,ys(e,"fragment","color_fragment")),n.fragmentShader=$c(n.fragmentShader,gs.emissivemap_fragment,ys(e,"fragment","emissivemap_fragment")),n.fragmentShader=fx(n.fragmentShader,gs.opaque_fragment,ys(e,"fragment","opaque_fragment"))}function Xc(n){return"pix3-gmesh-fx-v2:"+n.map(e=>e.type).join("+")}function gx(n){return typeof n=="object"&&n!==null&&typeof n.getShaderEffectStack=="function"}var Oe=class{nodeType;target;onAttachmentsChanged;effects=[];fxUniforms={};materials=new Set;revision=0;schemaCache=null;constructor(e){this.nodeType=e.nodeType,this.target=e.target,this.onAttachmentsChanged=e.onAttachmentsChanged}get materialTarget(){return this.target}retarget(e){if(e===this.target)return;this.target=e;let t=this.effects.filter(r=>{let i=fs(r.type);return i?!hs(i,e):!0});for(let r of t)this.detach(r.type);t.length>0&&console.warn(`[ShaderEffectStack] Dropped ${t.map(r=>`"${r.type}"`).join(", ")} \u2014 no GLSL for the "${e}" material.`)}install(e){e.onBeforeCompile=t=>{Kc(t,this.effects,this.fxUniforms)},e.customProgramCacheKey=()=>Xc(this.effects),this.materials.add(e),this.syncDefinesOn(e,!0)}uninstall(e){this.materials.delete(e)}attach(e,t){if(this.effects.some(o=>o.type===e))return!1;let r=fs(e);if(!r)return console.warn(`[ShaderEffectStack] Unknown shader effect "${e}" \u2014 skipped.`),!1;if(!hs(r,this.target))return console.warn(`[ShaderEffectStack] Effect "${e}" does not support the "${this.target}" material \u2014 skipped.`),!1;let i={type:e,info:r,enabled:typeof t?.enabled=="boolean"?t.enabled:!0,params:{},uniforms:r.createUniforms()};for(let o of r.params){let s=t?.params?.[o.key];i.params[o.key]=s!==void 0?Jm(s,o.type):yx(o.default)}return this.effects.push(i),this.applyParamsToUniforms(i),this.rebuildUniformBag(),this.revision+=1,this.schemaCache=null,this.syncDefines(!0),this.onAttachmentsChanged?.(),!0}detach(e){let t=this.effects.findIndex(i=>i.type===e);if(t<0)return null;let[r]=this.effects.splice(t,1);return this.rebuildUniformBag(),this.revision+=1,this.schemaCache=null,this.syncDefines(!0),this.onAttachmentsChanged?.(),r??null}setEnabled(e,t){let r=this.effects.find(i=>i.type===e);!r||r.enabled===t||(r.enabled=t,this.syncDefines(!0))}get(e){return this.effects.find(t=>t.type===e||t.info.id===e||t.info.key===e)}setParam(e,t,r){let i=this.get(e);if(!i)return!1;let o=i.info.params.find(s=>s.key===t);return o?(this.writeEffectParam(i,o,r),!0):!1}getParam(e,t){let r=this.get(e);if(!r)return;let i=r.info.params.find(o=>o.key===t);if(i)return Zm(r,i)}getAttached(){return this.effects}get isEmpty(){return this.effects.length===0}buildInstanceSchema(){if(this.effects.length===0)return null;if(this.schemaCache&&this.schemaCache.rev===this.revision)return this.schemaCache.schema;let e=[],t={};for(let i of this.effects){let o=`Effect: ${i.info.displayName}`;t[o]={label:i.info.displayName,expanded:!0},e.push(x(`fx.${i.info.key}.enabled`,"boolean",{ui:{label:"Enabled",group:o},getValue:()=>i.enabled,setValue:(s,a)=>this.setEnabled(i.type,!!a)}));for(let s of i.info.params)e.push(x(`fx.${i.info.key}.${s.key}`,s.type,{ui:{...s.ui??{},group:o,readOnly:()=>!i.enabled},getValue:()=>Zm(i,s),setValue:(a,l)=>this.writeEffectParam(i,s,l)}))}let r={nodeType:this.nodeType,properties:e,groups:t};return this.schemaCache={rev:this.revision,schema:r},r}tick(e){for(let t of this.effects)t.enabled&&t.info.onTick&&t.info.onTick({params:t.params,uniforms:t.uniforms},e)}serialize(){return this.effects.map(e=>vx(e))}rebuildUniformBag(){let e={};for(let t of this.effects)Object.assign(e,t.uniforms);this.fxUniforms=e}syncDefines(e){for(let t of this.materials)this.syncDefinesOn(t,e)}syncDefinesOn(e,t){e.defines??={};let r=e.defines;for(let i of Object.keys(r))i.startsWith("PIX3_FX_")&&delete r[i];for(let i of this.effects)i.enabled&&(r[i.info.define]="");t&&(e.needsUpdate=!0)}applyParamsToUniforms(e){for(let t of e.info.params)this.applyParamToUniform(e,t)}applyParamToUniform(e,t){if(!t.uniform)return;let r=e.uniforms[t.uniform];if(!r)return;let i=e.params[t.key];switch(t.type){case"number":r.value=Number(i);break;case"color":r.value.set(String(i));break;case"vector2":{let o=i;r.value.set(o.x,o.y);break}case"boolean":r.value=i?1:0;break}}writeEffectParam(e,t,r){e.params[t.key]=Jm(r,t.type),this.applyParamToUniform(e,t)}};function yx(n){return n&&typeof n=="object"?{...n}:n}function Jm(n,e){switch(e){case"number":{let t=Number(n);return Number.isFinite(t)?t:0}case"color":return String(n);case"vector2":{if(Array.isArray(n))return{x:Number(n[0])||0,y:Number(n[1])||0};let t=n;return{x:Number(t?.x)||0,y:Number(t?.y)||0}}case"boolean":return!!n}}function Zm(n,e){let t=n.params[e.key];if(e.type==="vector2"){let r=t;return{x:r.x,y:r.y}}return t}function bx(n,e,t){if(t==="vector2"){let r=n,i=e;return r.x===i.x&&r.y===i.y}return n===e}function Sx(n,e){if(e==="vector2"){let t=n;return{x:t.x,y:t.y}}return n}function vx(n){let e={type:n.type,enabled:n.enabled},t={};for(let r of n.info.params){let i=n.params[r.key];bx(i,r.default,r.type)||(t[r.key]=Sx(i,r.type))}return Object.keys(t).length>0&&(e.params=t),e}function ef(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.type==="texture"&&typeof e.url=="string"}function D(n){if(typeof n=="string"){let e=n.trim();return e.length>0?{type:"texture",url:e}:null}if(ef(n)){let e=n.url.trim();return e.length>0?{type:"texture",url:e}:null}if(typeof n=="object"&&n!==null){let e=n;if(typeof e.url=="string"){let t=e.url.trim();return t.length>0?{type:"texture",url:t}:null}}return null}var Ne="pix3Batchable2D",tf=[[-.5,.5],[.5,.5],[-.5,-.5],[.5,-.5]],rf=[[0,1],[1,1],[0,0],[1,0]],wx=[0,1,2,2,1,3],bs=new S,Qc=class{mesh;geometry;positions;uvs;colors;index;capacity;constructor(e=64){this.capacity=e,this.geometry=new le,this.positions=this.makeAttr(this.capacity*4,3),this.uvs=this.makeAttr(this.capacity*4,2),this.colors=this.makeAttr(this.capacity*4,4),this.index=this.makeIndex(this.capacity),this.geometry.setAttribute("position",this.positions),this.geometry.setAttribute("uv",this.uvs),this.geometry.setAttribute("color",this.colors),this.geometry.setIndex(this.index),this.mesh=new B(this.geometry),this.mesh.matrixAutoUpdate=!1,this.mesh.frustumCulled=!1,this.mesh.visible=!1}makeAttr(e,t){let r=new J(new Float32Array(e*t),t);return r.setUsage(se),r}makeIndex(e){let t=new Uint32Array(e*6);for(let r=0;r<e;r++){let i=r*4;for(let o=0;o<6;o++)t[r*6+o]=i+wx[o]}return new tm(t,1)}ensureCapacity(e){if(e<=this.capacity)return;let t=this.capacity;for(;t<e;)t*=2;this.capacity=t,this.positions=this.makeAttr(t*4,3),this.uvs=this.makeAttr(t*4,2),this.colors=this.makeAttr(t*4,4),this.index=this.makeIndex(t),this.geometry.setAttribute("position",this.positions),this.geometry.setAttribute("uv",this.uvs),this.geometry.setAttribute("color",this.colors),this.geometry.setIndex(this.index)}fill(e){this.ensureCapacity(e.length);let t=this.positions.array,r=this.uvs.array,i=this.colors.array,o=new L;for(let s=0;s<e.length;s++){let a=e[s],l=a.material,c=l.map,u=c?c.offset.x:0,d=c?c.offset.y:0,h=c?c.repeat.x:1,p=c?c.repeat.y:1;o.copy(l.color);let f=l.opacity,m=s*4;for(let g=0;g<4;g++){bs.set(tf[g][0],tf[g][1],0).applyMatrix4(a.matrixWorld);let y=(m+g)*3;t[y]=bs.x,t[y+1]=bs.y,t[y+2]=bs.z;let b=(m+g)*2;r[b]=u+rf[g][0]*h,r[b+1]=d+rf[g][1]*p;let v=(m+g)*4;i[v]=o.r,i[v+1]=o.g,i[v+2]=o.b,i[v+3]=f}}this.positions.needsUpdate=!0,this.uvs.needsUpdate=!0,this.colors.needsUpdate=!0,this.geometry.setDrawRange(0,e.length*6)}dispose(){this.geometry.dispose()}},Ji=class{group=new $r;pool=[];materials=new Map;batchMaps=new Map;suppressed=new Set;stats={batches:0,quads:0,passthrough:0};constructor(e){this.group.matrixAutoUpdate=!1,this.group.name="Pix3Batch2D",e.add(this.group)}get activeBatchMeshes(){return this.pool.filter(e=>e.mesh.visible).map(e=>e.mesh)}update(e){let t=this.segment(e),r=new Set;for(let o of t)for(let s of o.members)r.add(s.material);for(let o of r)o.visible=!1;for(let o of this.suppressed)r.has(o)||(o.visible=!0);this.suppressed=r;let i=0;for(let o=0;o<t.length;o++){let s=t[o],a=this.pool[o];a||(a=new Qc,this.pool[o]=a,this.group.add(a.mesh)),a.fill(s.members),a.mesh.material=this.materialFor(s),a.mesh.renderOrder=s.order,a.mesh.layers.set(s.overlay?3:1),a.mesh.visible=!0,i+=s.members.length}for(let o=t.length;o<this.pool.length;o++)this.pool[o].mesh.visible=!1;this.stats.batches=t.length,this.stats.quads=i}segment(e){let t=[],r=0,i=null,o=()=>{i&&(i.members.length>=2?t.push(i):r+=i.members.length,i=null)};for(let s of e){let a=this.keyFor(s);if(!a){o(),r++;continue}if(i&&i.key===a){i.members.push(s.mesh);continue}o();let l=s.mesh.material;i={members:[s.mesh],key:a,source:l.map,overlay:s.overlay,order:s.order}}return o(),this.stats.passthrough=r,t}keyFor(e){if(!e.visible)return null;let t=e.mesh;if(!t.userData||t.userData[Ne]!==!0)return null;let r=t.material;if(Array.isArray(r)||!(r instanceof R)||r.opacity<=0||r.blending!==st)return null;let i=r.map?r.map.source.uuid:"nomap";return`${e.overlay?"o":"m"}:${i}`}materialFor(e){let t=this.materials.get(e.key);return t||(t=new R({transparent:!0,depthTest:!1,vertexColors:!0,side:xe,color:16777215,map:e.source?this.batchMapFor(e.source):null}),this.materials.set(e.key,t)),t}batchMapFor(e){let t=e.source.uuid,r=this.batchMaps.get(t);return r||(r=e.clone(),r.offset.set(0,0),r.repeat.set(1,1),r.needsUpdate=!0,this.batchMaps.set(t,r)),r}dispose(){for(let e of this.suppressed)e.visible=!0;this.suppressed.clear();for(let e of this.pool)e.dispose();this.pool.length=0;for(let e of this.materials.values())e.dispose();this.materials.clear();for(let e of this.batchMaps.values())e.dispose();this.batchMaps.clear(),this.group.removeFromParent()}};var nf="__PIX3_ACTIVE_LOCALIZATION__";function Ss(n){globalThis[nf]=n??void 0}function Ye(){return globalThis[nf]??null}function Zi(n,e,t){if(!n)return e;let r=Ye();return r?r.tr(n,t):e}function $e(n){return{width:n.naturalWidth??n.width,height:n.naturalHeight??n.height}}var Le=class n extends M{texture;textureKey;width;height;textureAspectRatio;aspectRatioLocked;originalWidth;originalHeight;anchor;textureRegion=null;mesh;material;baseTexture=null;ownedTexture=null;effectStack;constructor(e){super(e,"Sprite2D"),this.texture=D(e.texture??e.texturePath??null),this.textureKey=e.textureKey??"",this.width=e.width,this.height=e.height,this.textureAspectRatio=e.textureAspectRatio??null,this.aspectRatioLocked=e.aspectRatioLocked??!1,this.originalWidth=null,this.originalHeight=null,this.anchor=n.normalizeAnchor(e.anchor),this.isContainer=!1,this.material=new R({color:e.color??"#ffffff",transparent:!0,depthTest:!1}),this.registerOpacityMaterial(this.material,1),this.mesh=new B(Me,this.material),this.mesh.name=`${this.name}-Mesh`,this.mesh.scale.set(this.width??64,this.height??64,1),this.mesh.userData[Ne]=!0,this.applyAnchorOffset(),this.add(this.mesh),this.effectStack=new Oe({nodeType:"Sprite2D",target:"basic",onAttachmentsChanged:()=>{this.mesh.userData[Ne]=this.effectStack.isEmpty}}),this.effectStack.install(this.material);let t=e.effects??this.properties.effects;for(let r of t??[])r&&typeof r.type=="string"&&this.effectStack.attach(r.type,{enabled:r.enabled,params:r.params});G(this,n.getPropertySchema)}getShaderEffectStack(){return this.effectStack}getInstancePropertySchema(){return this.effectStack.buildInstanceSchema()}attachEffect(e,t){return this.effectStack.attach(e,t)}detachEffect(e){return this.effectStack.detach(e)}setEffectEnabled(e,t){this.effectStack.setEnabled(e,t)}setEffectParam(e,t,r){return this.effectStack.setParam(e,t,r)}getAttachedEffects(){return this.effectStack.getAttached()}tick(e){this.effectStack.tick(e),super.tick(e)}static normalizeAnchor(e){if(!e)return{x:.5,y:.5};if(Array.isArray(e)){let i=Number(e[0]),o=Number(e[1]);return{x:Number.isFinite(i)?i:.5,y:Number.isFinite(o)?o:.5}}let t=Number(e.x),r=Number(e.y);return{x:Number.isFinite(t)?t:.5,y:Number.isFinite(r)?r:.5}}applyAnchorOffset(){let e=this.width??64,t=this.height??64;this.mesh.position.set((.5-this.anchor.x)*e,(.5-this.anchor.y)*t,0)}setAnchor(e){this.anchor=n.normalizeAnchor(e),this.applyAnchorOffset()}setTextureRegion(e){this.textureRegion=oc(e),this.applyTexturePresentation()}applyTexturePresentation(){let e=this.textureRegion;if(e&&this.baseTexture){this.ownedTexture||(this.ownedTexture=this.baseTexture.clone(),Y(this.ownedTexture));let t=Ui(Wi(this.baseTexture),e);lr(this.ownedTexture,t),this.material.map!==this.ownedTexture&&(this.material.map=this.ownedTexture,this.material.needsUpdate=!0);return}this.material.map!==this.baseTexture&&(this.material.map=this.baseTexture,this.material.needsUpdate=!0),this.ownedTexture&&(this.ownedTexture.dispose(),this.ownedTexture=null)}get texturePath(){return this.texture?.url??null}getEffectiveTexturePath(){if(this.textureKey){let e=Ye()?.trSprite(this.textureKey);if(e)return e}return this.texturePath}set texturePath(e){this.texture=D(e)}setTextureResource(e){this.texture=D(e)}setTexture(e){Y(e),this.baseTexture!==e&&this.ownedTexture&&(this.ownedTexture.dispose(),this.ownedTexture=null),this.baseTexture=e,this.material.color.set("#ffffff"),this.applyTexturePresentation();let t=Gi(e);if(t||e.image){let r=$e(e.image??{}),i=t?.width??r.width,o=t?.height??r.height;i&&o&&(this.textureAspectRatio=i/o,this.originalWidth=i,this.originalHeight=o,(this.width===void 0||this.height===void 0)&&this.updateSize(i,o))}}updateSize(e,t){this.width=e,this.height=t,this.mesh.scale.set(e,t,1),this.applyAnchorOffset(),this.refreshOpacity()}resetToOriginalSize(){!this.originalWidth||!this.originalHeight||this.updateSize(this.originalWidth,this.originalHeight)}disposeResources(){this.ownedTexture&&(this.ownedTexture.dispose(),this.ownedTexture=null),this.material.dispose()}static getPropertySchema(){let e=M.getPropertySchema();return{nodeType:"Sprite2D",extends:"Node2D",properties:[...e.properties,{name:"texture",type:"object",ui:{label:"Texture",description:"Path to the sprite texture",group:"Sprite",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.texture??{type:"texture",url:""},setValue:(t,r)=>{t.setTextureResource(r)}},{name:"textureKey",type:"string",ui:{label:"Texture Key",description:'Localization sprite key (locale table "sprites" section). When set and resolvable, the localized texture wins; the authored texture is the fallback',group:"Sprite",editor:"localization-key"},getValue:t=>t.textureKey,setValue:(t,r)=>{t.textureKey=String(r??"")}},{name:"anchor",type:"vector2",ui:{label:"Pivot",description:"Normalized pivot point used to position the sprite image",group:"Sprite",step:.01,precision:2},getValue:t=>{let r=t.anchor;return{x:r.x,y:r.y}},setValue:(t,r)=>{let i=t,o=r;i.setAnchor({x:o.x,y:o.y})}},{name:"width",type:"number",ui:{label:"Width",description:"Sprite width in pixels",group:"Size",editor:"sprite-size",step:1,precision:0,min:1,unit:"px"},getValue:t=>t.width??64,setValue:(t,r)=>{let i=t;i.updateSize(Number(r),i.height??64)}},{name:"height",type:"number",ui:{label:"Height",description:"Sprite height in pixels",group:"Size",editor:"sprite-size",step:1,precision:0,min:1,unit:"px"},getValue:t=>t.height??64,setValue:(t,r)=>{let i=t;i.updateSize(i.width??64,Number(r))}},{name:"aspectRatioLocked",type:"boolean",ui:{label:"Aspect Ratio Locked",description:"Maintain aspect ratio when resizing",group:"Size",hidden:!0},getValue:t=>t.aspectRatioLocked??!1,setValue:(t,r)=>{t.aspectRatioLocked=!!r}}],groups:{...e.groups,Sprite:{label:"Sprite",description:"Sprite-specific properties",expanded:!0},Size:{label:"Size",description:"Sprite dimensions in pixels",expanded:!0}}}}};function en(n){let e=n.trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[t]}catch{return[e]}}function Jc(n){let e=Number.isFinite(n.nodeWidth)?n.nodeWidth:0,t=Number.isFinite(n.nodeHeight)?n.nodeHeight:0,r=e,i=t;if(n.sizeMode==="native"){let a=n.frameSourceSize,l=n.clipFirstFrameSourceSize??a;if(a&&a.width>0&&a.height>0&&l&&l.width>0){let c=e/l.width;r=a.width*c,i=a.height*c}}let o=n.frame?.anchor.x??.5,s=n.frame?.anchor.y??.5;return{width:r,height:i,offsetX:(.5-n.anchor.x)*e+(.5-o)*r,offsetY:(.5-n.anchor.y)*t+(s-.5)*i}}function Zc(n,e){return{x:e.offsetX+(n.x-.5)*e.width,y:e.offsetY+(.5-n.y)*e.height,angle:n.angle??0}}function eu(n,e,t){let r=t?.width??0,i=t?.height??0;return r<=0||i<=0||n.length===0?[]:n.map(o=>({x:e.offsetX+(o.x/r-.5)*e.width,y:e.offsetY+(.5-o.y/i)*e.height}))}var ai=class{timeAccumulator=0;direction=1;finished=!1;finishedAtIndex=null;advance(e,t,r){let i=[];if(this.finished){if(r===this.finishedAtIndex)return{nextIndex:r,framesAdvanced:i,finished:!1};this.finished=!1,this.finishedAtIndex=null,this.timeAccumulator=0,this.direction=1}let{frameCount:o,fps:s,loop:a}=t,l=t.playbackMode??"linear",c=t.frameDurationMultiplier??(()=>1),u=r,d=!1;for(this.timeAccumulator+=e;;){let h=Math.max(.001,1/s*c(u));if(this.timeAccumulator<h)break;this.timeAccumulator-=h;let p=u,f=this.computeNextIndex(u,o,a,l);if(u=f.nextIndex,u!==p&&i.push(u),f.finished){d=!0,this.finished=!0,this.finishedAtIndex=u,this.timeAccumulator=0;break}}return{nextIndex:u,framesAdvanced:i,finished:d}}reset(){this.timeAccumulator=0,this.direction=1,this.finished=!1,this.finishedAtIndex=null}computeNextIndex(e,t,r,i){if(i==="ping-pong"&&t>1){let s=e+this.direction;if(s>=t){if(!r)return{nextIndex:t-1,finished:!0};this.direction=-1,s=Math.max(0,t-2)}else if(s<0){if(!r)return{nextIndex:0,finished:!0};this.direction=1,s=Math.min(t-1,1)}return{nextIndex:s,finished:!1}}let o=e+1;return o<t?{nextIndex:o,finished:!1}:r?{nextIndex:0,finished:!1}:{nextIndex:t-1,finished:!0}}};var xx=new S,of=new ae,sf=new Yr,Ke=class n extends M{animationResourcePath;currentClip;isPlaying;freeOnFinish;width;height;color;anchor;sizeMode;_currentFrame;frameSequencePlayer=new ai;animationResource=null;activeClip=null;spritesheetTexture=null;frameTextures=new Map;mesh;material;effectStack;constructor(e){super(e,"AnimatedSprite2D"),this.animationResourcePath=typeof e.animationResourcePath=="string"&&e.animationResourcePath.trim().length>0?e.animationResourcePath.trim():null,this.currentClip=typeof e.currentClip=="string"?e.currentClip.trim():"",this.isPlaying=e.isPlaying??!0,this.freeOnFinish=e.freeOnFinish??!1,this.width=e.width??64,this.height=e.height??64,this.color=e.color??"#ffffff",this.anchor=n.normalizeAnchor(e.anchor),this.sizeMode=e.sizeMode==="native"?"native":"stretch",this._currentFrame=Math.max(0,Math.floor(e.currentFrame??0)),this.isContainer=!1,this.animationResourcePath&&(this.properties.animationResourcePath=this.animationResourcePath),this.currentClip&&(this.properties.currentClip=this.currentClip),this.properties.isPlaying=this.isPlaying,this.freeOnFinish&&(this.properties.freeOnFinish=!0),this.properties.currentFrame=this._currentFrame,this.material=new R({color:this.color,transparent:!0,depthTest:!1}),this.registerOpacityMaterial(this.material,1),this.mesh=new B(Me,this.material),this.mesh.name=`${this.name}-Mesh`,this.mesh.userData[Ne]=!0,this.updateSize(),this.add(this.mesh),this.effectStack=new Oe({nodeType:"AnimatedSprite2D",target:"basic",onAttachmentsChanged:()=>{this.mesh.userData[Ne]=this.effectStack.isEmpty}}),this.effectStack.install(this.material);let t=e.effects??this.properties.effects;for(let r of t??[])r&&typeof r.type=="string"&&this.effectStack.attach(r.type,{enabled:r.enabled,params:r.params});G(this,n.getPropertySchema)}getShaderEffectStack(){return this.effectStack}getInstancePropertySchema(){return this.effectStack.buildInstanceSchema()}attachEffect(e,t){return this.effectStack.attach(e,t)}detachEffect(e){return this.effectStack.detach(e)}setEffectEnabled(e,t){this.effectStack.setEnabled(e,t)}setEffectParam(e,t,r){return this.effectStack.setParam(e,t,r)}getAttachedEffects(){return this.effectStack.getAttached()}get currentFrame(){return this._currentFrame}set currentFrame(e){let t=Math.max(0,Math.floor(e)),r=this.activeClip?.frames.length??0;this._currentFrame=r>0?Math.min(t,r-1):t,this.properties.currentFrame=this._currentFrame,this.refreshTexturePresentation()}setAnimationResource(e){this.animationResource=e,this.syncActiveClip(!1)}setFrameTexture(e,t){let r=Math.max(0,Math.floor(e)),i=this.frameTextures.get(r);i&&(i.dispose(),this.frameTextures.delete(r)),t&&this.frameTextures.set(r,this.cloneTexture(t)),r===this._currentFrame&&this.refreshTexturePresentation()}setSpritesheetTexture(e){this.spritesheetTexture&&(this.spritesheetTexture.dispose(),this.spritesheetTexture=null),e&&(this.spritesheetTexture=this.cloneTexture(e)),this.refreshTexturePresentation()}tick(e){super.tick(e),this.effectStack.tick(e);let t=this.activeClip;if(!this.isPlaying||!t||t.frames.length<=1||t.fps<=0)return;let r=this.frameSequencePlayer.advance(e,{frameCount:t.frames.length,fps:t.fps,loop:t.loop,playbackMode:t.playbackMode==="ping-pong"?"ping-pong":"linear",frameDurationMultiplier:i=>t.frames[i]?.durationMultiplier??1},this._currentFrame);for(let i of r.framesAdvanced)this.currentFrame=i,this.emitFrameEvents(i);r.finished&&(this.isPlaying=!1,this.properties.isPlaying=!1,this.emit("animation-finished",t.name),this.freeOnFinish&&this.queueFree())}emitFrameEvents(e){let t=this.activeClip?.frames[e];if(!(!t||!t.events||t.events.length===0))for(let r of t.events)r.signal.length!==0&&this.emit(r.signal,...en(r.args))}static getPropertySchema(){let e=M.getPropertySchema();return{...e,nodeType:"AnimatedSprite2D",properties:[...e.properties,{name:"width",type:"number",ui:{label:"Width",group:"Size",min:0,step:1},getValue:t=>t.width,setValue:(t,r)=>{let i=t;i.width=Number(r),i.updateSize()}},{name:"height",type:"number",ui:{label:"Height",group:"Size",min:0,step:1},getValue:t=>t.height,setValue:(t,r)=>{let i=t;i.height=Number(r),i.updateSize()}},{name:"sizeMode",type:"enum",ui:{label:"Size Mode",description:"Stretch: every frame fills Width\xD7Height. Native: each frame renders at its own pixel size, scaled uniformly from the clip\u2019s first frame.",group:"Size",options:{Stretch:"stretch",Native:"native"}},getValue:t=>t.sizeMode,setValue:(t,r)=>{let i=t;i.sizeMode=r==="native"?"native":"stretch",i.properties.sizeMode=i.sizeMode,i.updateSize()}},{name:"anchor",type:"vector2",ui:{label:"Pivot",description:"Normalized node pivot. Composes on top of each frame\u2019s own anchor, which is edited in the Sprite Editor.",group:"Size",step:.01,precision:2},getValue:t=>{let r=t.anchor;return{x:r.x,y:r.y}},setValue:(t,r)=>{let i=t,o=r;i.setAnchor({x:o.x,y:o.y}),i.properties.anchor={x:i.anchor.x,y:i.anchor.y}}},{name:"color",type:"color",ui:{label:"Color",group:"Style"},getValue:t=>t.color,setValue:(t,r)=>{let i=t;i.color=String(r),i.refreshTexturePresentation()}},{name:"animationResourcePath",type:"string",ui:{label:"Animation Asset",group:"Animation",editor:"animation-resource"},getValue:t=>t.animationResourcePath??"",setValue:(t,r)=>{let i=t,o=String(r??"").trim();i.animationResourcePath=o||null,i.animationResourcePath?i.properties.animationResourcePath=i.animationResourcePath:delete i.properties.animationResourcePath}},{name:"currentClip",type:"string",ui:{label:"Clip",group:"Animation"},getValue:t=>t.currentClip,setValue:(t,r)=>{let i=t;i.currentClip=String(r??"").trim(),i.currentClip?i.properties.currentClip=i.currentClip:delete i.properties.currentClip,i.syncActiveClip(!0)}},{name:"isPlaying",type:"boolean",ui:{label:"Playing",group:"Animation"},getValue:t=>t.isPlaying,setValue:(t,r)=>{let i=t;i.isPlaying=!!r,i.properties.isPlaying=i.isPlaying}},{name:"currentFrame",type:"number",ui:{label:"Current Frame",group:"Animation",min:0,step:1},getValue:t=>t.currentFrame,setValue:(t,r)=>{t.currentFrame=Number(r)}},{name:"freeOnFinish",type:"boolean",ui:{label:"Free on Finish",description:"Destroy this node when a non-looping clip finishes (one-shot VFX)",group:"Animation"},getValue:t=>t.freeOnFinish,setValue:(t,r)=>{let i=t;i.freeOnFinish=!!r,i.freeOnFinish?i.properties.freeOnFinish=!0:delete i.properties.freeOnFinish}}],groups:{...e.groups,Size:{label:"Size",expanded:!0},Style:{label:"Style",expanded:!0},Animation:{label:"Animation",expanded:!0}}}}getCurrentFrameData(){let e=this.activeClip?.frames??[];return e.length===0?null:e[this._currentFrame]??null}refreshTexturePresentation(){this.updateSize();let e=this.getCurrentFrameData(),t=e?this.frameTextures.get(this._currentFrame)??null:null,r=Jl(e)&&!!t,i=r?t:this.spritesheetTexture;if(i){this.material.map!==i&&(this.material.map=i,this.material.needsUpdate=!0);let o=Wi(i),s=null;!r&&e&&(s={x:e.offset.x,y:e.offset.y,width:e.repeat.x,height:e.repeat.y}),lr(i,Ui(o,s)),this.material.color.set("#ffffff")}else this.material.map&&(this.material.map=null,this.material.needsUpdate=!0),this.material.color.set(this.color)}syncActiveClip(e){let t=this.activeClip?.name??null;this.activeClip=rc(this.animationResource,this.currentClip);let r=this.activeClip?.name??this.currentClip;r!==this.currentClip&&(this.currentClip=r,r?this.properties.currentClip=r:delete this.properties.currentClip),e&&t!==this.activeClip?.name&&(this._currentFrame=0,this.properties.currentFrame=this._currentFrame,this.frameSequencePlayer.reset());let i=this.activeClip?.frames.length??0;i>0?(this._currentFrame=Math.max(0,Math.min(this._currentFrame,i-1)),this.properties.currentFrame=this._currentFrame):(this._currentFrame=Math.max(0,this._currentFrame),this.properties.currentFrame=this._currentFrame,this.frameSequencePlayer.reset()),this.refreshTexturePresentation()}cloneTexture(e){let t=e.clone();return Y(t),ac(e,t),t}static normalizeAnchor(e){if(!e)return{x:.5,y:.5};let[t,r]=Array.isArray(e)?e:[e.x,e.y],i=Number(t),o=Number(r);return{x:Number.isFinite(i)?i:.5,y:Number.isFinite(o)?o:.5}}setAnchor(e){this.anchor=n.normalizeAnchor(e),this.updateSize()}resolveFrameSourceSize(e,t){let r=e?.sourceSize;if(r&&r.width>0&&r.height>0)return r;let i=this.frameTextures.get(t)??this.spritesheetTexture,o=Gi(i);if(o&&o.width>0&&o.height>0)return o;let s=i?.image;return s&&Number(s.width)>0&&Number(s.height)>0?{width:Number(s.width),height:Number(s.height)}:null}resolveFrameLayout(e,t){return Jc({nodeWidth:this.width,nodeHeight:this.height,anchor:this.anchor,sizeMode:this.sizeMode,frame:e,frameSourceSize:this.resolveFrameSourceSize(e,t),clipFirstFrameSourceSize:this.resolveFrameSourceSize(this.activeClip?.frames[0]??null,0)})}updateSize(){let e=this.getCurrentFrameData(),t=this.resolveFrameLayout(e,this._currentFrame);this.mesh.scale.set(t.width,t.height,1),this.mesh.position.set(t.offsetX,t.offsetY,0)}getFramePoint(e,t=this._currentFrame){let r=this.activeClip?.frames??[];if(r.length===0)return null;let i=Math.max(0,Math.min(Math.floor(t),r.length-1)),o=r[i]??null,s=Zl(o,e);return s?Zc(s,this.resolveFrameLayout(o,i)):null}getFramePointWorld(e,t=this._currentFrame){let r=this.getFramePoint(e,t);if(!r)return null;this.updateWorldMatrix(!0,!1);let i=xx.set(r.x,r.y,0).applyMatrix4(this.matrixWorld);return of.extractRotation(this.matrixWorld),sf.setFromRotationMatrix(of),{x:i.x,y:i.y,z:i.z,angle:r.angle+E.radToDeg(sf.z)}}getClipPointNames(){return ec(this.activeClip)}getFrameCollisionPolygon(e=this._currentFrame){let t=this.activeClip?.frames??[];if(t.length===0)return[];let r=Math.max(0,Math.min(Math.floor(e),t.length-1)),i=t[r]??null;return!i||!i.collisionPolygon||i.collisionPolygon.length<3?[]:eu(i.collisionPolygon,this.resolveFrameLayout(i,r),this.resolveFrameSourceSize(i,r))}disposeResources(){this.spritesheetTexture&&(this.spritesheetTexture.dispose(),this.spritesheetTexture=null);for(let e of this.frameTextures.values())e.dispose();this.frameTextures.clear(),this.material.dispose()}};var tn=class{constructor(e){this.options=e;this.asset=e.asset,this.object=new this.asset.spine.SkeletonMesh({skeletonData:this.asset.skeletonData,twoColorTint:e.twoColorTint??!1,materialFactory:kx()}),this.object.name="SpineSkeletonMesh",this.object.zOffset=0,this.object.state.addListener({start:t=>{this.options.onStarted?.(af(t),t.trackIndex)},complete:t=>{let r=af(t);t.loop?this.options.onLooped?.(r,t.trackIndex):this.options.onFinished?.(r,t.trackIndex)},event:(t,r)=>{this.options.onEvent?.(r.data.name,{int:r.intValue,float:r.floatValue,string:r.stringValue},t.trackIndex)}}),this.object.update(0)}object;asset;disposed=!1;color={r:1,g:1,b:1};opacity=1;get skeletonAsset(){return this.asset}getAnimationNames(){return this.asset.skeletonData.animations.map(e=>e.name)}getSkinNames(){return this.asset.skeletonData.skins.map(e=>e.name)}getSetupBounds(){let e=this.asset.skeletonData;return{x:e.x,y:e.y,width:e.width,height:e.height}}getCurrentAnimation(e=0){return(this.object.state.tracks[e]??null)?.animation?.name??null}rewind(e=0){let t=this.object.state.tracks[e]??null,r=t?.animation?.name??null;if(!r){this.object.skeleton.setupPose(),this.object.update(0);return}let i=this.object.state.setAnimation(e,r,t?.loop??!1);i.mixDuration=0,this.object.update(0)}setDefaultMix(e){this.object.state.data.defaultMix=Math.max(0,e)}setMix(e,t,r){this.object.state.data.setMix(e,t,Math.max(0,r))}setTimeScale(e){this.object.state.timeScale=Number.isFinite(e)?e:1}play(e,t={}){let r=e.trim();if(!r||!this.asset.skeletonData.findAnimation(r))return!1;let i=this.object.state.setAnimation(t.trackIndex??0,r,t.loop??!1);return t.mixDuration!==void 0&&(i.mixDuration=Math.max(0,t.mixDuration)),!0}queue(e,t={}){let r=e.trim();if(!r||!this.asset.skeletonData.findAnimation(r))return!1;let i=this.object.state.addAnimation(t.trackIndex??0,r,t.loop??!1,t.delay??0);return t.mixDuration!==void 0&&(i.mixDuration=Math.max(0,t.mixDuration)),!0}stop(e={}){let{trackIndex:t,mixDuration:r}=e;if(r!==void 0&&r>0){this.object.state.setEmptyAnimation(t??0,r);return}t===void 0?this.object.state.clearTracks():this.object.state.clearTrack(t),this.object.skeleton.setupPose(),this.object.update(0)}setSkin(e){let t=e.trim();return t?this.asset.skeletonData.findSkin(t)?(this.object.skeleton.setSkin(t),this.object.skeleton.setupPoseSlots(),!0):!1:(this.object.skeleton.skin=null,this.object.skeleton.setupPoseSlots(),!0)}setTint(e,t){this.color=e,this.opacity=Px(t);let r=this.object.skeleton.color;r.r=e.r,r.g=e.g,r.b=e.b,r.a=this.opacity}setOpacity(e){this.setTint(this.color,e)}update(e){this.disposed||this.object.update(Math.max(0,e))}refresh(){this.update(0)}dispose(){this.disposed||(this.disposed=!0,this.object.removeFromParent(),this.object.dispose())}};function Px(n){return Number.isFinite(n)?Math.min(1,Math.max(0,n)):1}function af(n){return n.animation?.name??""}function kx(){return n=>new R({...n,depthTest:!1,depthWrite:!1,transparent:!0})}var ur=class n extends M{skeletonPath;atlasPath;texture;animation;loop;isPlaying;skin;timeScale;defaultMix;color;twoColorTint;freeOnFinish;previewInEditor;asset=null;view=null;tintColor=new L("#ffffff");appliedOpacity=-1;appliedTintHex="";constructor(e){super(e,"SpineSkeleton2D"),this.skeletonPath=vs(e.skeletonPath),this.atlasPath=vs(e.atlasPath),this.texture=D(e.texture??null),this.animation=typeof e.animation=="string"?e.animation.trim():"",this.loop=e.loop??!0,this.isPlaying=e.isPlaying??!0,this.skin=typeof e.skin=="string"?e.skin.trim():"",this.timeScale=e.timeScale??1,this.defaultMix=Math.max(0,e.defaultMix??0),this.color=e.color??"#ffffff",this.twoColorTint=e.twoColorTint??!1,this.freeOnFinish=e.freeOnFinish??!1,this.previewInEditor=e.previewInEditor??!1,this.isContainer=!1,this.tintColor.set(this.color),this.syncSerializedProperties(),G(this,n.getPropertySchema)}getAssetRequest(){return!this.skeletonPath||!this.atlasPath?null:{skeletonPath:this.skeletonPath,atlasPath:this.atlasPath,texturePath:this.texture?.url??null}}get texturePath(){return this.texture?.url??null}set texturePath(e){this.texture=D(e)}get isLoaded(){return this.view!==null}setSpineAsset(e){this.view&&(this.remove(this.view.object),this.view.dispose(),this.view=null),this.asset=e,this.appliedOpacity=-1,this.appliedTintHex="",e&&(this.view=new tn({asset:e,twoColorTint:this.twoColorTint,onStarted:(t,r)=>this.emit("animation-started",t,r),onLooped:(t,r)=>this.emit("animation-looped",t,r),onFinished:(t,r)=>{this.isPlaying=!1,this.properties.isPlaying=!1,this.emit("animation-finished",t,r),this.freeOnFinish&&this.queueFree()},onEvent:(t,r,i)=>this.emit("spine-event",t,r,i)}),this.view.setDefaultMix(this.defaultMix),this.view.setTimeScale(this.timeScale),this.skin&&this.view.setSkin(this.skin),this.applyTint(!0),this.applyAuthoredAnimation(),this.add(this.view.object))}getView(){return this.view}getAnimationNames(){return this.view?.getAnimationNames()??[]}getSkinNames(){return this.view?.getSkinNames()??[]}getSetupBounds(){return this.view?.getSetupBounds()??null}getCurrentAnimation(e=0){return this.view?.getCurrentAnimation(e)??null}play(e,t={}){let r=(e??this.animation).trim();return!this.view||!r?!1:this.view.play(r,{loop:t.loop??this.loop,...t})?((t.trackIndex??0)===0&&(ri(this,"animation",r),this.properties.animation=r),ri(this,"isPlaying",!0),this.properties.isPlaying=!0,!0):(console.warn(`[SpineSkeleton2D] Unknown animation "${r}" on node ${this.nodeId} (available: ${this.getAnimationNames().join(", ")||"none"})`),!1)}queue(e,t={}){return this.view?this.view.queue(e,{loop:t.loop??!1,...t}):!1}stop(e={}){this.isPlaying=!1,this.properties.isPlaying=!1,this.view?.stop(e)}resetToFirstFrame(e=0){this.view?.rewind(e)}pause(){this.isPlaying=!1,this.properties.isPlaying=!1}resume(){this.isPlaying=!0,this.properties.isPlaying=!0}setSkin(e){let t=e.trim();return this.view&&!this.view.setSkin(t)?(console.warn(`[SpineSkeleton2D] Unknown skin "${t}" on node ${this.nodeId} (available: ${this.getSkinNames().join(", ")||"none"})`),!1):(this.skin=t,t?this.properties.skin=t:delete this.properties.skin,this.view?.refresh(),!0)}setMix(e,t,r){this.view?.setMix(e,t,r)}setTimeScale(e){this.timeScale=Number.isFinite(e)?e:1,this.properties.timeScale=this.timeScale,this.view?.setTimeScale(this.timeScale)}tick(e){if(super.tick(e),!this.view)return;let t=this.applyTint(!1);this.isPlaying?this.view.update(e):t&&this.view.refresh()}advancePreview(e){this.applyTint(!1),this.view?.update(e)}static getPropertySchema(){let e=M.getPropertySchema();return{...e,nodeType:"SpineSkeleton2D",properties:[...e.properties,{name:"skeletonPath",type:"string",ui:{label:"Skeleton",description:"Spine skeleton export (.json or .skel)",group:"Spine",editor:"file-resource",extensions:["json","skel"]},getValue:t=>t.skeletonPath??"",setValue:(t,r)=>{let i=t;i.skeletonPath=vs(r),i.syncSerializedProperties()}},{name:"atlasPath",type:"string",ui:{label:"Atlas",description:"Spine atlas export (.atlas)",group:"Spine",editor:"file-resource",extensions:["atlas"]},getValue:t=>t.atlasPath??"",setValue:(t,r)=>{let i=t;i.atlasPath=vs(r),i.syncSerializedProperties()}},{name:"texture",type:"object",ui:{label:"Page Texture",description:"Optional override for a single-page atlas. Multi-page atlases always use the page names inside the .atlas file.",group:"Spine",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.texture,setValue:(t,r)=>{let i=t;i.texture=D(r),i.syncSerializedProperties()}},{name:"animation",type:"string",ui:{label:"Animation",group:"Animation"},getValue:t=>t.animation,setValue:(t,r)=>{let i=t,o=String(r??"").trim();i.animation=o,o?i.properties.animation=o:delete i.properties.animation,i.applyAuthoredAnimation()}},{name:"loop",type:"boolean",ui:{label:"Loop",group:"Animation"},getValue:t=>t.loop,setValue:(t,r)=>{let i=t;i.loop=!!r,i.properties.loop=i.loop,i.applyAuthoredAnimation()}},{name:"isPlaying",type:"boolean",ui:{label:"Playing",group:"Animation"},getValue:t=>t.isPlaying,setValue:(t,r)=>{let i=t;i.isPlaying=!!r,i.properties.isPlaying=i.isPlaying}},{name:"skin",type:"string",ui:{label:"Skin",group:"Animation"},getValue:t=>t.skin,setValue:(t,r)=>{t.setSkin(String(r??""))}},{name:"timeScale",type:"number",ui:{label:"Time Scale",group:"Animation",min:0,step:.05},getValue:t=>t.timeScale,setValue:(t,r)=>{t.setTimeScale(Number(r))}},{name:"defaultMix",type:"number",ui:{label:"Default Mix",description:"Crossfade duration between animations, in seconds",group:"Animation",min:0,step:.01,unit:"s"},getValue:t=>t.defaultMix,setValue:(t,r)=>{let i=t;i.defaultMix=Math.max(0,Number(r)||0),i.properties.defaultMix=i.defaultMix,i.view?.setDefaultMix(i.defaultMix)}},{name:"freeOnFinish",type:"boolean",ui:{label:"Free on Finish",description:"Destroy this node when a non-looping animation finishes",group:"Animation"},getValue:t=>t.freeOnFinish,setValue:(t,r)=>{let i=t;i.freeOnFinish=!!r,i.freeOnFinish?i.properties.freeOnFinish=!0:delete i.properties.freeOnFinish}},{name:"previewInEditor",type:"boolean",ui:{label:"Editor Preview",description:"Animate in the editor viewport instead of holding a single pose. Playback is off by default; Reset rewinds to the first frame.",group:"Animation",editor:"spine-preview"},getValue:t=>t.previewInEditor,setValue:(t,r)=>{let i=t;i.previewInEditor=!!r,i.previewInEditor?i.properties.previewInEditor=!0:delete i.properties.previewInEditor}},{name:"color",type:"color",ui:{label:"Tint",group:"Style"},getValue:t=>t.color,setValue:(t,r)=>{let i=t;i.color=String(r??"#ffffff"),i.properties.color=i.color,i.tintColor.set(i.color),i.applyTint(!0),i.view?.refresh()}},{name:"twoColorTint",type:"boolean",ui:{label:"Two Color Tint",description:"Enable spine tint-black rendering (skeletons exported with dark tint)",group:"Style"},getValue:t=>t.twoColorTint,setValue:(t,r)=>{let i=t,o=!!r;o!==i.twoColorTint&&(i.twoColorTint=o,o?i.properties.twoColorTint=!0:delete i.properties.twoColorTint,i.setSpineAsset(i.asset))}}],groups:{...e.groups,Spine:{label:"Spine",expanded:!0},Animation:{label:"Animation",expanded:!0},Style:{label:"Style",expanded:!0}}}}getInstancePropertySchema(){if(!this.view)return null;let e=this.getAnimationNames(),t=this.getSkinNames();if(e.length===0&&t.length===0)return null;let r=[];return e.length>0&&r.push({name:"animation",type:"select",ui:{label:"Animation",group:"Animation",options:["",...e]},getValue:i=>i.animation,setValue:(i,o)=>{let s=i,a=String(o??"").trim();s.animation=a,a?s.properties.animation=a:delete s.properties.animation,s.applyAuthoredAnimation()}}),t.length>0&&r.push({name:"skin",type:"select",ui:{label:"Skin",group:"Animation",options:["",...t]},getValue:i=>i.skin,setValue:(i,o)=>{i.setSkin(String(o??""))}}),{nodeType:"SpineSkeleton2D",properties:r}}disposeResources(){this.view&&(this.view.dispose(),this.view=null),this.asset=null}applyAuthoredAnimation(){if(this.view){if(!this.animation){this.view.stop();return}if(!this.view.play(this.animation,{loop:this.loop})){console.warn(`[SpineSkeleton2D] Unknown animation "${this.animation}" on node ${this.nodeId} (available: ${this.getAnimationNames().join(", ")||"none"})`);return}this.view.refresh()}}applyTint(e){if(!this.view)return!1;let t=this.computedOpacity;return!e&&this.appliedOpacity===t&&this.appliedTintHex===this.color?!1:(this.appliedOpacity=t,this.appliedTintHex=this.color,this.view.setTint({r:this.tintColor.r,g:this.tintColor.g,b:this.tintColor.b},t),!0)}syncSerializedProperties(){this.skeletonPath?this.properties.skeletonPath=this.skeletonPath:delete this.properties.skeletonPath,this.atlasPath?this.properties.atlasPath=this.atlasPath:delete this.properties.atlasPath,this.texture?this.properties.texture={...this.texture}:delete this.properties.texture,this.animation?this.properties.animation=this.animation:delete this.properties.animation,this.skin?this.properties.skin=this.skin:delete this.properties.skin,this.properties.loop=this.loop,this.properties.isPlaying=this.isPlaying,this.properties.timeScale=this.timeScale,this.properties.defaultMix=this.defaultMix,this.properties.color=this.color,this.twoColorTint?this.properties.twoColorTint=!0:delete this.properties.twoColorTint,this.freeOnFinish?this.properties.freeOnFinish=!0:delete this.properties.freeOnFinish,this.previewInEditor?this.properties.previewInEditor=!0:delete this.properties.previewInEditor}};function vs(n){if(typeof n!="string")return null;let e=n.trim();return e.length>0?e:null}var dr=class n extends M{width;height;color;mesh;material;constructor(e){super(e,"ColorRect2D"),this.width=e.width??100,this.height=e.height??100,this.color=e.color??"#ffffff",this.opacity=e.opacity??1,this.isContainer=!1,this.material=new R({color:this.color,transparent:!0,opacity:1,depthTest:!1}),this.registerOpacityMaterial(this.material,1),this.mesh=new B(Me,this.material),this.mesh.name=`${this.name}-Mesh`,this.mesh.scale.set(this.width,this.height,1),this.mesh.userData[Ne]=!0,this.add(this.mesh),G(this,n.getPropertySchema)}static getPropertySchema(){let e=M.getPropertySchema();return{...e,nodeType:"ColorRect2D",properties:[...e.properties,{name:"width",type:"number",ui:{label:"Width",group:"Size",min:0,step:1},getValue:t=>t.width,setValue:(t,r)=>{let i=t;i.width=Number(r),i.updateSize()}},{name:"height",type:"number",ui:{label:"Height",group:"Size",min:0,step:1},getValue:t=>t.height,setValue:(t,r)=>{let i=t;i.height=Number(r),i.updateSize()}},{name:"color",type:"color",ui:{label:"Color",group:"Style"},getValue:t=>t.color,setValue:(t,r)=>{let i=t;i.color=String(r),i.material.color.set(i.color)}}],groups:{...e.groups,Size:{label:"Size",expanded:!0},Style:{label:"Style",expanded:!0}}}}updateSize(){this.mesh.scale.set(this.width,this.height,1)}disposeResources(){this.material.dispose()}};var Xe=1e-4,lf=4096;function xs(n,e,t,r,i,o){let s=e-n;if(s<=Xe)return[];let a=[{start:n,end:e,uv0:t,uv1:r}];if(!Number.isFinite(i)||i<=Xe||s/i>lf)return a;let l=r-t,c=o-Math.floor(o);Number.isFinite(c)||(c=0);let u=[],d=n,h=t+c*l,p=(1-c)*i;p<=Xe&&(p=i,h=t);let f=0;for(;d<e-Xe&&f<=lf+2;){f+=1;let m=Math.min(p,e-d),g=m/i;u.push({start:d,end:d+m,uv0:h,uv1:h+g*l}),d+=m,h=t,p=i}return u}function Ps(n,e,t,r){return e-n<=Xe?[]:[{start:n,end:e,uv0:t,uv1:r}]}function tu(n,e,t){for(let r of t)if(!(r.end-r.start<=Xe))for(let i of e)i.end-i.start<=Xe||n.push({x0:i.start,y0:r.start,x1:i.end,y1:r.end,u0:i.uv0,v0:r.uv0,u1:i.uv1,v1:r.uv1})}function ws(n,e,t){let r=Math.max(0,Number.isFinite(n)?n:0),i=Math.max(0,Number.isFinite(e)?e:0),o=r+i;if(o>t&&o>Xe){let s=t/o;return{a:r*s,b:i*s}}return{a:r,b:i}}function li(n){let e=Math.max(0,Number.isFinite(n.width)?n.width:0),t=Math.max(0,Number.isFinite(n.height)?n.height:0),r=e/2,i=t/2,o=n.textureWidth>0?n.textureWidth:e>0?e:1,s=n.textureHeight>0?n.textureHeight:t>0?t:1,a=[];if(n.mode==="stretch")tu(a,Ps(-r,r,0,1),Ps(-i,i,0,1));else if(n.mode==="tile"){let l=Number.isFinite(n.tileScale.x)&&n.tileScale.x>0?n.tileScale.x:1,c=Number.isFinite(n.tileScale.y)&&n.tileScale.y>0?n.tileScale.y:1,u=Math.max(Xe,o*l),d=Math.max(Xe,s*c),h=xs(-r,r,0,1,u,n.tileOffset.x||0),p=xs(-i,i,0,1,d,n.tileOffset.y||0);tu(a,h,p)}else Ax(a,n,{width:e,height:t,halfW:r,halfH:i,srcW:o,srcH:s});return Tx(a)}function Ax(n,e,t){let{width:r,height:i,halfW:o,halfH:s,srcW:a,srcH:l}=t,c=Math.max(0,e.border.left),u=Math.max(0,e.border.right),d=Math.max(0,e.border.top),h=Math.max(0,e.border.bottom);e.mode==="three-slice-h"?(d=0,h=0):e.mode==="three-slice-v"&&(c=0,u=0);let p=ws(c,u,a),f=ws(h,d,l),m=p.a/a,g=1-p.b/a,y=f.a/l,b=1-f.b/l,v=ws(c,u,r),w=ws(h,d,i),k=[-o,-o+v.a,o-v.b,o],T=[-s,-s+w.a,s-w.b,s],N=[0,m,g,1],A=[0,y,b,1],F=a*(g-m),Z=l*(b-y),ne=e.axisStretchHorizontal==="tile",re=e.axisStretchVertical==="tile";for(let Be=0;Be<3;Be+=1)for(let Tt=0;Tt<3;Tt+=1){if(Tt===1&&Be===1&&!e.drawCenter)continue;let sw=Tt===1&&ne?xs(k[1],k[2],N[1],N[2],F,0):Ps(k[Tt],k[Tt+1],N[Tt],N[Tt+1]),aw=Be===1&&re?xs(T[1],T[2],A[1],A[2],Z,0):Ps(T[Be],T[Be+1],A[Be],A[Be+1]);tu(n,sw,aw)}}function Tx(n){let e=new Float32Array(n.length*18),t=new Float32Array(n.length*12),r=new Float32Array(n.length*18),i=0,o=0;for(let a of n){let l=[a.x0,a.y0,a.u0,a.v0,a.x1,a.y0,a.u1,a.v0,a.x1,a.y1,a.u1,a.v1,a.x0,a.y0,a.u0,a.v0,a.x1,a.y1,a.u1,a.v1,a.x0,a.y1,a.u0,a.v1];for(let c=0;c<6;c+=1){let u=c*4;e[i]=l[u],e[i+1]=l[u+1],e[i+2]=0,r[i]=0,r[i+1]=0,r[i+2]=1,i+=3,t[o]=l[u+2],t[o+1]=l[u+3],o+=2}}let s=new le;return s.setAttribute("position",new J(e,3)),s.setAttribute("uv",new J(t,2)),s.setAttribute("normal",new J(r,3)),s.computeBoundingBox(),s.computeBoundingSphere(),s}var cf=Object.freeze({left:0,right:0,top:0,bottom:0});function Ee(n){let e=t=>{let r=Number(t);return Number.isFinite(r)&&r>0?r:0};return{left:e(n?.left),right:e(n?.right),top:e(n?.top),bottom:e(n?.bottom)}}function ci(n){return n?!(n.left>0||n.right>0||n.top>0||n.bottom>0):!0}function hr(n){let e=Math.max(0,Number.isFinite(n.width)?n.width:0),t=Math.max(0,Number.isFinite(n.height)?n.height:0),r=n.border??cf;return ci(r)?new z(e,t):li({mode:"nine-slice",width:e,height:t,textureWidth:n.textureWidth??0,textureHeight:n.textureHeight??0,border:r,drawCenter:!0,axisStretchHorizontal:"stretch",axisStretchVertical:"stretch",tileScale:{x:1,y:1},tileOffset:{x:0,y:0}})}var Cx=["stretch","tile","nine-slice","three-slice-h","three-slice-v"],Mx=["stretch","tile"],Dx=128,pr=class n extends M{texture;width;height;patchMode;sliceBorder;drawCenter;axisStretchHorizontal;axisStretchVertical;tileScale;tileOffset;anchor;textureWidth;textureHeight;mesh;geometry;material;constructor(e){super(e,"TiledSprite2D"),this.texture=D(e.texture??e.texturePath??null),this.width=n.toSize(e.width),this.height=n.toSize(e.height),this.patchMode=n.normalizePatchMode(e.patchMode),this.sliceBorder=n.normalizeBorder(e.sliceBorder),this.drawCenter=e.drawCenter??!0,this.axisStretchHorizontal=n.normalizeAxis(e.axisStretchHorizontal),this.axisStretchVertical=n.normalizeAxis(e.axisStretchVertical),this.tileScale=n.toVector2(e.tileScale,1,1),this.tileOffset=n.toVector2(e.tileOffset,0,0),this.anchor=n.normalizeAnchor(e.anchor),this.textureWidth=0,this.textureHeight=0,this.isContainer=!1,this.geometry=li(this.buildGeometryParams()),this.material=new R({color:e.color??"#ffffff",transparent:!0,depthTest:!1}),this.registerOpacityMaterial(this.material,1),this.mesh=new B(this.geometry,this.material),this.mesh.name=`${this.name}-Mesh`,this.applyAnchorOffset(),this.add(this.mesh),G(this,n.getPropertySchema)}buildGeometryParams(){return{mode:this.patchMode,width:this.width,height:this.height,textureWidth:this.textureWidth,textureHeight:this.textureHeight,border:this.sliceBorder,drawCenter:this.drawCenter,axisStretchHorizontal:this.axisStretchHorizontal,axisStretchVertical:this.axisStretchVertical,tileScale:{x:this.tileScale.x,y:this.tileScale.y},tileOffset:{x:this.tileOffset.x,y:this.tileOffset.y}}}rebuildGeometry(){let e=li(this.buildGeometryParams());this.geometry.dispose(),this.geometry=e,this.mesh.geometry=e,this.applyAnchorOffset(),this.material.needsUpdate=!0,this.refreshOpacity()}applyAnchorOffset(){this.mesh.position.set((.5-this.anchor.x)*this.width,(.5-this.anchor.y)*this.height,0)}updateSize(e,t){this.width=n.toSize(e),this.height=n.toSize(t),this.rebuildGeometry()}setPatchMode(e){this.patchMode=n.normalizePatchMode(e),this.rebuildGeometry()}setSliceBorder(e){this.sliceBorder=n.normalizeBorder({...this.sliceBorder,...e}),this.rebuildGeometry()}setDrawCenter(e){this.drawCenter=!!e,this.rebuildGeometry()}setAxisStretchHorizontal(e){this.axisStretchHorizontal=n.normalizeAxis(e),this.rebuildGeometry()}setAxisStretchVertical(e){this.axisStretchVertical=n.normalizeAxis(e),this.rebuildGeometry()}setTileScale(e,t){this.tileScale.set(Number.isFinite(e)?e:1,Number.isFinite(t)?t:1),this.rebuildGeometry()}setTileOffset(e,t){this.tileOffset.set(Number.isFinite(e)?e:0,Number.isFinite(t)?t:0),this.rebuildGeometry()}setAnchor(e){this.anchor=n.normalizeAnchor(e),this.applyAnchorOffset()}get texturePath(){return this.texture?.url??null}set texturePath(e){this.texture=D(e)}setTextureResource(e){this.texture=D(e)}setTexture(e){if(Y(e),this.material.map=e,this.material.color.set("#ffffff"),this.material.needsUpdate=!0,e.image){let t=e.image,r=t.naturalWidth??t.width,i=t.naturalHeight??t.height;r&&i&&(this.textureWidth=r,this.textureHeight=i)}this.rebuildGeometry()}disposeResources(){this.geometry.dispose(),this.material.dispose()}static toSize(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:Dx}static normalizePatchMode(e){return Cx.includes(e)?e:"stretch"}static normalizeAxis(e){return Mx.includes(e)?e:"stretch"}static normalizeBorder(e){return Ee(e)}static normalizeAnchor(e){if(!e)return{x:.5,y:.5};let t=Array.isArray(e)?e[0]:e.x,r=Array.isArray(e)?e[1]:e.y,i=Number(t),o=Number(r);return{x:Number.isFinite(i)?i:.5,y:Number.isFinite(o)?o:.5}}static toVector2(e,t,r){if(!e)return new I(t,r);let i=Array.isArray(e)?e[0]:e.x,o=Array.isArray(e)?e[1]:e.y,s=Number(i),a=Number(o);return new I(Number.isFinite(s)?s:t,Number.isFinite(a)?a:r)}static getPropertySchema(){let e=M.getPropertySchema();return{nodeType:"TiledSprite2D",extends:"Node2D",properties:[...e.properties,{name:"patchMode",type:"enum",ui:{label:"Mode",description:"How the texture fills the rectangle",group:"Patch",options:{Stretch:"stretch",Tile:"tile","9-Slice":"nine-slice","3-Slice Horizontal":"three-slice-h","3-Slice Vertical":"three-slice-v"}},getValue:t=>t.patchMode,setValue:(t,r)=>{t.setPatchMode(String(r))}},{name:"texture",type:"object",ui:{label:"Texture",description:"Path to the texture",group:"Patch",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.texture??{type:"texture",url:""},setValue:(t,r)=>{t.setTextureResource(r)}},{name:"anchor",type:"vector2",ui:{label:"Pivot",description:"Normalized pivot point used to position the image",group:"Patch",step:.01,precision:2},getValue:t=>{let r=t.anchor;return{x:r.x,y:r.y}},setValue:(t,r)=>{let i=r;t.setAnchor({x:i.x,y:i.y})}},{name:"width",type:"number",ui:{label:"Width",description:"Width in pixels",group:"Size",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.width,setValue:(t,r)=>{let i=t;i.updateSize(Number(r),i.height)}},{name:"height",type:"number",ui:{label:"Height",description:"Height in pixels",group:"Size",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.height,setValue:(t,r)=>{let i=t;i.updateSize(i.width,Number(r))}},{name:"sliceBorderLeft",type:"number",ui:{label:"Left",description:"Left border inset (source px)",group:"Slice",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.left,setValue:(t,r)=>{t.setSliceBorder({left:Number(r)})}},{name:"sliceBorderRight",type:"number",ui:{label:"Right",description:"Right border inset (source px)",group:"Slice",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.right,setValue:(t,r)=>{t.setSliceBorder({right:Number(r)})}},{name:"sliceBorderTop",type:"number",ui:{label:"Top",description:"Top border inset (source px)",group:"Slice",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.top,setValue:(t,r)=>{t.setSliceBorder({top:Number(r)})}},{name:"sliceBorderBottom",type:"number",ui:{label:"Bottom",description:"Bottom border inset (source px)",group:"Slice",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.bottom,setValue:(t,r)=>{t.setSliceBorder({bottom:Number(r)})}},{name:"drawCenter",type:"boolean",ui:{label:"Draw Center",description:"Draw the centre patch (uncheck for a hollow frame)",group:"Slice"},getValue:t=>t.drawCenter,setValue:(t,r)=>{t.setDrawCenter(!!r)}},{name:"axisStretchHorizontal",type:"enum",ui:{label:"Horizontal Fill",description:"How the horizontal middle fills in slice modes",group:"Slice",options:{Stretch:"stretch",Tile:"tile"}},getValue:t=>t.axisStretchHorizontal,setValue:(t,r)=>{t.setAxisStretchHorizontal(String(r))}},{name:"axisStretchVertical",type:"enum",ui:{label:"Vertical Fill",description:"How the vertical middle fills in slice modes",group:"Slice",options:{Stretch:"stretch",Tile:"tile"}},getValue:t=>t.axisStretchVertical,setValue:(t,r)=>{t.setAxisStretchVertical(String(r))}},{name:"tileScale",type:"vector2",ui:{label:"Tile Scale",description:"Tile size multiplier (Tile mode)",group:"Tile",step:.01,precision:2},getValue:t=>{let r=t.tileScale;return{x:r.x,y:r.y}},setValue:(t,r)=>{let i=r;t.setTileScale(i.x,i.y)}},{name:"tileOffset",type:"vector2",ui:{label:"Tile Offset",description:"UV phase offset in tiles (Tile mode)",group:"Tile",step:.01,precision:2},getValue:t=>{let r=t.tileOffset;return{x:r.x,y:r.y}},setValue:(t,r)=>{let i=r;t.setTileOffset(i.x,i.y)}}],groups:{...e.groups,Patch:{label:"Patch",description:"Texture and fill mode",expanded:!0},Size:{label:"Size",description:"Rectangle dimensions in pixels",expanded:!0},Slice:{label:"Slice",description:"9-slice / 3-slice borders",expanded:!0},Tile:{label:"Tile",description:"Tiling scale and offset",expanded:!1}}}}};var Ae=class extends M{_width;_height;constructor(e,t="Group2D"){super(e,t),this._width=Number.isFinite(e.width)?Math.max(0,e.width??0):100,this._height=Number.isFinite(e.height)?Math.max(0,e.height??0):100,this.isContainer=!0}get width(){return this._width}set width(e){let t=Number.isFinite(e)?Math.max(0,e):this._width;this._width!==t&&(this._width=t,this.reflowAnchoredChildren())}get height(){return this._height}set height(e){let t=Number.isFinite(e)?Math.max(0,e):this._height;this._height!==t&&(this._height=t,this.reflowAnchoredChildren())}getSize(){return new I(this._width,this._height)}setSize(e,t){let r=Number.isFinite(e)?Math.max(0,e):this._width,i=Number.isFinite(t)?Math.max(0,t):this._height,o=this._width!==r||this._height!==i;this._width=r,this._height=i,o&&this.reflowAnchoredChildren()}static getPropertySchema(){let e=M.getPropertySchema();return{nodeType:"Group2D",extends:"Node2D",properties:[...e.properties,{name:"width",type:"number",ui:{label:"Width",group:"Size",step:1,precision:0,min:0},getValue:t=>t.width,setValue:(t,r)=>{t.width=Number(r)}},{name:"height",type:"number",ui:{label:"Height",group:"Size",step:1,precision:0,min:0},getValue:t=>t.height,setValue:(t,r)=>{t.height=Number(r)}}],groups:{...e.groups,Size:{label:"Size",description:"Group dimensions",expanded:!0}}}}};var Bt=class n extends O{active=!1;elapsed=0;appliedOffset=new S;onTriggerSignal=()=>{this.trigger()};constructor(e,t){super(e,t),this.config={amplitude:8,frequency:24,duration:.35,decay:1.5,triggerEvent:"",playOnStart:!1}}static getPropertySchema(){return{nodeType:"ShakeBehavior",properties:[{name:"amplitude",type:"number",ui:{label:"Amplitude",group:"Shake",min:0,step:.5},getValue:e=>e.getAmplitude(),setValue:(e,t)=>{e.config.amplitude=n.num(t,8,0)}},{name:"frequency",type:"number",ui:{label:"Frequency",group:"Shake",min:0,step:1},getValue:e=>e.getFrequency(),setValue:(e,t)=>{e.config.frequency=n.num(t,24,0)}},{name:"duration",type:"number",ui:{label:"Duration",group:"Shake",min:0,step:.05,precision:2,unit:"s"},getValue:e=>e.getDuration(),setValue:(e,t)=>{e.config.duration=n.num(t,.35,0)}},{name:"decay",type:"number",ui:{label:"Decay",description:"Falloff power (0 = steady, 1 = linear, >1 = punchy tail)",group:"Shake",min:0,step:.1,precision:2},getValue:e=>e.getDecay(),setValue:(e,t)=>{e.config.decay=n.num(t,1.5,0)}},{name:"triggerEvent",type:"string",ui:{label:"Trigger Event",description:"Node signal that starts the shake (empty = manual/API only)",group:"Shake"},getValue:e=>e.getTriggerEvent(),setValue:(e,t)=>{e.setTriggerEvent(t)}},{name:"playOnStart",type:"boolean",ui:{label:"Play On Start",group:"Shake"},getValue:e=>!!e.config.playOnStart,setValue:(e,t)=>{e.config.playOnStart=!!t}}],groups:{Shake:{label:"Shake",expanded:!0}}}}onStart(){this.bindTrigger(),this.config.playOnStart&&this.trigger()}onDetach(){this.unbindTrigger(),this.restore(),this.active=!1,super.onDetach()}play(e={}){e.amplitude!=null&&(this.config.amplitude=n.num(e.amplitude,8,0)),e.frequency!=null&&(this.config.frequency=n.num(e.frequency,24,0)),e.duration!=null&&(this.config.duration=n.num(e.duration,.35,0)),e.decay!=null&&(this.config.decay=n.num(e.decay,1.5,0)),this.trigger()}trigger(){this.elapsed=0,this.active=!0}stop(){this.active=!1,this.restore()}onUpdate(e){if(!this.node||(this.restore(),!this.active))return;this.elapsed+=e;let t=this.getDuration();if(t>0&&this.elapsed>=t){this.active=!1;return}let r=t>0?this.elapsed/t:0,i=Math.pow(Math.max(0,1-r),this.getDecay()),o=this.getAmplitude()*i,s=this.elapsed*this.getFrequency(),a=this.node instanceof U;this.appliedOffset.set(mr(s,0)*o,mr(s,100)*o,a?mr(s,200)*o*.5:0),this.node.position.add(this.appliedOffset)}restore(){this.node&&(this.appliedOffset.x||this.appliedOffset.y||this.appliedOffset.z)&&this.node.position.sub(this.appliedOffset),this.appliedOffset.set(0,0,0)}bindTrigger(){let e=this.getTriggerEvent();this.node&&e&&this.node.connect(e,this,this.onTriggerSignal)}unbindTrigger(){let e=this.getTriggerEvent();this.node&&e&&this.node.disconnect(e,this,this.onTriggerSignal)}getAmplitude(){return n.num(this.config.amplitude,8,0)}getFrequency(){return n.num(this.config.frequency,24,0)}getDuration(){return n.num(this.config.duration,.35,0)}getDecay(){return n.num(this.config.decay,1.5,0)}getTriggerEvent(){return typeof this.config.triggerEvent=="string"?this.config.triggerEvent.trim():""}setTriggerEvent(e){let t=!!this.node;t&&this.unbindTrigger(),this.config.triggerEvent=typeof e=="string"?e.trim():"",t&&this.bindTrigger()}static num(e,t,r){let i=typeof e=="number"?e:Number(e);return Number.isFinite(i)?Math.max(r,i):t}};function mr(n,e){return Math.sin(n*1.373+e*12.9898)*.5+Math.sin(n*2.917+e*7.233)*.3+Math.sin(n*5.109+e*19.19)*.2}function rn(n,e){if(n<=0||e<=0)return 1;let t=1-Math.exp(-n*e);return t<0?0:t>1?1:t}function fr(n,e,t){let r=e-n;return Math.abs(r)<=t?n:r>0?e-t:e+t}function gr(n,e,t){let r=e-t,i=e+t;return n<r?r:n>i?i:n}var ks={priority:10,zoom:1,followDamping:8,shakeAmplitude:8,shakeFrequency:24,shakeDuration:.35,shakeDecay:1.5},Vt=class extends M{priorityValue;zoomValue;offset=new I;followTargetId;followDampingValue;followOffset=new I;deadzone=new I;limitsEnabledValue;limitsCenter=new I;limitsSize=new I(1e3,1e3);shakeAmplitudeValue;shakeFrequencyValue;shakeDurationValue;shakeDecayValue;shakeActive=!1;shakeElapsed=0;shakeOffset=new I;scratchWorld=new S;scratchTarget=new S;scratchLocal=new S;constructor(e){super(e,"Camera2D");let t=ks;this.priorityValue=e.priority??t.priority,this.zoomValue=Math.max(.01,e.zoom??t.zoom),e.offset&&this.offset.set(e.offset.x,e.offset.y),this.followTargetId=e.followTargetId??"",this.followDampingValue=Math.max(0,e.followDamping??t.followDamping),e.followOffset&&this.followOffset.set(e.followOffset.x,e.followOffset.y),e.deadzone&&this.deadzone.set(Math.max(0,e.deadzone.x),Math.max(0,e.deadzone.y)),this.limitsEnabledValue=e.limitsEnabled??!1,e.limitsCenter&&this.limitsCenter.set(e.limitsCenter.x,e.limitsCenter.y),e.limitsSize&&this.limitsSize.set(Math.max(0,e.limitsSize.x),Math.max(0,e.limitsSize.y)),this.shakeAmplitudeValue=Math.max(0,e.shakeAmplitude??t.shakeAmplitude),this.shakeFrequencyValue=Math.max(0,e.shakeFrequency??t.shakeFrequency),this.shakeDurationValue=Math.max(0,e.shakeDuration??t.shakeDuration),this.shakeDecayValue=Math.max(0,e.shakeDecay??t.shakeDecay)}get priority(){return this.priorityValue}set priority(e){let t=Number(e);this.priorityValue=Number.isFinite(t)?t:this.priorityValue}get zoom(){return this.zoomValue}set zoom(e){let t=Number(e);Number.isFinite(t)&&t>0&&(this.zoomValue=t)}get limitsEnabled(){return this.limitsEnabledValue}set limitsEnabled(e){this.limitsEnabledValue=!!e}tick(e){super.tick(e),this.solve(e)}solve(e){this.solveFollow(e),this.advanceShake(e)}computeView(e){this.updateWorldMatrix(!0,!1),this.getWorldPosition(this.scratchWorld);let t=this.scratchWorld.x+this.offset.x,r=this.scratchWorld.y+this.offset.y,i=Math.max(.01,this.zoomValue);if(this.limitsEnabledValue){let o=e.width/2/i,s=e.height/2/i,a=Math.max(0,this.limitsSize.x/2-o),l=Math.max(0,this.limitsSize.y/2-s);t=gr(t,this.limitsCenter.x,a),r=gr(r,this.limitsCenter.y,l)}return{x:t,y:r,zoom:i}}getShakeOffset(e){return e.copy(this.shakeOffset)}shake(e={}){e.amplitude!=null&&Number.isFinite(e.amplitude)&&(this.shakeAmplitudeValue=Math.max(0,e.amplitude)),e.frequency!=null&&Number.isFinite(e.frequency)&&(this.shakeFrequencyValue=Math.max(0,e.frequency)),e.duration!=null&&Number.isFinite(e.duration)&&(this.shakeDurationValue=Math.max(0,e.duration)),e.decay!=null&&Number.isFinite(e.decay)&&(this.shakeDecayValue=Math.max(0,e.decay)),this.shakeElapsed=0,this.shakeActive=!0}stopShake(){this.shakeActive=!1,this.shakeOffset.set(0,0)}advanceShake(e){if(!this.shakeActive){this.shakeOffset.set(0,0);return}this.shakeElapsed+=Math.max(0,e);let t=this.shakeDurationValue;if(t>0&&this.shakeElapsed>=t){this.shakeActive=!1,this.shakeOffset.set(0,0);return}let r=t>0?this.shakeElapsed/t:0,i=Math.pow(Math.max(0,1-r),this.shakeDecayValue),o=this.shakeAmplitudeValue*i,s=this.shakeElapsed*this.shakeFrequencyValue;this.shakeOffset.set(mr(s,0)*o,mr(s,100)*o)}solveFollow(e){let t=this.resolveTarget(this.followTargetId);if(!t||t===this)return;t.getWorldPosition(this.scratchTarget);let r=this.scratchTarget.x+this.followOffset.x,i=this.scratchTarget.y+this.followOffset.y;this.updateWorldMatrix(!0,!1),this.getWorldPosition(this.scratchWorld);let o=fr(this.scratchWorld.x,r,this.deadzone.x),s=fr(this.scratchWorld.y,i,this.deadzone.y),a=rn(this.followDampingValue,e),l=this.scratchWorld.x+(o-this.scratchWorld.x)*a,c=this.scratchWorld.y+(s-this.scratchWorld.y)*a;this.setWorldPosition2D(l,c)}setWorldPosition2D(e,t){this.scratchLocal.set(e,t,0),this.parent&&(this.parent.updateWorldMatrix(!0,!1),this.parent.worldToLocal(this.scratchLocal)),this.position.x=this.scratchLocal.x,this.position.y=this.scratchLocal.y,this.updateWorldMatrix(!0,!1)}resolveTarget(e){if(!e)return null;if(this.scene)return this.scene.findNode(e);let t=this;for(;t.parentNode;)t=t.parentNode;return t.findNode(e)}serializeConfig(){return{priority:this.priorityValue,zoom:this.zoomValue,offset:[this.offset.x,this.offset.y],followTargetId:this.followTargetId,followDamping:this.followDampingValue,followOffset:[this.followOffset.x,this.followOffset.y],deadzone:[this.deadzone.x,this.deadzone.y],limitsEnabled:this.limitsEnabledValue,limitsCenter:[this.limitsCenter.x,this.limitsCenter.y],limitsSize:[this.limitsSize.x,this.limitsSize.y],shakeAmplitude:this.shakeAmplitudeValue,shakeFrequency:this.shakeFrequencyValue,shakeDuration:this.shakeDurationValue,shakeDecay:this.shakeDecayValue}}static getPropertySchema(){let e=super.getPropertySchema(),t={nodeType:"Camera2D",properties:[x("priority","number",{ui:{label:"Priority",description:"Highest-priority visible Camera2D drives the 2D view (animatable)",group:"Camera",step:1,precision:0},getValue:r=>r.priority,setValue:(r,i)=>{r.priority=Number(i)},validation:{validate:r=>Number.isFinite(Number(r))}}),x("zoom","number",{ui:{label:"Zoom",description:">1 magnifies (zooms in), <1 zooms out",group:"Camera",min:.01,step:.05,precision:2},getValue:r=>r.zoom,setValue:(r,i)=>{r.zoom=Number(i)},validation:{validate:r=>Number.isFinite(Number(r))&&Number(r)>0}}),x("offset","vector2",{ui:{label:"Offset",description:"Framing offset added to position (never written by follow / shake)",group:"Camera",step:1,precision:0},getValue:r=>nn(r.offset),setValue:(r,i)=>on(r.offset,i)}),x("followTargetId","node",{ui:{label:"Follow Target",description:"Node whose position this camera follows (empty = authored position)",group:"Follow"},getValue:r=>r.followTargetId,setValue:(r,i)=>{r.followTargetId=typeof i=="string"?i:""}}),x("followOffset","vector2",{ui:{label:"Follow Offset",group:"Follow",step:1,precision:0},getValue:r=>nn(r.followOffset),setValue:(r,i)=>on(r.followOffset,i)}),x("followDamping","number",{ui:{label:"Follow Damping",description:"Higher = snappier follow (0 = instant)",group:"Follow",min:0,step:.1,precision:2},getValue:r=>r.followDampingValue,setValue:(r,i)=>{let o=Number(i);Number.isFinite(o)&&o>=0&&(r.followDampingValue=o)}}),x("deadzone","vector2",{ui:{label:"Deadzone",description:"World half-extents the target can move within before the camera follows",group:"Follow",min:0,step:1,precision:0},getValue:r=>nn(r.deadzone),setValue:(r,i)=>on(r.deadzone,i,0)}),x("limitsEnabled","boolean",{ui:{label:"Limits",description:"Clamp the visible view inside an axis-aligned world box",group:"Limits"},getValue:r=>r.limitsEnabledValue,setValue:(r,i)=>{r.limitsEnabledValue=!!i}}),x("limitsCenter","vector2",{ui:{label:"Limits Center",group:"Limits",step:1,precision:0,readOnly:r=>!r.limitsEnabledValue},getValue:r=>nn(r.limitsCenter),setValue:(r,i)=>on(r.limitsCenter,i)}),x("limitsSize","vector2",{ui:{label:"Limits Size",group:"Limits",min:0,step:1,precision:0,readOnly:r=>!r.limitsEnabledValue},getValue:r=>nn(r.limitsSize),setValue:(r,i)=>on(r.limitsSize,i,0)}),x("shakeAmplitude","number",{ui:{label:"Shake Amplitude",group:"Shake",min:0,step:.5,precision:2},getValue:r=>r.shakeAmplitudeValue,setValue:(r,i)=>{let o=Number(i);Number.isFinite(o)&&o>=0&&(r.shakeAmplitudeValue=o)}}),x("shakeFrequency","number",{ui:{label:"Shake Frequency",group:"Shake",min:0,step:1,precision:1},getValue:r=>r.shakeFrequencyValue,setValue:(r,i)=>{let o=Number(i);Number.isFinite(o)&&o>=0&&(r.shakeFrequencyValue=o)}}),x("shakeDuration","number",{ui:{label:"Shake Duration",group:"Shake",min:0,step:.05,precision:2,unit:"s"},getValue:r=>r.shakeDurationValue,setValue:(r,i)=>{let o=Number(i);Number.isFinite(o)&&o>=0&&(r.shakeDurationValue=o)}}),x("shakeDecay","number",{ui:{label:"Shake Decay",description:"Falloff power (0 = steady, 1 = linear, >1 = punchy tail)",group:"Shake",min:0,step:.1,precision:2},getValue:r=>r.shakeDecayValue,setValue:(r,i)=>{let o=Number(i);Number.isFinite(o)&&o>=0&&(r.shakeDecayValue=o)}})],groups:{Camera:{label:"Camera",expanded:!0},Follow:{label:"Follow",expanded:!0},Limits:{label:"Limits",expanded:!1},Shake:{label:"Shake",expanded:!1}}};return ce(e,t)}};function ru(n){let e=null,t=r=>{for(let i of r){i instanceof Vt&&i.visible&&(e===null||i.priority>e.priority)&&(e=i);let o=i.children.filter(s=>s instanceof V);o.length>0&&t(o)}};return t(n),e}function nn(n){return{x:n.x,y:n.y}}function on(n,e,t=Number.NEGATIVE_INFINITY){let r=e,i=Number(r?.x),o=Number(r?.y);n.set(Number.isFinite(i)?Math.max(t,i):n.x,Number.isFinite(o)?Math.max(t,o):n.y)}var sn=class extends Ae{constructor(e){super(e,"CanvasLayer2D"),this.isCanvasLayer=!0}static getPropertySchema(){return{...Ae.getPropertySchema(),nodeType:"CanvasLayer2D",extends:"Group2D"}}};var uf=5,Ot=class extends U{light;constructor(e){super(e,"DirectionalLight");let t=new L(e.color??"#ffffff"),r=typeof e.intensity=="number"?e.intensity:1;this.light=new Jo(t,r),this.light.castShadow=e.castShadow??!0,this.light.position.set(0,0,0);let i=typeof e.shadowCameraSize=="number"?e.shadowCameraSize:20;this.light.shadow.camera.left=-i,this.light.shadow.camera.right=i,this.light.shadow.camera.top=i,this.light.shadow.camera.bottom=-i,this.light.shadow.camera.near=.1,this.light.shadow.camera.far=500,this.light.shadow.camera.updateProjectionMatrix();let o=typeof e.shadowMapSize=="number"?e.shadowMapSize:2048;this.light.shadow.mapSize.set(o,o),this.add(this.light),this.add(this.light.target),this.light.target.position.set(0,0,-uf),this.light.target.updateMatrixWorld(!0)}getTargetPosition(){return this.light.target.updateMatrixWorld(!0),this.light.target.getWorldPosition(new S)}setTargetPosition(e){let t=this.getWorldPosition(new S),r=e.clone().sub(t),i=r.lengthSq()>1e-8?r.normalize():new S(0,0,1).applyQuaternion(this.getWorldQuaternion(new _)),o=t.add(i.multiplyScalar(uf));this.lookAt(o);let s=o.clone();this.worldToLocal(s),this.light.target.position.copy(s),this.light.target.updateMatrixWorld(!0)}static getPropertySchema(){let e=super.getPropertySchema(),t={nodeType:"DirectionalLight",properties:[x("color","color",{ui:{label:"Color",group:"Light"},getValue:r=>"#"+r.light.color.getHexString(),setValue:(r,i)=>{r.light.color.set(String(i))}}),x("intensity","number",{ui:{label:"Intensity",group:"Light",step:.1,precision:2},getValue:r=>r.light.intensity,setValue:(r,i)=>{r.light.intensity=Number(i)}}),x("castShadow","boolean",{ui:{label:"Cast Shadow",group:"Light"},getValue:r=>r.light.castShadow,setValue:(r,i)=>{r.light.castShadow=!!i}}),x("shadowCameraSize","number",{ui:{label:"Shadow Area",group:"Shadow",step:1,precision:0,description:"Half-size of the shadow frustum (\xB1units from center)"},getValue:r=>r.light.shadow.camera.right,setValue:(r,i)=>{let o=r,s=Math.max(.1,Number(i));o.light.shadow.camera.left=-s,o.light.shadow.camera.right=s,o.light.shadow.camera.top=s,o.light.shadow.camera.bottom=-s,o.light.shadow.camera.updateProjectionMatrix()}}),x("shadowMapSize","number",{ui:{label:"Shadow Map Res",group:"Shadow",step:256,precision:0,description:"Shadow map resolution (pixels)"},getValue:r=>r.light.shadow.mapSize.width,setValue:(r,i)=>{let o=r,s=Math.max(64,Number(i));o.light.shadow.mapSize.set(s,s)}})],groups:{Light:{label:"Light",expanded:!0},Shadow:{label:"Shadow",expanded:!1}}};return ce(e,t)}};var Lt=class extends U{light;constructor(e){super(e,"PointLight");let t=new L(e.color??"#ffffff"),r=typeof e.intensity=="number"?e.intensity:1,i=typeof e.distance=="number"?e.distance:0,o=typeof e.decay=="number"?e.decay:2;this.light=new Qo(t,r,i,o),this.light.castShadow=e.castShadow??!0,this.add(this.light)}static getPropertySchema(){let e=super.getPropertySchema(),t={nodeType:"PointLight",properties:[x("color","color",{ui:{label:"Color",group:"Light"},getValue:r=>"#"+r.light.color.getHexString(),setValue:(r,i)=>{r.light.color.set(String(i))}}),x("intensity","number",{ui:{label:"Intensity",group:"Light",step:.1,precision:2},getValue:r=>r.light.intensity,setValue:(r,i)=>{r.light.intensity=Number(i)}}),x("distance","number",{ui:{label:"Range",group:"Light",step:.1,precision:2},getValue:r=>r.light.distance,setValue:(r,i)=>{r.light.distance=Number(i)}}),x("decay","number",{ui:{label:"Decay",group:"Light",step:.1,precision:2},getValue:r=>r.light.decay,setValue:(r,i)=>{r.light.decay=Number(i)}}),x("castShadow","boolean",{ui:{label:"Cast Shadow",group:"Light"},getValue:r=>r.light.castShadow,setValue:(r,i)=>{r.light.castShadow=!!i}})],groups:{Light:{label:"Light",expanded:!0}}};return ce(e,t)}};var df=5,Ft=class extends U{light;constructor(e){super(e,"SpotLight");let t=new L(e.color??"#ffffff"),r=typeof e.intensity=="number"?e.intensity:1,i=typeof e.distance=="number"?e.distance:0,o=typeof e.angle=="number"?e.angle:Math.PI/3,s=typeof e.penumbra=="number"?e.penumbra:0,a=typeof e.decay=="number"?e.decay:2;this.light=new Xo(t,r,i,o,s,a),this.light.castShadow=e.castShadow??!0,this.light.position.set(0,0,0),this.add(this.light),this.add(this.light.target),this.light.target.position.set(0,0,-df),this.light.target.updateMatrixWorld(!0)}getTargetPosition(){return this.light.target.updateMatrixWorld(!0),this.light.target.getWorldPosition(new S)}setTargetPosition(e){let t=this.getWorldPosition(new S),r=e.clone().sub(t),i=r.lengthSq()>1e-8?r.normalize():new S(0,0,1).applyQuaternion(this.getWorldQuaternion(new _)),o=t.add(i.multiplyScalar(df));this.lookAt(o);let s=o.clone();this.worldToLocal(s),this.light.target.position.copy(s),this.light.target.updateMatrixWorld(!0)}static getPropertySchema(){let e=super.getPropertySchema(),t={nodeType:"SpotLight",properties:[x("color","color",{ui:{label:"Color",group:"Light"},getValue:r=>"#"+r.light.color.getHexString(),setValue:(r,i)=>{r.light.color.set(String(i))}}),x("intensity","number",{ui:{label:"Intensity",group:"Light",step:.1,precision:2},getValue:r=>r.light.intensity,setValue:(r,i)=>{r.light.intensity=Number(i)}}),x("distance","number",{ui:{label:"Range",group:"Light",step:.1,precision:2},getValue:r=>r.light.distance,setValue:(r,i)=>{r.light.distance=Number(i)}}),x("angle","number",{ui:{label:"Angle",group:"Light",unit:"\xB0",step:.1,precision:1},getValue:r=>r.light.angle*180/Math.PI,setValue:(r,i)=>{r.light.angle=Number(i)*Math.PI/180}}),x("penumbra","number",{ui:{label:"Penumbra",group:"Light",step:.01,precision:2},getValue:r=>r.light.penumbra,setValue:(r,i)=>{r.light.penumbra=Number(i)}}),x("decay","number",{ui:{label:"Decay",group:"Light",step:.1,precision:2},getValue:r=>r.light.decay,setValue:(r,i)=>{r.light.decay=Number(i)}}),x("castShadow","boolean",{ui:{label:"Cast Shadow",group:"Light"},getValue:r=>r.light.castShadow,setValue:(r,i)=>{r.light.castShadow=!!i}})],groups:{Light:{label:"Light",expanded:!0}}};return ce(e,t)}};var _t=class extends U{light;constructor(e){super(e,"AmbientLight");let t=new L(e.color??"#ffffff"),r=typeof e.intensity=="number"?e.intensity:.5;this.light=new ym(t,r),this.add(this.light)}static getPropertySchema(){let e=super.getPropertySchema(),t={nodeType:"AmbientLight",properties:[x("color","color",{ui:{label:"Color",group:"Light"},getValue:r=>"#"+r.light.color.getHexString(),setValue:(r,i)=>{r.light.color.set(String(i))}}),x("intensity","number",{ui:{label:"Intensity",group:"Light",step:.1,precision:2},getValue:r=>r.light.intensity,setValue:(r,i)=>{r.light.intensity=Number(i)}})],groups:{Light:{label:"Light",expanded:!0}}};return ce(e,t)}};var iu=["Group","Node2D","Node3D","ColorRect2D","Sprite2D","TiledSprite2D","AnimatedSprite2D","SpineSkeleton2D","Label2D","Layout2D","Group2D","CanvasLayer2D","Camera2D","Button2D","Slider2D","Bar2D","Checkbox2D","Joystick2D","ScrollContainer2D","InventorySlot2D","GeometryMesh","MeshInstance","InstancedMesh3D","Sprite3D","AnimatedSprite3D","Particles3D","AmbientLightNode","DirectionalLightNode","HemisphereLightNode","PointLightNode","SpotLightNode","Camera3D","VirtualCamera3D","PostProcess","AudioPlayer"],an=n=>n.toLowerCase().replace(/[^a-z0-9]/g,""),pf={ambientlight:"AmbientLightNode",ambientlight3d:"AmbientLightNode",directionallight:"DirectionalLightNode",directionallight3d:"DirectionalLightNode",hemispherelight:"HemisphereLightNode",hemispherelight3d:"HemisphereLightNode",pointlight:"PointLightNode",pointlight3d:"PointLightNode",spotlight:"SpotLightNode",spotlight3d:"SpotLightNode",meshinstance3d:"MeshInstance"},Nx=new Map(iu.map(n=>[an(n),n])),As=n=>{if(typeof n!="string"||n.trim().length===0)return null;let e=an(n);return Nx.get(e)??pf[e]??null},nu=n=>As(n)!==null,hf=[...iu.map(n=>[an(n),n]),...Object.entries(pf)],mf=n=>{let e=an(n);if(e.length===0)return;let t,r=Number.POSITIVE_INFINITY;for(let[s,a]of hf){let l=Ex(e,s);l<r&&(r=l,t=a)}if(r<=2)return t;let i,o=0;for(let[s,a]of hf)s.length<5||s.length<=o||(e.includes(s)||s.includes(e))&&(i=a,o=s.length);return i},ou=(n,e)=>{let t=mf(e),r=t?` Did you mean "${t}"?`:"";return`Unknown node type "${e}" on node "${n}" \u2014 it was loaded as an inert placeholder and does nothing.${r}`},Ex=(n,e)=>{if(n===e)return 0;if(n.length===0)return e.length;if(e.length===0)return n.length;let t=Array.from({length:e.length+1},(r,i)=>i);for(let r=1;r<=n.length;r++){let i=[r];for(let o=1;o<=e.length;o++){let s=t[o-1]+(n[r-1]===e[o-1]?0:1);i[o]=Math.min(i[o-1]+1,t[o]+1,s)}t=i}return t[e.length]};var zt=class extends U{light;constructor(e){super(e,"HemisphereLight");let t=new L(e.skyColor??"#ffffff"),r=new L(e.groundColor??"#444444"),i=typeof e.intensity=="number"?e.intensity:.5;this.light=new gm(t,r,i),this.add(this.light)}static getPropertySchema(){let e=super.getPropertySchema(),t={nodeType:"HemisphereLight",properties:[x("skyColor","color",{ui:{label:"Sky Color",group:"Light"},getValue:r=>"#"+r.light.color.getHexString(),setValue:(r,i)=>{r.light.color.set(String(i))}}),x("groundColor","color",{ui:{label:"Ground Color",group:"Light"},getValue:r=>"#"+r.light.groundColor.getHexString(),setValue:(r,i)=>{r.light.groundColor.set(String(i))}}),x("intensity","number",{ui:{label:"Intensity",group:"Light",step:.1,precision:2},getValue:r=>r.light.intensity,setValue:(r,i)=>{r.light.intensity=Number(i)}})],groups:{Light:{label:"Light",expanded:!0}}};return ce(e,t)}};var ht=class n extends U{texture;width;height;color;billboard;billboardRoll;textureAspectRatio;aspectRatioLocked;originalWidth;originalHeight;mesh;geometry;material;billboardPivot;static tempWorldQuaternion=new _;static tempLocalQuaternion=new _;constructor(e){super(e,"Sprite3D"),this.texture=D(e.texture??e.texturePath??null),this.width=typeof e.width=="number"&&e.width>0?e.width:1,this.height=typeof e.height=="number"&&e.height>0?e.height:1,this.color=e.color??"#ffffff",this.billboard=e.billboard??!1,this.billboardRoll=e.billboardRoll??0,this.textureAspectRatio=e.textureAspectRatio??null,this.aspectRatioLocked=e.aspectRatioLocked??!1,this.originalWidth=null,this.originalHeight=null,this.geometry=new z(this.width,this.height),this.material=new R({color:this.color,transparent:!0,side:xe,depthWrite:!1}),this.mesh=new B(this.geometry,this.material),this.mesh.name=`${this.name}-Mesh`,this.billboardPivot=this.mesh,this.add(this.billboardPivot),this.registerOpacityMaterial(this.material),G(this,n.getPropertySchema)}get texturePath(){return this.texture?.url??null}set texturePath(e){this.texture=D(e)}setTextureResource(e){this.texture=D(e)}setTexture(e){if(e.colorSpace=Pe,this.material.map=e,this.material.color.set("#ffffff"),this.material.transparent=!0,this.material.needsUpdate=!0,e.image){let t=e.image,{width:r,height:i}=$e(t);r&&i&&(this.textureAspectRatio=r/i,this.originalWidth=r,this.originalHeight=i)}}clearTexture(){this.material.map=null,this.material.needsUpdate=!0}setSize(e,t){let r=Number.isFinite(e)&&e>0?e:this.width,i=Number.isFinite(t)&&t>0?t:this.height;r===this.width&&i===this.height||(this.width=r,this.height=i,this.geometry.dispose(),this.geometry=new z(this.width,this.height),this.mesh.geometry=this.geometry)}resetToOriginalSize(){!this.originalWidth||!this.originalHeight||this.setSize(this.originalWidth,this.originalHeight)}applyBillboard(e){if(!this.billboard){this.billboardPivot.quaternion.identity();return}this.getWorldQuaternion(n.tempWorldQuaternion),n.tempLocalQuaternion.copy(n.tempWorldQuaternion).invert().multiply(e),this.billboardPivot.quaternion.copy(n.tempLocalQuaternion),this.billboardPivot.rotateZ(E.degToRad(this.billboardRoll))}static getPropertySchema(){let e=U.getPropertySchema();return{nodeType:"Sprite3D",extends:"Node3D",properties:[...e.properties,{name:"texture",type:"object",ui:{label:"Texture",description:"Path to the sprite texture",group:"Sprite",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.texture??{type:"texture",url:""},setValue:(t,r)=>{t.setTextureResource(r)}},{name:"width",type:"number",ui:{label:"Width",description:"Sprite width in world units",group:"Sprite",editor:"sprite-size",step:.01,precision:2,min:.01},getValue:t=>t.width,setValue:(t,r)=>{let i=t;i.setSize(Number(r),i.height)}},{name:"height",type:"number",ui:{label:"Height",description:"Sprite height in world units",group:"Sprite",editor:"sprite-size",step:.01,precision:2,min:.01},getValue:t=>t.height,setValue:(t,r)=>{let i=t;i.setSize(i.width,Number(r))}},{name:"billboard",type:"boolean",ui:{label:"Billboard",description:"Face the active camera while keeping world placement",group:"Sprite"},getValue:t=>t.billboard,setValue:(t,r)=>{t.billboard=!!r}},{name:"billboardRoll",type:"number",ui:{label:"Billboard Roll",description:"Additional roll angle when billboard is enabled",group:"Sprite",step:.1,precision:1,unit:"\xB0"},getValue:t=>t.billboardRoll,setValue:(t,r)=>{t.billboardRoll=Number(r)}},{name:"opacity",type:"number",ui:{label:"Opacity",description:"Sprite opacity (use show()/hide() to fade at runtime)",group:"Sprite",step:.01,precision:2,min:0,max:1},getValue:t=>t.opacity,setValue:(t,r)=>{t.opacity=Number(r)}},{name:"textureAspectRatio",type:"number",ui:{hidden:!0},getValue:t=>t.textureAspectRatio??null,setValue:(t,r)=>{t.textureAspectRatio=r===null?null:Number(r)}},{name:"aspectRatioLocked",type:"boolean",ui:{hidden:!0},getValue:t=>t.aspectRatioLocked,setValue:(t,r)=>{t.aspectRatioLocked=!!r}}],groups:{...e.groups,Sprite:{label:"Sprite",description:"3D sprite rendering properties",expanded:!0}}}}};var yr=class n extends U{frames;width;height;color;fps;playing;loop;freeOnFinish;billboard;_currentFrame=0;frameSequencePlayer=new ai;mesh;geometry;material;loadedTextures=[];billboardPivot;static tempWorldQuaternion=new _;static tempLocalQuaternion=new _;constructor(e){super(e,"AnimatedSprite3D"),this.frames=(e.frames||[]).map(D),this.width=e.width??1,this.height=e.height??1,this.color=e.color??"#ffffff",this.fps=e.fps??10,this.playing=e.playing??!0,this.loop=e.loop??!0,this.freeOnFinish=e.freeOnFinish??!1,this.billboard=e.billboard??!0,this.geometry=new z(this.width,this.height),this.material=new R({color:this.color,transparent:!0,side:xe,depthWrite:!1}),this.mesh=new B(this.geometry,this.material),this.mesh.name=`${this.name}-Mesh`,this.billboardPivot=this.mesh,this.add(this.billboardPivot),this.registerOpacityMaterial(this.material),G(this,n.getPropertySchema)}get currentFrame(){return this._currentFrame}set currentFrame(e){if(this.frames.length===0){this._currentFrame=0;return}this._currentFrame=Math.max(0,Math.min(e,this.frames.length-1)),this.updateTexture()}setTextureForFrame(e,t){this.loadedTextures[e]=t,e===this._currentFrame&&this.updateTexture()}updateTexture(){let e=this.loadedTextures[this._currentFrame];if(e){let t=e;"colorSpace"in e?t.colorSpace="srgb":"encoding"in e&&(t.encoding=3001),this.material.map=e,this.material.color.set("#ffffff")}else this.material.map=null,this.material.color.set(this.color);this.material.needsUpdate=!0}applyBillboard(e){if(!this.billboard){this.billboardPivot.quaternion.identity();return}this.getWorldQuaternion(n.tempWorldQuaternion),n.tempLocalQuaternion.copy(n.tempWorldQuaternion).invert().multiply(e),this.billboardPivot.quaternion.copy(n.tempLocalQuaternion)}tick(e){if(super.tick(e),!this.playing||this.frames.length<=1||this.fps<=0)return;let t=this.frameSequencePlayer.advance(e,{frameCount:this.frames.length,fps:this.fps,loop:this.loop,playbackMode:"linear"},this._currentFrame);t.framesAdvanced.length>0&&(this.currentFrame=t.nextIndex),t.finished&&(this.playing=!1,this.emit("animation-finished"),this.freeOnFinish&&this.queueFree())}static getPropertySchema(){let e=U.getPropertySchema();return{...e,nodeType:"AnimatedSprite3D",properties:[...e.properties,{name:"width",type:"number",ui:{label:"Width",group:"Size",min:0,step:.1},getValue:t=>t.width,setValue:(t,r)=>{let i=t;i.width=Number(r),i.updateGeometry()}},{name:"height",type:"number",ui:{label:"Height",group:"Size",min:0,step:.1},getValue:t=>t.height,setValue:(t,r)=>{let i=t;i.height=Number(r),i.updateGeometry()}},{name:"color",type:"color",ui:{label:"Color",group:"Style"},getValue:t=>t.color,setValue:(t,r)=>{let i=t;i.color=String(r),i.updateTexture()}},{name:"fps",type:"number",ui:{label:"FPS",group:"Animation",min:1,step:1},getValue:t=>t.fps,setValue:(t,r)=>{t.fps=Number(r)}},{name:"playing",type:"boolean",ui:{label:"Playing",group:"Animation"},getValue:t=>t.playing,setValue:(t,r)=>{t.playing=!!r}},{name:"loop",type:"boolean",ui:{label:"Loop",group:"Animation"},getValue:t=>t.loop,setValue:(t,r)=>{t.loop=!!r}},{name:"freeOnFinish",type:"boolean",ui:{label:"Free on Finish",description:"Destroy this node when a non-looping sequence finishes (one-shot VFX)",group:"Animation"},getValue:t=>t.freeOnFinish,setValue:(t,r)=>{t.freeOnFinish=!!r}},{name:"currentFrame",type:"number",ui:{label:"Current Frame",group:"Animation",min:0,step:1},getValue:t=>t.currentFrame,setValue:(t,r)=>{t.currentFrame=Number(r)}},{name:"billboard",type:"boolean",ui:{label:"Billboard",group:"Style"},getValue:t=>t.billboard,setValue:(t,r)=>{t.billboard=!!r}},{name:"opacity",type:"number",ui:{label:"Opacity",description:"Sprite opacity (use show()/hide() to fade at runtime)",group:"Style",step:.01,precision:2,min:0,max:1},getValue:t=>t.opacity,setValue:(t,r)=>{t.opacity=Number(r)}}],groups:{...e.groups,Size:{label:"Size",expanded:!0},Style:{label:"Style",expanded:!0},Animation:{label:"Animation",expanded:!0}}}}updateGeometry(){this.geometry.dispose(),this.geometry=new z(this.width,this.height),this.mesh.geometry=this.geometry}disposeResources(){this.geometry.dispose(),this.material.dispose()}};var ff=new S(0,1,0),Ts=new S(0,0,1),su=new S(0,0,0),gf=2,yf=64,pt=class n extends U{texture;emitterShape;emitterRadius;emitterBoxSize;particleShape;emissionRate;maxParticles;lifetime;speed;speedSpread;gravity;particleSize;sizeRandomness;startColor;endColor;startAlpha;endAlpha;billboard;playing;loop;prewarm;preview;disableRotation;simulationSpace;trailEnabled;trailLifetime;trailWidth;trailSegments;trailFade;subEmitterId;subEmitterBurstCount;subEmitterInheritVelocity;particles=[];emissionAccumulator=0;activeCount=0;isPrewarming=!1;renderRoot;instancedMesh=null;material;instanceColorAttr;instanceAlphaAttr;trailMesh=null;trailMaterial=null;trailData=null;trailPositions=null;trailColors=null;trailIndices=null;subEmitterCacheId="";subEmitterCache=null;deathScratch=[];startColorVec=new L;endColorVec=new L;tempColor=new L;tempMatrix=new ae;tempMatInv=new ae;tempScale=new S(1,1,1);tempQuat=new _;tempQuatWorld=new _;tempQuatNode=new _;tempQuatRot=new _;tempVelocity=new S;tempDirection=new S;tempDeathPos=new S;tempDeathVel=new S;tempBurstPos=new S;tempBurstVel=new S;tempCamSim=new S;tempTrailP=new S;tempTrailPrev=new S;tempTrailNext=new S;tempTrailDir=new S;tempTrailView=new S;tempTrailSide=new S;constructor(e){super(e,"Particles3D"),this.texture=D(e.texture??e.texturePath??null),this.emitterShape=e.emitterShape??"point",this.emitterRadius=Math.max(0,e.emitterRadius??.5),this.emitterBoxSize=e.emitterBoxSize??{x:1,y:1,z:1},this.particleShape=e.particleShape??"plane",this.emissionRate=Math.max(0,e.emissionRate??24),this.maxParticles=Math.max(1,Math.floor(e.maxParticles??512)),this.lifetime=Math.max(.01,e.lifetime??2),this.speed=Math.max(0,e.speed??2),this.speedSpread=Math.max(0,e.speedSpread??.5),this.gravity=e.gravity??{x:0,y:0,z:0},this.particleSize=Math.max(.001,e.particleSize??.2),this.sizeRandomness=E.clamp(e.sizeRandomness??.2,0,1),this.startColor=e.startColor??"#ffffff",this.endColor=e.endColor??"#ffd24d",this.startAlpha=E.clamp(e.startAlpha??1,0,1),this.endAlpha=E.clamp(e.endAlpha??0,0,1),this.billboard=e.billboard??!0,this.playing=e.playing??!0,this.loop=e.loop??!0,this.prewarm=e.prewarm??!1,this.preview=e.preview??!1,this.disableRotation=e.disableRotation??!1,this.simulationSpace=e.simulationSpace??"local",this.trailEnabled=e.trailEnabled??!1,this.trailLifetime=Math.max(.05,e.trailLifetime??.3),this.trailWidth=E.clamp(e.trailWidth??.05,.001,2),this.trailSegments=E.clamp(Math.floor(e.trailSegments??16),gf,yf),this.trailFade=E.clamp(e.trailFade??1,0,1),this.subEmitterId=e.subEmitterId??"",this.subEmitterBurstCount=E.clamp(Math.floor(e.subEmitterBurstCount??8),0,128),this.subEmitterInheritVelocity=E.clamp(e.subEmitterInheritVelocity??0,0,1),this.material=new R({color:"#ffffff",transparent:!0,depthWrite:!1,blending:at,vertexColors:!1,side:xe}),this.configureMaterialForInstanceAlpha(),this.renderRoot=new B,this.renderRoot.name=`${this.name}-Particles`,this.add(this.renderRoot),this.instanceColorAttr=new qe(new Float32Array(this.maxParticles*3),3),this.instanceColorAttr.setUsage(se),this.instanceAlphaAttr=new qe(new Float32Array(this.maxParticles),1),this.instanceAlphaAttr.setUsage(se),this.initializeParticles(),this.rebuildRenderer(),this.simulationSpace==="world"&&(this.renderRoot.matrixAutoUpdate=!1),this.trailEnabled&&(this.allocateTrailBuffers(),this.buildTrailMesh()),this.prewarm&&this.playing&&this.prewarmSimulation(),G(this,n.getPropertySchema)}get texturePath(){return this.texture?.url??null}set texturePath(e){this.texture=D(e)}setTextureResource(e){this.texture=D(e)}setTexture(e){this.material.map=e,this.material.needsUpdate=!0}clearTexture(){this.material.map=null,this.material.needsUpdate=!0}setMaxParticles(e){let t=Math.max(1,Math.floor(e));t!==this.maxParticles&&(this.maxParticles=t,this.instanceColorAttr=new qe(new Float32Array(this.maxParticles*3),3),this.instanceColorAttr.setUsage(se),this.instanceAlphaAttr=new qe(new Float32Array(this.maxParticles),1),this.instanceAlphaAttr.setUsage(se),this.initializeParticles(),this.rebuildRenderer(),this.trailEnabled&&(this.allocateTrailBuffers(),this.buildTrailMesh()))}setParticleShape(e){e!==this.particleShape&&(this.particleShape=e,this.rebuildRenderer())}restart(){for(let e of this.particles)e.active=!1,e.age=0,e.trailHead=0,e.trailLen=0,e.trailTimer=0;this.activeCount=0,this.emissionAccumulator=0,this.deathScratch.length=0,this.instancedMesh&&(this.instancedMesh.count=0,this.instancedMesh.instanceMatrix.needsUpdate=!0),this.collapseAllTrails()}syncRenderState(e,t){this.simulationSpace==="world"&&this.syncWorldCompensation(),this.applyBillboardInternal(e),this.updateTrailGeometry(t)}applyBillboard(e){this.syncRenderState(e,su)}applyBillboardInternal(e){if(!this.billboard||this.particleShape!=="plane"||!this.instancedMesh)return;this.simulationSpace==="world"?this.tempQuatNode.copy(e):(this.getWorldQuaternion(this.tempQuatWorld),this.tempQuatNode.copy(this.tempQuatWorld).invert().multiply(e));let t=0;for(let r=0;r<this.particles.length;r+=1){let i=this.particles[r];i.active&&(this.tempQuat.copy(this.tempQuatNode),this.tempQuatRot.setFromAxisAngle(Ts,i.rotation),this.tempQuat.multiply(this.tempQuatRot),this.tempScale.set(i.size,i.size,i.size),this.tempMatrix.compose(i.position,this.tempQuat,this.tempScale),this.instancedMesh.setMatrixAt(t,this.tempMatrix),t+=1)}this.instancedMesh.instanceMatrix.needsUpdate=!0}tick(e){if(super.tick(e),!this.playing&&!this.preview||e<=0)return;this.simulationSpace==="world"&&this.syncWorldCompensation();let t=Math.min(e,1/20);this.spawnParticles(t),this.updateParticles(t)}initializeParticles(){this.particles=[];for(let e=0;e<this.maxParticles;e+=1)this.particles.push({active:!1,age:0,lifetime:this.lifetime,position:new S,velocity:new S,size:this.particleSize,rotation:0,angularVelocity:0,trailHead:0,trailLen:0,trailTimer:0})}prewarmSimulation(){let e=.016666666666666666,t=Math.min(this.lifetime,3),r=Math.floor(t/e);this.isPrewarming=!0;try{for(let i=0;i<r;i+=1)this.spawnParticles(e),this.updateParticles(e)}finally{this.isPrewarming=!1}}spawnParticles(e){if(!this.loop&&this.activeCount>=this.maxParticles)return;this.emissionAccumulator+=this.emissionRate*e;let t=Math.floor(this.emissionAccumulator);if(!(t<=0)){this.emissionAccumulator-=t;for(let r=0;r<this.particles.length&&t>0;r+=1){let i=this.particles[r];i.active||(this.activateParticle(i,r),t-=1)}}}activateParticle(e,t=-1,r,i){e.active=!0,e.age=0,e.lifetime=this.lifetime*E.lerp(.85,1.15,Math.random()),e.rotation=this.disableRotation?0:Math.random()*Math.PI*2,e.angularVelocity=this.disableRotation?0:E.lerp(-3,3,Math.random()),this.assignSpawnPosition(e.position),this.tempDirection.set(E.randFloatSpread(2),Math.random()*1.5,E.randFloatSpread(2)),this.tempDirection.lengthSq()<1e-5&&this.tempDirection.copy(ff),this.tempDirection.normalize();let o=E.randFloatSpread(this.speedSpread*2),s=Math.max(0,this.speed+o);e.velocity.copy(this.tempDirection.multiplyScalar(s)),r?e.position.add(r):this.simulationSpace==="world"&&(e.position.applyMatrix4(this.matrixWorld),e.velocity.applyQuaternion(this.getWorldQuaternion(this.tempQuatWorld))),i&&e.velocity.addScaledVector(i,1);let a=1-this.sizeRandomness+Math.random()*this.sizeRandomness;e.size=Math.max(.001,this.particleSize*a),e.trailHead=0,e.trailLen=0,e.trailTimer=0,this.trailEnabled&&this.trailData&&t>=0&&(this.writeTrailSample(t,e),e.trailLen=1)}assignSpawnPosition(e){if(this.emitterShape==="sphere"){this.tempDirection.set(E.randFloatSpread(2),E.randFloatSpread(2),E.randFloatSpread(2)),this.tempDirection.lengthSq()<1e-5&&this.tempDirection.copy(ff),this.tempDirection.normalize().multiplyScalar(Math.random()*this.emitterRadius),e.copy(this.tempDirection);return}if(this.emitterShape==="box"){e.set(E.randFloatSpread(this.emitterBoxSize.x),E.randFloatSpread(this.emitterBoxSize.y),E.randFloatSpread(this.emitterBoxSize.z));return}e.set(0,0,0)}updateParticles(e){if(!this.instancedMesh)return;this.startColorVec.set(this.startColor),this.endColorVec.set(this.endColor);let t=0;for(let r=0;r<this.particles.length;r+=1){let i=this.particles[r];if(!i.active)continue;if(i.age+=e,i.age>=i.lifetime){i.active=!1,this.subEmitterId!==""&&this.recordDeath(i);continue}this.tempVelocity.set(this.gravity.x,this.gravity.y,this.gravity.z).multiplyScalar(e),i.velocity.add(this.tempVelocity),i.position.addScaledVector(i.velocity,e),i.rotation+=i.angularVelocity*e,this.trailEnabled&&this.trailData&&this.advanceTrailSampling(r,i,e);let o=E.clamp(i.age/i.lifetime,0,1),s=E.lerp(this.startAlpha,this.endAlpha,o);this.tempColor.copy(this.startColorVec).lerp(this.endColorVec,o),this.tempQuat.identity(),(!this.billboard||this.particleShape!=="plane")&&this.tempQuat.setFromAxisAngle(Ts,i.rotation),this.tempScale.set(i.size,i.size,i.size),this.tempMatrix.compose(i.position,this.tempQuat,this.tempScale),this.instancedMesh.setMatrixAt(t,this.tempMatrix),this.instanceColorAttr.setXYZ(t,this.tempColor.r,this.tempColor.g,this.tempColor.b),this.instanceAlphaAttr.setX(t,s),t+=1}this.activeCount=t,this.instancedMesh.count=t,this.instancedMesh.instanceMatrix.needsUpdate=!0,this.instanceColorAttr.needsUpdate=!0,this.instanceAlphaAttr.needsUpdate=!0,this.flushSubEmission()}buildRenderGeometry(){return this.particleShape==="cube"?new Jr(1,1,1):this.particleShape==="sphere"?new Yo(.5,8,8):new z(1,1)}rebuildRenderer(){this.instancedMesh&&(this.renderRoot.remove(this.instancedMesh),this.instancedMesh.geometry.dispose());let e=this.buildRenderGeometry();this.instancedMesh=new Xr(e,this.material,this.maxParticles),this.instancedMesh.instanceMatrix.setUsage(se),this.instancedMesh.frustumCulled=!1,this.instancedMesh.count=0,this.instancedMesh.instanceColor=this.instanceColorAttr,this.instancedMesh.geometry.setAttribute("instanceAlpha",this.instanceAlphaAttr),this.renderRoot.add(this.instancedMesh)}configureMaterialForInstanceAlpha(){this.material.onBeforeCompile=e=>{e.vertexShader=e.vertexShader.replace("#include <color_pars_vertex>",`#include <color_pars_vertex>
|
|
191
|
-
attribute float instanceAlpha;
|
|
192
|
-
varying float vInstanceAlpha;`).replace("#include <color_vertex>",`#include <color_vertex>
|
|
193
|
-
vInstanceAlpha = instanceAlpha;`),e.fragmentShader=e.fragmentShader.replace("#include <color_pars_fragment>",`#include <color_pars_fragment>
|
|
194
|
-
varying float vInstanceAlpha;`).replace("vec4 diffuseColor = vec4( diffuse, opacity );","vec4 diffuseColor = vec4( diffuse, opacity * vInstanceAlpha );")},this.material.customProgramCacheKey=()=>"pix3-particles3d-instance-alpha-v1",this.material.needsUpdate=!0}syncWorldCompensation(){if(this.simulationSpace!=="world")return;this.updateWorldMatrix(!0,!1);let e=this.matrixWorld.determinant();Math.abs(e)<1e-8||(this.tempMatInv.copy(this.matrixWorld).invert(),this.renderRoot.matrix.copy(this.tempMatInv),this.renderRoot.matrixWorldNeedsUpdate=!0)}setSimulationSpace(e){e!==this.simulationSpace&&(this.simulationSpace=e,this.restart(),e==="world"?(this.renderRoot.matrixAutoUpdate=!1,this.syncWorldCompensation()):(this.renderRoot.matrix.identity(),this.renderRoot.matrixAutoUpdate=!0,this.renderRoot.matrixWorldNeedsUpdate=!0))}recordDeath(e){this.tempDeathPos.copy(e.position),this.tempDeathVel.copy(e.velocity),this.simulationSpace==="local"&&(this.tempDeathPos.applyMatrix4(this.matrixWorld),this.tempDeathVel.applyQuaternion(this.getWorldQuaternion(this.tempQuatWorld))),this.deathScratch.push(this.tempDeathPos.x,this.tempDeathPos.y,this.tempDeathPos.z,this.tempDeathVel.x,this.tempDeathVel.y,this.tempDeathVel.z)}flushSubEmission(){if(this.deathScratch.length===0)return;if(this.isPrewarming){this.deathScratch.length=0;return}let e=this.resolveSubEmitter();if(!e){this.deathScratch.length=0;return}let t=this.subEmitterInheritVelocity;for(let r=0;r+5<this.deathScratch.length;r+=6)this.tempDeathPos.set(this.deathScratch[r],this.deathScratch[r+1],this.deathScratch[r+2]),this.tempDeathVel.set(this.deathScratch[r+3],this.deathScratch[r+4],this.deathScratch[r+5]).multiplyScalar(t),e.emitBurstAt(this.tempDeathPos,this.subEmitterBurstCount,this.tempDeathVel);this.deathScratch.length=0}resolveSubEmitter(){let e=this.subEmitterId;if(!e)return this.subEmitterCache=null,this.subEmitterCacheId="",null;if(this.subEmitterCache&&this.subEmitterCacheId===e)return this.subEmitterCache;let t=null;if(this.scene)t=this.scene.findNode(e);else{let r=this;for(;r.parentNode;)r=r.parentNode;t=r.findNode(e)}return this.subEmitterCache=t instanceof n?t:null,this.subEmitterCacheId=e,this.subEmitterCache}emitBurstAt(e,t,r){let i=Math.max(0,Math.floor(t));if(i<=0)return;let o=this.tempBurstPos.copy(e),s;r&&(s=this.tempBurstVel.copy(r)),this.simulationSpace==="local"&&(this.updateWorldMatrix(!0,!1),this.tempMatInv.copy(this.matrixWorld).invert(),o.applyMatrix4(this.tempMatInv),s&&s.applyQuaternion(this.getWorldQuaternion(this.tempQuatWorld).invert()));let a=i;for(let l=0;l<this.particles.length&&a>0;l+=1){let c=this.particles[l];c.active||(this.activateParticle(c,l,o,s),a-=1)}}setTrailEnabled(e){let t=!!e;t!==this.trailEnabled&&(this.trailEnabled=t,t?(this.allocateTrailBuffers(),this.buildTrailMesh(),this.resetTrailState()):(this.disposeTrailMesh(),this.trailData=null,this.trailPositions=null,this.trailColors=null,this.trailIndices=null))}setTrailSegments(e){let t=E.clamp(Math.floor(e),gf,yf);t!==this.trailSegments&&(this.trailSegments=t,this.trailEnabled&&(this.allocateTrailBuffers(),this.buildTrailMesh(),this.resetTrailState()))}resetTrailState(){for(let e of this.particles)e.trailHead=0,e.trailLen=0,e.trailTimer=0}allocateTrailBuffers(){let e=this.trailSegments,t=this.maxParticles;this.trailData=new Float32Array(t*e*3),this.trailPositions=new Float32Array(t*e*2*3),this.trailColors=new Float32Array(t*e*2*4);let r=new Uint32Array(t*(e-1)*6),i=0;for(let o=0;o<t;o+=1){let s=o*e*2;for(let a=0;a<e-1;a+=1){let l=s+a*2,c=l+1,u=s+(a+1)*2,d=u+1;r[i]=l,r[i+1]=c,r[i+2]=u,r[i+3]=c,r[i+4]=d,r[i+5]=u,i+=6}}this.trailIndices=r}buildTrailMesh(){if(this.disposeTrailMesh(),!this.trailPositions||!this.trailColors||!this.trailIndices)return;let e=new le,t=new lt(this.trailPositions,3);t.setUsage(se);let r=new lt(this.trailColors,4);r.setUsage(se),e.setAttribute("position",t),e.setAttribute("color",r),e.setIndex(new lt(this.trailIndices,1)),this.trailMaterial=new R({transparent:!0,depthWrite:!1,blending:at,side:xe,vertexColors:!0}),this.trailMesh=new B(e,this.trailMaterial),this.trailMesh.frustumCulled=!1,this.trailMesh.name=`${this.name}-Trails`,this.renderRoot.add(this.trailMesh)}disposeTrailMesh(){this.trailMesh&&(this.renderRoot.remove(this.trailMesh),this.trailMesh.geometry.dispose(),this.trailMesh=null),this.trailMaterial&&(this.trailMaterial.dispose(),this.trailMaterial=null)}writeTrailSample(e,t){if(!this.trailData)return;let r=(e*this.trailSegments+t.trailHead)*3;this.trailData[r]=t.position.x,this.trailData[r+1]=t.position.y,this.trailData[r+2]=t.position.z}advanceTrailSampling(e,t,r){let i=this.trailSegments,o=this.trailLifetime/(i-1);if(o<=0)return;t.trailTimer+=r;let s=i;for(;t.trailTimer>=o&&s>0;)t.trailTimer-=o,t.trailHead=(t.trailHead+1)%i,this.writeTrailSample(e,t),t.trailLen=Math.min(t.trailLen+1,i),s-=1}readTrailPoint(e,t,r,i){if(r<=0||!this.trailData){i.copy(t.position);return}let o=this.trailSegments,s=Math.min(r,t.trailLen),a=((t.trailHead-(s-1))%o+o)%o,l=(e*o+a)*3;i.set(this.trailData[l],this.trailData[l+1],this.trailData[l+2])}writeTrailVertex(e,t,r,i,o,s){let a=this.trailPositions,l=this.trailColors;if(!a||!l)return;let c=e*3;a[c]=t.x,a[c+1]=t.y,a[c+2]=t.z;let u=e*4;l[u]=r,l[u+1]=i,l[u+2]=o,l[u+3]=s}collapseAllTrails(){if(!this.trailMesh||!this.trailPositions||!this.trailColors)return;this.trailPositions.fill(0),this.trailColors.fill(0);let e=this.trailMesh.geometry;e.getAttribute("position").needsUpdate=!0,e.getAttribute("color").needsUpdate=!0}updateTrailGeometry(e){if(!this.trailEnabled||!this.trailMesh||!this.trailData)return;let t=this.trailSegments;this.tempCamSim.copy(e),this.simulationSpace==="local"&&(this.updateWorldMatrix(!0,!1),this.tempMatInv.copy(this.matrixWorld).invert(),this.tempCamSim.applyMatrix4(this.tempMatInv)),this.startColorVec.set(this.startColor),this.endColorVec.set(this.endColor);let r=this.trailWidth/2;for(let o=0;o<this.particles.length;o+=1){let s=this.particles[o],a=o*t*2;if(!s.active||s.trailLen<1){for(let d=0;d<t;d+=1){let h=a+d*2;this.writeTrailVertex(h,su,0,0,0,0),this.writeTrailVertex(h+1,su,0,0,0,0)}continue}let l=E.clamp(s.age/s.lifetime,0,1),c=E.lerp(this.startAlpha,this.endAlpha,l);this.tempColor.copy(this.startColorVec).lerp(this.endColorVec,l);let u=s.trailLen;for(let d=0;d<t;d+=1){let h=a+d*2,p=h+1;if(d>u){this.writeTrailVertex(h,s.position,0,0,0,0),this.writeTrailVertex(p,s.position,0,0,0,0);continue}this.readTrailPoint(o,s,d,this.tempTrailP),this.readTrailPoint(o,s,Math.max(d-1,0),this.tempTrailPrev),this.readTrailPoint(o,s,Math.min(d+1,u),this.tempTrailNext),this.tempTrailDir.copy(this.tempTrailPrev).sub(this.tempTrailNext),this.tempTrailDir.lengthSq()<1e-10&&this.tempTrailDir.copy(Ts),this.tempTrailDir.normalize(),this.tempTrailView.copy(this.tempCamSim).sub(this.tempTrailP),this.tempTrailView.lengthSq()<1e-10&&this.tempTrailView.copy(Ts),this.tempTrailView.normalize(),this.tempTrailSide.copy(this.tempTrailDir).cross(this.tempTrailView);let f=d/(t-1);if(this.tempTrailSide.lengthSq()<1e-12){this.writeTrailVertex(h,this.tempTrailP,0,0,0,0),this.writeTrailVertex(p,this.tempTrailP,0,0,0,0);continue}this.tempTrailSide.normalize().multiplyScalar(r*(1-f));let m=c*(1-this.trailFade*f);this.tempTrailPrev.copy(this.tempTrailP).add(this.tempTrailSide),this.writeTrailVertex(h,this.tempTrailPrev,this.tempColor.r,this.tempColor.g,this.tempColor.b,m),this.tempTrailNext.copy(this.tempTrailP).sub(this.tempTrailSide),this.writeTrailVertex(p,this.tempTrailNext,this.tempColor.r,this.tempColor.g,this.tempColor.b,m)}}let i=this.trailMesh.geometry;i.getAttribute("position").needsUpdate=!0,i.getAttribute("color").needsUpdate=!0}static getPropertySchema(){let e=U.getPropertySchema();return{nodeType:"Particles3D",extends:"Node3D",properties:[...e.properties,{name:"texture",type:"object",ui:{label:"Texture",group:"Rendering",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.texture??{type:"texture",url:""},setValue:(t,r)=>t.setTextureResource(r)},{name:"particleShape",type:"enum",ui:{label:"Particle Shape",group:"Rendering",options:["plane","sphere","cube"]},getValue:t=>t.particleShape,setValue:(t,r)=>{let i=String(r);(i==="plane"||i==="sphere"||i==="cube")&&t.setParticleShape(i)}},{name:"particleSize",type:"number",ui:{label:"Particle Size",group:"Rendering",min:.01,max:5,step:.01,precision:2,slider:!0},getValue:t=>t.particleSize,setValue:(t,r)=>{t.particleSize=Math.max(.01,Number(r))}},{name:"sizeRandomness",type:"number",ui:{label:"Size Randomness",group:"Rendering",min:0,max:1,step:.01,precision:2,slider:!0},getValue:t=>t.sizeRandomness,setValue:(t,r)=>{t.sizeRandomness=E.clamp(Number(r),0,1)}},{name:"startColor",type:"color",ui:{label:"Start Color",group:"Rendering"},getValue:t=>t.startColor,setValue:(t,r)=>{t.startColor=String(r)}},{name:"endColor",type:"color",ui:{label:"End Color",group:"Rendering"},getValue:t=>t.endColor,setValue:(t,r)=>{t.endColor=String(r)}},{name:"startAlpha",type:"number",ui:{label:"Start Alpha",group:"Rendering",min:0,max:1,step:.01,precision:2,slider:!0},getValue:t=>t.startAlpha,setValue:(t,r)=>{t.startAlpha=E.clamp(Number(r),0,1)}},{name:"endAlpha",type:"number",ui:{label:"End Alpha",group:"Rendering",min:0,max:1,step:.01,precision:2,slider:!0},getValue:t=>t.endAlpha,setValue:(t,r)=>{t.endAlpha=E.clamp(Number(r),0,1)}},{name:"billboard",type:"boolean",ui:{label:"Billboard",group:"Rendering"},getValue:t=>t.billboard,setValue:(t,r)=>{t.billboard=!!r}},{name:"emitterShape",type:"enum",ui:{label:"Emitter Shape",group:"Emitter",options:["point","sphere","box"]},getValue:t=>t.emitterShape,setValue:(t,r)=>{let i=String(r);(i==="point"||i==="sphere"||i==="box")&&(t.emitterShape=i)}},{name:"emitterRadius",type:"number",ui:{label:"Emitter Radius",group:"Emitter",min:0,max:10,step:.01,precision:2,slider:!0},getValue:t=>t.emitterRadius,setValue:(t,r)=>{t.emitterRadius=Math.max(0,Number(r))}},{name:"emitterBoxSize",type:"vector3",ui:{label:"Emitter Box Size",group:"Emitter",step:.01,precision:2},getValue:t=>({...t.emitterBoxSize}),setValue:(t,r)=>{let i=r;t.emitterBoxSize={x:Math.max(0,Number(i.x)),y:Math.max(0,Number(i.y)),z:Math.max(0,Number(i.z))}}},{name:"emissionRate",type:"number",ui:{label:"Emission Rate",group:"Emission",min:0,max:1e3,step:1,precision:0,slider:!0},getValue:t=>t.emissionRate,setValue:(t,r)=>{t.emissionRate=Math.max(0,Number(r))}},{name:"maxParticles",type:"number",ui:{label:"Max Particles",group:"Emission",min:1,max:1e4,step:1,precision:0,slider:!0},getValue:t=>t.maxParticles,setValue:(t,r)=>t.setMaxParticles(Number(r))},{name:"lifetime",type:"number",ui:{label:"Lifetime",group:"Emission",unit:"s",min:.01,max:30,step:.01,precision:2,slider:!0},getValue:t=>t.lifetime,setValue:(t,r)=>{t.lifetime=Math.max(.01,Number(r))}},{name:"speed",type:"number",ui:{label:"Speed",group:"Emission",min:0,max:100,step:.01,precision:2,slider:!0},getValue:t=>t.speed,setValue:(t,r)=>{t.speed=Math.max(0,Number(r))}},{name:"speedSpread",type:"number",ui:{label:"Speed Spread",group:"Emission",min:0,max:20,step:.01,precision:2,slider:!0},getValue:t=>t.speedSpread,setValue:(t,r)=>{t.speedSpread=Math.max(0,Number(r))}},{name:"gravity",type:"vector3",ui:{label:"Gravity",group:"Emission",step:.01,precision:2},getValue:t=>({...t.gravity}),setValue:(t,r)=>{let i=r;t.gravity={x:Number(i.x),y:Number(i.y),z:Number(i.z)}}},{name:"disableRotation",type:"boolean",ui:{label:"Disable Rotation",group:"Emission"},getValue:t=>t.disableRotation,setValue:(t,r)=>{t.disableRotation=!!r}},{name:"playing",type:"boolean",ui:{label:"Playing",group:"Runtime"},getValue:t=>t.playing,setValue:(t,r)=>{t.playing=!!r}},{name:"loop",type:"boolean",ui:{label:"Loop",group:"Runtime"},getValue:t=>t.loop,setValue:(t,r)=>{t.loop=!!r}},{name:"prewarm",type:"boolean",ui:{label:"Prewarm",group:"Runtime"},getValue:t=>t.prewarm,setValue:(t,r)=>{t.prewarm=!!r}},{name:"preview",type:"boolean",ui:{label:"Preview",group:"Runtime"},getValue:t=>t.preview,setValue:(t,r)=>{let i=t,o=!!r;i.preview&&!o&&i.restart(),i.preview=o}},{name:"simulationSpace",type:"enum",ui:{label:"Simulation Space",group:"Runtime",options:["local","world"]},getValue:t=>t.simulationSpace,setValue:(t,r)=>{let i=String(r);(i==="local"||i==="world")&&t.setSimulationSpace(i)}},{name:"trailEnabled",type:"boolean",ui:{label:"Enable Trails",group:"Trails",description:"Draw a camera-facing ribbon behind each particle. Best with Simulation Space = world."},getValue:t=>t.trailEnabled,setValue:(t,r)=>{t.setTrailEnabled(!!r)}},{name:"trailLifetime",type:"number",ui:{label:"Trail Lifetime",group:"Trails",unit:"s",min:.05,max:5,step:.01,precision:2,slider:!0},getValue:t=>t.trailLifetime,setValue:(t,r)=>{t.trailLifetime=Math.max(.05,Number(r))}},{name:"trailWidth",type:"number",ui:{label:"Trail Width",group:"Trails",min:.001,max:2,step:.001,precision:3,slider:!0},getValue:t=>t.trailWidth,setValue:(t,r)=>{t.trailWidth=E.clamp(Number(r),.001,2)}},{name:"trailSegments",type:"number",ui:{label:"Trail Segments",group:"Trails",description:"Ribbon resolution. Keep Max Particles moderate when trails are enabled.",min:2,max:64,step:1,precision:0,slider:!0},getValue:t=>t.trailSegments,setValue:(t,r)=>{t.setTrailSegments(Number(r))}},{name:"trailFade",type:"number",ui:{label:"Trail Fade",group:"Trails",min:0,max:1,step:.01,precision:2,slider:!0},getValue:t=>t.trailFade,setValue:(t,r)=>{t.trailFade=E.clamp(Number(r),0,1)}},{name:"subEmitterId",type:"node",ui:{label:"Sub Emitter",group:"Sub Emitter",description:"Particles3D fired as a burst at each particle death (author it with Emission Rate = 0).",nodeTypes:["Particles3D"]},getValue:t=>t.subEmitterId,setValue:(t,r)=>{t.subEmitterId=r==null?"":String(r)}},{name:"subEmitterBurstCount",type:"number",ui:{label:"Burst Count",group:"Sub Emitter",min:0,max:128,step:1,precision:0,slider:!0},getValue:t=>t.subEmitterBurstCount,setValue:(t,r)=>{t.subEmitterBurstCount=E.clamp(Math.floor(Number(r)),0,128)}},{name:"subEmitterInheritVelocity",type:"number",ui:{label:"Inherit Velocity",group:"Sub Emitter",min:0,max:1,step:.01,precision:2,slider:!0},getValue:t=>t.subEmitterInheritVelocity,setValue:(t,r)=>{t.subEmitterInheritVelocity=E.clamp(Number(r),0,1)}}],groups:{...e.groups,Rendering:{label:"Rendering",description:"Particle rendering settings",expanded:!0},Emitter:{label:"Emitter",description:"Emitter shape and spawn volume",expanded:!0},Emission:{label:"Emission",description:"Emission rates and movement",expanded:!0},Runtime:{label:"Runtime",description:"Simulation runtime controls",expanded:!0},Trails:{label:"Trails",description:"Per-particle ribbon trails",expanded:!1},"Sub Emitter":{label:"Sub Emitter",description:"Burst another emitter on particle death",expanded:!1}}}}};function Ix(n){if(typeof n!="object"||n===null)return!1;let e=n;return typeof e.getInteractions=="function"&&typeof e.invokeInteraction=="function"}function Qe(n,e,t=null){let r=n?.[e];if(r==null)return t;let i=ds("number",r);return typeof i=="number"&&Number.isFinite(i)?i:t}function au(n,e,t=null){let r=n?.[e];if(r==null)return t;let i=ds("boolean",r);return typeof i=="boolean"?i:t}function Rx(n,e,t=null){let r=n?.[e];if(typeof r!="string")return t;let i=r.trim();return i.length>0?i:t}var lu=-1,cu=-2,br=class n extends M{static BASE_OPACITY=.3;static HANDLE_OPACITY=.8;static FADE_SPEED=6;enabled;radius;handleRadius;axisHorizontal;axisVertical;baseColor;handleColor;floating;baseMesh;handleMesh;baseMaterial;handleMaterial;isDragging=!1;inputVector=new I;authoredLocalPosition=new S;dragCenterWorld=new I;visibilityAlpha=1;visibilityTarget=1;tmpWorldPos=new S;pendingResetAfterHide=!1;ownedPointerId=null;legacyPointerWasDown=!1;candidateWorld=new I;constructor(e){super(e,"Joystick2D");let t=this.properties.enabled;this.enabled=e.enabled??(typeof t=="boolean"?t:!0),this.radius=e.radius??50,this.handleRadius=e.handleRadius??20,this.axisHorizontal=e.axisHorizontal??"Horizontal",this.axisVertical=e.axisVertical??"Vertical",this.baseColor=e.baseColor??"#ffffff",this.handleColor=e.handleColor??"#cccccc",this.floating=e.floating??!1;let r=new Ll(this.radius,32);this.baseMaterial=new R({color:this.baseColor,transparent:!0,opacity:n.BASE_OPACITY,depthTest:!1}),this.registerOpacityMaterial(this.baseMaterial,n.BASE_OPACITY),this.baseMesh=new B(r,this.baseMaterial),this.baseMesh.renderOrder=999,this.add(this.baseMesh);let i=new Ll(this.handleRadius,32);this.handleMaterial=new R({color:this.handleColor,transparent:!0,opacity:n.HANDLE_OPACITY,depthTest:!1}),this.registerOpacityMaterial(this.handleMaterial,n.HANDLE_OPACITY),this.handleMesh=new B(i,this.handleMaterial),this.handleMesh.position.z=1,this.handleMesh.renderOrder=1e3,this.add(this.handleMesh),this.authoredLocalPosition.copy(this.position),this.floating&&(this.visibilityAlpha=0,this.visibilityTarget=0,this.applyVisibility()),G(this,n.getPropertySchema)}tick(e){super.tick(e),this.updateFromPointers(),this.floating&&this.updateVisibility(e)}updateFromPointers(){if(!this.enabled){this.abortDrag();return}let e=this.input,t=e&&e.width?this.collectCandidatePointers(e):[],r=t.length===1&&t[0].pointerId===cu?t[0]:null,i=r!==null&&r.down&&!this.legacyPointerWasDown;this.legacyPointerWasDown=r?.down??!1;let o=this.semanticPointer;if(o){let l=e?this.findClaimingPointer(e,t,i):null;if(!l){this.driveDragFrame({pointerId:lu,worldX:o.x,worldY:o.y,down:o.down},!1);return}this.semanticPointer=null,this.ownedPointerId=l.pointerId,this.driveDragFrame(l,!0);return}if(!e||t.length===0)return;let s=this.ownedPointerId;if(s!==null){let l=t.find(u=>u.pointerId===s);if(!l){this.finishOwnedPointer();return}let c=this.screenPointToWorld(l.x,l.y,this.candidateWorld);if(!c)return;this.driveDragFrame({pointerId:s,worldX:c.x,worldY:c.y,down:l.down},!1);return}let a=this.findClaimingPointer(e,t,i);a&&(this.ownedPointerId=a.pointerId,this.driveDragFrame(a,!0))}collectCandidatePointers(e){let t=e.getActivePointers();return t.length>0?t.map(r=>({pointerId:r.pointerId,x:r.x,y:r.y,down:!0})):[{pointerId:cu,x:e.pointerPosition.x,y:e.pointerPosition.y,down:e.isPointerDown}]}findClaimingPointer(e,t,r){for(let i of t){if(!i.down)continue;let o=i.pointerId===cu;if(this.floating&&(!(o?r:n.hasDownEventThisFrame(e,i.pointerId))||(o?e.isHoveringUI:e.isPointerOverUI(i.pointerId))))continue;let s=this.screenPointToWorld(i.x,i.y,this.candidateWorld);if(!s)return null;if(!(!this.floating&&!this.isWithinBase(s.x,s.y)))return{pointerId:i.pointerId,worldX:s.x,worldY:s.y,down:!0}}return null}static hasDownEventThisFrame(e,t){for(let r of e.pointerEvents)if(r.type==="down"&&r.pointerId===t)return!0;return!1}isWithinBase(e,t){this.getWorldPosition(this.tmpWorldPos);let r=e-this.tmpWorldPos.x,i=t-this.tmpWorldPos.y;return Math.sqrt(r*r+i*i)<this.radius}driveDragFrame(e,t){if(this.isDragging){e.down?this.continueDrag(e.worldX,e.worldY):this.releaseDrag();return}if(!(!t||!e.down)){if(this.floating){this.beginFloatingDrag(e.worldX,e.worldY),this.continueDrag(e.worldX,e.worldY);return}this.isDragging=!0}}beginFloatingDrag(e,t){this.isDragging=!0,this.pendingResetAfterHide=!1,this.handleMesh.position.set(0,0,this.handleMesh.position.z),this.setCenterFromWorld(e,t),this.visibilityTarget=1}continueDrag(e,t){if(this.floating){this.updateHandleAndAxes(e-this.dragCenterWorld.x,t-this.dragCenterWorld.y);return}this.getWorldPosition(this.tmpWorldPos),this.updateHandleAndAxes(e-this.tmpWorldPos.x,t-this.tmpWorldPos.y)}finishOwnedPointer(){this.releaseDrag()}releaseDrag(){this.semanticPointer=null,this.ownedPointerId=null,this.isDragging&&this.endDrag()}abortDrag(){!this.isDragging&&this.ownedPointerId===null&&this.semanticPointer===null||this.releaseDrag()}static DIRECTIONS={right:[1,0],left:[-1,0],up:[0,1],down:[0,-1],upright:[Math.SQRT1_2,Math.SQRT1_2],upleft:[-Math.SQRT1_2,Math.SQRT1_2],downright:[Math.SQRT1_2,-Math.SQRT1_2],downleft:[-Math.SQRT1_2,-Math.SQRT1_2]};semanticPointer=null;getInteractions(){return[{name:"setStick",description:"Push the stick in a direction and hold it there",args:[{name:"dir",type:"string",ui:{label:"Direction",description:"up/down/left/right/upleft/\u2026 or an angle in degrees (0 = right, CCW)",options:Object.keys(n.DIRECTIONS)}},{name:"magnitude",type:"number",defaultValue:1,ui:{label:"Magnitude",min:0,max:1,description:"0..1 of the stick radius"}}]},{name:"releaseStick",description:"Let go of the stick (axes return to zero)"}]}invokeInteraction(e,t){if(!this.enabled)return!1;switch(e){case"setStick":{let r=this.resolveDirection(t?.dir);if(!r)return!1;let i=Math.max(0,Math.min(1,Qe(t,"magnitude",1)??1));return this.pushStick(r,i)}case"releaseStick":return this.releaseStick();default:return!1}}resolveDirection(e){if(typeof e=="number"&&Number.isFinite(e)){let o=e*Math.PI/180;return[Math.cos(o),Math.sin(o)]}if(typeof e!="string")return null;let t=e.trim().toLowerCase().replace(/[\s_-]/g,""),r=n.DIRECTIONS[t];if(r)return r;let i=Number(t);if(Number.isFinite(i)&&t.length>0){let o=i*Math.PI/180;return[Math.cos(o),Math.sin(o)]}return null}pushStick(e,t){this.getWorldPosition(this.tmpWorldPos);let r=this.tmpWorldPos.x,i=this.tmpWorldPos.y;this.runSemanticStickFrame(r,i);let o=this.radius*t,s=r+e[0]*o,a=i+e[1]*o;return this.runSemanticStickFrame(s,a),!0}runSemanticStickFrame(e,t){this.semanticPointer={x:e,y:t,down:!0},this.ownedPointerId=lu;let r=this.floating||this.isWithinBase(e,t);this.driveDragFrame({pointerId:lu,worldX:e,worldY:t,down:!0},r),this.isDragging||(this.semanticPointer=null,this.ownedPointerId=null)}releaseStick(){return this.releaseDrag(),!0}updateHandleAndAxes(e,t){let r=Math.atan2(t,e),i=Math.sqrt(e*e+t*t),o=Math.min(i,this.radius),s=Math.cos(r)*o,a=Math.sin(r)*o;this.handleMesh.position.x=s,this.handleMesh.position.y=a,this.inputVector.set(s/this.radius,a/this.radius),this.input?.setAxis(this.axisHorizontal,this.inputVector.x),this.input?.setAxis(this.axisVertical,this.inputVector.y)}endDrag(){if(this.isDragging=!1,this.inputVector.set(0,0),this.input?.setAxis(this.axisHorizontal,0),this.input?.setAxis(this.axisVertical,0),this.floating){this.visibilityTarget=0,this.pendingResetAfterHide=!0;return}this.handleMesh.position.x=0,this.handleMesh.position.y=0}updateVisibility(e){let t=this.visibilityTarget-this.visibilityAlpha;if(Math.abs(t)<=Number.EPSILON){this.visibilityAlpha=this.visibilityTarget,this.applyVisibility();return}let r=Math.min(e,1/30),i=n.FADE_SPEED*r;Math.abs(t)<=i?this.visibilityAlpha=this.visibilityTarget:this.visibilityAlpha+=Math.sign(t)*i,this.applyVisibility(),this.visibilityAlpha===0&&this.pendingResetAfterHide&&(this.pendingResetAfterHide=!1,this.position.copy(this.authoredLocalPosition),this.handleMesh.position.x=0,this.handleMesh.position.y=0)}applyVisibility(){this.setOpacityMaterialBase(this.baseMaterial,n.BASE_OPACITY*this.visibilityAlpha),this.setOpacityMaterialBase(this.handleMaterial,n.HANDLE_OPACITY*this.visibilityAlpha)}setCenterFromWorld(e,t){this.position.set(e,t,this.position.z),this.dragCenterWorld.set(e,t)}static getPropertySchema(){let e=M.getPropertySchema();return{nodeType:"Joystick2D",extends:"Node2D",properties:[...e.properties,{name:"enabled",type:"boolean",ui:{label:"Enabled",group:"Joystick"},getValue:t=>t.enabled,setValue:(t,r)=>{let i=t;i.enabled=!!r,i.properties.enabled=i.enabled,i.enabled||i.abortDrag()}},{name:"radius",type:"number",ui:{label:"Radius",group:"Joystick"},getValue:t=>t.radius,setValue:(t,r)=>{t.radius=Number(r)}},{name:"floating",type:"boolean",ui:{label:"Floating Position",group:"Joystick"},getValue:t=>t.floating,setValue:(t,r)=>{let i=t;i.floating=!!r,i.semanticPointer=null,i.ownedPointerId=null,i.endDrag(),i.floating?(i.visibilityAlpha=0,i.visibilityTarget=0,i.pendingResetAfterHide=!1,i.position.copy(i.authoredLocalPosition),i.handleMesh.position.set(0,0,i.handleMesh.position.z)):(i.pendingResetAfterHide=!1,i.position.copy(i.authoredLocalPosition),i.handleMesh.position.set(0,0,i.handleMesh.position.z),i.visibilityAlpha=1,i.visibilityTarget=1),i.applyVisibility()}},{name:"axisHorizontal",type:"string",ui:{label:"Horz Axis",group:"Input"},getValue:t=>t.axisHorizontal,setValue:(t,r)=>{t.axisHorizontal=String(r)}},{name:"axisVertical",type:"string",ui:{label:"Vert Axis",group:"Input"},getValue:t=>t.axisVertical,setValue:(t,r)=>{t.axisVertical=String(r)}}],groups:{...e.groups,Joystick:{label:"Joystick",expanded:!0},Input:{label:"Input Mapping",expanded:!0}}}}};var Bx=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong","inherit","initial","unset"]),Vx=/^-?[A-Za-z_][A-Za-z0-9_-]*$/;function bf(n){let e=(n??"").trim();return e.length===0?"sans-serif":e.split(",").map(t=>t.trim()).filter(t=>t.length>0).map(t=>t.startsWith('"')||t.startsWith("'")||Bx.has(t.toLowerCase())||Vx.test(t)?t:`"${t.replace(/["\\]/g,"\\$&")}"`).join(", ")}function Sf(n){if(n==null)return"";if(typeof n=="number")return Number.isFinite(n)&&n>0?String(Math.round(n)):"";let e=n.trim().toLowerCase();return e.length===0||e==="normal"||e==="400"?"":e}function vf(n,e,t){let r=Number.isFinite(n)&&n>0?n:16,i=Sf(t);return`${i?`${i} `:""}${r}px ${bf(e)}`}function ln(n,e,t,r,i){if(e.length===0)return;let o=Math.max(0,i.outlineWidth??0),s=i.shadowColor?.trim()?i.shadowColor:"",a=i.shadowOffsetX??0,l=i.shadowOffsetY??0,c=Math.max(0,i.shadowBlur??0),u=Math.max(0,i.glowBlur??0),d=Math.max(0,Math.round(i.glowPasses??0));if(n.fillStyle=i.color,o>0&&(n.lineJoin="round",n.miterLimit=2,n.lineWidth=o*2,n.strokeStyle=i.outlineColor?.trim()?i.outlineColor:"#000000"),s&&(a!==0||l!==0||c>0)&&(n.save(),n.shadowColor=s,n.shadowOffsetX=a,n.shadowOffsetY=l,n.shadowBlur=c,o>0&&n.strokeText(e,t,r),n.fillText(e,t,r),n.restore()),o>0&&n.strokeText(e,t,r),u>0&&d>0){n.save(),n.shadowColor=i.glowColor?.trim()?i.glowColor:i.color,n.shadowBlur=u;for(let h=0;h<d;h++)n.fillText(e,t,r);n.restore()}n.fillText(e,t,r)}function Sr(n,e){n.font=vf(e.fontSize,e.fontFamily,e.fontWeight);let t=e.letterSpacing??0,r=n;t!==0&&"letterSpacing"in r?r.letterSpacing=`${t}px`:t===0&&r.letterSpacing&&(r.letterSpacing="0px")}function cn(n){let e=Math.max(0,n.outlineWidth??0),t=Math.max(0,n.glowBlur??0),i=!!n.shadowColor?.trim()?Math.max(Math.abs(n.shadowOffsetX??0),Math.abs(n.shadowOffsetY??0))+Math.max(0,n.shadowBlur??0):0;return e<=0&&t<=0&&i<=0?0:Math.ceil(t*1.5+e+i+2)}var Fe="pix3Overlay2D",Ox=[],Lx=[],uu=0,Fx=(n,e)=>n.z-e.z;function wf(n,e,t,r){let i=n.units[n.count];i?(i.obj=e,i.z=t,i.visible=r):n.units.push({obj:e,z:t,visible:r}),n.count++}function xf(n){return!!(n.userData&&n.userData[Fe])}function Pf(n){return n.obj?n.obj.renderOrder:0}function kf(n,e){let t=n.units;for(let r=e+1;r<n.count;r++){let i=t[r],o=Pf(i),s=r-1;for(;s>=e&&Pf(t[s])>o;)t[s+1]=t[s],s--;t[s+1]=i}}function Af(n,e,t,r){n.renderOrder=e.next++;let i=t&&n.visible!==!1;r&&r(n,n.renderOrder,n.layers.isEnabled(3),i);let o=n.children;for(let s=0;s<o.length;s++)Af(o[s],e,i,r)}function Tf(n,e,t,r){let i=t&&n.visible!==!1,o=n.zAsRelative?r+n.zIndex:n.zIndex;o!==0&&(e.needsSort=!0);let s=n.children,a=s.length,l=e.count;for(let u=0;u<a;u++){let d=s[u];!(d instanceof M)&&!xf(d)&&wf(e,d,o,i)}kf(e,l);for(let u=0;u<a;u++){let d=s[u];d instanceof M&&Tf(d,e,i,o)}let c=e.count;for(let u=0;u<a;u++){let d=s[u];!(d instanceof M)&&xf(d)&&wf(e,d,o,i)}kf(e,c)}function Cs(n,e){let t=uu===0;uu++;try{let r={units:t?Ox:[],count:0,needsSort:!1};for(let s=0;s<n.length;s++){let a=n[s];a instanceof M&&Tf(a,r,!0,0)}let i=r.units;if(r.needsSort){let s=t?Lx:[];s.length=r.count;for(let a=0;a<r.count;a++)s[a]=i[a];s.sort(Fx),i=s}let o={next:0};for(let s=0;s<r.count;s++){let a=i[s],l=a.obj;l&&Af(l,o,a.visible,e)}for(let s=0;s<r.count;s++)r.units[s].obj=null}finally{uu--}}var Cf=-1,_x=-2,Je=class n extends Ae{dragScrollEnabled;wheelScrollEnabled;inertiaEnabled;showScrollbar;wheelSensitivity;dragThreshold;inertiaDamping;scrollbarWidth;scrollbarMinHeight;scrollbarInset;scrollbarColor;scrollbarTrackColor;scrollbarThumbTexture;scrollbarTrackTexture;_scrollY;tmpWorldPos=new S;tmpWorldScale=new S;pointerWorld=new I;candidateWorld=new I;ownedPointerId=null;clippingPlanes=[new Vi(new S(1,0,0),0),new Vi(new S(-1,0,0),0),new Vi(new S(0,1,0),0),new Vi(new S(0,-1,0),0)];appliedClippingMaterials=new Set;childBasePositions=new Map;dragMode=null;pointerStartedInside=!1;pointerWasDown=!1;lastAppliedScrollY=0;lastPointerWorldY=0;pointerDownWorldY=0;pointerDownScrollY=0;scrollVelocity=0;thumbHeight=0;thumbCenterY=0;trackCenterX=0;trackGeometry;thumbGeometry;trackMaterial;thumbMaterial;trackMesh;thumbMesh;constructor(e){super(e,"ScrollContainer2D"),this.dragScrollEnabled=e.dragScrollEnabled??!0,this.wheelScrollEnabled=e.wheelScrollEnabled??!0,this.inertiaEnabled=e.inertiaEnabled??!0,this.showScrollbar=e.showScrollbar??!0,this.wheelSensitivity=e.wheelSensitivity??1,this.dragThreshold=Math.max(0,e.dragThreshold??6),this.inertiaDamping=Math.max(.01,e.inertiaDamping??14),this.scrollbarWidth=Math.max(2,e.scrollbarWidth??8),this.scrollbarMinHeight=Math.max(8,e.scrollbarMinHeight??24),this.scrollbarInset=Math.max(0,e.scrollbarInset??8),this.scrollbarColor=e.scrollbarColor??"#f5f7ff",this.scrollbarTrackColor=e.scrollbarTrackColor??"#ffffff",this.scrollbarThumbTexture=D(e.scrollbarThumbTexture??null),this.scrollbarTrackTexture=D(e.scrollbarTrackTexture??null),this._scrollY=Math.max(0,e.scrollY??0),this.trackGeometry=new z(this.scrollbarWidth,Math.max(1,this.height)),this.thumbGeometry=new z(this.scrollbarWidth,Math.max(1,this.height)),this.trackMaterial=new R({color:this.scrollbarTrackColor,transparent:!0,opacity:.18,depthTest:!1}),this.thumbMaterial=new R({color:this.scrollbarColor,transparent:!0,opacity:.92,depthTest:!1}),this.registerOpacityMaterial(this.trackMaterial,.18),this.registerOpacityMaterial(this.thumbMaterial,.92),this.trackMesh=new B(this.trackGeometry,this.trackMaterial),this.trackMesh.renderOrder=1e3,this.trackMesh.userData[Fe]=!0,this.trackMesh.position.z=.25,this.trackMesh.visible=!1,this.trackMesh.name=`${this.name}-ScrollbarTrack`,this.add(this.trackMesh),this.thumbMesh=new B(this.thumbGeometry,this.thumbMaterial),this.thumbMesh.renderOrder=1001,this.thumbMesh.userData[Fe]=!0,this.thumbMesh.position.z=.3,this.thumbMesh.visible=!1,this.thumbMesh.name=`${this.name}-ScrollbarThumb`,this.add(this.thumbMesh),G(this,n.getPropertySchema)}get scrollY(){return this._scrollY}set scrollY(e){let t=this.hasScrollableChildren()?this.getMaxScrollY():Number.POSITIVE_INFINITY,r=n.clampScroll(e,t);this._scrollY!==r&&(this._scrollY=r,this.properties.scrollY=r,this.syncScrollbarVisuals())}setScrollbarThumbTexture(e){e&&Y(e),this.thumbMaterial.map=e,this.setOpacityMaterialBase(this.thumbMaterial,e?1:.92),this.thumbMaterial.needsUpdate=!0}setScrollbarTrackTexture(e){e&&Y(e),this.trackMaterial.map=e,this.setOpacityMaterialBase(this.trackMaterial,e?1:.18),this.trackMaterial.needsUpdate=!0}setScrollbarThumbTextureRef(e){let t=D(e),r=this.scrollbarThumbTexture?.url!==t?.url;this.scrollbarThumbTexture=t,r&&!t&&this.setScrollbarThumbTexture(null)}setScrollbarTrackTextureRef(e){let t=D(e),r=this.scrollbarTrackTexture?.url!==t?.url;this.scrollbarTrackTexture=t,r&&!t&&this.setScrollbarTrackTexture(null)}hasActivePointerCapture(){return this.dragMode!==null}isPointInViewportBounds(e){this.getWorldPosition(this.tmpWorldPos),this.getWorldScale(this.tmpWorldScale);let t=this.width*Math.abs(this.tmpWorldScale.x)/2,r=this.height*Math.abs(this.tmpWorldScale.y)/2,i=Math.abs(e.x-this.tmpWorldPos.x),o=Math.abs(e.y-this.tmpWorldPos.y);return i<=t&&o<=r}getContentNode(){let e=this.getScrollableChildren();return e.length===1?e[0]:null}getContentHeight(){let e=this.getContentBounds();return e?Math.max(0,e.maxY-e.minY):0}getMaxScrollY(){let e=this.getContentBounds();if(!e)return 0;let t=-this.height/2;return Math.max(0,t-e.minY)}tick(e){this.updatePointerAndScroll(e),this.applyScrollOffset(),this.applyClippingPlanes(),this.syncScrollbarVisuals(),super.tick(e)}semanticPointer=null;static SEMANTIC_FRAME_DT=1/60;getInteractions(){return[{name:"scrollBy",description:"Drag the content by an offset",args:[{name:"delta",type:"number",ui:{label:"Delta",description:"Change in scroll offset, in scene units"}}]},{name:"scrollTo",description:"Drag the content to an absolute scroll offset",args:[{name:"offset",type:"number",ui:{label:"Offset",min:0,description:"Target scrollY"}}]},{name:"fling",description:"Flick the content and let inertia carry it",args:[{name:"velocity",type:"number",ui:{label:"Velocity",description:"Scene units per second at release"}}]}]}invokeInteraction(e,t){switch(e){case"scrollBy":{let r=Qe(t,"delta");return r===null?!1:this.dragScrollBy(r,0)}case"scrollTo":{let r=Qe(t,"offset");return r===null?!1:this.dragScrollBy(r-this.scrollY,0)}case"fling":{let r=Qe(t,"velocity");return r===null?!1:this.dragScrollBy(0,r)}default:return!1}}dragScrollBy(e,t){if(!this.dragScrollEnabled)return!1;let r=n.SEMANTIC_FRAME_DT;this.getWorldPosition(this.tmpWorldPos);let i=this.tmpWorldPos.x,o=this.tmpWorldPos.y,s=Math.sign(e||t||1);this.pointerWasDown=!1,this.dragMode=null,this.ownedPointerId=Cf;try{this.runSemanticScrollFrame(i,o,!0,r),this.dragMode!=="content"&&(o+=s*(this.dragThreshold+1),this.runSemanticScrollFrame(i,o,!0,r)),e!==0&&(o+=e,this.runSemanticScrollFrame(i,o,!0,r)),t!==0?(o+=t*r,this.runSemanticScrollFrame(i,o,!0,r)):this.runSemanticScrollFrame(i,o,!0,r),this.runSemanticScrollFrame(i,o,!1,r)}finally{this.semanticPointer=null,this.ownedPointerId=null}return!0}runSemanticScrollFrame(e,t,r,i){this.semanticPointer={x:e,y:t,down:r},this.updatePointerAndScroll(i),this.applyScrollOffset(),this.syncScrollbarVisuals()}static getPropertySchema(){let e=Ae.getPropertySchema();return{nodeType:"ScrollContainer2D",extends:"Group2D",properties:[...e.properties,{name:"scrollY",type:"number",ui:{label:"Scroll Y",group:"Scroll",min:0,step:1,precision:0},getValue:t=>t.scrollY,setValue:(t,r)=>{t.scrollY=Number(r)}},{name:"dragScrollEnabled",type:"boolean",ui:{label:"Drag Scroll",group:"Scroll"},getValue:t=>t.dragScrollEnabled,setValue:(t,r)=>{t.dragScrollEnabled=!!r}},{name:"wheelScrollEnabled",type:"boolean",ui:{label:"Wheel Scroll",group:"Scroll"},getValue:t=>t.wheelScrollEnabled,setValue:(t,r)=>{t.wheelScrollEnabled=!!r}},{name:"inertiaEnabled",type:"boolean",ui:{label:"Inertia",group:"Scroll"},getValue:t=>t.inertiaEnabled,setValue:(t,r)=>{t.inertiaEnabled=!!r}},{name:"showScrollbar",type:"boolean",ui:{label:"Show Scrollbar",group:"Scrollbar"},getValue:t=>t.showScrollbar,setValue:(t,r)=>{t.showScrollbar=!!r}},{name:"wheelSensitivity",type:"number",ui:{label:"Wheel Sensitivity",group:"Scroll",min:.1,step:.1,precision:2},getValue:t=>t.wheelSensitivity,setValue:(t,r)=>{t.wheelSensitivity=Math.max(.1,Number(r))}},{name:"dragThreshold",type:"number",ui:{label:"Drag Threshold",group:"Scroll",min:0,step:1,precision:0},getValue:t=>t.dragThreshold,setValue:(t,r)=>{t.dragThreshold=Math.max(0,Number(r))}},{name:"inertiaDamping",type:"number",ui:{label:"Inertia Damping",group:"Scroll",min:.01,step:.1,precision:2},getValue:t=>t.inertiaDamping,setValue:(t,r)=>{t.inertiaDamping=Math.max(.01,Number(r))}},{name:"scrollbarWidth",type:"number",ui:{label:"Width",group:"Scrollbar",min:2,step:1,precision:0},getValue:t=>t.scrollbarWidth,setValue:(t,r)=>{t.scrollbarWidth=Math.max(2,Number(r))}},{name:"scrollbarMinHeight",type:"number",ui:{label:"Min Height",group:"Scrollbar",min:8,step:1,precision:0},getValue:t=>t.scrollbarMinHeight,setValue:(t,r)=>{t.scrollbarMinHeight=Math.max(8,Number(r))}},{name:"scrollbarInset",type:"number",ui:{label:"Inset",group:"Scrollbar",min:0,step:1,precision:0},getValue:t=>t.scrollbarInset,setValue:(t,r)=>{t.scrollbarInset=Math.max(0,Number(r))}},{name:"scrollbarColor",type:"color",ui:{label:"Thumb Color",group:"Scrollbar"},getValue:t=>t.scrollbarColor,setValue:(t,r)=>{let i=t;i.scrollbarColor=String(r),i.thumbMaterial.color.setStyle(i.scrollbarColor)}},{name:"scrollbarTrackColor",type:"color",ui:{label:"Track Color",group:"Scrollbar"},getValue:t=>t.scrollbarTrackColor,setValue:(t,r)=>{let i=t;i.scrollbarTrackColor=String(r),i.trackMaterial.color.setStyle(i.scrollbarTrackColor)}},{name:"scrollbarThumbTexture",type:"object",ui:{label:"Thumb Sprite",group:"Scrollbar",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.scrollbarThumbTexture??{type:"texture",url:""},setValue:(t,r)=>{t.setScrollbarThumbTextureRef(r)}},{name:"scrollbarTrackTexture",type:"object",ui:{label:"Track Sprite",group:"Scrollbar",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.scrollbarTrackTexture??{type:"texture",url:""},setValue:(t,r)=>{t.setScrollbarTrackTextureRef(r)}}],groups:{...e.groups,Scroll:{label:"Scroll",expanded:!0},Scrollbar:{label:"Scrollbar",expanded:!0}}}}disposeResources(){this.clearClippingPlanes(),this.trackGeometry.dispose(),this.thumbGeometry.dispose(),this.trackMaterial.dispose(),this.thumbMaterial.dispose()}updatePointerAndScroll(e){let t=this.input,r=this.semanticPointer,i,o;if(r)this.pointerWorld.set(r.x,r.y),i=r.down,o=Cf;else{if(!t){this.pointerWasDown=!1,this.ownedPointerId=null;return}let l=this.resolveDrivingPointer(t);if(!l){this.pointerWasDown=!1;return}this.pointerWorld.set(l.worldX,l.worldY),i=l.down,o=l.pointerId}let s=this.pointerWorld,a=this.isPointInViewportBounds(s);if((a||this.dragMode!==null)&&(o>=0?t?.registerHover(this.nodeId,o):t?.registerHover(this.nodeId)),!this.pointerWasDown&&i?(this.pointerStartedInside=a,this.pointerDownWorldY=s.y,this.lastPointerWorldY=s.y,this.pointerDownScrollY=this.scrollY,this.scrollVelocity=0,a&&this.isPointInThumbBounds(s)&&(this.dragMode="thumb")):this.pointerWasDown&&!i&&(this.pointerStartedInside=!1,this.dragMode=null,this.ownedPointerId=null),this.wheelScrollEnabled&&t&&a&&t.wheelDelta.y!==0&&(this.scrollY+=t.wheelDelta.y*this.wheelSensitivity,this.scrollVelocity=0),i&&this.dragMode==="thumb"){let l=Math.max(1,this.height-this.thumbHeight),c=Math.max(0,this.getMaxScrollY());if(c>0){let u=this.pointerWorld.y-this.pointerDownWorldY;this.scrollY=this.pointerDownScrollY-u*c/l}}else if(this.dragScrollEnabled&&i&&this.pointerStartedInside){let l=this.pointerWorld.y-this.pointerDownWorldY;if(this.dragMode==="content"){let c=this.pointerWorld.y-this.lastPointerWorldY;this.scrollY+=c;let u=Math.max(1/240,e);this.scrollVelocity=c/u}else Math.abs(l)>=this.dragThreshold&&this.getMaxScrollY()>0&&(this.dragMode="content",this.lastPointerWorldY=this.pointerWorld.y)}else if(!i&&this.dragMode===null&&this.inertiaEnabled&&Math.abs(this.scrollVelocity)>.5){let l=Math.exp(-this.inertiaDamping*Math.max(0,e)),c=this.scrollVelocity*(1+l)*.5;this.scrollY+=c*Math.max(0,e),this.scrollVelocity*=l,Math.abs(this.scrollVelocity)<.5&&(this.scrollVelocity=0)}!i&&(this.scrollY<=0||this.scrollY>=this.getMaxScrollY())&&(this.scrollVelocity=0),this.lastPointerWorldY=this.pointerWorld.y,this.pointerWasDown=i,this.scrollY=this._scrollY}resolveDrivingPointer(e){let t=this.collectCandidatePointers(e),r=this.ownedPointerId;if(r!==null){let o=t.find(s=>s.pointerId===r);return o?this.resolveCandidate(o):this.finishOwnedPointer(e,r)}let i=null;for(let o of t){let s=this.resolveCandidate(o);if(!s)continue;let a=this.isPointInViewportBounds(this.candidateWorld);if(o.down&&a)return this.ownedPointerId=o.pointerId,s;if((a||i===null)&&(i={...s,down:!1}),a)break}return i}collectCandidatePointers(e){let t=e.getActivePointers();return t.length>0?t.map(r=>({pointerId:r.pointerId,x:r.x,y:r.y,down:!0})):[{pointerId:_x,x:e.pointerPosition.x,y:e.pointerPosition.y,down:e.isPointerDown}]}resolveCandidate(e){let t=this.screenPointToWorld(e.x,e.y,this.candidateWorld);return t?{pointerId:e.pointerId,worldX:t.x,worldY:t.y,down:e.down}:null}finishOwnedPointer(e,t){let r=n.findTerminalEvent(e,t);if(r?.type==="up"){let i=this.screenPointToWorld(r.x,r.y,this.candidateWorld);if(i)return{pointerId:t,worldX:i.x,worldY:i.y,down:!1}}else this.scrollVelocity=0;return{pointerId:t,worldX:this.pointerWorld.x,worldY:this.pointerWorld.y,down:!1}}static findTerminalEvent(e,t){let r=e.pointerEvents;for(let i=r.length-1;i>=0;i-=1){let o=r[i];if(o.pointerId===t&&(o.type==="up"||o.type==="cancel"))return o}return null}getScrollableChildren(){let e=[];for(let t of this.children)t instanceof M&&e.push(t);return e}hasScrollableChildren(){return this.getScrollableChildren().length>0}applyScrollOffset(){let e=this.getScrollableChildren();if(e.length===0){this.lastAppliedScrollY=0;return}let t=n.clampScroll(this._scrollY,this.getMaxScrollY());n.areClose(this._scrollY,t)||(this._scrollY=t);for(let r of e){let i=this.syncChildBasePosition(r);r.position.set(i.x,i.y+t,i.z)}this.lastAppliedScrollY=t}syncChildBasePosition(e){let t=this.childBasePositions.get(e.nodeId);if(!t){let i=e.position.clone();return this.childBasePositions.set(e.nodeId,i),i}let r=t.y+this.lastAppliedScrollY;return(!n.areClose(e.position.x,t.x)||!n.areClose(e.position.z,t.z)||!n.areClose(e.position.y,r))&&t.set(e.position.x,e.position.y-this.lastAppliedScrollY,e.position.z),t}applyClippingPlanes(){let e=this.getScrollableChildren();if(e.length===0){this.clearClippingPlanes();return}this.getWorldPosition(this.tmpWorldPos),this.getWorldScale(this.tmpWorldScale);let t=this.width*Math.abs(this.tmpWorldScale.x)/2,r=this.height*Math.abs(this.tmpWorldScale.y)/2,i=this.tmpWorldPos.x-t,o=this.tmpWorldPos.x+t,s=this.tmpWorldPos.y-r,a=this.tmpWorldPos.y+r;this.clippingPlanes[0].constant=-i,this.clippingPlanes[1].constant=o,this.clippingPlanes[2].constant=-s,this.clippingPlanes[3].constant=a;let l=new Set;for(let c of e)c.traverse(u=>{let d=u;if(!d.material)return;let h=Array.isArray(d.material)?d.material:[d.material];for(let p of h)p.clippingPlanes=this.clippingPlanes,p.clipIntersection=!1,p.needsUpdate=!0,l.add(p)});for(let c of this.appliedClippingMaterials)l.has(c)||(c.clippingPlanes=null,c.needsUpdate=!0);this.appliedClippingMaterials.clear();for(let c of l)this.appliedClippingMaterials.add(c)}clearClippingPlanes(){for(let e of this.appliedClippingMaterials)e.clippingPlanes=null,e.needsUpdate=!0;this.appliedClippingMaterials.clear()}syncScrollbarVisuals(){let e=this.getContentHeight(),t=this.getMaxScrollY(),r=this.showScrollbar&&e>this.height+.001;if(this.trackMesh.visible=r,this.thumbMesh.visible=r,!r)return;this.trackCenterX=this.width/2-this.scrollbarInset-this.scrollbarWidth/2;let i=Math.max(1,this.height),o=i/Math.max(i,e);this.thumbHeight=Math.max(this.scrollbarMinHeight,Math.min(i,i*o));let s=Math.max(0,i-this.thumbHeight),a=t>0?Math.min(1,this.scrollY/t):0;this.thumbCenterY=i/2-this.thumbHeight/2-a*s,this.trackMesh.position.set(this.trackCenterX,0,.25),this.thumbMesh.position.set(this.trackCenterX,this.thumbCenterY,.3),(!n.areClose(this.trackGeometry.parameters.width,this.scrollbarWidth)||!n.areClose(this.trackGeometry.parameters.height,i))&&(this.trackGeometry.dispose(),this.trackGeometry=new z(this.scrollbarWidth,i),this.trackMesh.geometry=this.trackGeometry),(!n.areClose(this.thumbGeometry.parameters.width,this.scrollbarWidth)||!n.areClose(this.thumbGeometry.parameters.height,this.thumbHeight))&&(this.thumbGeometry.dispose(),this.thumbGeometry=new z(this.scrollbarWidth,this.thumbHeight),this.thumbMesh.geometry=this.thumbGeometry),this.trackMaterial.color.setStyle(this.scrollbarTrackColor),this.thumbMaterial.color.setStyle(this.scrollbarColor)}getContentBounds(){let e=this.getScrollableChildren();if(e.length===0)return null;let t=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(let i of e){let o=this.syncChildBasePosition(i),s=this.getChildVerticalExtents(i);t=Math.min(t,o.y+s.minY),r=Math.max(r,o.y+s.maxY)}return!Number.isFinite(t)||!Number.isFinite(r)?null:{minY:t,maxY:r}}getChildVerticalExtents(e){let t=e.getCurrentLayoutSize(),r=Math.max(0,t.height),i=e,o=n.clampNormalizedAnchor(i.anchor?.y??.5);return{minY:-o*r,maxY:(1-o)*r}}isPointInThumbBounds(e){if(!this.showScrollbar||!this.thumbMesh.visible)return!1;this.getWorldPosition(this.tmpWorldPos),this.getWorldScale(this.tmpWorldScale);let t=this.tmpWorldPos.x+this.trackCenterX*this.tmpWorldScale.x,r=this.tmpWorldPos.y+this.thumbCenterY*this.tmpWorldScale.y,i=this.scrollbarWidth*Math.abs(this.tmpWorldScale.x)/2,o=this.thumbHeight*Math.abs(this.tmpWorldScale.y)/2;return e.x>=t-i&&e.x<=t+i&&e.y>=r-o&&e.y<=r+o}static areClose(e,t){return Math.abs(e-t)<=.001}static clampScroll(e,t){let r=Number.isFinite(e)?e:0,i=Number.isFinite(t)?Math.max(0,t):r;return Math.max(0,Math.min(r,i))}static clampNormalizedAnchor(e){return Number.isFinite(e)?Math.max(0,Math.min(1,e)):.5}};var ui=-1,zx=-2,te=class extends M{_enabled=!0;_label;_labelKey;_labelFontFamily;_labelFontSize;_labelColor;_labelAlign;_labelFontWeight;_labelOutlineWidth;_labelOutlineColor;_labelShadowColor;_labelShadowOffsetX;_labelShadowOffsetY;_labelLetterSpacing;labelReactive=!1;texturePath;get label(){return this._label}set label(e){this._label!==e&&(this._label=e,this.refreshLabelIfReactive())}get labelKey(){return this._labelKey}set labelKey(e){this._labelKey!==e&&(this._labelKey=e,this.refreshLabelIfReactive())}get labelFontFamily(){return this._labelFontFamily}set labelFontFamily(e){this._labelFontFamily!==e&&(this._labelFontFamily=e,this.refreshLabelIfReactive())}get labelFontSize(){return this._labelFontSize}set labelFontSize(e){this._labelFontSize!==e&&(this._labelFontSize=e,this.refreshLabelIfReactive())}get labelColor(){return this._labelColor}set labelColor(e){this._labelColor!==e&&(this._labelColor=e,this.refreshLabelIfReactive())}get labelFontWeight(){return this._labelFontWeight}set labelFontWeight(e){this._labelFontWeight!==e&&(this._labelFontWeight=e,this.refreshLabelIfReactive())}get labelOutlineWidth(){return this._labelOutlineWidth}set labelOutlineWidth(e){let t=Math.max(0,Number.isFinite(e)?e:0);this._labelOutlineWidth!==t&&(this._labelOutlineWidth=t,this.refreshLabelIfReactive())}get labelOutlineColor(){return this._labelOutlineColor}set labelOutlineColor(e){this._labelOutlineColor!==e&&(this._labelOutlineColor=e,this.refreshLabelIfReactive())}get labelShadowColor(){return this._labelShadowColor}set labelShadowColor(e){let t=e&&e.trim().length>0?e:null;this._labelShadowColor!==t&&(this._labelShadowColor=t,this.refreshLabelIfReactive())}get labelShadowOffsetX(){return this._labelShadowOffsetX}set labelShadowOffsetX(e){let t=Number.isFinite(e)?e:0;this._labelShadowOffsetX!==t&&(this._labelShadowOffsetX=t,this.refreshLabelIfReactive())}get labelShadowOffsetY(){return this._labelShadowOffsetY}set labelShadowOffsetY(e){let t=Number.isFinite(e)?e:0;this._labelShadowOffsetY!==t&&(this._labelShadowOffsetY=t,this.refreshLabelIfReactive())}get labelLetterSpacing(){return this._labelLetterSpacing}set labelLetterSpacing(e){let t=Number.isFinite(e)?e:0;this._labelLetterSpacing!==t&&(this._labelLetterSpacing=t,this.refreshLabelIfReactive())}get labelAlign(){return this._labelAlign}set labelAlign(e){this._labelAlign!==e&&(this._labelAlign=e,this.refreshLabelIfReactive())}refreshLabelIfReactive(){this.labelReactive&&this.updateLabel()}isHovering=!1;isPressed=!1;tmpWorldPos=new S;onHoverEnter;onHoverExit;onPressed;onReleased;labelMesh=null;labelTexture=null;skinTexture=null;skinMaterials=new Set;constructor(e,t){super(e,t),this._enabled=e.enabled??!0,this._label=e.label??"",this._labelKey=e.labelKey??"",this._labelFontFamily=e.labelFontFamily??"Arial",this._labelFontSize=e.labelFontSize??16,this._labelColor=e.labelColor??"#ffffff",this._labelAlign=e.labelAlign??"center",this._labelFontWeight=e.labelFontWeight??"normal",this._labelOutlineWidth=Math.max(0,e.labelOutlineWidth??0),this._labelOutlineColor=e.labelOutlineColor??"#000000",this._labelShadowColor=e.labelShadowColor?.trim()?e.labelShadowColor:null,this._labelShadowOffsetX=e.labelShadowOffsetX??0,this._labelShadowOffsetY=e.labelShadowOffsetY??0,this._labelLetterSpacing=e.labelLetterSpacing??0,this.texturePath=e.texturePath??null,this.texturePath&&this.tryLoadTextureFromPath(this.texturePath),(this._label.trim().length>0||this._labelKey.length>0)&&this.updateLabel(),this.labelReactive=!0}disposeResources(){super.disposeResources(),this.labelTexture?.dispose(),this.labelTexture=null}get enabled(){return this._enabled}set enabled(e){let t=!!e;this._enabled!==t&&(this._enabled=t,this.onEnabledChanged(t))}onEnabledChanged(e){}registerSkinMaterial(e){this.registerOpacityMaterial(e),this.skinMaterials.add(e),this.skinTexture&&(e.map=this.skinTexture,e.color.set("#ffffff"),e.transparent=!0,e.needsUpdate=!0)}applySkinTexture(e){this.skinTexture=e;for(let t of this.skinMaterials)t.map=e,e&&(t.color.set("#ffffff"),t.transparent=!0),t.needsUpdate=!0}tryLoadTextureFromPath(e){let t=/^([a-z]+[a-z0-9+.-]*):\/\//i.exec(e),r=t?t[1].toLowerCase():"";if(!(r===""||r==="http"||r==="https"))return;new Zr().load(e,o=>{Y(o),this.applySkinTexture(o)},void 0,()=>{})}isPointInBounds(e){return!1}updatePointerStateFromInput(){let e=this.input,t=this.semanticPointer;if(t){let s=e?this.collectCandidatePointers(e):null,a=s?this.findClaimingPointer(s):null;return a?(this.semanticPointer=null,this.ownedPointerId=null,this.driveWithPointer(a)):(this.currentPointerId=ui,this.updatePointerState(t.x,t.y,t.down),this.currentPointerId=null,!0)}if(!e)return!1;let r=this.collectCandidatePointers(e),i=this.ownedPointerId;if(i!==null){let s=r.find(a=>a.pointerId===i);if(s){let a=this.resolveCandidate(s);return a?this.driveWithPointer(a):!1}return this.finishOwnedPointer(i)}let o=this.findClaimingPointer(r);return o?this.driveWithPointer(o):this.observeWithoutOwnership(r)}collectCandidatePointers(e){let t=e.getActivePointers();return t.length>0?t.map(r=>({pointerId:r.pointerId,x:r.x,y:r.y,down:!0})):[{pointerId:zx,x:e.pointerPosition.x,y:e.pointerPosition.y,down:e.isPointerDown}]}resolveCandidate(e){let t=this.screenPointToWorld(e.x,e.y,this.candidateWorld);return t?{pointerId:e.pointerId,down:e.down,worldX:t.x,worldY:t.y}:null}findClaimingPointer(e){for(let t of e){if(!t.down)continue;let r=this.resolveCandidate(t);if(!r)return null;if(this.isPointInBounds(this.candidateWorld))return r}return null}driveWithPointer(e){return this.ownedPointerId=e.pointerId,this.currentPointerId=e.pointerId,this.updatePointerState(e.worldX,e.worldY,e.down),this.ownedPointerId!==ui&&!this.isPressed&&(this.ownedPointerId=null),!0}finishOwnedPointer(e){let t=this.findTerminalEvent(e);if(this.ownedPointerId=null,this.currentPointerId=null,t?.type==="up"){let r=this.screenPointToWorld(t.x,t.y,this.candidateWorld);if(r)return this.currentPointerId=e,this.updatePointerState(r.x,r.y,!1),this.currentPointerId=null,!0}return this.cancelPointerInteraction(),!0}findTerminalEvent(e){let t=this.input?.pointerEvents;if(!t)return null;for(let r=t.length-1;r>=0;r-=1){let i=t[r];if(i.pointerId===e&&(i.type==="up"||i.type==="cancel"))return i}return null}observeWithoutOwnership(e){let t=null;for(let r of e){let i=this.resolveCandidate(r);if(i){if(this.isPointInBounds(this.candidateWorld)){t=i;break}t??=i}}return t?(this.currentPointerId=t.pointerId,this.updatePointerState(t.worldX,t.worldY,!1),this.currentPointerId=null,!0):!1}ownedPointerId=null;currentPointerId=null;candidateWorld=new I;semanticPointer=null;get hasSemanticPointerHold(){return this.semanticPointer!==null}getSemanticPointerPoint(e=new I){return this.getWorldPosition(this.tmpWorldPos),e.set(this.tmpWorldPos.x,this.tmpWorldPos.y)}runSemanticPointerFrame(e,t,r){return this.canAcceptSemanticPointer(e)?(this.semanticPointer=r?{x:e.x,y:e.y,down:t}:null,this.ownedPointerId=r?ui:null,this.currentPointerId=ui,this.updatePointerState(e.x,e.y,t),this.currentPointerId=null,!0):!1}canAcceptSemanticPointer(e=this.getSemanticPointerPoint()){return this.enabled&&this.isVisibleInTree()&&this.isPointerAllowedByAncestorScrollContainers(e)}clearSemanticPointer(){this.semanticPointer=null,this.ownedPointerId===ui&&(this.ownedPointerId=null)}getInteractions(){return[{name:"hover",description:"Rest the pointer on the control (stays hovered)"},{name:"press",description:"Press and hold the control"},{name:"release",description:"Release a held press"},{name:"click",description:"Press and release inside the control"}]}invokeInteraction(e,t){return this.performInteraction(e,t)}performInteraction(e,t){switch(e){case"hover":return this.runSemanticPointerFrame(this.getSemanticPointerPoint(),!1,!0);case"press":return this.runSemanticPointerFrame(this.getSemanticPointerPoint(),!0,!0);case"release":return this.runSemanticPointerFrame(this.getSemanticPointerPoint(),!1,!1);case"click":return this.runSemanticClick();default:return!1}}runSemanticClick(e=this.getSemanticPointerPoint()){return this.runSemanticPointerFrame(e,!0,!0)?this.runSemanticPointerFrame(e,!1,!1):!1}updatePointerState(e,t,r){if(!this.enabled){this.cancelPointerInteraction();return}if(!this.isVisibleInTree()){this.cancelPointerInteraction();return}let i=new I(e,t);if(!this.isPointerAllowedByAncestorScrollContainers(i)){this.cancelPointerInteraction();return}let o=this.isPointInBounds(i),s=this.isPressed&&this.capturesPointer();if(o&&!this.isHovering?(this.isHovering=!0,this.onHoverEnter?.(),this.onHover(!0)):!o&&this.isHovering&&(this.isHovering=!1,this.onHoverExit?.(),this.onHover(!1),this.isPressed&&!s&&(this.isPressed=!1,this.onReleased?.(),this.onPress(!1))),this.isHovering&&this.input){let a=this.currentPointerId;a!==null&&a>=0?this.input.registerHover(this.nodeId,a):this.input.registerHover(this.nodeId)}o&&r&&!this.isPressed?(this.isPressed=!0,this.emit("pointerdown"),this.emit("pressed"),this.onPressed?.(),this.onPress(!0)):!r&&this.isPressed&&(this.isPressed=!1,this.emit("pointerup"),this.emit("released"),o&&this.emit("click"),this.onReleased?.(),this.onPress(!1),o&&this.onClick()),this.isPressed&&r&&this.onPointerDrag(i)}cancelPointerInteraction(){this.semanticPointer=null,this.ownedPointerId=null,this.isHovering&&(this.isHovering=!1,this.onHoverExit?.(),this.onHover(!1)),this.isPressed&&(this.isPressed=!1,this.onReleased?.(),this.onPress(!1))}onHover(e){}onPress(e){}onClick(){}onPointerDrag(e){}capturesPointer(){return!1}isPointerAllowedByAncestorScrollContainers(e){let t=this.parent;for(;t;){if(t instanceof Je&&(!t.isPointInViewportBounds(e)||t.hasActivePointerCapture()))return!1;t=t.parent}return!0}createLabelTexture(e,t=256,r=64){let i=typeof window<"u"&&window.devicePixelRatio||1,o=Math.max(1,Math.min(3,i)),s=document.createElement("canvas");s.width=Math.max(1,Math.round(t*o)),s.height=Math.max(1,Math.round(r*o));let a=s.getContext("2d");if(!a)throw new Error("Could not get canvas 2D context");a.setTransform(1,0,0,1,0,0),a.scale(o,o),a.fillStyle="rgba(0, 0, 0, 0)",a.fillRect(0,0,t,r),Sr(a,{fontSize:this.labelFontSize,fontFamily:this.labelFontFamily,fontWeight:this.labelFontWeight,letterSpacing:this.labelLetterSpacing}),a.textBaseline="middle";let l=cn({outlineWidth:this.labelOutlineWidth,shadowColor:this.labelShadowColor,shadowOffsetX:this.labelShadowOffsetX,shadowOffsetY:this.labelShadowOffsetY}),c=t/2;this.labelAlign==="left"?(a.textAlign="left",c=10+l):this.labelAlign==="right"?(a.textAlign="right",c=t-10-l):a.textAlign="center",ln(a,e,c,r/2,{color:this.labelColor,outlineWidth:this.labelOutlineWidth,outlineColor:this.labelOutlineColor,shadowColor:this.labelShadowColor,shadowOffsetX:this.labelShadowOffsetX,shadowOffsetY:this.labelShadowOffsetY});let u=new Mt(s);return u.userData={...u.userData??{},logicalWidth:t,logicalHeight:r,dpr:o},Y(u),u}getDisplayText(){return this.labelKey?Zi(this.labelKey,this.label):this.label}refreshLocalizedLabel(){this.updateLabel()}updateLabel(){let e=this.getDisplayText();if(!e){this.labelMesh&&(this.remove(this.labelMesh),this.labelMesh=null,this.labelTexture&&(this.labelTexture.dispose(),this.labelTexture=null));return}this.labelTexture&&(this.labelTexture.dispose(),this.labelTexture=null);let t=Math.max(128,Math.ceil(e.length*this.labelFontSize*.75)+24),r=Math.max(32,Math.ceil(this.labelFontSize*2));if(this.labelTexture=this.createLabelTexture(e,t,r),this.labelMesh)this.labelMesh.material.map=this.labelTexture,this.labelMesh.material.needsUpdate=!0;else{let i=new R({map:this.labelTexture,transparent:!0,depthTest:!1});this.registerOpacityMaterial(i,1);let o=new z(1,1);this.labelMesh=new B(o,i),this.labelMesh.renderOrder=1001,this.labelMesh.position.z=2,this.add(this.labelMesh)}if(this.labelMesh&&this.labelTexture){let i=this.labelTexture.image,o=this.labelTexture.userData??{},s=o.dpr??1,a=o.logicalWidth??i.width/s,l=o.logicalHeight??i.height/s;this.labelMesh.scale.set(a,l,1)}}static getPropertySchema(){let e=M.getPropertySchema();return{nodeType:"UIControl2D",extends:"Node2D",properties:[...e.properties,{name:"enabled",type:"boolean",ui:{label:"Enabled",group:"Control"},getValue:t=>t.enabled,setValue:(t,r)=>{t.enabled=!!r}},{name:"label",type:"string",ui:{label:"Label",group:"Label",description:"Text displayed on the control"},getValue:t=>t.label,setValue:(t,r)=>{t.label=String(r)}},{name:"labelKey",type:"string",ui:{label:"Label Key",group:"Label",editor:"localization-key",description:"Localization key; when set, its translation is shown instead of the literal label"},getValue:t=>t.labelKey,setValue:(t,r)=>{t.labelKey=String(r)}},{name:"labelFontSize",type:"number",ui:{label:"Font Size",group:"Label",min:8,max:200,step:1},getValue:t=>t.labelFontSize,setValue:(t,r)=>{t.labelFontSize=Number(r)}},{name:"labelFontFamily",type:"string",ui:{label:"Font Family",group:"Label",description:"A family registered by the project manifest, or a system font"},getValue:t=>t.labelFontFamily,setValue:(t,r)=>{t.labelFontFamily=String(r)}},{name:"labelFontWeight",type:"number",ui:{label:"Font Weight",group:"Label",min:100,max:900,step:100},getValue:t=>{let r=t.labelFontWeight;if(typeof r=="number")return r;let i=r.trim().toLowerCase();if(i==="bold")return 700;let o=Number(i);return Number.isFinite(o)&&o>0?o:400},setValue:(t,r)=>{t.labelFontWeight=Number(r)}},{name:"labelOutlineWidth",type:"number",ui:{label:"Outline Width",group:"Label",min:0,max:12,step:.5,description:"Half-width in px; the sticker outline the UI kit draws captions with"},getValue:t=>t.labelOutlineWidth,setValue:(t,r)=>{t.labelOutlineWidth=Number(r)}},{name:"labelOutlineColor",type:"color",ui:{label:"Outline Color",group:"Label"},getValue:t=>t.labelOutlineColor,setValue:(t,r)=>{t.labelOutlineColor=String(r)}},{name:"labelShadowColor",type:"color",ui:{label:"Shadow Color",group:"Label",description:"Empty = no drop shadow"},getValue:t=>t.labelShadowColor??"",setValue:(t,r)=>{let i=String(r).trim();t.labelShadowColor=i.length>0?i:null}},{name:"labelShadowOffsetY",type:"number",ui:{label:"Shadow Offset Y",group:"Label",min:-12,max:12,step:.5},getValue:t=>t.labelShadowOffsetY,setValue:(t,r)=>{t.labelShadowOffsetY=Number(r)}},{name:"labelShadowOffsetX",type:"number",ui:{label:"Shadow Offset X",group:"Label",min:-12,max:12,step:.5},getValue:t=>t.labelShadowOffsetX,setValue:(t,r)=>{t.labelShadowOffsetX=Number(r)}},{name:"labelLetterSpacing",type:"number",ui:{label:"Letter Spacing",group:"Label",min:-4,max:12,step:.1},getValue:t=>t.labelLetterSpacing,setValue:(t,r)=>{t.labelLetterSpacing=Number(r)}},{name:"labelColor",type:"color",ui:{label:"Font Color",group:"Label"},getValue:t=>t.labelColor,setValue:(t,r)=>{t.labelColor=String(r)}},{name:"labelAlign",type:"select",ui:{label:"Alignment",group:"Label",options:["left","center","right"]},getValue:t=>t.labelAlign,setValue:(t,r)=>{let i=String(r);(i==="left"||i==="center"||i==="right")&&(t.labelAlign=i)}},{name:"texturePath",type:"string",ui:{label:"Texture",group:"Skin",description:"Optional skin texture path (png/webp with transparency)"},getValue:t=>t.texturePath??"",setValue:(t,r)=>{let i=t,o=String(r).trim();i.texturePath=o.length>0?o:null,i.texturePath?i.tryLoadTextureFromPath(i.texturePath):i.applySkinTexture(null)}}],groups:{...e.groups,Control:{label:"Control",expanded:!0},Label:{label:"Label",expanded:!1},Skin:{label:"Skin",expanded:!1}}}}};var mt=class n extends te{width;height;backgroundColor;hoverColor;pressedColor;buttonAction;textureNormal;textureHover;texturePressed;textureDisabled;stateTextureKeys;sliceBorder;buttonMesh;buttonMaterial;skinGeometry=null;skinTextureWidth=0;skinTextureHeight=0;skinEffectsActive=!1;effectStack;stateTextures={normal:null,hover:null,pressed:null,disabled:null};constructor(e){super(e,"Button2D"),this.width=e.width??100,this.height=e.height??40,this.backgroundColor=e.backgroundColor??"#4a4a4a",this.hoverColor=e.hoverColor??"#5a5a5a",this.pressedColor=e.pressedColor??"#3a3a3a",this.buttonAction=e.buttonAction??"Submit",this.textureNormal=D(e.textureNormal??null),this.textureHover=D(e.textureHover??null),this.texturePressed=D(e.texturePressed??null),this.textureDisabled=D(e.textureDisabled??null),this.stateTextureKeys={...e.stateTextureKeys??{}},this.sliceBorder=Ee(e.sliceBorder),this.buttonMaterial=new R({color:this.backgroundColor,transparent:!0,opacity:1,depthTest:!1}),this.registerSkinMaterial(this.buttonMaterial),this.buttonMesh=new B(Me,this.buttonMaterial),this.buttonMesh.scale.set(this.width,this.height,1),this.buttonMesh.renderOrder=999,this.add(this.buttonMesh),this.applySkinGeometry(),this.refreshSkinState(),this.effectStack=new Oe({nodeType:"Button2D",target:"basic",onAttachmentsChanged:()=>{this.skinEffectsActive=!this.effectStack.isEmpty,this.updateSkinBatchable()}}),this.effectStack.install(this.buttonMaterial);let t=e.effects??this.properties.effects;for(let r of t??[])r&&typeof r.type=="string"&&this.effectStack.attach(r.type,{enabled:r.enabled,params:r.params});G(this,n.getPropertySchema)}getShaderEffectStack(){return this.effectStack}getInstancePropertySchema(){return this.effectStack.buildInstanceSchema()}attachEffect(e,t){return this.effectStack.attach(e,t)}detachEffect(e){return this.effectStack.detach(e)}setEffectEnabled(e,t){this.effectStack.setEnabled(e,t)}setEffectParam(e,t,r){return this.effectStack.setParam(e,t,r)}getAttachedEffects(){return this.effectStack.getAttached()}isPointInBounds(e){this.getWorldPosition(this.tmpWorldPos);let t=Math.abs(e.x-this.tmpWorldPos.x),r=Math.abs(e.y-this.tmpWorldPos.y);return t<=this.width/2&&r<=this.height/2}tick(e){super.tick(e),this.effectStack.tick(e),this.updatePointerStateFromInput()}onPress(e){this.refreshSkinState(),this.input?.setButton(this.buttonAction,e)}onHover(e){this.refreshSkinState()}onEnabledChanged(e){!e&&this.isPressed&&(this.isPressed=!1,this.input?.setButton(this.buttonAction,!1)),this.refreshSkinState()}applySkinTexture(e){this.skinTexture=e,this.refreshSkinState()}setStateTexture(e,t){t&&Y(t),this.stateTextures[e]=t,this.refreshSkinState()}resolveStateTexture(){let e=this.stateTextures.normal??this.skinTexture;return this.enabled?this.isPressed?this.stateTextures.pressed??e:this.isHovering?this.stateTextures.hover??e:e:this.stateTextures.disabled??e}resolveStateColor(){return this.enabled?this.isPressed?this.pressedColor:this.isHovering?this.hoverColor:this.backgroundColor:this.backgroundColor}refreshSkinState(){if(!this.buttonMaterial)return;let e=this.resolveStateTexture(),t=this.buttonMaterial.map!==null;e?(this.buttonMaterial.map=e,this.buttonMaterial.color.set("#ffffff"),this.buttonMaterial.transparent=!0):(this.buttonMaterial.map=null,this.buttonMaterial.color.setStyle(this.resolveStateColor())),t!==(e!==null)&&(this.buttonMaterial.needsUpdate=!0),this.captureSkinTextureSize(e)}captureSkinTextureSize(e){let t=0,r=0;if(e?.image){let i=$e(e.image);t=i.width??0,r=i.height??0}t===this.skinTextureWidth&&r===this.skinTextureHeight||(this.skinTextureWidth=t,this.skinTextureHeight=r,ci(this.sliceBorder)||this.applySkinGeometry())}applySkinGeometry(){if(ci(this.sliceBorder))this.skinGeometry&&(this.skinGeometry.dispose(),this.skinGeometry=null),this.buttonMesh.geometry=Me,this.buttonMesh.scale.set(this.width,this.height,1);else{let e=hr({width:this.width,height:this.height,textureWidth:this.skinTextureWidth,textureHeight:this.skinTextureHeight,border:this.sliceBorder});this.skinGeometry?.dispose(),this.skinGeometry=e,this.buttonMesh.geometry=e,this.buttonMesh.scale.set(1,1,1)}this.updateSkinBatchable()}updateSkinBatchable(){this.buttonMesh.userData[Ne]=!this.skinEffectsActive&&ci(this.sliceBorder)}setSliceBorder(e){this.sliceBorder=Ee({...this.sliceBorder,...e}),this.applySkinGeometry()}getEffectiveStateTexturePath(e){let t=this.stateTextureKeys[e];if(t){let r=Ye()?.trSprite(t);if(r)return r}switch(e){case"normal":return this.textureNormal?.url??null;case"hover":return this.textureHover?.url??null;case"pressed":return this.texturePressed?.url??null;case"disabled":return this.textureDisabled?.url??null}}hasLocalizedStateTextures(){return!!(this.stateTextureKeys.normal||this.stateTextureKeys.hover||this.stateTextureKeys.pressed||this.stateTextureKeys.disabled)}setStateTextureKey(e,t){let r=String(t??"");(this.stateTextureKeys[e]??"")!==r&&(r?this.stateTextureKeys[e]=r:delete this.stateTextureKeys[e])}setStateTextureRef(e,t){let r=D(t),i=null;switch(e){case"normal":i=this.textureNormal,this.textureNormal=r;break;case"hover":i=this.textureHover,this.textureHover=r;break;case"pressed":i=this.texturePressed,this.texturePressed=r;break;case"disabled":i=this.textureDisabled,this.textureDisabled=r;break}i?.url!==r?.url&&(this.stateTextures[e]=null,this.refreshSkinState())}static getPropertySchema(){let e=te.getPropertySchema();return{nodeType:"Button2D",extends:"UIControl2D",properties:[...e.properties,{name:"width",type:"number",ui:{label:"Width",group:"Button",min:10,max:500,step:1},getValue:t=>t.width,setValue:(t,r)=>{let i=t;i.width=Number(r),i.applySkinGeometry()}},{name:"height",type:"number",ui:{label:"Height",group:"Button",min:10,max:500,step:1},getValue:t=>t.height,setValue:(t,r)=>{let i=t;i.height=Number(r),i.applySkinGeometry()}},{name:"backgroundColor",type:"color",ui:{label:"Color",group:"Button"},getValue:t=>t.backgroundColor,setValue:(t,r)=>{let i=t;i.backgroundColor=String(r),i.refreshSkinState()}},{name:"hoverColor",type:"color",ui:{label:"Hover Color",group:"Button"},getValue:t=>t.hoverColor,setValue:(t,r)=>{let i=t;i.hoverColor=String(r),i.refreshSkinState()}},{name:"pressedColor",type:"color",ui:{label:"Pressed Color",group:"Button"},getValue:t=>t.pressedColor,setValue:(t,r)=>{let i=t;i.pressedColor=String(r),i.refreshSkinState()}},{name:"buttonAction",type:"string",ui:{label:"Button Action",group:"Input",description:"Virtual button name"},getValue:t=>t.buttonAction,setValue:(t,r)=>{t.buttonAction=String(r)}},{name:"textureNormal",type:"object",ui:{label:"Normal Sprite",group:"Skin",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.textureNormal??{type:"texture",url:""},setValue:(t,r)=>{t.setStateTextureRef("normal",r)}},{name:"textureHover",type:"object",ui:{label:"Hover Sprite",group:"Skin",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.textureHover??{type:"texture",url:""},setValue:(t,r)=>{t.setStateTextureRef("hover",r)}},{name:"texturePressed",type:"object",ui:{label:"Pressed Sprite",group:"Skin",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.texturePressed??{type:"texture",url:""},setValue:(t,r)=>{t.setStateTextureRef("pressed",r)}},{name:"textureDisabled",type:"object",ui:{label:"Disabled Sprite",group:"Skin",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.textureDisabled??{type:"texture",url:""},setValue:(t,r)=>{t.setStateTextureRef("disabled",r)}},{name:"sliceBorderLeft",type:"number",ui:{label:"Slice Left",group:"Skin",description:"Left 9-slice inset of the state skins (source px); 0 = stretch",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.left,setValue:(t,r)=>{t.setSliceBorder({left:Number(r)})}},{name:"sliceBorderRight",type:"number",ui:{label:"Slice Right",group:"Skin",description:"Right 9-slice inset of the state skins (source px); 0 = stretch",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.right,setValue:(t,r)=>{t.setSliceBorder({right:Number(r)})}},{name:"sliceBorderTop",type:"number",ui:{label:"Slice Top",group:"Skin",description:"Top 9-slice inset of the state skins (source px); 0 = stretch",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.top,setValue:(t,r)=>{t.setSliceBorder({top:Number(r)})}},{name:"sliceBorderBottom",type:"number",ui:{label:"Slice Bottom",group:"Skin",description:"Bottom 9-slice inset of the state skins (source px); 0 = stretch",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.bottom,setValue:(t,r)=>{t.setSliceBorder({bottom:Number(r)})}},{name:"textureNormalKey",type:"string",ui:{label:"Normal Sprite Key",group:"Skin",editor:"localization-key",description:"Localization sprite key for the normal state (wins over the authored sprite when resolvable)"},getValue:t=>t.stateTextureKeys.normal??"",setValue:(t,r)=>{t.setStateTextureKey("normal",r)}},{name:"textureHoverKey",type:"string",ui:{label:"Hover Sprite Key",group:"Skin",editor:"localization-key",description:"Localization sprite key for the hover state"},getValue:t=>t.stateTextureKeys.hover??"",setValue:(t,r)=>{t.setStateTextureKey("hover",r)}},{name:"texturePressedKey",type:"string",ui:{label:"Pressed Sprite Key",group:"Skin",editor:"localization-key",description:"Localization sprite key for the pressed state"},getValue:t=>t.stateTextureKeys.pressed??"",setValue:(t,r)=>{t.setStateTextureKey("pressed",r)}},{name:"textureDisabledKey",type:"string",ui:{label:"Disabled Sprite Key",group:"Skin",editor:"localization-key",description:"Localization sprite key for the disabled state"},getValue:t=>t.stateTextureKeys.disabled??"",setValue:(t,r)=>{t.setStateTextureKey("disabled",r)}}],groups:{...e.groups,Button:{label:"Button",expanded:!0}}}}};var vr=class n extends te{width;height;handleSize;trackBackgroundColor;trackFilledColor;handleColor;minValue;maxValue;value;axisName;textureTrack;textureFill;textureThumb;sliceBorder;trackMesh;filledTrackMesh;handleMesh;trackMaterial;filledTrackMaterial;handleMaterial;trackGeometry;filledTrackGeometry;handleGeometry;slotTextures={track:null,fill:null,thumb:null};slotTextureSizes={track:{width:0,height:0},fill:{width:0,height:0},thumb:{width:0,height:0}};constructor(e){super(e,"Slider2D"),this.width=e.width??200,this.height=e.height??20,this.handleSize=e.handleSize??20,this.trackBackgroundColor=e.trackBackgroundColor??"#333333",this.trackFilledColor=e.trackFilledColor??"#4a9eff",this.handleColor=e.handleColor??"#ffffff",this.minValue=e.minValue??0,this.maxValue=e.maxValue??100,this.value=Math.max(this.minValue,Math.min(this.maxValue,e.value??50)),this.axisName=e.axisName??"Slider",this.textureTrack=D(e.textureTrack??null),this.textureFill=D(e.textureFill??null),this.textureThumb=D(e.textureThumb??null),this.sliceBorder=Ee(e.sliceBorder),this.trackGeometry=this.buildSlotGeometry("track",this.width,this.height),this.trackMaterial=new R({color:this.trackBackgroundColor,transparent:!0,opacity:1,depthTest:!1}),this.registerSkinMaterial(this.trackMaterial),this.trackMesh=new B(this.trackGeometry,this.trackMaterial),this.trackMesh.renderOrder=999,this.add(this.trackMesh),this.filledTrackGeometry=new z(0,this.height),this.filledTrackMaterial=new R({color:this.trackFilledColor,transparent:!0,opacity:1,depthTest:!1}),this.registerOpacityMaterial(this.filledTrackMaterial,1),this.filledTrackMesh=new B(this.filledTrackGeometry,this.filledTrackMaterial),this.filledTrackMesh.renderOrder=1e3,this.filledTrackMesh.position.z=.1,this.add(this.filledTrackMesh),this.handleGeometry=new z(this.handleSize,this.height),this.handleMaterial=new R({color:this.handleColor,transparent:!0,opacity:1,depthTest:!1}),this.registerOpacityMaterial(this.handleMaterial,1),this.handleMesh=new B(this.handleGeometry,this.handleMaterial),this.handleMesh.renderOrder=1001,this.handleMesh.position.z=.2,this.add(this.handleMesh),this.updateSliderVisuals(),G(this,n.getPropertySchema)}isPointInBounds(e){this.getWorldPosition(this.tmpWorldPos);let t=Math.abs(e.x-this.tmpWorldPos.x),r=Math.abs(e.y-this.tmpWorldPos.y);return t<=this.width/2&&r<=this.height/2}tick(e){super.tick(e),this.updatePointerStateFromInput()}capturesPointer(){return!0}onPointerDrag(e){this.updateSliderFromPointer(e.x)}get isDragging(){return this.isPressed}getInteractions(){let e={name:"value",type:"number",ui:{label:"Value",min:this.minValue,max:this.maxValue}};return[...super.getInteractions(),{name:"setValue",description:"Set the value programmatically (tests the reaction to a value change)",args:[e]},{name:"dragTo",description:"Grab the handle and drag it to a value (tests the drag itself)",args:[e]}]}performInteraction(e,t){switch(e){case"setValue":{let r=Qe(t,"value");return r===null||!this.canAcceptSemanticPointer()?!1:(this.setValue(r),!0)}case"dragTo":{let r=Qe(t,"value");return r===null?!1:this.dragHandleTo(r)}default:return super.performInteraction(e,t)}}dragHandleTo(e){let t=Math.max(this.minValue,Math.min(this.maxValue,e)),r=this.getSemanticPointerPoint(),i=this.worldXForValue(this.value),o=this.worldXForValue(t),s=(i+o)/2;return!this.runSemanticPointerFrame(r.set(i,r.y),!0,!0)||!this.runSemanticPointerFrame(r.set(s,r.y),!0,!0)||!this.runSemanticPointerFrame(r.set(o,r.y),!0,!0)?!1:this.runSemanticPointerFrame(r.set(o,r.y),!1,!1)}worldXForValue(e){this.getWorldPosition(this.tmpWorldPos);let t=this.maxValue-this.minValue,r=t===0?0:(e-this.minValue)/t;return this.tmpWorldPos.x+(r-.5)*this.width}updateSliderFromPointer(e){this.getWorldPosition(this.tmpWorldPos);let t=e-this.tmpWorldPos.x,r=Math.max(0,Math.min(1,(t+this.width/2)/this.width)),i=this.minValue+r*(this.maxValue-this.minValue);this.setValue(i)}setValue(e){let t=this.value;if(this.value=Math.max(this.minValue,Math.min(this.maxValue,e)),this.value!==t){this.updateSliderVisuals();let r=(this.value-this.minValue)/(this.maxValue-this.minValue);this.input?.setAxis(this.axisName,r)}}updateSliderVisuals(){let e=(this.value-this.minValue)/(this.maxValue-this.minValue),t=this.width*e;this.filledTrackGeometry.dispose(),this.filledTrackGeometry=this.buildSlotGeometry("fill",t,this.height),this.filledTrackMesh.geometry=this.filledTrackGeometry,this.filledTrackMesh.position.x=-this.width/2+t/2;let r=-this.width/2+t;this.handleMesh.position.x=r}buildSlotGeometry(e,t,r){let i=this.slotTextureSizes[e];return hr({width:t,height:r,textureWidth:i.width,textureHeight:i.height,border:e==="thumb"?null:this.sliceBorder})}rebuildTrackGeometry(){this.trackGeometry.dispose(),this.trackGeometry=this.buildSlotGeometry("track",this.width,this.height),this.trackMesh.geometry=this.trackGeometry,this.updateSliderVisuals()}setSliceBorder(e){this.sliceBorder=Ee({...this.sliceBorder,...e}),this.rebuildTrackGeometry()}setSlotTexture(e,t){t&&Y(t),this.slotTextures[e]=t;let r=t?.image!==void 0&&t.image!==null?$e(t.image):{};this.slotTextureSizes[e]={width:r.width??0,height:r.height??0};let i=this.materialForSlot(e);t?(i.map=t,i.color.set("#ffffff"),i.transparent=!0):(i.map=null,i.color.setStyle(this.colorForSlot(e))),i.needsUpdate=!0,e==="thumb"?(this.handleGeometry.dispose(),this.handleGeometry=new z(this.handleSize,this.height),this.handleMesh.geometry=this.handleGeometry):this.rebuildTrackGeometry()}getSlotTexturePath(e){switch(e){case"track":return this.textureTrack?.url??null;case"fill":return this.textureFill?.url??null;case"thumb":return this.textureThumb?.url??null}}materialForSlot(e){switch(e){case"track":return this.trackMaterial;case"fill":return this.filledTrackMaterial;case"thumb":return this.handleMaterial}}colorForSlot(e){switch(e){case"track":return this.trackBackgroundColor;case"fill":return this.trackFilledColor;case"thumb":return this.handleColor}}setSlotTextureRef(e,t){let r=D(t),i=this.getSlotTexturePath(e);switch(e){case"track":this.textureTrack=r;break;case"fill":this.textureFill=r;break;case"thumb":this.textureThumb=r;break}i!==(r?.url??null)&&this.setSlotTexture(e,null)}refreshSlotColor(e){this.slotTextures[e]||this.materialForSlot(e).color.setStyle(this.colorForSlot(e))}static getPropertySchema(){let e=te.getPropertySchema();return{nodeType:"Slider2D",extends:"UIControl2D",properties:[...e.properties,{name:"width",type:"number",ui:{label:"Width",group:"Slider",min:50,max:500,step:1},getValue:t=>t.width,setValue:(t,r)=>{let i=t;i.width=Number(r),i.rebuildTrackGeometry()}},{name:"height",type:"number",ui:{label:"Height",group:"Slider",min:5,max:100,step:1},getValue:t=>t.height,setValue:(t,r)=>{let i=t;i.height=Number(r),i.handleGeometry.dispose(),i.handleGeometry=new z(i.handleSize,i.height),i.handleMesh.geometry=i.handleGeometry,i.rebuildTrackGeometry()}},{name:"handleSize",type:"number",ui:{label:"Handle Size",group:"Slider",min:5,max:100,step:1},getValue:t=>t.handleSize,setValue:(t,r)=>{let i=t;i.handleSize=Number(r),i.handleGeometry.dispose(),i.handleGeometry=new z(i.handleSize,i.height),i.handleMesh.geometry=i.handleGeometry,i.updateSliderVisuals()}},{name:"value",type:"number",ui:{label:"Value",group:"Slider",step:.1},getValue:t=>t.value,setValue:(t,r)=>{t.setValue(Number(r))}},{name:"minValue",type:"number",ui:{label:"Min Value",group:"Slider",step:.1},getValue:t=>t.minValue,setValue:(t,r)=>{let i=t;i.minValue=Number(r),i.value<i.minValue&&i.setValue(i.minValue),i.updateSliderVisuals()}},{name:"maxValue",type:"number",ui:{label:"Max Value",group:"Slider",step:.1},getValue:t=>t.maxValue,setValue:(t,r)=>{let i=t;i.maxValue=Number(r),i.value>i.maxValue&&i.setValue(i.maxValue),i.updateSliderVisuals()}},{name:"trackBackgroundColor",type:"color",ui:{label:"Background Color",group:"Slider"},getValue:t=>t.trackBackgroundColor,setValue:(t,r)=>{let i=t;i.trackBackgroundColor=String(r),i.refreshSlotColor("track")}},{name:"trackFilledColor",type:"color",ui:{label:"Filled Color",group:"Slider"},getValue:t=>t.trackFilledColor,setValue:(t,r)=>{let i=t;i.trackFilledColor=String(r),i.refreshSlotColor("fill")}},{name:"handleColor",type:"color",ui:{label:"Handle Color",group:"Slider"},getValue:t=>t.handleColor,setValue:(t,r)=>{let i=t;i.handleColor=String(r),i.refreshSlotColor("thumb")}},{name:"textureTrack",type:"object",ui:{label:"Track Sprite",group:"Skin",description:"Sprite for the track background",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.textureTrack??{type:"texture",url:""},setValue:(t,r)=>{t.setSlotTextureRef("track",r)}},{name:"textureFill",type:"object",ui:{label:"Fill Sprite",group:"Skin",description:"Sprite for the filled portion of the track",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.textureFill??{type:"texture",url:""},setValue:(t,r)=>{t.setSlotTextureRef("fill",r)}},{name:"textureThumb",type:"object",ui:{label:"Thumb Sprite",group:"Skin",description:"Sprite for the draggable handle (never sliced)",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.textureThumb??{type:"texture",url:""},setValue:(t,r)=>{t.setSlotTextureRef("thumb",r)}},{name:"sliceBorderLeft",type:"number",ui:{label:"Slice Left",group:"Skin",description:"Left 9-slice inset of the track/fill sprites (source px); 0 = stretch",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.left,setValue:(t,r)=>{t.setSliceBorder({left:Number(r)})}},{name:"sliceBorderRight",type:"number",ui:{label:"Slice Right",group:"Skin",description:"Right 9-slice inset of the track/fill sprites (source px); 0 = stretch",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.right,setValue:(t,r)=>{t.setSliceBorder({right:Number(r)})}},{name:"sliceBorderTop",type:"number",ui:{label:"Slice Top",group:"Skin",description:"Top 9-slice inset of the track/fill sprites (source px); 0 = stretch",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.top,setValue:(t,r)=>{t.setSliceBorder({top:Number(r)})}},{name:"sliceBorderBottom",type:"number",ui:{label:"Slice Bottom",group:"Skin",description:"Bottom 9-slice inset of the track/fill sprites (source px); 0 = stretch",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.bottom,setValue:(t,r)=>{t.setSliceBorder({bottom:Number(r)})}},{name:"axisName",type:"string",ui:{label:"Axis Name",group:"Input",description:"Virtual axis name"},getValue:t=>t.axisName,setValue:(t,r)=>{t.axisName=String(r)}}],groups:{...e.groups,Slider:{label:"Slider",expanded:!0},Skin:{label:"Skin",description:"Sprites replacing the flat colours",expanded:!0}}}}};var wr=class n extends te{width;height;backBackgroundColor;barColor;minValue;maxValue;value;showBorder;borderColor;borderWidth;textureTrough;textureFill;sliceBorder;backgroundMesh;barMesh;borderMesh=null;backgroundMaterial;barMaterial;borderMaterial=null;backgroundGeometry;barGeometry;borderGeometry=null;slotTextures={trough:null,fill:null};slotTextureSizes={trough:{width:0,height:0},fill:{width:0,height:0}};constructor(e){super(e,"Bar2D"),this.width=e.width??150,this.height=e.height??20,this.backBackgroundColor=e.backBackgroundColor??"#333333",this.barColor=e.barColor??"#ff4444",this.minValue=e.minValue??0,this.maxValue=e.maxValue??100,this.value=Math.max(this.minValue,Math.min(this.maxValue,e.value??100)),this.showBorder=e.showBorder??!0,this.borderColor=e.borderColor??"#000000",this.borderWidth=e.borderWidth??2,this.textureTrough=D(e.textureTrough??null),this.textureFill=D(e.textureFill??null),this.sliceBorder=Ee(e.sliceBorder),this.backgroundGeometry=this.buildSlotGeometry("trough",this.width,this.height),this.backgroundMaterial=new R({color:this.backBackgroundColor,transparent:!0,opacity:1,depthTest:!1}),this.registerSkinMaterial(this.backgroundMaterial),this.backgroundMesh=new B(this.backgroundGeometry,this.backgroundMaterial),this.backgroundMesh.renderOrder=999,this.add(this.backgroundMesh),this.barGeometry=new z(0,this.height),this.barMaterial=new R({color:this.barColor,transparent:!0,opacity:1,depthTest:!1}),this.registerOpacityMaterial(this.barMaterial,1),this.barMesh=new B(this.barGeometry,this.barMaterial),this.barMesh.renderOrder=1e3,this.barMesh.position.z=.1,this.add(this.barMesh),this.showBorder&&this.createBorder(),this.updateBarVisuals(),G(this,n.getPropertySchema)}createBorder(){this.borderGeometry=this.buildBorderGeometry(),this.borderMaterial=new R({color:this.borderColor,transparent:!0,opacity:1,depthTest:!1,wireframe:!1}),this.registerOpacityMaterial(this.borderMaterial,1),this.borderMesh=new B(this.borderGeometry,this.borderMaterial),this.borderMesh.renderOrder=998,this.borderMesh.position.z=-.1,this.add(this.borderMesh)}buildBorderGeometry(){return new z(this.width+this.borderWidth*2,this.height+this.borderWidth*2)}rebuildBorderGeometry(){this.borderMesh&&(this.borderGeometry?.dispose(),this.borderGeometry=this.buildBorderGeometry(),this.borderMesh.geometry=this.borderGeometry)}isPointInBounds(e){return!1}setValue(e){let t=this.value;this.value=Math.max(this.minValue,Math.min(this.maxValue,e)),this.value!==t&&this.updateBarVisuals()}updateBarVisuals(){let e=(this.value-this.minValue)/(this.maxValue-this.minValue),t=Math.max(0,this.width*e);this.barGeometry.dispose(),this.barGeometry=this.buildSlotGeometry("fill",t,this.height),this.barMesh.geometry=this.barGeometry,this.barMesh.position.x=-this.width/2+t/2}buildSlotGeometry(e,t,r){let i=this.slotTextureSizes[e];return hr({width:t,height:r,textureWidth:i.width,textureHeight:i.height,border:this.sliceBorder})}rebuildTroughGeometry(){this.backgroundGeometry.dispose(),this.backgroundGeometry=this.buildSlotGeometry("trough",this.width,this.height),this.backgroundMesh.geometry=this.backgroundGeometry,this.rebuildBorderGeometry(),this.updateBarVisuals()}setSliceBorder(e){this.sliceBorder=Ee({...this.sliceBorder,...e}),this.rebuildTroughGeometry()}setSlotTexture(e,t){t&&Y(t),this.slotTextures[e]=t;let r=t?.image!==void 0&&t.image!==null?$e(t.image):{};this.slotTextureSizes[e]={width:r.width??0,height:r.height??0};let i=e==="trough"?this.backgroundMaterial:this.barMaterial;t?(i.map=t,i.color.set("#ffffff"),i.transparent=!0):(i.map=null,i.color.setStyle(e==="trough"?this.backBackgroundColor:this.barColor)),i.needsUpdate=!0,this.rebuildTroughGeometry()}getSlotTexturePath(e){return e==="trough"?this.textureTrough?.url??null:this.textureFill?.url??null}setSlotTextureRef(e,t){let r=D(t),i=this.getSlotTexturePath(e);e==="trough"?this.textureTrough=r:this.textureFill=r,i!==(r?.url??null)&&this.setSlotTexture(e,null)}refreshSlotColor(e){if(this.slotTextures[e])return;(e==="trough"?this.backgroundMaterial:this.barMaterial).color.setStyle(e==="trough"?this.backBackgroundColor:this.barColor)}static getPropertySchema(){let e=te.getPropertySchema();return{nodeType:"Bar2D",extends:"UIControl2D",properties:[...e.properties,{name:"width",type:"number",ui:{label:"Width",group:"Bar",min:20,max:500,step:1},getValue:t=>t.width,setValue:(t,r)=>{let i=t;i.width=Number(r),i.rebuildTroughGeometry()}},{name:"height",type:"number",ui:{label:"Height",group:"Bar",min:5,max:200,step:1},getValue:t=>t.height,setValue:(t,r)=>{let i=t;i.height=Number(r),i.rebuildTroughGeometry()}},{name:"value",type:"number",ui:{label:"Value",group:"Bar",step:.1},getValue:t=>t.value,setValue:(t,r)=>{t.setValue(Number(r))}},{name:"minValue",type:"number",ui:{label:"Min Value",group:"Bar",step:.1},getValue:t=>t.minValue,setValue:(t,r)=>{let i=t;i.minValue=Number(r),i.value<i.minValue&&i.setValue(i.minValue),i.updateBarVisuals()}},{name:"maxValue",type:"number",ui:{label:"Max Value",group:"Bar",step:.1},getValue:t=>t.maxValue,setValue:(t,r)=>{let i=t;i.maxValue=Number(r),i.value>i.maxValue&&i.setValue(i.maxValue),i.updateBarVisuals()}},{name:"backBackgroundColor",type:"color",ui:{label:"Background Color",group:"Bar"},getValue:t=>t.backBackgroundColor,setValue:(t,r)=>{let i=t;i.backBackgroundColor=String(r),i.refreshSlotColor("trough")}},{name:"barColor",type:"color",ui:{label:"Bar Color",group:"Bar"},getValue:t=>t.barColor,setValue:(t,r)=>{let i=t;i.barColor=String(r),i.refreshSlotColor("fill")}},{name:"textureTrough",type:"object",ui:{label:"Trough Sprite",group:"Skin",description:"Sprite for the empty trough behind the fill",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.textureTrough??{type:"texture",url:""},setValue:(t,r)=>{t.setSlotTextureRef("trough",r)}},{name:"textureFill",type:"object",ui:{label:"Fill Sprite",group:"Skin",description:"Sprite for the filled portion",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.textureFill??{type:"texture",url:""},setValue:(t,r)=>{t.setSlotTextureRef("fill",r)}},{name:"sliceBorderLeft",type:"number",ui:{label:"Slice Left",group:"Skin",description:"Left 9-slice inset of the trough/fill sprites (source px); 0 = stretch",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.left,setValue:(t,r)=>{t.setSliceBorder({left:Number(r)})}},{name:"sliceBorderRight",type:"number",ui:{label:"Slice Right",group:"Skin",description:"Right 9-slice inset of the trough/fill sprites (source px); 0 = stretch",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.right,setValue:(t,r)=>{t.setSliceBorder({right:Number(r)})}},{name:"sliceBorderTop",type:"number",ui:{label:"Slice Top",group:"Skin",description:"Top 9-slice inset of the trough/fill sprites (source px); 0 = stretch",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.top,setValue:(t,r)=>{t.setSliceBorder({top:Number(r)})}},{name:"sliceBorderBottom",type:"number",ui:{label:"Slice Bottom",group:"Skin",description:"Bottom 9-slice inset of the trough/fill sprites (source px); 0 = stretch",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.bottom,setValue:(t,r)=>{t.setSliceBorder({bottom:Number(r)})}},{name:"showBorder",type:"boolean",ui:{label:"Show Border",group:"Bar"},getValue:t=>t.showBorder,setValue:(t,r)=>{let i=t;i.showBorder=!!r,i.showBorder&&!i.borderMesh?i.createBorder():!i.showBorder&&i.borderMesh&&(i.remove(i.borderMesh),i.borderGeometry?.dispose(),i.borderMaterial?.dispose(),i.borderMesh=null,i.borderGeometry=null,i.borderMaterial=null)}},{name:"borderColor",type:"color",ui:{label:"Border Color",group:"Bar"},getValue:t=>t.borderColor,setValue:(t,r)=>{let i=t;i.borderColor=String(r),i.borderMaterial&&i.borderMaterial.color.setStyle(i.borderColor)}}],groups:{...e.groups,Bar:{label:"Bar",expanded:!0},Skin:{label:"Skin",description:"Sprites replacing the flat colours",expanded:!0}}}}};var xr=class n extends te{size;checked;uncheckedColor;checkedColor;checkmarkColor;checkmarkAction;textureBox;textureBoxChecked;textureMark;slotTextures={box:null,boxChecked:null,mark:null};boxMesh;boxMaterial;checkMesh=null;checkMaterial=null;geometry;checkGeometry=null;constructor(e){super(e,"Checkbox2D"),this.size=e.size??30,this.checked=e.checked??!1,this.uncheckedColor=e.uncheckedColor??"#ffffff",this.checkedColor=e.checkedColor??"#4a9eff",this.checkmarkColor=e.checkmarkColor??"#ffffff",this.checkmarkAction=e.checkmarkAction??"Checkbox",this.textureBox=D(e.textureBox??null),this.textureBoxChecked=D(e.textureBoxChecked??null),this.textureMark=D(e.textureMark??null),this.geometry=new z(this.size,this.size),this.boxMaterial=new R({color:this.checked?this.checkedColor:this.uncheckedColor,transparent:!0,opacity:1,depthTest:!1}),this.registerSkinMaterial(this.boxMaterial),this.boxMesh=new B(this.geometry,this.boxMaterial),this.boxMesh.renderOrder=999,this.add(this.boxMesh),this.checked&&this.createCheckmark(),e.labelAlign===void 0&&(this.labelAlign="left"),this.label.trim().length>0&&this.updateLabel(),G(this,n.getPropertySchema)}static LABEL_GAP=6;updateLabel(){super.updateLabel(),this.labelMesh&&(this.labelMesh.position.x=this.size/2+this.labelMesh.scale.x/2+n.LABEL_GAP,this.labelMesh.position.y=0)}createCheckmark(){let e=this.slotTextures.mark;this.checkGeometry=n.buildMarkGeometry(this.size,e!==null),this.checkMaterial=new R({color:e?"#ffffff":this.checkmarkColor,map:e,transparent:!0,opacity:1,depthTest:!1}),this.registerOpacityMaterial(this.checkMaterial,1),this.checkMesh=new B(this.checkGeometry,this.checkMaterial),this.checkMesh.renderOrder=1e3,this.checkMesh.position.z=.1,this.checkMesh.rotation.z=e?0:Math.PI/4,this.add(this.checkMesh)}static buildMarkGeometry(e,t){if(t)return new z(e,e);let r=e*.6;return new z(r,r*.5)}destroyCheckmark(){this.checkMesh&&(this.remove(this.checkMesh),this.checkGeometry?.dispose(),this.checkMaterial?.dispose(),this.checkMesh=null,this.checkGeometry=null,this.checkMaterial=null)}setSlotTexture(e,t){if(t&&Y(t),this.slotTextures[e]=t,e==="mark"){this.checked&&(this.destroyCheckmark(),this.createCheckmark());return}this.refreshBoxSkin()}getSlotTexturePath(e){switch(e){case"box":return this.textureBox?.url??null;case"boxChecked":return this.textureBoxChecked?.url??null;case"mark":return this.textureMark?.url??null}}setSlotTextureRef(e,t){let r=D(t),i=this.getSlotTexturePath(e);switch(e){case"box":this.textureBox=r;break;case"boxChecked":this.textureBoxChecked=r;break;case"mark":this.textureMark=r;break}i!==(r?.url??null)&&this.setSlotTexture(e,null)}resolveBoxTexture(){return this.checked?this.slotTextures.boxChecked??this.slotTextures.box:this.slotTextures.box}refreshBoxSkin(){if(!this.boxMaterial)return;let e=this.resolveBoxTexture(),t=this.boxMaterial.map!==null;e?(this.boxMaterial.map=e,this.boxMaterial.color.set("#ffffff"),this.boxMaterial.transparent=!0):(this.boxMaterial.map=null,this.boxMaterial.color.setStyle(this.checked?this.checkedColor:this.uncheckedColor)),t!==(e!==null)&&(this.boxMaterial.needsUpdate=!0)}isPointInBounds(e){this.getWorldPosition(this.tmpWorldPos);let t=e.x-this.tmpWorldPos.x,r=e.y-this.tmpWorldPos.y,i=this.size/2;return this.labelMesh&&(i=Math.max(i,this.labelMesh.position.x+this.labelMesh.scale.x/2)),t>=-this.size/2&&t<=i&&Math.abs(r)<=this.size/2}pendingActionRelease=!1;tick(e){super.tick(e),this.pendingActionRelease&&(this.pendingActionRelease=!1,this.input?.setButton(this.checkmarkAction,!1)),this.updatePointerStateFromInput()}onClick(){this.toggle()}getInteractions(){return[...super.getInteractions(),{name:"toggle",description:"Flip the checkbox by clicking it"},{name:"setChecked",description:"Click the checkbox only if that reaches the requested state",args:[{name:"checked",type:"boolean",ui:{label:"Checked",description:"Desired state after the interaction"}}]}]}performInteraction(e,t){switch(e){case"toggle":return this.runSemanticClick();case"setChecked":{let r=au(t,"checked");return r===null||!this.canAcceptSemanticPointer()?!1:this.checked===r?!0:this.runSemanticClick()}default:return super.performInteraction(e,t)}}toggle(){let e=!this.checked;this.input?.setButton(this.checkmarkAction,!0),this.input?.setAxis(this.checkmarkAction,e?1:0),this.pendingActionRelease=!0,this.applyChecked(e)}applyChecked(e){this.checked!==e&&(ri(this,"checked",e),this.updateCheckboxVisuals(),this.emit("toggled",e))}updateCheckboxVisuals(){this.refreshBoxSkin(),this.checked&&!this.checkMesh?this.createCheckmark():!this.checked&&this.checkMesh&&this.destroyCheckmark()}static getPropertySchema(){let e=te.getPropertySchema();return{nodeType:"Checkbox2D",extends:"UIControl2D",properties:[...e.properties,{name:"size",type:"number",ui:{label:"Size",group:"Checkbox",min:10,max:100,step:1},getValue:t=>t.size,setValue:(t,r)=>{let i=t;i.size=Number(r),i.geometry.dispose(),i.geometry=new z(i.size,i.size),i.boxMesh.geometry=i.geometry,i.checked&&i.checkGeometry&&(i.checkGeometry.dispose(),i.checkGeometry=n.buildMarkGeometry(i.size,i.slotTextures.mark!==null),i.checkMesh&&(i.checkMesh.geometry=i.checkGeometry))}},{name:"checked",type:"boolean",ui:{label:"Checked",group:"Checkbox"},getValue:t=>t.checked,setValue:(t,r)=>{t.applyChecked(!!r)}},{name:"uncheckedColor",type:"color",ui:{label:"Unchecked Color",group:"Checkbox"},getValue:t=>t.uncheckedColor,setValue:(t,r)=>{let i=t;i.uncheckedColor=String(r),i.refreshBoxSkin()}},{name:"checkedColor",type:"color",ui:{label:"Checked Color",group:"Checkbox"},getValue:t=>t.checkedColor,setValue:(t,r)=>{let i=t;i.checkedColor=String(r),i.refreshBoxSkin()}},{name:"checkmarkColor",type:"color",ui:{label:"Checkmark Color",group:"Checkbox"},getValue:t=>t.checkmarkColor,setValue:(t,r)=>{let i=t;i.checkmarkColor=String(r),i.checkMaterial&&!i.slotTextures.mark&&i.checkMaterial.color.setStyle(i.checkmarkColor)}},{name:"textureBox",type:"object",ui:{label:"Box Sprite",group:"Skin",description:"Sprite for the box (also the checked fallback)",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.textureBox??{type:"texture",url:""},setValue:(t,r)=>{t.setSlotTextureRef("box",r)}},{name:"textureBoxChecked",type:"object",ui:{label:"Checked Box Sprite",group:"Skin",description:"Optional sprite for the box while checked",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.textureBoxChecked??{type:"texture",url:""},setValue:(t,r)=>{t.setSlotTextureRef("boxChecked",r)}},{name:"textureMark",type:"object",ui:{label:"Mark Sprite",group:"Skin",description:"Sprite drawn over the box while checked",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.textureMark??{type:"texture",url:""},setValue:(t,r)=>{t.setSlotTextureRef("mark",r)}},{name:"checkmarkAction",type:"string",ui:{label:"Action",group:"Input",description:"Virtual button/axis name"},getValue:t=>t.checkmarkAction,setValue:(t,r)=>{t.checkmarkAction=String(r)}}],groups:{...e.groups,Checkbox:{label:"Checkbox",expanded:!0},Skin:{label:"Skin",description:"Sprites replacing the flat colours",expanded:!0}}}}};var Pr=class n extends te{width;height;backdropColor;borderColor;borderWidth;quantity;showQuantity;quantityFontSize;selectionColor;selectedAction;selected=!1;slotMesh;slotMaterial;borderMesh=null;borderMaterial=null;quantityMesh=null;quantityTexture=null;slotGeometry;borderGeometry=null;constructor(e){super(e,"InventorySlot2D"),this.width=e.width??60,this.height=e.height??60,this.backdropColor=e.backdropColor??"#555555",this.borderColor=e.borderColor??"#888888",this.borderWidth=e.borderWidth??2,this.quantity=Math.max(0,e.quantity??0),this.showQuantity=e.showQuantity??!0,this.quantityFontSize=e.quantityFontSize??12,this.selectionColor=e.selectionColor??"#ffff00",this.selectedAction=e.selectedAction??"SlotSelected",this.slotGeometry=new z(this.width,this.height),this.slotMaterial=new R({color:this.backdropColor,transparent:!0,opacity:1,depthTest:!1}),this.registerSkinMaterial(this.slotMaterial),this.slotMesh=new B(this.slotGeometry,this.slotMaterial),this.slotMesh.renderOrder=999,this.add(this.slotMesh),this.createBorder(),this.showQuantity&&this.quantity>0&&this.updateQuantityDisplay(),G(this,n.getPropertySchema)}createBorder(){this.borderGeometry=new z(this.width,this.height),this.borderMaterial=new R({color:this.borderColor,transparent:!0,opacity:1,depthTest:!1,wireframe:!1}),this.registerOpacityMaterial(this.borderMaterial,1),this.borderMesh=new B(this.borderGeometry,this.borderMaterial),this.borderMesh.renderOrder=1e3,this.borderMesh.position.z=.1,this.add(this.borderMesh)}createQuantityTexture(){let e=document.createElement("canvas");e.width=64,e.height=64;let t=e.getContext("2d");if(!t)throw new Error("Could not get canvas 2D context");t.fillStyle="rgba(0, 0, 0, 0)",t.fillRect(0,0,64,64),t.fillStyle="#ffffff",t.font=`bold ${this.quantityFontSize}px Arial`,t.textAlign="right",t.textBaseline="bottom",t.fillText(String(this.quantity),60,60);let r=new Mt(e);return Y(r),r}updateQuantityDisplay(){if(!this.showQuantity||this.quantity<=0){this.quantityMesh&&(this.remove(this.quantityMesh),this.quantityMesh=null,this.quantityTexture?.dispose(),this.quantityTexture=null);return}if(this.quantityTexture?.dispose(),this.quantityTexture=this.createQuantityTexture(),!this.quantityMesh){let t=new R({map:this.quantityTexture,transparent:!0,depthTest:!1});this.registerOpacityMaterial(t,1);let r=new z(this.width*.8,this.height*.8);this.quantityMesh=new B(r,t),this.quantityMesh.renderOrder=1001,this.quantityMesh.position.z=.2,this.add(this.quantityMesh);return}let e=this.quantityMesh.material;e.map=this.quantityTexture,e.needsUpdate=!0}isPointInBounds(e){this.getWorldPosition(this.tmpWorldPos);let t=Math.abs(e.x-this.tmpWorldPos.x),r=Math.abs(e.y-this.tmpWorldPos.y);return t<=this.width/2&&r<=this.height/2}tick(e){super.tick(e),this.updatePointerStateFromInput()}onClick(){this.select()}getInteractions(){return[...super.getInteractions(),{name:"activate",description:"Click the slot to select/deselect it"}]}performInteraction(e,t){return e==="activate"?this.runSemanticClick():super.performInteraction(e,t)}select(){this.selected=!this.selected,this.updateSlotVisuals(),this.input?.setButton(this.selectedAction,this.selected),this.emit("toggled",this.selected)}setQuantity(e){this.quantity=Math.max(0,e),this.updateQuantityDisplay()}updateSlotVisuals(){this.selected?(this.slotMaterial.color.setStyle(this.selectionColor),this.borderMaterial&&this.borderMaterial.color.setStyle(this.selectionColor)):(this.slotMaterial.color.setStyle(this.backdropColor),this.borderMaterial&&this.borderMaterial.color.setStyle(this.borderColor))}static getPropertySchema(){let e=te.getPropertySchema();return{nodeType:"InventorySlot2D",extends:"UIControl2D",properties:[...e.properties,{name:"width",type:"number",ui:{label:"Width",group:"Slot",min:20,max:200,step:1},getValue:t=>t.width,setValue:(t,r)=>{let i=t;i.width=Number(r),i.slotGeometry.dispose(),i.slotGeometry=new z(i.width,i.height),i.slotMesh.geometry=i.slotGeometry,i.borderGeometry&&(i.borderGeometry.dispose(),i.borderGeometry=new z(i.width,i.height),i.borderMesh&&(i.borderMesh.geometry=i.borderGeometry))}},{name:"height",type:"number",ui:{label:"Height",group:"Slot",min:20,max:200,step:1},getValue:t=>t.height,setValue:(t,r)=>{let i=t;i.height=Number(r),i.slotGeometry.dispose(),i.slotGeometry=new z(i.width,i.height),i.slotMesh.geometry=i.slotGeometry,i.borderGeometry&&(i.borderGeometry.dispose(),i.borderGeometry=new z(i.width,i.height),i.borderMesh&&(i.borderMesh.geometry=i.borderGeometry))}},{name:"quantity",type:"number",ui:{label:"Quantity",group:"Slot",min:0,step:1},getValue:t=>t.quantity,setValue:(t,r)=>{t.setQuantity(Number(r))}},{name:"showQuantity",type:"boolean",ui:{label:"Show Quantity",group:"Slot"},getValue:t=>t.showQuantity,setValue:(t,r)=>{let i=t;i.showQuantity=!!r,i.updateQuantityDisplay()}},{name:"backdropColor",type:"color",ui:{label:"Backdrop Color",group:"Slot"},getValue:t=>t.backdropColor,setValue:(t,r)=>{let i=t;i.backdropColor=String(r),i.selected||i.slotMaterial.color.setStyle(i.backdropColor)}},{name:"borderColor",type:"color",ui:{label:"Border Color",group:"Slot"},getValue:t=>t.borderColor,setValue:(t,r)=>{let i=t;i.borderColor=String(r),!i.selected&&i.borderMaterial&&i.borderMaterial.color.setStyle(i.borderColor)}},{name:"selectionColor",type:"color",ui:{label:"Selection Color",group:"Slot"},getValue:t=>t.selectionColor,setValue:(t,r)=>{t.selectionColor=String(r)}},{name:"selectedAction",type:"string",ui:{label:"Selection Action",group:"Input",description:"Virtual button name"},getValue:t=>t.selectedAction,setValue:(t,r)=>{t.selectedAction=String(r)}}],groups:{...e.groups,Slot:{label:"Slot",expanded:!0}}}}};var du=["left","center","right"],Ms=["top","middle","bottom"],Mf=1.25,Ds=4,di=4;function hu(n,e){return!(e>0)||!(n>0)?0:n*.35*Math.min(e,di)}function Df(n){return n>0?Math.min(3,Math.max(1,Math.ceil(n))):0}function pu(n,e=0,t=0,r){return cn({glowBlur:hu(n,e),outlineWidth:t,shadowColor:r?.color??null,shadowOffsetX:r?.offsetX??0,shadowOffsetY:r?.offsetY??0,shadowBlur:r?.blur??0})}function mu(n,e,t){let r=t.maxWidth&&t.maxWidth>0?t.maxWidth:0,i=t.fontSize*(t.lineHeightFactor??Mf),o=[],s=c=>{o.push({text:c,width:c.length>0?e(c):0})};for(let c of n.split(`
|
|
195
|
-
`)){if(r<=0||c.length===0||e(c)<=r){s(c);continue}let u="";for(let d of c.split(" ")){let h=u.length>0?`${u} ${d}`:d;if(e(h)<=r||u.length===0){u=h;continue}s(u),u=d}for(;u.length>1&&e(u)>r;){let d=u.length-1;for(;d>1&&e(u.slice(0,d))>r;)d-=1;s(u.slice(0,d)),u=u.slice(d)}s(u)}let a=0,l=0;for(let c of o)a=Math.max(a,c.width),l+=c.text.length;return{lines:o,lineHeight:i,textWidth:a,textHeight:o.length*i,totalChars:l}}function fu(n,e){let{layout:t,width:r,height:i}=e,o=e.paddingX??0,s=e.paddingY??0;n.clearRect(0,0,r,i),n.fillStyle=e.color,Sr(n,{fontSize:e.fontSize,fontFamily:e.fontFamily,fontWeight:e.fontWeight,letterSpacing:e.letterSpacing}),n.textBaseline="middle";let a=r/2;e.align==="left"?(n.textAlign="left",a=o):e.align==="right"?(n.textAlign="right",a=r-o):n.textAlign="center";let l=(i-t.textHeight)/2;e.vAlign==="top"?l=s:e.vAlign==="bottom"&&(l=i-s-t.textHeight);let c=Math.min(di,Math.max(0,e.glowStrength??0)),u=hu(e.fontSize,c),d=Df(c),h=e.glowColor?.trim()?e.glowColor:e.color,p={color:e.color,outlineWidth:e.outlineWidth,outlineColor:e.outlineColor,shadowColor:e.shadowColor,shadowOffsetX:e.shadowOffsetX,shadowOffsetY:e.shadowOffsetY,shadowBlur:e.shadowBlur,glowColor:h,glowBlur:u,glowPasses:d},f=e.visibleCharacters??1/0;for(let m=0;m<t.lines.length&&!(f<=0);m++){let g=t.lines[m].text,y=f>=g.length?g:g.slice(0,Math.max(0,Math.floor(f)));if(f-=g.length,y.length===0)continue;let b=l+m*t.lineHeight+t.lineHeight/2;ln(n,y,a,b,p)}}var ft=class n extends te{width;height;labelVAlign;typewriterSpeed;glowColor;glowStrength;outlineColor;outlineWidth;renderState=null;typewriterVisible=0;typewriterActive=!1;labelKeyParams=null;constructor(e){super(e,"Label2D"),this.width=e.width??0,this.height=e.height??0,this.labelVAlign=e.labelVAlign??"middle",this.typewriterSpeed=e.typewriterSpeed??0,this.glowColor=e.glowColor??"#ffffff",this.glowStrength=n.clampGlowStrength(e.glowStrength??0),this.outlineColor=e.outlineColor??e.labelOutlineColor??"#000000",this.outlineWidth=Math.max(0,e.outlineWidth??e.labelOutlineWidth??0),this.updateLabel(),G(this,n.getPropertySchema)}get labelOutlineWidth(){return this.outlineWidth??0}set labelOutlineWidth(e){let t=Math.max(0,Number.isFinite(e)?e:0);this.outlineWidth!==t&&(this.outlineWidth=t,this.updateLabel())}get labelOutlineColor(){return this.outlineColor??"#000000"}set labelOutlineColor(e){this.outlineColor!==e&&(this.outlineColor=e,this.updateLabel())}getDisplayText(){return this.labelKey?Zi(this.labelKey,this.label,this.labelKeyParams??void 0):this.label}setText(e){this.labelKey===""&&this.label===e||(this.labelKeyParams=null,this.labelKey="",this.label=e,this.updateLabel())}setTextKey(e,t){this.labelKeyParams=t??null,this.labelKey=e,this.updateLabel()}get isTyping(){return this.typewriterActive}skipTypewriter(){this.typewriterActive&&(this.typewriterVisible=this.renderState?.layout.totalChars??0,this.finishTypewriter())}restartTypewriter(){this.typewriterSpeed<=0||!this.renderState||(this.typewriterVisible=0,this.typewriterActive=this.renderState.layout.totalChars>0,this.repaint())}tick(e){if(super.tick(e),this.typewriterActive&&this.typewriterSpeed>0&&this.renderState){let t=Math.floor(this.typewriterVisible);this.typewriterVisible+=e*this.typewriterSpeed,this.typewriterVisible>=this.renderState.layout.totalChars?this.finishTypewriter():Math.floor(this.typewriterVisible)!==t&&this.repaint()}this.updatePointerStateFromInput()}isPointInBounds(e){let t=this.renderState;if(!t)return!1;this.getWorldPosition(this.tmpWorldPos);let r=Math.abs(e.x-this.tmpWorldPos.x),i=Math.abs(e.y-this.tmpWorldPos.y);return r<=(t.boxWidth-t.pad*2)/2&&i<=(t.boxHeight-t.pad*2)/2}updateLabel(){let e=this.getDisplayText();if(e.length===0){this.renderState=null,this.typewriterActive=!1,this.labelMesh&&(this.remove(this.labelMesh),this.labelMesh=null),this.labelTexture?.dispose(),this.labelTexture=null;return}let t=this.width??0,r=this.height??0,i=Math.max(1,this.labelFontSize||16),o=this.renderState?.canvas??document.createElement("canvas"),s=this.renderState?.ctx??o.getContext("2d");if(!s)throw new Error("Could not get canvas 2D context");Sr(s,{fontSize:i,fontFamily:this.labelFontFamily,fontWeight:this.labelFontWeight,letterSpacing:this.labelLetterSpacing});let a=mu(e,b=>s.measureText(b).width,{fontSize:i,maxWidth:t>0?t:0}),l=pu(i,this.glowStrength??0,this.outlineWidth??0,{color:this.labelShadowColor,offsetX:this.labelShadowOffsetX,offsetY:this.labelShadowOffsetY}),c=(t>0?t:Math.ceil(a.textWidth)+Ds)+l*2,u=(r>0?r:Math.ceil(a.textHeight)+Ds)+l*2,d=typeof window<"u"&&window.devicePixelRatio||1,h=Math.max(1,Math.min(3,d)),p=Math.max(1,Math.round(c*h)),f=Math.max(1,Math.round(u*h)),m=o.width!==p||o.height!==f;m&&(o.width=p,o.height=f),s.setTransform(h,0,0,h,0,0);let g=this.renderState?.text!==e;this.renderState={canvas:o,ctx:s,layout:a,boxWidth:c,boxHeight:u,text:e,pad:l};let y=(this.typewriterSpeed??0)>0;if(g?(this.typewriterVisible=0,this.typewriterActive=y&&a.totalChars>0):y||(this.typewriterActive=!1),(!this.labelTexture||this.labelTexture.image!==o||m)&&(this.labelTexture?.dispose(),this.labelTexture=new Mt(o),Y(this.labelTexture)),this.labelTexture.userData={...this.labelTexture.userData??{},logicalWidth:c,logicalHeight:u,dpr:h},this.labelMesh){let b=this.labelMesh.material;b.map=this.labelTexture,b.needsUpdate=!0}else{let b=new R({map:this.labelTexture,transparent:!0,depthTest:!1});this.registerOpacityMaterial(b,1),this.labelMesh=new B(new z(1,1),b),this.labelMesh.renderOrder=1001,this.labelMesh.position.z=2,this.add(this.labelMesh)}this.labelMesh.scale.set(c,u,1),this.repaint()}finishTypewriter(){this.typewriterVisible=this.renderState?.layout.totalChars??0,this.typewriterActive=!1,this.repaint(),this.emit("typewriter-complete")}repaint(){let e=this.renderState;!e||!this.labelTexture||(fu(e.ctx,{layout:e.layout,fontFamily:this.labelFontFamily,fontSize:Math.max(1,this.labelFontSize||16),color:this.labelColor,align:this.labelAlign,vAlign:this.labelVAlign??"middle",width:e.boxWidth,height:e.boxHeight,paddingX:e.pad,paddingY:e.pad,visibleCharacters:this.typewriterActive?Math.floor(this.typewriterVisible):1/0,glowColor:this.glowColor,glowStrength:this.glowStrength??0,outlineColor:this.outlineColor,outlineWidth:this.outlineWidth??0,fontWeight:this.labelFontWeight,shadowColor:this.labelShadowColor,shadowOffsetX:this.labelShadowOffsetX,shadowOffsetY:this.labelShadowOffsetY,letterSpacing:this.labelLetterSpacing}),this.labelTexture.needsUpdate=!0)}static getPropertySchema(){let e=te.getPropertySchema(),t=new Set(["labelOutlineWidth","labelOutlineColor"]);return{nodeType:"Label2D",extends:"UIControl2D",properties:[...e.properties.filter(i=>!t.has(i.name)).map(i=>i.name==="labelAlign"?{...i,type:"enum",ui:{...i.ui,options:[...du]}}:i),{name:"width",type:"number",ui:{label:"Width",group:"Label",min:0,step:1,unit:"px",description:"Fixed box width; text word-wraps to it. 0 = auto-size, no wrapping"},getValue:i=>i.width,setValue:(i,o)=>{let s=i;s.width=Math.max(0,Number(o)||0),s.updateLabel()}},{name:"height",type:"number",ui:{label:"Height",group:"Label",min:0,step:1,unit:"px",description:"Fixed box height for vertical alignment. 0 = auto-size to the lines"},getValue:i=>i.height,setValue:(i,o)=>{let s=i;s.height=Math.max(0,Number(o)||0),s.updateLabel()}},{name:"labelVAlign",type:"enum",ui:{label:"V-Alignment",group:"Label",options:[...Ms],description:"Vertical text placement inside a fixed-height box"},getValue:i=>i.labelVAlign,setValue:(i,o)=>{let s=i,a=String(o);Ms.includes(a)&&(s.labelVAlign=a,s.updateLabel())}},{name:"typewriterSpeed",type:"number",ui:{label:"Typewriter Speed",group:"Label",min:0,step:1,unit:"chars/s",description:"Reveal the text character by character in play mode; 0 = off"},getValue:i=>i.typewriterSpeed,setValue:(i,o)=>{let s=i;s.typewriterSpeed=Math.max(0,Number(o)||0),s.restartTypewriter()}},{name:"glowColor",type:"color",ui:{label:"Glow Color",group:"Label",description:"Colour of the canvas glow; only visible while Glow Strength > 0"},getValue:i=>i.glowColor,setValue:(i,o)=>{let s=i;s.glowColor=String(o),s.updateLabel()}},{name:"glowStrength",type:"number",ui:{label:"Glow Strength",group:"Label",min:0,max:di,step:.1,precision:2,description:"Neon glow around the glyphs (canvas shadow); 0 = off. Works on HUD text, which never blooms"},getValue:i=>i.glowStrength,setValue:(i,o)=>{let s=i;s.glowStrength=n.clampGlowStrength(Number(o)),s.updateLabel()}},{name:"outlineColor",type:"color",ui:{label:"Outline Color",group:"Label",description:"Colour of the outline; only visible while Outline Width > 0"},getValue:i=>i.outlineColor,setValue:(i,o)=>{let s=i;s.outlineColor=String(o),s.updateLabel()}},{name:"outlineWidth",type:"number",ui:{label:"Outline Width",group:"Label",min:0,max:16,step:.5,precision:2,unit:"px",description:"Contrast outline drawn under the text; 0 = off"},getValue:i=>i.outlineWidth,setValue:(i,o)=>{let s=i;s.outlineWidth=Math.max(0,Number(o)||0),s.updateLabel()}}],groups:{...e.groups,Label:{...e.groups?.Label,label:"Label",expanded:!0}}}}static clampGlowStrength(e){return Number.isFinite(e)?Math.min(di,Math.max(0,e)):0}};var gt=class n extends V{audioTrack;autoplay;loop;volume;bus;pitchVariation;volumeVariation;playback=null;autoPlayed=!1;constructor(e){super({...e,type:"AudioPlayer"}),this.audioTrack=n.normalizeTrack(e.audioTrack??this.properties.audioTrack),this.autoplay=n.toBoolean(e.autoplay??this.properties.autoplay,!1),this.loop=n.toBoolean(e.loop??this.properties.loop,!1),this.volume=n.clampVolume(e.volume??this.properties.volume,1),this.bus=n.normalizeBus(e.bus??this.properties.bus),this.pitchVariation=n.clampVariation(e.pitchVariation??this.properties.pitchVariation),this.volumeVariation=n.clampVariation(e.volumeVariation??this.properties.volumeVariation),G(this,n.getPropertySchema)}get treeIcon(){return"speaker"}tick(e){super.tick(e),!this.autoPlayed&&this.autoplay&&(this.autoPlayed=!0,this.play())}async play(){if(!this.audioTrack){console.warn(`[AudioPlayer] Node "${this.name}" has no audio track configured.`);return}let e=this.scene;if(!e){console.warn(`[AudioPlayer] Node "${this.name}" is not attached to a running scene.`);return}let t=e.getAssetLoader(),r=e.getAudioService();if(!t||!r){console.warn("[AudioPlayer] Audio services are not available in the current runtime context.");return}try{let i=await t.loadAudio(this.audioTrack),o=e.getAudioService();if(!o)return;let s=t.getAudioMetadata(this.audioTrack);this.stop(),this.playback=o.play(i,{resourcePath:this.audioTrack,sizeBytes:s?.sizeBytes,loop:this.loop,volume:this.volume,bus:this.bus,pitchVariation:this.pitchVariation,volumeVariation:this.volumeVariation})}catch(i){console.warn(`[AudioPlayer] Failed to play "${this.audioTrack}":`,i)}}stop(){this.playback?.stop(),this.playback=null}serializeConfig(){return{audioTrack:this.audioTrack??void 0,autoplay:this.autoplay,loop:this.loop,volume:this.volume,bus:this.bus,pitchVariation:this.pitchVariation,volumeVariation:this.volumeVariation}}static getPropertySchema(){let e=V.getPropertySchema();return{nodeType:"AudioPlayer",extends:"NodeBase",properties:[...e.properties,{name:"audioTrack",type:"string",ui:{label:"Audio Track",description:"Asset URL (res://..., data:audio/..., or absolute URL)",group:"Audio",editor:"audio-resource"},getValue:t=>t.audioTrack??"",setValue:(t,r)=>{t.audioTrack=n.normalizeTrack(r)}},{name:"autoplay",type:"boolean",ui:{label:"Autoplay",group:"Audio"},getValue:t=>t.autoplay,setValue:(t,r)=>{let i=t;i.autoplay=n.toBoolean(r,!1),i.autoplay||(i.autoPlayed=!1)}},{name:"loop",type:"boolean",ui:{label:"Loop",group:"Audio"},getValue:t=>t.loop,setValue:(t,r)=>{t.loop=n.toBoolean(r,!1)}},{name:"volume",type:"number",ui:{label:"Volume",group:"Audio",min:0,max:1,step:.01,precision:2},getValue:t=>t.volume,setValue:(t,r)=>{t.volume=n.clampVolume(r,1)}},{name:"bus",type:"enum",ui:{label:"Bus",group:"Audio",options:[...ut]},getValue:t=>t.bus,setValue:(t,r)=>{t.bus=n.normalizeBus(r)}},{name:"pitchVariation",type:"number",ui:{label:"Pitch Variation",description:"Random \xB1 playback-rate spread per shot",group:"Audio",min:0,max:1,step:.01,precision:2},getValue:t=>t.pitchVariation,setValue:(t,r)=>{t.pitchVariation=n.clampVariation(r)}},{name:"volumeVariation",type:"number",ui:{label:"Volume Variation",description:"Random \xB1 volume spread per shot",group:"Audio",min:0,max:1,step:.01,precision:2},getValue:t=>t.volumeVariation,setValue:(t,r)=>{t.volumeVariation=n.clampVariation(r)}}],groups:{...e.groups,Audio:{label:"Audio",expanded:!0}}}}static normalizeTrack(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}static toBoolean(e,t){if(typeof e=="boolean")return e;if(typeof e=="string"){let r=e.trim().toLowerCase();if(r==="true")return!0;if(r==="false")return!1}return t}static clampVolume(e,t){let r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?Math.min(1,Math.max(0,r)):t}static normalizeBus(e){return typeof e=="string"&&ut.includes(e)?e:"sfx"}static clampVariation(e){let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?Math.min(1,Math.max(0,t)):0}};var kr=["standard","lambert","basic"],gu="standard",Ar=n=>typeof n=="string"&&kr.includes(n)?n:gu,yu=n=>n==="basic"?"basic":"standard",bu=n=>{let e=n;return e?.isMeshStandardMaterial===!0||e?.isMeshPhysicalMaterial===!0?"standard":e?.isMeshLambertMaterial===!0?"lambert":e?.isMeshBasicMaterial===!0?"basic":null},Tr=(n,e)=>{switch(n){case"basic":return new R({color:e.color});case"lambert":return new pm({color:e.color});default:return new sr({color:e.color,roughness:e.roughness,metalness:e.metalness})}};var Su=["box","sphere","plane","cylinder","cone","torus"],yt=class n extends U{_geometry;_material;_geometryKind;_size;_aoMapSrc;_aoMapIntensity=1;_aoSuppressed=!1;_mapSrc="";_materialType;effectStack;constructor(e){super(e,"GeometryMesh");let t=Nf(e.geometry),r=e.size??[1,1,1];this._geometryKind=t,this._size=[r[0],r[1],r[2]];let i=n.buildGeometry(t,this._size),o=e.material??{},s=new L(o.color??"#4e8df5"),a=typeof o.roughness=="number"?o.roughness:.35,l=typeof o.metalness=="number"?o.metalness:.25;this._materialType=Ar(o.type),this.effectStack=new Oe({nodeType:"GeometryMesh",target:yu(this._materialType)});let c=Tr(this._materialType,{color:s,roughness:a,metalness:l});this._aoMapIntensity=typeof o.aoMapIntensity=="number"?Ef(o.aoMapIntensity):1,c.aoMapIntensity=this._aoMapIntensity,this.installEffectComposer(c);let u=new B(i,c);this.castShadow=e.castShadow??!0,this.receiveShadow=e.receiveShadow??!0,u.castShadow=this.castShadow,u.receiveShadow=this.receiveShadow,u.name=`${this.name}-Mesh`,this.add(u),this._geometry=i,this._material=c,this._aoMapSrc=typeof o.aoMap=="string"?o.aoMap:"",this._mapSrc=typeof o.map=="string"?o.map:"";for(let d of o.effects??[])d&&typeof d.type=="string"&&this.attachEffect(d.type,{enabled:d.enabled,params:d.params})}disposeResources(){try{this._geometry?.dispose()}catch{}try{this._material?.dispose?.()}catch{}}static buildGeometry(e,t){let r=Math.max(1e-4,t[0]),i=Math.max(1e-4,t[1]),o=Math.max(1e-4,t[2]);switch(e){case"sphere":return new Yo(r/2,32,16);case"plane":{let s=new z(r,o);return s.rotateX(-Math.PI/2),s}case"cylinder":return new cm(r/2,r/2,i,32);case"cone":return new um(r/2,i,32);case"torus":{let s=r/2,a=Math.max(.02,Math.min(s*.6,i*.25));return new dm(s,a,20,40)}default:return new Jr(r,i,o)}}get materialType(){return this._materialType}set materialType(e){let t=Ar(e);if(t===this._materialType)return;let r=this._material,i=this._colorMaterial?.color.clone()??new L("#4e8df5"),o=this._colorMaterial?.map??null,s=this._stdMaterial,a=Tr(t,{color:i,roughness:s?.roughness??.35,metalness:s?.metalness??.25});this._materialType=t,this.effectStack.retarget(yu(t)),r&&this.effectStack.uninstall(r),this.installEffectComposer(a);let l=a;o&&(l.map=o);let c=s?.aoMap??null;c&&(l.aoMap=c,a.aoMapIntensity=this._aoSuppressed?0:this._aoMapIntensity);let u=this._mesh;u&&(u.material=a),this._material=a,a.needsUpdate=!0;try{r?.dispose?.()}catch{}}rebuildGeometry(){let e=n.buildGeometry(this._geometryKind,this._size),t=this._geometry,r=this._mesh;r&&(r.geometry=e),this._geometry=e,this._colorMaterial?.aoMap&&n.applyLightmapUV(this._geometryKind,e);try{t?.dispose()}catch{}}ensureLightmapUV(){n.applyLightmapUV(this._geometryKind,this._geometry)}get renderMesh(){return this._mesh}setAOMap(e){let t=this._colorMaterial;t&&(e&&(e.channel=1,e.flipY=!1,n.applyLightmapUV(this._geometryKind,this._geometry)),t.aoMap=e,t.needsUpdate=!0)}get aoMapIntensity(){return this._aoMapIntensity}set aoMapIntensity(e){this._aoMapIntensity=Ef(e);let t=this._colorMaterial;t&&!this._aoSuppressed&&(t.aoMapIntensity=this._aoMapIntensity)}setAOSuppressed(e){this._aoSuppressed=e;let t=this._colorMaterial;t&&(t.aoMapIntensity=e?0:this._aoMapIntensity)}get aoMapSrc(){return this._aoMapSrc}set aoMapSrc(e){this._aoMapSrc=typeof e=="string"?e:""}setMap(e){let t=this._colorMaterial;t&&(e&&(e.colorSpace=Pe),t.map=e,t.needsUpdate=!0)}setMapResource(e){this._mapSrc=Ux(e)}get mapSrc(){return this._mapSrc}set mapSrc(e){this._mapSrc=typeof e=="string"?e:""}getShaderEffectStack(){return this.effectStack}installEffectComposer(e){this.effectStack.install(e)}attachEffect(e,t){return this.effectStack.attach(e,t)}detachEffect(e){return this.effectStack.detach(e)}setEffectEnabled(e,t){this.effectStack.setEnabled(e,t)}getAttachedEffects(){return this.effectStack.getAttached()}getInstancePropertySchema(){return this.effectStack.buildInstanceSchema()}tick(e){this.effectStack.tick(e),super.tick(e)}static applyLightmapUV(e,t){if(!t)return;let r=t.getAttribute("uv");if(r){if(e==="box"){let s=.3333333333333333,a=1/2,l=.04,c=new Float32Array(r.count*2);for(let u=0;u<r.count;u+=1){let d=Math.floor(u/4)%6,h=d%3,p=Math.floor(d/3),f=r.getX(u),m=r.getY(u);c[u*2]=(h+l+f*(1-2*l))*s,c[u*2+1]=(p+l+m*(1-2*l))*a}t.setAttribute("uv1",new J(c,2));return}t.setAttribute("uv1",new J(r.array.slice(0),r.itemSize))}}get geometryKind(){return this._geometryKind}set geometryKind(e){let t=Nf(e);t!==this._geometryKind&&(this._geometryKind=t,this.rebuildGeometry())}get size(){return[this._size[0],this._size[1],this._size[2]]}set size(e){this._size=[Number.isFinite(e[0])?e[0]:this._size[0],Number.isFinite(e[1])?e[1]:this._size[1],Number.isFinite(e[2])?e[2]:this._size[2]],this.rebuildGeometry()}serializeConfig(){let e=this._colorMaterial,t={type:this._materialType};e&&(t.color="#"+e.color.getHexString());let r=this._stdMaterial;return r&&(t.roughness=r.roughness,t.metalness=r.metalness),this._aoMapSrc&&(t.aoMap=this._aoMapSrc,t.aoMapIntensity=this._aoMapIntensity),this._mapSrc&&(t.map=this._mapSrc),this.effectStack.isEmpty||(t.effects=this.effectStack.serialize()),{geometry:this._geometryKind,size:[this._size[0],this._size[1],this._size[2]],castShadow:this.castShadow,receiveShadow:this.receiveShadow,material:t}}applyShadowFlags(){let e=this._mesh;e&&(e.castShadow=this.castShadow,e.receiveShadow=this.receiveShadow)}get _mesh(){return this.children.find(e=>e instanceof B)}get _colorMaterial(){let e=this._mesh?.material;return e&&!Array.isArray(e)&&"color"in e?e:void 0}get _stdMaterial(){let e=this._mesh?.material;return e instanceof sr?e:void 0}static getPropertySchema(){let e=super.getPropertySchema(),t={nodeType:"GeometryMesh",properties:[x("geometry","enum",{ui:{label:"Shape",group:"Geometry",options:[...Su]},getValue:r=>r.geometryKind,setValue:(r,i)=>{r.geometryKind=String(i)}}),x("size","vector3",{ui:{label:"Size",description:"Interpreted per shape (box: extents, sphere: diameter, etc.)",group:"Geometry",min:0,step:.01,precision:2},getValue:r=>{let i=r._size;return{x:i[0],y:i[1],z:i[2]}},setValue:(r,i)=>{let o=i;r.size=[Number(o?.x),Number(o?.y),Number(o?.z)]}}),x("materialType","enum",{ui:{label:"Material",description:"standard = PBR (desktop look), lambert = diffuse-only (the mobile default), basic = unlit (needs no light at all)",group:"Material",options:[...kr]},getValue:r=>r.materialType,setValue:(r,i)=>{r.materialType=String(i)}}),x("color","color",{ui:{label:"Color",group:"Material"},getValue:r=>{let i=r._colorMaterial;return i?"#"+i.color.getHexString():"#4e8df5"},setValue:(r,i)=>{let o=r._colorMaterial;o&&o.color.set(String(i))}}),x("roughness","number",{ui:{label:"Roughness",group:"Material",step:.01,precision:2,min:0,max:1,readOnly:r=>!r._stdMaterial},getValue:r=>r._stdMaterial?.roughness??.35,setValue:(r,i)=>{let o=r._stdMaterial;o&&(o.roughness=Number(i))}}),x("metalness","number",{ui:{label:"Metalness",group:"Material",step:.01,precision:2,min:0,max:1,readOnly:r=>!r._stdMaterial},getValue:r=>r._stdMaterial?.metalness??.25,setValue:(r,i)=>{let o=r._stdMaterial;o&&(o.metalness=Number(i))}}),x("aoMapIntensity","number",{ui:{label:"AO Intensity",description:"Strength of the baked ambient-occlusion map (0 = off)",group:"Material",min:0,max:1,step:.01,precision:2,slider:!0,readOnly:r=>!r._colorMaterial?.aoMap},getValue:r=>r.aoMapIntensity,setValue:(r,i)=>{r.aoMapIntensity=Number(i)}}),x("castShadow","boolean",{ui:{label:"Cast Shadow",description:"Whether this mesh casts shadows in the scene",group:"Rendering"},getValue:r=>r.castShadow,setValue:(r,i)=>{let o=r;o.castShadow=!!i,o.applyShadowFlags()}}),x("receiveShadow","boolean",{ui:{label:"Receive Shadow",description:"Whether this mesh receives shadows cast by other objects",group:"Rendering"},getValue:r=>r.receiveShadow,setValue:(r,i)=>{let o=r;o.receiveShadow=!!i,o.applyShadowFlags()}}),x("map","object",{ui:{label:"Albedo Map",description:"Diffuse texture (res://). Required for the UV Scroll effect to be visible.",group:"Material",editor:"texture-resource",resourceType:"texture"},getValue:r=>({type:"texture",url:r._mapSrc}),setValue:(r,i)=>{r.setMapResource(i)}})],groups:{Geometry:{label:"Geometry",expanded:!0},Material:{label:"Material",expanded:!0},Rendering:{label:"Rendering",description:"Shadow and rendering properties",expanded:!0}}};return ce(e,t)}};function Nf(n){let e=typeof n=="string"?n.toLowerCase():"";return Su.includes(e)?e:"box"}function Ef(n){let e=Number(n);return Number.isFinite(e)?e<0?0:e>1?1:e:1}function Ux(n){if(typeof n=="string")return n;if(n&&typeof n=="object"){let e=n.url;if(typeof e=="string")return e}return""}var If=new Jr(1,1,1),Ns="#ffffff",vu=1,wu=0,Wx="standard",Rf=n=>Array.isArray(n)?n[0]:n,xu=new S,Pu=new _,ku=new S(1,1,1),Bf=new ae,Gx=new L,bt=class extends U{mesh;maxInstances;castShadow;receiveShadow;enablePerInstanceColor;matrixBuffer;colorBuffer;_materialType;_ownsMaterial;transformsDirty=!1;colorsDirty=!1;boundsDirty=!1;constructor(e){super(e,"InstancedMesh3D");let t=Math.floor(e.maxInstances);if(!Number.isFinite(t)||t<=0)throw new Error("[InstancedMesh3D] maxInstances must be a positive integer.");this.maxInstances=t,this.castShadow=e.castShadow??!1,this.receiveShadow=e.receiveShadow??!1,this.enablePerInstanceColor=e.enablePerInstanceColor??!1;let r=e.geometry??If,i=e.materialConfig??{};this._ownsMaterial=e.material===void 0;let o=e.material??Tr(Ar(i.type),{color:new L(i.color??Ns),roughness:typeof i.roughness=="number"?i.roughness:vu,metalness:typeof i.metalness=="number"?i.metalness:wu});this._materialType=(e.material?bu(Rf(e.material)):null)??Ar(i.type),this.mesh=new Xr(r,o,t),this.mesh.name=`${this.name}-mesh`,this.mesh.castShadow=this.castShadow,this.mesh.receiveShadow=this.receiveShadow,this.mesh.frustumCulled=e.frustumCulled??!1,this.mesh.count=0,this.mesh.instanceMatrix.setUsage(se),this.matrixBuffer=this.mesh.instanceMatrix.array,this.enablePerInstanceColor?(this.colorBuffer=new Float32Array(t*3),this.mesh.instanceColor=new qe(this.colorBuffer,3),this.mesh.instanceColor.setUsage(se),Gx.toArray(this.colorBuffer,0)):this.colorBuffer=null,this.add(this.mesh)}disposeResources(){this.mesh.dispose(),this.mesh.geometry!==If&&this.mesh.geometry.dispose();let e=this.mesh.material;for(let t of Array.isArray(e)?e:[e])t?.dispose()}get materialSlots(){let e=this.mesh.material;return Array.isArray(e)?e.filter(Boolean):e?[e]:[]}get singleMaterial(){return this.materialSlots[0]??null}get materialType(){return this._materialType}set materialType(e){let t=Ar(e);if(t===this._materialType&&this._ownsMaterial)return;let r=this.materialSlots,i=r.map(o=>Tr(t,{color:this.colorOf(o)?.clone()??new L(Ns),...this.pbrOf(o)}));this._materialType=t,this.mesh.material=Array.isArray(this.mesh.material)?i:i[0]??Tr(t,{color:new L(Ns),roughness:vu,metalness:wu}),this._ownsMaterial=!0;for(let o of r)o.dispose()}get color(){let e=this.colorOf(this.singleMaterial);return e?`#${e.getHexString()}`:Ns}set color(e){for(let t of this.materialSlots)this.colorOf(t)?.set(e)}serializeMaterialConfig(){if(Array.isArray(this.mesh.material)||!this.singleMaterial)return null;let e={type:this._materialType,color:this.color};return this._materialType==="standard"&&Object.assign(e,this.pbrOf(this.singleMaterial)),e}colorOf(e){let t=e?.color;return t instanceof L?t:null}pbrOf(e){let t=e;return{roughness:typeof t?.roughness=="number"?t.roughness:vu,metalness:typeof t?.metalness=="number"?t.metalness:wu}}get visibleInstanceCount(){return this.mesh.count}set visibleInstanceCount(e){this.mesh.count=this.clampVisibleCount(e)}setGeometry(e){this.mesh.geometry=e,this.boundsDirty=!0}setMaterial(e){let t=this.materialSlots;this.mesh.material=e,this._materialType=bu(Rf(e))??Wx,this._ownsMaterial=!1;for(let r of t)(Array.isArray(e)?e.includes(r):e===r)||r.dispose()}writeMatrices(e,t={}){let r=this.validateCount(e.count),i=r*16;if(e.matrices.length<i)throw new Error("[InstancedMesh3D] Matrices array is smaller than count * 16.");this.matrixBuffer.set(e.matrices.subarray(0,i),0),this.applyWriteOptions(r,t,!0,!1)}writeTransforms(e,t={}){let r=this.validateCount(e.count);this.validateOptionalArrayLength(e.positions,r*3,"positions"),this.validateOptionalArrayLength(e.rotations,r*4,"rotations"),this.validateOptionalArrayLength(e.scales,r*3,"scales");for(let i=0;i<r;i+=1){let o=i*3,s=i*4,a=i*16;e.positions?xu.set(e.positions[o]??0,e.positions[o+1]??0,e.positions[o+2]??0):xu.set(0,0,0),e.rotations?Pu.set(e.rotations[s]??0,e.rotations[s+1]??0,e.rotations[s+2]??0,e.rotations[s+3]??1):Pu.set(0,0,0,1),e.scales?ku.set(e.scales[o]??1,e.scales[o+1]??1,e.scales[o+2]??1):ku.set(1,1,1),Bf.compose(xu,Pu,ku),Bf.toArray(this.matrixBuffer,a)}this.applyWriteOptions(r,t,!0,!1)}writeColors(e,t={}){if(!this.colorBuffer||!this.mesh.instanceColor)throw new Error("[InstancedMesh3D] Per-instance colors are disabled. Enable enablePerInstanceColor first.");let r=this.validateCount(e.count),i=r*3;if(e.colors.length<i)throw new Error("[InstancedMesh3D] Colors array is smaller than count * 3.");this.colorBuffer.set(e.colors.subarray(0,i),0),this.applyWriteOptions(r,t,!1,!0)}markTransformsDirty(){this.transformsDirty=!0}markColorsDirty(){this.colorBuffer&&(this.colorsDirty=!0)}flush(){this.transformsDirty&&(this.mesh.instanceMatrix.needsUpdate=!0,this.transformsDirty=!1),this.colorsDirty&&this.mesh.instanceColor&&(this.mesh.instanceColor.needsUpdate=!0,this.colorsDirty=!1),this.boundsDirty&&(this.mesh.computeBoundingBox(),this.mesh.computeBoundingSphere(),this.boundsDirty=!1)}clearInstances(){this.mesh.count=0}getInstanceMatrixBuffer(){return this.matrixBuffer}getInstanceColorBuffer(){return this.colorBuffer}static getPropertySchema(){let e=U.getPropertySchema();return{nodeType:"InstancedMesh3D",extends:"Node3D",properties:[...e.properties,{name:"maxInstances",type:"number",ui:{label:"Max Instances",group:"Rendering",readOnly:!0},getValue:t=>t.maxInstances,setValue:()=>{}},{name:"materialType",type:"enum",ui:{label:"Material Type",description:"standard = PBR (desktop-class cost), lambert = diffuse-only (the mobile default), basic = unlit",group:"Material",options:[...kr]},getValue:t=>t.materialType,setValue:(t,r)=>{t.materialType=String(r)}},{name:"color",type:"color",ui:{label:"Color",description:"Shared by every instance; per-instance colour multiplies it",group:"Material"},getValue:t=>t.color,setValue:(t,r)=>{t.color=String(r)}},{name:"castShadow",type:"boolean",ui:{label:"Cast Shadow",group:"Rendering"},getValue:t=>t.mesh.castShadow,setValue:(t,r)=>{t.mesh.castShadow=!!r}},{name:"receiveShadow",type:"boolean",ui:{label:"Receive Shadow",group:"Rendering"},getValue:t=>t.mesh.receiveShadow,setValue:(t,r)=>{t.mesh.receiveShadow=!!r}},{name:"enablePerInstanceColor",type:"boolean",ui:{label:"Per-Instance Color",group:"Rendering",readOnly:!0},getValue:t=>t.enablePerInstanceColor,setValue:()=>{}},{name:"visibleInstanceCount",type:"number",ui:{label:"Visible Instances",group:"Debug",readOnly:!0},getValue:t=>t.visibleInstanceCount,setValue:()=>{}}],groups:{...e.groups,Material:{label:"Material",description:"The one material every instance renders with",expanded:!0},Rendering:{label:"Rendering",description:"Instanced mesh rendering options",expanded:!0},Debug:{label:"Debug",description:"Runtime-only instancing diagnostics",expanded:!1}}}}applyWriteOptions(e,t,r,i){t.visibleCount!==void 0?this.visibleInstanceCount=t.visibleCount:this.mesh.count<e&&(this.visibleInstanceCount=e),r&&t.markTransformDirty!==!1&&(this.transformsDirty=!0),i&&t.markColorDirty!==!1&&(this.colorsDirty=!0),t.computeBoundingSphere&&(this.boundsDirty=!0)}validateCount(e){let t=Math.floor(e);if(!Number.isFinite(t)||t<0)throw new Error("[InstancedMesh3D] Instance count must be a non-negative integer.");if(t>this.maxInstances)throw new Error(`[InstancedMesh3D] Instance count ${t} exceeds maxInstances ${this.maxInstances}.`);return t}clampVisibleCount(e){let t=Math.floor(e);if(!Number.isFinite(t)||t<0)throw new Error("[InstancedMesh3D] visibleInstanceCount must be a non-negative integer.");return Math.min(t,this.maxInstances)}validateOptionalArrayLength(e,t,r){if(e&&e.length<t)throw new Error(`[InstancedMesh3D] ${r} array is smaller than required stride.`)}};var Lf=3,Es=new ae,Au=new S,Vf=new S,Of=new _,Is=(n,e,t,r)=>{e instanceof S?Au.copy(e):Au.set(e,t??0,r??0),n.updateWorldMatrix(!0,!1),Vf.setFromMatrixPosition(n.matrixWorld),Es.lookAt(Vf,Au,n.up),n.quaternion.setFromRotationMatrix(Es);let i=n.parent;i&&(Es.extractRotation(i.matrixWorld),Of.setFromRotationMatrix(Es),n.quaternion.premultiply(Of.invert()))},fe=class extends U{camera;targetDistance=Lf;shakeRafId=null;projectionMode;perspectiveFov;orthographicSizeValue;constructor(e){super(e,"Camera3D"),this.projectionMode=e.projection??"perspective",this.perspectiveFov=e.fov??60,this.orthographicSizeValue=e.orthographicSize??5,this.camera=new ye,this.add(this.camera),this.rebuildCamera({projection:this.projectionMode,fov:this.perspectiveFov,near:e.near??.1,far:e.far??1e3,orthographicSize:this.orthographicSizeValue})}lookAt(e,t,r){Is(this,e,t,r)}getTargetPosition(){let e=this.getWorldPosition(new S),t=this.getWorldQuaternion(new _),r=new S(0,0,-1).applyQuaternion(t);return e.add(r.multiplyScalar(this.targetDistance))}setTargetPosition(e){let t=this.getWorldPosition(new S),r=e.clone().sub(t),i=r.length();i>1e-6&&(this.targetDistance=i);let s=(r.lengthSq()>1e-8?r.normalize():new S(0,0,-1).applyQuaternion(this.getWorldQuaternion(new _))).clone(),a=this.parent;if(a){let c=a.getWorldQuaternion(new _);s.applyQuaternion(c.invert())}s.normalize();let l=new _().setFromUnitVectors(new S(0,0,-1),s);this.quaternion.copy(l),this.camera.position.set(0,0,0),this.camera.rotation.set(0,0,0)}get fov(){return this.perspectiveFov}set fov(e){this.perspectiveFov=Number(e),this.camera instanceof ye&&(this.camera.fov=this.perspectiveFov,this.camera.updateProjectionMatrix())}get projection(){return this.projectionMode}set projection(e){this.rebuildCamera({projection:e})}get near(){return this.camera.near}set near(e){let t=Number(e);(this.camera instanceof ye||this.camera instanceof me)&&(this.camera.near=t,this.camera.updateProjectionMatrix())}get far(){return this.camera.far}set far(e){let t=Number(e);(this.camera instanceof ye||this.camera instanceof me)&&(this.camera.far=t,this.camera.updateProjectionMatrix())}get orthographicSize(){return this.orthographicSizeValue}set orthographicSize(e){let t=Math.max(1e-4,Number(e));this.orthographicSizeValue=t,this.camera instanceof me&&this.applyOrthographicSize(this.camera,t)}updateAspectRatio(e){if(this.camera instanceof ye){this.camera.aspect!==e&&(this.camera.aspect=e,this.camera.updateProjectionMatrix());return}if(this.camera instanceof me){let t=Number.isFinite(e)&&e>0?e:1,r=this.orthographicSize/2,i=r*t;(this.camera.left!==-i||this.camera.right!==i||this.camera.top!==r||this.camera.bottom!==-r)&&(this.camera.left=-i,this.camera.right=i,this.camera.top=r,this.camera.bottom=-r,this.camera.updateProjectionMatrix())}}shake(e=.2,t=.35){if(e<=0||t<=0)return;this.stopShake();let r=performance.now(),i=o=>{let s=(o-r)/1e3,a=Math.min(1,s/t);if(a>=1){this.stopShake();return}let l=1-a,c=e*l;this.camera.position.set((Math.random()*2-1)*c,(Math.random()*2-1)*c,(Math.random()*2-1)*c*.35),this.shakeRafId=requestAnimationFrame(i)};this.shakeRafId=requestAnimationFrame(i)}stopShake(){this.shakeRafId!==null&&(cancelAnimationFrame(this.shakeRafId),this.shakeRafId=null),this.camera.position.set(0,0,0)}rebuildCamera(e){let t=e.projection??this.projectionMode,r=e.near??this.near??.1,i=e.far??this.far??1e3;this.projectionMode=t,this.perspectiveFov=e.fov??this.perspectiveFov??60,this.orthographicSizeValue=Math.max(1e-4,e.orthographicSize??this.orthographicSizeValue??5);let o=this.camera,s=t==="perspective"?new ye(this.perspectiveFov,1,r,i):new me(-1,1,1,-1,r,i);s.layers.mask=o.layers.mask,s.position.copy(o.position),s.quaternion.copy(o.quaternion),s.scale.copy(o.scale),s.visible=o.visible,s.name=o.name,s.matrixAutoUpdate=o.matrixAutoUpdate,s.matrix.copy(o.matrix),s.matrixWorld.copy(o.matrixWorld),s.matrixWorldAutoUpdate=o.matrixWorldAutoUpdate,s.matrixWorldNeedsUpdate=o.matrixWorldNeedsUpdate,this.remove(o),this.camera=s,this.add(this.camera),this.camera.position.set(0,0,0),this.camera.rotation.set(0,0,0),this.camera instanceof me?this.applyOrthographicSize(this.camera,this.orthographicSizeValue):this.camera instanceof ye&&(this.camera.fov=this.perspectiveFov,this.camera.updateProjectionMatrix())}applyOrthographicSize(e,t){let r=Math.max(1e-4,t)/2;e.left=-r,e.right=r,e.top=r,e.bottom=-r,e.updateProjectionMatrix()}static getPropertySchema(){let e=super.getPropertySchema(),t={nodeType:"Camera3D",properties:[x("projection","enum",{ui:{label:"Projection",group:"Camera",options:["perspective","orthographic"]},getValue:r=>r.projection,setValue:(r,i)=>{r.projection=i==="orthographic"?"orthographic":"perspective"}}),x("fov","number",{getValue:r=>r.fov,setValue:(r,i)=>{r.fov=Number(i)},validation:{validate:r=>Number.isFinite(Number(r))&&Number(r)>0},ui:{label:"Field of View",group:"Camera",unit:"\xB0",step:.1,precision:1,readOnly:r=>r.projection!=="perspective"}}),x("orthographicSize","number",{ui:{label:"Orthographic Size",group:"Camera",step:.1,precision:2,readOnly:r=>r.projection!=="orthographic"},getValue:r=>r.orthographicSize,setValue:(r,i)=>{r.orthographicSize=Number(i)},validation:{validate:r=>Number.isFinite(Number(r))&&Number(r)>0}}),x("near","number",{ui:{label:"Near Plane",group:"Camera",step:.01,precision:2},getValue:r=>r.near,setValue:(r,i)=>{r.near=Number(i)},validation:{validate:r=>Number.isFinite(Number(r))&&Number(r)>0}}),x("far","number",{ui:{label:"Far Plane",group:"Camera",step:1,precision:0},getValue:r=>r.far,setValue:(r,i)=>{r.far=Number(i)},validation:{validate:r=>Number.isFinite(Number(r))&&Number(r)>0}})],groups:{Camera:{label:"Camera",expanded:!0}}};return ce(e,t)}};var Rs=2.5949095,Ff=1.70158+1,_f=2*Math.PI/3,zf=2*Math.PI/4.5;function Bs(n){if(n<1/2.75)return 7.5625*n*n;if(n<2/2.75){let i=n-.5454545454545454;return 7.5625*i*i+.75}if(n<2.5/2.75){let i=n-.8181818181818182;return 7.5625*i*i+.9375}let r=n-2.625/2.75;return 7.5625*r*r+.984375}var Vs={linear:n=>n,step:()=>0,sineIn:n=>1-Math.cos(n*Math.PI/2),sineOut:n=>Math.sin(n*Math.PI/2),sineInOut:n=>-(Math.cos(Math.PI*n)-1)/2,quadIn:n=>n*n,quadOut:n=>1-(1-n)*(1-n),quadInOut:n=>n<.5?2*n*n:1-Math.pow(-2*n+2,2)/2,cubicIn:n=>n*n*n,cubicOut:n=>1-Math.pow(1-n,3),cubicInOut:n=>n<.5?4*n*n*n:1-Math.pow(-2*n+2,3)/2,expoIn:n=>n===0?0:Math.pow(2,10*n-10),expoOut:n=>n===1?1:1-Math.pow(2,-10*n),expoInOut:n=>n===0?0:n===1?1:n<.5?Math.pow(2,20*n-10)/2:(2-Math.pow(2,-20*n+10))/2,backIn:n=>Ff*n*n*n-1.70158*n*n,backOut:n=>1+Ff*Math.pow(n-1,3)+1.70158*Math.pow(n-1,2),backInOut:n=>n<.5?Math.pow(2*n,2)*((Rs+1)*2*n-Rs)/2:(Math.pow(2*n-2,2)*((Rs+1)*(n*2-2)+Rs)+2)/2,elasticIn:n=>n===0?0:n===1?1:-Math.pow(2,10*n-10)*Math.sin((n*10-10.75)*_f),elasticOut:n=>n===0?0:n===1?1:Math.pow(2,-10*n)*Math.sin((n*10-.75)*_f)+1,elasticInOut:n=>n===0?0:n===1?1:n<.5?-(Math.pow(2,20*n-10)*Math.sin((20*n-11.125)*zf))/2:Math.pow(2,-20*n+10)*Math.sin((20*n-11.125)*zf)/2+1,bounceIn:n=>1-Bs(1-n),bounceOut:Bs,bounceInOut:n=>n<.5?(1-Bs(1-2*n))/2:(1+Bs(2*n-1))/2},Tu=Object.keys(Vs);function _e(n){return typeof n=="string"&&n in Vs}function St(n,e){let t=e<=0?0:e>=1?1:e;return(Vs[n]??Vs.linear)(t)}var qx=new S(0,1,0),ze={priority:10,fov:60,orthographicSize:5,followDamping:8,rotationDamping:8,lookAtWeight:1,blendDuration:1,blendEasing:"cubicInOut"},vt=class extends U{priorityValue;fovValue;orthographicSizeValue;followTargetId;followDampingValue;followOffset=new S;deadzone=new S;lookAtTargetId;lookAtWeightValue;rotationDampingValue;confinerEnabledValue;confinerCenter=new S;confinerSize=new S(10,10,10);blendDurationValue;blendEasingValue;authoredQuaternion=null;scratchWorldPos=new S;scratchTargetPos=new S;scratchDesired=new S;scratchLocal=new S;scratchLookMatrix=new ae;scratchLookQuat=new _;scratchBlendQuat=new _;scratchCurrentQuat=new _;scratchParentQuat=new _;constructor(e){super(e,"VirtualCamera3D");let t=ze;this.priorityValue=e.priority??t.priority,this.fovValue=e.fov??t.fov,this.orthographicSizeValue=Math.max(1e-4,e.orthographicSize??t.orthographicSize),this.followTargetId=e.followTargetId??"",this.followDampingValue=Math.max(0,e.followDamping??t.followDamping),e.followOffset&&this.followOffset.set(e.followOffset.x,e.followOffset.y,e.followOffset.z),e.deadzone&&this.deadzone.set(Math.max(0,e.deadzone.x),Math.max(0,e.deadzone.y),Math.max(0,e.deadzone.z)),this.lookAtTargetId=e.lookAtTargetId??"",this.lookAtWeightValue=Uf(e.lookAtWeight??t.lookAtWeight),this.rotationDampingValue=Math.max(0,e.rotationDamping??t.rotationDamping),this.confinerEnabledValue=e.confinerEnabled??!1,e.confinerCenter&&this.confinerCenter.set(e.confinerCenter.x,e.confinerCenter.y,e.confinerCenter.z),e.confinerSize&&this.confinerSize.set(Math.max(0,e.confinerSize.x),Math.max(0,e.confinerSize.y),Math.max(0,e.confinerSize.z)),this.blendDurationValue=Math.max(0,e.blendDuration??t.blendDuration),this.blendEasingValue=e.blendEasing??t.blendEasing}get priority(){return this.priorityValue}set priority(e){let t=Number(e);this.priorityValue=Number.isFinite(t)?t:this.priorityValue}get fov(){return this.fovValue}set fov(e){let t=Number(e);Number.isFinite(t)&&t>0&&(this.fovValue=t)}get orthographicSize(){return this.orthographicSizeValue}set orthographicSize(e){let t=Number(e);Number.isFinite(t)&&t>0&&(this.orthographicSizeValue=t)}get blendDuration(){return this.blendDurationValue}set blendDuration(e){let t=Number(e);this.blendDurationValue=Number.isFinite(t)?Math.max(0,t):this.blendDurationValue}get blendEasing(){return this.blendEasingValue}set blendEasing(e){_e(e)&&(this.blendEasingValue=e)}solve(e){this.authoredQuaternion===null&&(this.authoredQuaternion=this.getWorldQuaternion(new _)),this.solveFollow(e),this.applyConfiner(),this.solveLookAt(e)}getDesiredWorldPosition(e){return this.getWorldPosition(e)}getDesiredWorldQuaternion(e){return this.getWorldQuaternion(e)}serializeConfig(){return{priority:this.priorityValue,fov:this.fovValue,orthographicSize:this.orthographicSizeValue,followTargetId:this.followTargetId,followDamping:this.followDampingValue,followOffset:[this.followOffset.x,this.followOffset.y,this.followOffset.z],deadzone:[this.deadzone.x,this.deadzone.y,this.deadzone.z],lookAtTargetId:this.lookAtTargetId,lookAtWeight:this.lookAtWeightValue,rotationDamping:this.rotationDampingValue,confinerEnabled:this.confinerEnabledValue,confinerCenter:[this.confinerCenter.x,this.confinerCenter.y,this.confinerCenter.z],confinerSize:[this.confinerSize.x,this.confinerSize.y,this.confinerSize.z],blendDuration:this.blendDurationValue,blendEasing:this.blendEasingValue}}resolveTarget(e){if(!e)return null;if(this.scene)return this.scene.findNode(e);let t=this;for(;t.parentNode;)t=t.parentNode;return t.findNode(e)}solveFollow(e){let t=this.resolveTarget(this.followTargetId);if(!t||t===this)return;t.getWorldPosition(this.scratchTargetPos),this.scratchDesired.copy(this.scratchTargetPos).add(this.followOffset),this.getWorldPosition(this.scratchWorldPos);let r=fr(this.scratchWorldPos.x,this.scratchDesired.x,this.deadzone.x),i=fr(this.scratchWorldPos.y,this.scratchDesired.y,this.deadzone.y),o=fr(this.scratchWorldPos.z,this.scratchDesired.z,this.deadzone.z),s=rn(this.followDampingValue,e),a=this.scratchWorldPos.x+(r-this.scratchWorldPos.x)*s,l=this.scratchWorldPos.y+(i-this.scratchWorldPos.y)*s,c=this.scratchWorldPos.z+(o-this.scratchWorldPos.z)*s;this.setWorldPosition(a,l,c)}applyConfiner(){if(!this.confinerEnabledValue)return;this.getWorldPosition(this.scratchWorldPos);let e=this.confinerSize.x/2,t=this.confinerSize.y/2,r=this.confinerSize.z/2,i=gr(this.scratchWorldPos.x,this.confinerCenter.x,e),o=gr(this.scratchWorldPos.y,this.confinerCenter.y,t),s=gr(this.scratchWorldPos.z,this.confinerCenter.z,r);(i!==this.scratchWorldPos.x||o!==this.scratchWorldPos.y||s!==this.scratchWorldPos.z)&&this.setWorldPosition(i,o,s)}lookAt(e,t,r){Is(this,e,t,r)}solveLookAt(e){let t=this.resolveTarget(this.lookAtTargetId);if(!t||t===this||this.authoredQuaternion===null||(this.getWorldPosition(this.scratchWorldPos),t.getWorldPosition(this.scratchTargetPos),this.scratchWorldPos.distanceToSquared(this.scratchTargetPos)<1e-10))return;this.scratchLookMatrix.lookAt(this.scratchWorldPos,this.scratchTargetPos,qx),this.scratchLookQuat.setFromRotationMatrix(this.scratchLookMatrix),this.scratchBlendQuat.copy(this.authoredQuaternion).slerp(this.scratchLookQuat,this.lookAtWeightValue),this.getWorldQuaternion(this.scratchCurrentQuat);let r=rn(this.rotationDampingValue,e);this.scratchCurrentQuat.slerp(this.scratchBlendQuat,r),this.setWorldQuaternion(this.scratchCurrentQuat)}setWorldPosition(e,t,r){this.scratchLocal.set(e,t,r),this.parent&&(this.parent.updateWorldMatrix(!0,!1),this.parent.worldToLocal(this.scratchLocal)),this.position.copy(this.scratchLocal),this.updateWorldMatrix(!0,!1)}setWorldQuaternion(e){this.parent?(this.parent.getWorldQuaternion(this.scratchParentQuat),this.scratchParentQuat.invert().multiply(e),this.quaternion.copy(this.scratchParentQuat)):this.quaternion.copy(e),this.updateWorldMatrix(!0,!1)}get treeIcon(){return"camera"}static getPropertySchema(){let e=super.getPropertySchema(),t={nodeType:"VirtualCamera3D",properties:[x("priority","number",{ui:{label:"Priority",description:"Highest-priority live virtual camera wins (animatable)",group:"Virtual Camera",step:1,precision:0},getValue:r=>r.priority,setValue:(r,i)=>{r.priority=Number(i)},validation:{validate:r=>Number.isFinite(Number(r))}}),x("fov","number",{ui:{label:"Field of View",group:"Virtual Camera",unit:"\xB0",step:.1,precision:1},getValue:r=>r.fov,setValue:(r,i)=>{r.fov=Number(i)},validation:{validate:r=>Number.isFinite(Number(r))&&Number(r)>0}}),x("orthographicSize","number",{ui:{label:"Orthographic Size",description:"Applied when the render camera is orthographic",group:"Virtual Camera",step:.1,precision:2},getValue:r=>r.orthographicSize,setValue:(r,i)=>{r.orthographicSize=Number(i)},validation:{validate:r=>Number.isFinite(Number(r))&&Number(r)>0}}),x("followTargetId","node",{ui:{label:"Follow Target",description:"Node whose position this camera follows (empty = authored position)",group:"Follow"},getValue:r=>r.followTargetId,setValue:(r,i)=>{r.followTargetId=typeof i=="string"?i:""}}),x("followOffset","vector3",{ui:{label:"Follow Offset",group:"Follow",step:.01,precision:2},getValue:r=>Os(r.followOffset),setValue:(r,i)=>Ls(r.followOffset,i)}),x("followDamping","number",{ui:{label:"Follow Damping",description:"Higher = snappier follow (0 = instant)",group:"Follow",min:0,step:.1,precision:2},getValue:r=>r.followDampingValue,setValue:(r,i)=>{let o=Number(i);Number.isFinite(o)&&o>=0&&(r.followDampingValue=o)}}),x("deadzone","vector3",{ui:{label:"Deadzone",description:"World half-extents the target can move within before the camera follows",group:"Follow",min:0,step:.01,precision:2},getValue:r=>Os(r.deadzone),setValue:(r,i)=>Ls(r.deadzone,i,0)}),x("lookAtTargetId","node",{ui:{label:"Look At Target",description:"Node this camera orients toward (empty = authored rotation)",group:"Look At"},getValue:r=>r.lookAtTargetId,setValue:(r,i)=>{r.lookAtTargetId=typeof i=="string"?i:""}}),x("lookAtWeight","number",{ui:{label:"Look At Weight",description:"0 = keep authored rotation, 1 = fully track the target",group:"Look At",min:0,max:1,step:.01,precision:2,slider:!0},getValue:r=>r.lookAtWeightValue,setValue:(r,i)=>{r.lookAtWeightValue=Uf(Number(i))}}),x("rotationDamping","number",{ui:{label:"Rotation Damping",description:"Higher = snappier aim (0 = instant)",group:"Look At",min:0,step:.1,precision:2},getValue:r=>r.rotationDampingValue,setValue:(r,i)=>{let o=Number(i);Number.isFinite(o)&&o>=0&&(r.rotationDampingValue=o)}}),x("confinerEnabled","boolean",{ui:{label:"Confiner",description:"Clamp the camera position inside an axis-aligned box",group:"Confiner"},getValue:r=>r.confinerEnabledValue,setValue:(r,i)=>{r.confinerEnabledValue=!!i}}),x("confinerCenter","vector3",{ui:{label:"Confiner Center",group:"Confiner",step:.01,precision:2,readOnly:r=>!r.confinerEnabledValue},getValue:r=>Os(r.confinerCenter),setValue:(r,i)=>Ls(r.confinerCenter,i)}),x("confinerSize","vector3",{ui:{label:"Confiner Size",group:"Confiner",min:0,step:.01,precision:2,readOnly:r=>!r.confinerEnabledValue},getValue:r=>Os(r.confinerSize),setValue:(r,i)=>Ls(r.confinerSize,i,0)}),x("blendDuration","number",{ui:{label:"Blend In",description:"Seconds to blend the render camera toward this one when it becomes active",group:"Blend",min:0,step:.05,precision:2,unit:"s"},getValue:r=>r.blendDuration,setValue:(r,i)=>{r.blendDuration=Number(i)}}),x("blendEasing","enum",{ui:{label:"Blend Easing",group:"Blend",options:[...Tu]},getValue:r=>r.blendEasing,setValue:(r,i)=>{r.blendEasing=i}})],groups:{"Virtual Camera":{label:"Virtual Camera",expanded:!0},Follow:{label:"Follow",expanded:!0},"Look At":{label:"Look At",expanded:!0},Confiner:{label:"Confiner",expanded:!1},Blend:{label:"Blend",expanded:!1}}};return ce(e,t)}};function Uf(n){return Number.isFinite(n)?n<0?0:n>1?1:n:0}function Os(n){return{x:n.x,y:n.y,z:n.z}}function Ls(n,e,t=Number.NEGATIVE_INFINITY){let r=e,i=Number(r?.x),o=Number(r?.y),s=Number(r?.z);n.set(Number.isFinite(i)?Math.max(t,i):n.x,Number.isFinite(o)?Math.max(t,o):n.y,Number.isFinite(s)?Math.max(t,s):n.z)}var Mu=["inherit","off","baked","realtime","adaptive"],Gf=["off","baked","realtime","adaptive"],qf="__PIX3_PROJECT_AO_MODE__";function Hx(n){globalThis[qf]=jf(n)}function Hf(){let n=globalThis[qf];return jf(n)}function jf(n){let e=typeof n=="string"?n.toLowerCase():"";return Gf.includes(e)?e:"baked"}var Yf={affect2D:!0,bloomEnabled:!0,bloomIntensity:1,bloomThreshold:.9,bloomSmoothing:.025,bloomRadius:.85,vignetteEnabled:!1,vignetteOffset:.35,vignetteDarkness:.5,chromaticAberrationEnabled:!1,chromaticAberrationOffset:.002,aoMode:"inherit",ssaoIntensity:2.5,ssaoRadius:.25,lutEnabled:!1,lutSrc:"",lutIntensity:1},et=class extends V{affect2DValue;bloomEnabledValue;bloomIntensityValue;bloomThresholdValue;bloomSmoothingValue;bloomRadiusValue;vignetteEnabledValue;vignetteOffsetValue;vignetteDarknessValue;chromaticAberrationEnabledValue;chromaticAberrationOffsetValue;aoModeValue;ssaoIntensityValue;ssaoRadiusValue;lutEnabledValue;lutSrcValue;lutIntensityValue;constructor(e){super({...e,type:"PostProcess"}),this.isContainer=!1;let t=Yf,r=this.properties;this.affect2DValue=un(e.affect2D??r.affect2D,t.affect2D),this.bloomEnabledValue=un(e.bloomEnabled??r.bloomEnabled,t.bloomEnabled),this.bloomIntensityValue=Ze(e.bloomIntensity??r.bloomIntensity,t.bloomIntensity,0),this.bloomThresholdValue=Ze(e.bloomThreshold??r.bloomThreshold,t.bloomThreshold,0),this.bloomSmoothingValue=Ze(e.bloomSmoothing??r.bloomSmoothing,t.bloomSmoothing,0),this.bloomRadiusValue=Ze(e.bloomRadius??r.bloomRadius,t.bloomRadius,0),this.vignetteEnabledValue=un(e.vignetteEnabled??r.vignetteEnabled,t.vignetteEnabled),this.vignetteOffsetValue=Ze(e.vignetteOffset??r.vignetteOffset,t.vignetteOffset,0),this.vignetteDarknessValue=Ze(e.vignetteDarkness??r.vignetteDarkness,t.vignetteDarkness,0),this.chromaticAberrationEnabledValue=un(e.chromaticAberrationEnabled??r.chromaticAberrationEnabled,t.chromaticAberrationEnabled),this.chromaticAberrationOffsetValue=Ze(e.chromaticAberrationOffset??r.chromaticAberrationOffset,t.chromaticAberrationOffset,0),this.aoModeValue=Wf(e.aoMode??r.aoMode??t.aoMode),this.ssaoIntensityValue=Ze(e.ssaoIntensity??r.ssaoIntensity,t.ssaoIntensity,0),this.ssaoRadiusValue=Ze(e.ssaoRadius??r.ssaoRadius,t.ssaoRadius,0),this.lutEnabledValue=un(e.lutEnabled??r.lutEnabled,t.lutEnabled),this.lutSrcValue=jx(e.lutSrc??r.lutSrc,t.lutSrc),this.lutIntensityValue=Ze(e.lutIntensity??r.lutIntensity,t.lutIntensity,0)}get treeIcon(){return"sparkles"}get affect2D(){return this.affect2DValue}set affect2D(e){this.affect2DValue=!!e}get bloomEnabled(){return this.bloomEnabledValue}set bloomEnabled(e){this.bloomEnabledValue=!!e}get bloomIntensity(){return this.bloomIntensityValue}set bloomIntensity(e){this.bloomIntensityValue=wt(e,0,this.bloomIntensityValue)}get bloomThreshold(){return this.bloomThresholdValue}set bloomThreshold(e){this.bloomThresholdValue=wt(e,0,this.bloomThresholdValue)}get bloomSmoothing(){return this.bloomSmoothingValue}set bloomSmoothing(e){this.bloomSmoothingValue=wt(e,0,this.bloomSmoothingValue)}get bloomRadius(){return this.bloomRadiusValue}set bloomRadius(e){this.bloomRadiusValue=wt(e,0,this.bloomRadiusValue)}get vignetteEnabled(){return this.vignetteEnabledValue}set vignetteEnabled(e){this.vignetteEnabledValue=!!e}get vignetteOffset(){return this.vignetteOffsetValue}set vignetteOffset(e){this.vignetteOffsetValue=wt(e,0,this.vignetteOffsetValue)}get vignetteDarkness(){return this.vignetteDarknessValue}set vignetteDarkness(e){this.vignetteDarknessValue=wt(e,0,this.vignetteDarknessValue)}get chromaticAberrationEnabled(){return this.chromaticAberrationEnabledValue}set chromaticAberrationEnabled(e){this.chromaticAberrationEnabledValue=!!e}get chromaticAberrationOffset(){return this.chromaticAberrationOffsetValue}set chromaticAberrationOffset(e){this.chromaticAberrationOffsetValue=wt(e,0,this.chromaticAberrationOffsetValue)}get aoMode(){return this.aoModeValue}set aoMode(e){this.aoModeValue=Wf(e)}getResolvedAOMode(){let e=this.aoModeValue==="inherit"?Hf():this.aoModeValue;return e==="adaptive"?$f()?"realtime":"baked":e}get ssaoIntensity(){return this.ssaoIntensityValue}set ssaoIntensity(e){this.ssaoIntensityValue=wt(e,0,this.ssaoIntensityValue)}get ssaoRadius(){return this.ssaoRadiusValue}set ssaoRadius(e){this.ssaoRadiusValue=wt(e,0,this.ssaoRadiusValue)}get lutEnabled(){return this.lutEnabledValue}set lutEnabled(e){this.lutEnabledValue=!!e}get lutSrc(){return this.lutSrcValue}set lutSrc(e){this.lutSrcValue=typeof e=="string"?e:""}get lutIntensity(){return this.lutIntensityValue}set lutIntensity(e){this.lutIntensityValue=Yx(e,this.lutIntensityValue)}isActive(){return this.bloomEnabledValue||this.vignetteEnabledValue||this.chromaticAberrationEnabledValue||this.getResolvedAOMode()==="realtime"||this.lutEnabledValue&&this.lutSrcValue.length>0}getConfig(){return{affect2D:this.affect2DValue,bloom:{enabled:this.bloomEnabledValue,intensity:this.bloomIntensityValue,threshold:this.bloomThresholdValue,smoothing:this.bloomSmoothingValue,radius:this.bloomRadiusValue},vignette:{enabled:this.vignetteEnabledValue,offset:this.vignetteOffsetValue,darkness:this.vignetteDarknessValue},chromaticAberration:{enabled:this.chromaticAberrationEnabledValue,offset:this.chromaticAberrationOffsetValue},ssao:{enabled:this.getResolvedAOMode()==="realtime",intensity:this.ssaoIntensityValue,radius:this.ssaoRadiusValue},lut:{enabled:this.lutEnabledValue,src:this.lutSrcValue,intensity:this.lutIntensityValue}}}serializeConfig(){return{affect2D:this.affect2DValue,bloomEnabled:this.bloomEnabledValue,bloomIntensity:this.bloomIntensityValue,bloomThreshold:this.bloomThresholdValue,bloomSmoothing:this.bloomSmoothingValue,bloomRadius:this.bloomRadiusValue,vignetteEnabled:this.vignetteEnabledValue,vignetteOffset:this.vignetteOffsetValue,vignetteDarkness:this.vignetteDarknessValue,chromaticAberrationEnabled:this.chromaticAberrationEnabledValue,chromaticAberrationOffset:this.chromaticAberrationOffsetValue,aoMode:this.aoModeValue,ssaoIntensity:this.ssaoIntensityValue,ssaoRadius:this.ssaoRadiusValue,lutEnabled:this.lutEnabledValue,lutSrc:this.lutSrcValue,lutIntensity:this.lutIntensityValue}}static getPropertySchema(){return{nodeType:"PostProcess",extends:"NodeBase",properties:[...V.getPropertySchema().properties,x("affect2D","boolean",{ui:{label:"Affect 2D",description:"When on, the 2D content layer also passes through the effect stack",group:"General"},getValue:t=>t.affect2D,setValue:(t,r)=>{t.affect2D=!!r}}),x("bloomEnabled","boolean",{ui:{label:"Enabled",group:"Bloom"},getValue:t=>t.bloomEnabled,setValue:(t,r)=>{t.bloomEnabled=!!r}}),x("bloomIntensity","number",{ui:{label:"Intensity",description:"Overall bloom strength (animatable \u2014 a flash is 3 keys)",group:"Bloom",min:0,step:.05,precision:2,readOnly:t=>!t.bloomEnabled},getValue:t=>t.bloomIntensity,setValue:(t,r)=>{t.bloomIntensity=Number(r)},validation:{validate:t=>Number.isFinite(Number(t))&&Number(t)>=0}}),x("bloomThreshold","number",{ui:{label:"Threshold",description:"Luminance below this is not bloomed",group:"Bloom",min:0,max:1,step:.01,precision:2,slider:!0,readOnly:t=>!t.bloomEnabled},getValue:t=>t.bloomThreshold,setValue:(t,r)=>{t.bloomThreshold=Number(r)}}),x("bloomSmoothing","number",{ui:{label:"Smoothing",group:"Bloom",min:0,max:1,step:.005,precision:3,readOnly:t=>!t.bloomEnabled},getValue:t=>t.bloomSmoothing,setValue:(t,r)=>{t.bloomSmoothing=Number(r)}}),x("bloomRadius","number",{ui:{label:"Radius",group:"Bloom",min:0,max:1,step:.01,precision:2,slider:!0,readOnly:t=>!t.bloomEnabled},getValue:t=>t.bloomRadius,setValue:(t,r)=>{t.bloomRadius=Number(r)}}),x("vignetteEnabled","boolean",{ui:{label:"Enabled",group:"Vignette"},getValue:t=>t.vignetteEnabled,setValue:(t,r)=>{t.vignetteEnabled=!!r}}),x("vignetteOffset","number",{ui:{label:"Offset",group:"Vignette",min:0,max:1,step:.01,precision:2,slider:!0,readOnly:t=>!t.vignetteEnabled},getValue:t=>t.vignetteOffset,setValue:(t,r)=>{t.vignetteOffset=Number(r)}}),x("vignetteDarkness","number",{ui:{label:"Darkness",group:"Vignette",min:0,max:1,step:.01,precision:2,slider:!0,readOnly:t=>!t.vignetteEnabled},getValue:t=>t.vignetteDarkness,setValue:(t,r)=>{t.vignetteDarkness=Number(r)}}),x("chromaticAberrationEnabled","boolean",{ui:{label:"Enabled",group:"Chromatic Aberration"},getValue:t=>t.chromaticAberrationEnabled,setValue:(t,r)=>{t.chromaticAberrationEnabled=!!r}}),x("chromaticAberrationOffset","number",{ui:{label:"Offset",description:"RGB channel separation (animatable \u2014 a damage pulse)",group:"Chromatic Aberration",min:0,max:.1,step:5e-4,precision:4,readOnly:t=>!t.chromaticAberrationEnabled},getValue:t=>t.chromaticAberrationOffset,setValue:(t,r)=>{t.chromaticAberrationOffset=Number(r)}}),x("aoMode","enum",{ui:{label:"Mode",description:"Off \xB7 Baked (per-mesh maps, cheap) \xB7 Realtime (SSAO, desktop) \xB7 Adaptive (by device)",group:"Ambient Occlusion",options:[...Mu]},getValue:t=>t.aoMode,setValue:(t,r)=>{t.aoMode=String(r)}}),x("ssaoIntensity","number",{ui:{label:"SSAO Intensity",group:"Ambient Occlusion",min:0,max:4,step:.05,precision:2,slider:!0,readOnly:t=>!Cu(t.aoMode)},getValue:t=>t.ssaoIntensity,setValue:(t,r)=>{t.ssaoIntensity=Number(r)}}),x("ssaoRadius","number",{ui:{label:"SSAO Radius",description:"Sampling radius (larger = broader, softer occlusion)",group:"Ambient Occlusion",min:0,max:2,step:.01,precision:2,slider:!0,readOnly:t=>!Cu(t.aoMode)},getValue:t=>t.ssaoRadius,setValue:(t,r)=>{t.ssaoRadius=Number(r)}}),x("lutEnabled","boolean",{ui:{label:"Enabled",description:"Color grading via a lookup table (.cube / .3dl)",group:"Color Grading"},getValue:t=>t.lutEnabled,setValue:(t,r)=>{t.lutEnabled=!!r}}),x("lutSrc","string",{ui:{label:"LUT",description:"Asset URL of a .cube or .3dl lookup table",group:"Color Grading",readOnly:t=>!t.lutEnabled},getValue:t=>t.lutSrc,setValue:(t,r)=>{t.lutSrc=typeof r=="string"?r:""}}),x("lutIntensity","number",{ui:{label:"Intensity",group:"Color Grading",min:0,max:1,step:.01,precision:2,slider:!0,readOnly:t=>!t.lutEnabled},getValue:t=>t.lutIntensity,setValue:(t,r)=>{t.lutIntensity=Number(r)}})],groups:{General:{label:"General",expanded:!0},Bloom:{label:"Bloom",expanded:!0},Vignette:{label:"Vignette",expanded:!1},"Chromatic Aberration":{label:"Chromatic Aberration",expanded:!1},"Ambient Occlusion":{label:"Ambient Occlusion",expanded:!0},"Color Grading":{label:"Color Grading",expanded:!1}}}}};function Wf(n){let e=typeof n=="string"?n.toLowerCase():"";return Mu.includes(e)?e:"baked"}function Cu(n){return n==="realtime"||n==="adaptive"}function $f(){if(typeof navigator>"u")return!1;let n=navigator;if(typeof n.userAgentData?.mobile=="boolean"?n.userAgentData.mobile:/Mobi|Android|iPhone|iPad|iPod/i.test(n.userAgent??""))return!1;let t=typeof n.hardwareConcurrency=="number"?n.hardwareConcurrency:4,r=typeof n.deviceMemory=="number"?n.deviceMemory:8;return t>=6&&r>=4}function un(n,e){return typeof n=="boolean"?n:e}function jx(n,e){return typeof n=="string"?n:e}function Ze(n,e,t=Number.NEGATIVE_INFINITY){let r=Number(n);return Number.isFinite(r)?Math.max(t,r):e}function wt(n,e,t){let r=Number(n);return Number.isFinite(r)?Math.max(e,r):t}function Yx(n,e){let t=Number(n);return Number.isFinite(t)?t<0?0:t>1?1:t:e}var Fb=_p(ch(),1);var Pi=new S(0,0,0),Lb=new S(1,1,1),ee=new I(0,0),he=new I(1,1),ve=class extends Error{details;constructor(e,t){super(e),this.name="SceneValidationError",this.details=t}},uh=class{assetLoader;scriptRegistry;resourceManager;constructor(e,t,r){this.assetLoader=e,this.scriptRegistry=t,this.resourceManager=r}async parseScene(e,t={}){let r;console.debug("[SceneLoader.parseScene] Starting parse",{contentLength:e.length,contentPreview:e.substring(0,100),filePath:t.filePath});try{r=(0,Fb.parse)(e)}catch(a){throw new ve(`Failed to parse scene YAML${t.filePath?` (${t.filePath})`:""}.`,[a.message])}if(!r)throw console.error("[SceneLoader.parseScene] YAML parser returned null",{contentLength:e.length,contentPreview:e.substring(0,100),filePath:t.filePath}),new ve(`Scene document is empty or invalid${t.filePath?` (${t.filePath})`:""}.`,["The YAML parser returned null or undefined"]);let i=new Map,o=[],s=[...t.instanceStack??[]];for(let a of r.root??[]){let l=await this.instantiateNode(a,null,i,t.filePath??"unknown",s);o.push(l)}return{version:r.version,description:r.description,metadata:r.metadata??{},rootNodes:o,nodeMap:i}}async instantiateNode(e,t,r,i,o){if(e.instance)return await this.instantiateInstanceNode(e,t,r,i,o);if(r.has(e.id))throw new ve(`Duplicate node id "${e.id}" detected.`,[i]);let s=await this.createNodeFromDefinition(e);if(Array.isArray(e.groups))for(let l of e.groups)typeof l=="string"&&l.trim().length>0&&s.addToGroup(l);r.set(s.nodeId,s),us(s,e.components,this.scriptRegistry),t&&t.adoptChild(s);let a=e.children??[];for(let l of a)await this.instantiateNode(l,s,r,i,o);return s}async instantiatePrefab(e,t){let r={id:t,instance:e};return await this.instantiateInstanceNode(r,null,new Map,`runtime-instantiate:${e}`,[])}async instantiateInstanceNode(e,t,r,i,o){if(r.has(e.id))throw new ve(`Duplicate node id "${e.id}" detected.`,[i]);let s=e.instance;if(!s)throw new ve("Instance node is missing an instance path.",[i]);let a=this.normalizeInstancePath(s);if(o.includes(a)){let f=[...o,a].join(" -> ");throw new ve(`Instance cycle detected for "${a}".`,[f])}let l=[...o,a],c=await this.resourceManager.readText(a),u=await this.parseScene(c,{filePath:a,instanceStack:l});if(!u.rootNodes.length)throw new ve(`Instance "${a}" has no root nodes.`,[i]);if(u.rootNodes.length>1)throw new ve(`Instance "${a}" must contain exactly one root node.`,[i]);let d=u.rootNodes[0],h=new Set(r.keys());h.add(e.id);let p=await this.cloneNodeWithRuntimeIds(d,e.id,r,e.id,a,this.normalizeLocalId(d.nodeId),a,h);return p.name=e.name??p.name,this.addGroupsFromDefinition(p,e),this.mergeMetadata(p,e.metadata??{}),this.remapNodeReferences(p),this.snapshotPrefabBaseProperties(p),this.applyLegacyInstanceRootProperties(p,e.properties??{}),this.applyInstanceOverrides(p,e.overrides??null),t&&t.adoptChild(p),this.registerSubtree(r,p,i),p}normalizeInstancePath(e){return e.replace(/\\/g,"/").trim()}normalizeLocalId(e){return e.replace(/\\/g,"/").replace(/^\/+/,"").trim()}addGroupsFromDefinition(e,t){if(Array.isArray(t.groups))for(let r of t.groups)typeof r=="string"&&r.trim().length>0&&e.addToGroup(r)}mergeMetadata(e,t){Object.assign(e.metadata,t)}registerSubtree(e,t,r){let i=[t];for(;i.length>0;){let o=i.pop();if(o){if(e.has(o.nodeId))throw new ve(`Duplicate node id "${o.nodeId}" detected.`,[r]);e.set(o.nodeId,o);for(let s of o.children)s instanceof V&&i.push(s)}}}async cloneNodeWithRuntimeIds(e,t,r,i,o,s,a,l){let c=this.getPrefabMarker(e),u=this.normalizeLocalId(c?.localId??e.nodeId),d=c?.sourcePath??o,h={id:t,type:e.type,name:e.name,instancePath:t===i?a??e.instancePath??void 0:e.instancePath??void 0,groups:Array.from(e.groups),properties:this.captureNodeComparableProperties(e),metadata:{...e.metadata},components:Yi(e)},p=this.createPrefabMarker({localId:u,effectiveLocalId:s,instanceRootId:i,sourcePath:d}),f=h.metadata??{};f.__pix3Prefab=p,h.metadata=f;let m=await this.createNodeFromDefinition(h);this.populateNodeComponents(m,h.components??[]);for(let g of e.children){if(!(g instanceof V))continue;let y=this.generateUniqueRuntimeNodeId(this.normalizeLocalId(g.nodeId),r,l),b=this.getPrefabMarker(g),v=this.normalizeLocalId(b?.localId??g.nodeId),w=`${s}/${v}`,k=await this.cloneNodeWithRuntimeIds(g,y,r,i,d,w,null,l);m.adoptChild(k)}return m}createPrefabMarker(e){return{localId:this.normalizeLocalId(e.localId),effectiveLocalId:this.normalizeLocalId(e.effectiveLocalId),instanceRootId:e.instanceRootId,sourcePath:e.sourcePath}}populateNodeComponents(e,t){us(e,t,this.scriptRegistry)}resolvePendingComponents(e){return jc(e,this.scriptRegistry)}generateUniqueRuntimeNodeId(e,t,r){let i=e.replace(/[^a-zA-Z0-9_-]/g,"-").toLowerCase()||"node",o=i,s=1;for(;t.has(o)||r.has(o);)o=`${i}-${s}`,s+=1;return r.add(o),o}remapNodeReferences(e){let t=new Map,r=new Map;this.walkSubtree(e,i=>{let o=this.getPrefabMarker(i);o&&(t.has(o.sourcePath)||t.set(o.sourcePath,new Map),t.get(o.sourcePath)?.set(o.localId,i.nodeId),r.set(o.effectiveLocalId,i.nodeId))}),this.walkSubtree(e,i=>{let o=this.getPrefabMarker(i),s=o?t.get(o.sourcePath)??null:null,a=ke(i);this.remapPropertiesBySchema(i,a.properties,s,r);for(let l of i.components){let c=this.scriptRegistry.getComponentPropertySchema(l.type);c&&this.remapPropertiesBySchema(l,c.properties,s,r)}})}remapPropertiesBySchema(e,t,r,i){for(let o of t){if(o.type!=="node")continue;let s=o.getValue(e);if(typeof s!="string"||!s.trim())continue;let a=(r?r.get(this.normalizeLocalId(s)):void 0)??i.get(this.normalizeLocalId(s));a&&a!==s&&o.setValue(e,a)}}snapshotPrefabBaseProperties(e){let t={};this.walkSubtree(e,o=>{let s=this.getPrefabMarker(o);s&&(t[s.effectiveLocalId]=this.captureNodeComparableProperties(o))});let r=this.getPrefabMarker(e);if(!r)return;let i={...r,basePropertiesByLocalId:t};e.metadata.__pix3Prefab=i}captureNodeComparableProperties(e){let t=ke(e),r={};for(let i of t.properties)i.ui?.hidden||i.ui?.readOnly===!0||(r[i.name]=this.cloneValue(i.getValue(e)));return r}applyInstanceOverrides(e,t){if(!t||!t.byLocalId)return;let r=new Map;this.walkSubtree(e,s=>{let a=this.getPrefabMarker(s);a&&r.set(a.effectiveLocalId,s)});let o=this.getPrefabMarker(e)?.effectiveLocalId??"";for(let[s,a]of Object.entries(t.byLocalId)){let l=this.normalizeLocalId(s),c=o&&l!==o?`${o}/${l}`:l,u=r.get(c)??r.get(l);if(!u){console.warn(`[SceneLoader] Override target "${s}" not found in instance.`);continue}this.applyLegacyInstanceRootProperties(u,a.properties??{})}}applyLegacyInstanceRootProperties(e,t){if(!t||Object.keys(t).length===0)return;let r=ke(e),i=new Map(r.properties.map(o=>[o.name,o]));for(let[o,s]of Object.entries(t)){if(o==="transform"){this.applyTransformOverride(e,i,s);continue}let a=i.get(o);if(!a){e.properties[o]=this.cloneValue(s);continue}a.setValue(e,this.normalizePropertyValue(s,a))}}applyTransformOverride(e,t,r){let i=this.asRecord(r);if(!i)return;let o=i.position??i.translate,s=i.rotationEuler??i.rotation??i.euler,a=i.scale,l=t.get("position");l&&o!==void 0&&l.setValue(e,this.normalizePropertyValue(o,l));let c=t.get("rotation");c&&s!==void 0&&c.setValue(e,this.normalizePropertyValue(s,c));let u=t.get("scale");u&&a!==void 0&&u.setValue(e,this.normalizePropertyValue(a,u))}normalizePropertyValue(e,t){if(t.type==="vector2"){let r=this.readVector2(e,ee);return{x:r.x,y:r.y}}if(t.type==="vector3"||t.type==="euler"){let r=this.readVector3(e,Pi);return{x:r.x,y:r.y,z:r.z}}return e}walkSubtree(e,t){let r=[e];for(;r.length>0;){let i=r.pop();if(i){t(i);for(let o of i.children)o instanceof V&&r.push(o)}}}getPrefabMarker(e){let r=e.metadata.__pix3Prefab;if(!r||typeof r!="object")return null;let i=r;return typeof i.localId!="string"||typeof i.effectiveLocalId!="string"||typeof i.instanceRootId!="string"||typeof i.sourcePath!="string"?null:i}cloneValue(e){return e==null||typeof e!="object"?e:JSON.parse(JSON.stringify(e))}async createNodeFromDefinition(e){let t={id:e.id,name:e.name,instancePath:e.instancePath??null,properties:{...e.properties??{}},metadata:e.metadata??{}};switch(As(e.type)??e.type){case"ColorRect2D":{let r=t.properties,i=this.asRecord(r.transform);return new dr({...t,properties:r,position:this.readVector2(i?.position??r.position,ee),scale:this.readVector2(i?.scale??r.scale,he),rotation:typeof(i?.rotation??r.rotation)=="number"?i?.rotation??r.rotation:0,layout:this.parseNode2DLayout(r),flow:this.parseNode2DFlow(r),width:this.asNumber(r.width,void 0),height:this.asNumber(r.height,void 0),color:typeof r.color=="string"?r.color:void 0,opacity:typeof r.opacity=="number"?r.opacity:void 0})}case"AnimatedSprite2D":{let r=t.properties,i=this.asRecord(r.transform),o=typeof r.animationResourcePath=="string"&&r.animationResourcePath.trim().length>0?r.animationResourcePath.trim():null,s=new Ke({...t,properties:r,position:this.readVector2(i?.position??r.position,ee),scale:this.readVector2(i?.scale??r.scale,he),rotation:typeof(i?.rotation??r.rotation)=="number"?i?.rotation??r.rotation:0,layout:this.parseNode2DLayout(r),flow:this.parseNode2DFlow(r),opacity:this.asNumber(r.opacity,void 0),animationResourcePath:o,currentClip:typeof r.currentClip=="string"?r.currentClip:void 0,isPlaying:typeof r.isPlaying=="boolean"?r.isPlaying:void 0,freeOnFinish:typeof r.freeOnFinish=="boolean"?r.freeOnFinish:void 0,currentFrame:typeof r.currentFrame=="number"?r.currentFrame:void 0,width:this.asNumber(r.width,void 0),height:this.asNumber(r.height,void 0),color:typeof r.color=="string"?r.color:void 0,anchor:this.readVector2(r.anchor,new I(.5,.5)),sizeMode:r.sizeMode==="native"?"native":void 0});return o&&this.loadAnimatedSprite2DAsset(s,o),s}case"SpineSkeleton2D":{let r=t.properties,i=this.asRecord(r.transform),o=new ur({...t,properties:r,position:this.readVector2(i?.position??r.position,ee),scale:this.readVector2(i?.scale??r.scale,he),rotation:typeof(i?.rotation??r.rotation)=="number"?i?.rotation??r.rotation:0,layout:this.parseNode2DLayout(r),flow:this.parseNode2DFlow(r),opacity:this.asNumber(r.opacity,void 0),skeletonPath:this.asString(r.skeletonPath)??null,atlasPath:this.asString(r.atlasPath)??null,texture:D(r.texture??r.texturePath??null),animation:this.asString(r.animation),loop:typeof r.loop=="boolean"?r.loop:void 0,isPlaying:typeof r.isPlaying=="boolean"?r.isPlaying:void 0,skin:this.asString(r.skin),timeScale:this.asNumber(r.timeScale,void 0),defaultMix:this.asNumber(r.defaultMix,void 0),color:this.asString(r.color),twoColorTint:typeof r.twoColorTint=="boolean"?r.twoColorTint:void 0,freeOnFinish:typeof r.freeOnFinish=="boolean"?r.freeOnFinish:void 0,previewInEditor:typeof r.previewInEditor=="boolean"?r.previewInEditor:void 0});return this.loadSpineSkeleton2DAsset(o),o}case"Sprite2D":{let r=t.properties,i=this.asRecord(r.transform),o=D(r.texture??r.texturePath??null),s=new Le({...t,properties:r,position:this.readVector2(i?.position??r.position,ee),scale:this.readVector2(i?.scale??r.scale,he),rotation:typeof(i?.rotation??r.rotation)=="number"?i?.rotation??r.rotation:0,layout:this.parseNode2DLayout(r),flow:this.parseNode2DFlow(r),opacity:this.asNumber(r.opacity,void 0),texture:o,textureKey:this.asString(r.textureKey),width:this.asNumber(r.width,void 0),height:this.asNumber(r.height,void 0),aspectRatioLocked:typeof r.aspectRatioLocked=="boolean"?r.aspectRatioLocked:void 0,anchor:this.readVector2(r.anchor,new I(.5,.5)),color:typeof r.color=="string"?r.color:void 0}),a=s.getEffectiveTexturePath();if(a)try{let l=await this.assetLoader.loadTexture(a);s.setTexture(l)}catch(l){console.warn(`[SceneLoader] Error loading texture for Sprite2D "${s.nodeId}":`,l)}return s}case"TiledSprite2D":{let r=t.properties,i=this.asRecord(r.transform),o=D(r.texture??r.texturePath??null),s=o?.url??null,a=new pr({...t,properties:r,position:this.readVector2(i?.position??r.position,ee),scale:this.readVector2(i?.scale??r.scale,he),rotation:typeof(i?.rotation??r.rotation)=="number"?i?.rotation??r.rotation:0,layout:this.parseNode2DLayout(r),flow:this.parseNode2DFlow(r),opacity:this.asNumber(r.opacity,void 0),texture:o,width:this.asNumber(r.width,void 0),height:this.asNumber(r.height,void 0),patchMode:typeof r.patchMode=="string"?r.patchMode:void 0,sliceBorder:{left:this.asNumber(r.sliceBorderLeft,0),right:this.asNumber(r.sliceBorderRight,0),top:this.asNumber(r.sliceBorderTop,0),bottom:this.asNumber(r.sliceBorderBottom,0)},drawCenter:typeof r.drawCenter=="boolean"?r.drawCenter:void 0,axisStretchHorizontal:typeof r.axisStretchHorizontal=="string"?r.axisStretchHorizontal:void 0,axisStretchVertical:typeof r.axisStretchVertical=="string"?r.axisStretchVertical:void 0,tileScale:this.readVector2(r.tileScale,new I(1,1)),tileOffset:this.readVector2(r.tileOffset,ee),anchor:this.readVector2(r.anchor,new I(.5,.5)),color:typeof r.color=="string"?r.color:void 0});if(s)try{let l=await this.assetLoader.loadTexture(s,{atlas:!1});a.setTexture(l)}catch(l){console.warn(`[SceneLoader] Error loading texture for TiledSprite2D "${a.nodeId}":`,l)}return a}case"AudioPlayer":{let r=t.properties;return new gt({...t,audioTrack:this.asString(r.audioTrack),autoplay:typeof r.autoplay=="boolean"?r.autoplay:void 0,loop:typeof r.loop=="boolean"?r.loop:void 0,volume:this.asNumber(r.volume,void 0),bus:this.asString(r.bus),pitchVariation:this.asNumber(r.pitchVariation,void 0),volumeVariation:this.asNumber(r.volumeVariation,void 0)})}case"PostProcess":return new et({...t});case"Group":return new V({...t,type:"Group"});case"Node3D":case void 0:{let r=this.parseNode3DTransforms(t.properties);return new U({...t,properties:r.restProps,position:r.position,rotation:r.rotation,rotationOrder:r.rotationOrder,scale:r.scale})}case"Node2D":{let r=t.properties,i=t.properties,o=this.asRecord(i.transform),s=o?.rotation??r.rotation;return new M({...t,position:this.readVector2(o?.position??r.position,ee),scale:this.readVector2(o?.scale??r.scale,he),rotation:typeof s=="number"?s:0,layout:this.parseNode2DLayout(i),flow:this.parseNode2DFlow(i),opacity:this.asNumber(r.opacity,void 0)})}case"Layout2D":throw new ve("Layout2D nodes are no longer supported.",[`Node ${e.id} still uses legacy type Layout2D. Replace it with root Node2D/Group2D anchors and project viewport settings.`]);case"Group2D":{let r=t.properties,i=this.asRecord(r.transform);return new Ae({...t,position:this.readVector2(i?.position??r.position,ee),scale:this.readVector2(i?.scale??r.scale,he),rotation:typeof(i?.rotation??r.rotation)=="number"?i?.rotation??r.rotation:0,layout:this.parseNode2DLayout(r),flow:this.parseNode2DFlow(r),opacity:this.asNumber(r.opacity,void 0),width:this.asNumber(r.width,100),height:this.asNumber(r.height,100)})}case"CanvasLayer2D":{let r=t.properties,i=this.asRecord(r.transform);return new sn({...t,position:this.readVector2(i?.position??r.position,ee),scale:this.readVector2(i?.scale??r.scale,he),rotation:typeof(i?.rotation??r.rotation)=="number"?i?.rotation??r.rotation:0,layout:this.parseNode2DLayout(r),flow:this.parseNode2DFlow(r),opacity:this.asNumber(r.opacity,void 0),width:this.asNumber(r.width,100),height:this.asNumber(r.height,100)})}case"Camera2D":{let r=t.properties,i=this.asRecord(r.transform),o=ks;return new Vt({...t,position:this.readVector2(i?.position??r.position,ee),scale:this.readVector2(i?.scale??r.scale,he),rotation:typeof(i?.rotation??r.rotation)=="number"?i?.rotation??r.rotation:0,layout:this.parseNode2DLayout(r),flow:this.parseNode2DFlow(r),opacity:this.asNumber(r.opacity,void 0),priority:this.asNumber(r.priority,o.priority),zoom:this.asNumber(r.zoom,o.zoom),offset:this.readVector2(r.offset,ee),followTargetId:this.asString(r.followTargetId)??"",followDamping:this.asNumber(r.followDamping,o.followDamping),followOffset:this.readVector2(r.followOffset,ee),deadzone:this.readVector2(r.deadzone,ee),limitsEnabled:typeof r.limitsEnabled=="boolean"?r.limitsEnabled:!1,limitsCenter:this.readVector2(r.limitsCenter,ee),limitsSize:r.limitsSize!==void 0?this.readVector2(r.limitsSize,ee):void 0,shakeAmplitude:this.asNumber(r.shakeAmplitude,o.shakeAmplitude),shakeFrequency:this.asNumber(r.shakeFrequency,o.shakeFrequency),shakeDuration:this.asNumber(r.shakeDuration,o.shakeDuration),shakeDecay:this.asNumber(r.shakeDecay,o.shakeDecay)})}case"ScrollContainer2D":{let r=t.properties,i=this.asRecord(r.transform),o=D(r.scrollbarThumbTexture??null),s=D(r.scrollbarTrackTexture??null),a=new Je({...t,position:this.readVector2(i?.position??r.position,ee),scale:this.readVector2(i?.scale??r.scale,he),rotation:typeof(i?.rotation??r.rotation)=="number"?i?.rotation??r.rotation:0,layout:this.parseNode2DLayout(r),flow:this.parseNode2DFlow(r),opacity:this.asNumber(r.opacity,void 0),width:this.asNumber(r.width,100),height:this.asNumber(r.height,100),scrollY:this.asNumber(r.scrollY,0),dragScrollEnabled:typeof r.dragScrollEnabled=="boolean"?r.dragScrollEnabled:void 0,wheelScrollEnabled:typeof r.wheelScrollEnabled=="boolean"?r.wheelScrollEnabled:void 0,inertiaEnabled:typeof r.inertiaEnabled=="boolean"?r.inertiaEnabled:void 0,showScrollbar:typeof r.showScrollbar=="boolean"?r.showScrollbar:void 0,wheelSensitivity:this.asNumber(r.wheelSensitivity,void 0),dragThreshold:this.asNumber(r.dragThreshold,void 0),inertiaDamping:this.asNumber(r.inertiaDamping,void 0),scrollbarWidth:this.asNumber(r.scrollbarWidth,void 0),scrollbarMinHeight:this.asNumber(r.scrollbarMinHeight,void 0),scrollbarInset:this.asNumber(r.scrollbarInset,void 0),scrollbarColor:this.asString(r.scrollbarColor),scrollbarTrackColor:this.asString(r.scrollbarTrackColor),scrollbarThumbTexture:o,scrollbarTrackTexture:s});if(o)try{a.setScrollbarThumbTexture(await this.assetLoader.loadTexture(o.url))}catch(l){console.warn(`[SceneLoader] Error loading scrollbar thumb texture for ScrollContainer2D "${a.nodeId}":`,l)}if(s)try{a.setScrollbarTrackTexture(await this.assetLoader.loadTexture(s.url))}catch(l){console.warn(`[SceneLoader] Error loading scrollbar track texture for ScrollContainer2D "${a.nodeId}":`,l)}return a}case"Joystick2D":{let r=t.properties,i=this.asRecord(r.transform);return new br({...t,position:this.readVector2(i?.position??r.position,ee),scale:this.readVector2(i?.scale??r.scale,he),rotation:typeof(i?.rotation??r.rotation)=="number"?i?.rotation??r.rotation:0,layout:this.parseNode2DLayout(r),flow:this.parseNode2DFlow(r),opacity:this.asNumber(r.opacity,void 0),radius:this.asNumber(r.radius,void 0),handleRadius:this.asNumber(r.handleRadius,void 0),axisHorizontal:this.asString(r.axisHorizontal),axisVertical:this.asString(r.axisVertical),baseColor:this.asString(r.baseColor),handleColor:this.asString(r.handleColor),floating:typeof r.floating=="boolean"?r.floating:void 0})}case"Button2D":{let r=t.properties,i=this.asRecord(r.transform),o=[["normal",D(r.textureNormal??null)],["hover",D(r.textureHover??null)],["pressed",D(r.texturePressed??null)],["disabled",D(r.textureDisabled??null)]],s={};{let l=this.asRecord(r.stateTextureKeys);for(let c of["normal","hover","pressed","disabled"]){let u=l?this.asString(l[c]):void 0;u&&(s[c]=u)}}let a=new mt({...t,position:this.readVector2(i?.position??r.position,ee),scale:this.readVector2(i?.scale??r.scale,he),rotation:typeof(i?.rotation??r.rotation)=="number"?i?.rotation??r.rotation:0,layout:this.parseNode2DLayout(r),flow:this.parseNode2DFlow(r),opacity:this.asNumber(r.opacity,void 0),width:this.asNumber(r.width,void 0),height:this.asNumber(r.height,void 0),backgroundColor:this.asString(r.backgroundColor),hoverColor:this.asString(r.hoverColor),pressedColor:this.asString(r.pressedColor),buttonAction:this.asString(r.buttonAction),label:this.asString(r.label),labelKey:this.asString(r.labelKey),...this.readLabelStyle(r),labelAlign:this.asString(r.labelAlign),texturePath:this.asString(r.texturePath),enabled:typeof r.enabled=="boolean"?r.enabled:void 0,textureNormal:o[0][1],textureHover:o[1][1],texturePressed:o[2][1],textureDisabled:o[3][1],stateTextureKeys:s,sliceBorder:this.readSliceBorder(r)});for(let[l]of o){let c=a.getEffectiveStateTexturePath(l);if(c)try{a.setStateTexture(l,await this.assetLoader.loadTexture(c))}catch(u){console.warn(`[SceneLoader] Error loading ${l} texture for Button2D "${a.nodeId}":`,u)}}return a}case"Label2D":{let r=t.properties,i=this.asRecord(r.transform);return new ft({...t,position:this.readVector2(i?.position??r.position,ee),scale:this.readVector2(i?.scale??r.scale,he),rotation:typeof(i?.rotation??r.rotation)=="number"?i?.rotation??r.rotation:0,layout:this.parseNode2DLayout(r),flow:this.parseNode2DFlow(r),opacity:this.asNumber(r.opacity,void 0),label:this.asString(r.label),labelKey:this.asString(r.labelKey),...this.readLabelStyle(r),labelAlign:this.asString(r.labelAlign),labelVAlign:this.asString(r.labelVAlign),width:this.asNumber(r.width,void 0),height:this.asNumber(r.height,void 0),typewriterSpeed:this.asNumber(r.typewriterSpeed,void 0),glowColor:this.asString(r.glowColor),glowStrength:this.asNumber(r.glowStrength,void 0),outlineColor:this.asString(r.outlineColor),outlineWidth:this.asNumber(r.outlineWidth,void 0),enabled:typeof r.enabled=="boolean"?r.enabled:void 0})}case"Slider2D":{let r=t.properties,i=this.asRecord(r.transform),o=new vr({...t,position:this.readVector2(i?.position??r.position,ee),scale:this.readVector2(i?.scale??r.scale,he),rotation:typeof(i?.rotation??r.rotation)=="number"?i?.rotation??r.rotation:0,layout:this.parseNode2DLayout(r),flow:this.parseNode2DFlow(r),opacity:this.asNumber(r.opacity,void 0),width:this.asNumber(r.width,void 0),height:this.asNumber(r.height,void 0),handleSize:this.asNumber(r.handleSize,void 0),trackBackgroundColor:this.asString(r.trackBackgroundColor),trackFilledColor:this.asString(r.trackFilledColor),handleColor:this.asString(r.handleColor),minValue:this.asNumber(r.minValue,void 0),maxValue:this.asNumber(r.maxValue,void 0),value:this.asNumber(r.value,void 0),axisName:this.asString(r.axisName),label:this.asString(r.label),labelKey:this.asString(r.labelKey),...this.readLabelStyle(r),labelAlign:this.asString(r.labelAlign),texturePath:this.asString(r.texturePath),enabled:typeof r.enabled=="boolean"?r.enabled:void 0,textureTrack:D(r.textureTrack??null),textureFill:D(r.textureFill??null),textureThumb:D(r.textureThumb??null),sliceBorder:this.readSliceBorder(r)});for(let s of["track","fill","thumb"]){let a=o.getSlotTexturePath(s);if(a)try{o.setSlotTexture(s,await this.assetLoader.loadTexture(a))}catch(l){console.warn(`[SceneLoader] Error loading ${s} texture for Slider2D "${o.nodeId}":`,l)}}return o}case"Bar2D":{let r=t.properties,i=this.asRecord(r.transform),o=new wr({...t,position:this.readVector2(i?.position??r.position,ee),scale:this.readVector2(i?.scale??r.scale,he),rotation:typeof(i?.rotation??r.rotation)=="number"?i?.rotation??r.rotation:0,layout:this.parseNode2DLayout(r),flow:this.parseNode2DFlow(r),opacity:this.asNumber(r.opacity,void 0),width:this.asNumber(r.width,void 0),height:this.asNumber(r.height,void 0),backBackgroundColor:this.asString(r.backBackgroundColor),barColor:this.asString(r.barColor),minValue:this.asNumber(r.minValue,void 0),maxValue:this.asNumber(r.maxValue,void 0),value:this.asNumber(r.value,void 0),showBorder:typeof r.showBorder=="boolean"?r.showBorder:void 0,borderColor:this.asString(r.borderColor),borderWidth:this.asNumber(r.borderWidth,void 0),label:this.asString(r.label),labelKey:this.asString(r.labelKey),...this.readLabelStyle(r),labelAlign:this.asString(r.labelAlign),texturePath:this.asString(r.texturePath),enabled:typeof r.enabled=="boolean"?r.enabled:void 0,textureTrough:D(r.textureTrough??null),textureFill:D(r.textureFill??null),sliceBorder:this.readSliceBorder(r)});for(let s of["trough","fill"]){let a=o.getSlotTexturePath(s);if(a)try{o.setSlotTexture(s,await this.assetLoader.loadTexture(a))}catch(l){console.warn(`[SceneLoader] Error loading ${s} texture for Bar2D "${o.nodeId}":`,l)}}return o}case"Checkbox2D":{let r=t.properties,i=this.asRecord(r.transform),o=new xr({...t,position:this.readVector2(i?.position??r.position,ee),scale:this.readVector2(i?.scale??r.scale,he),rotation:typeof(i?.rotation??r.rotation)=="number"?i?.rotation??r.rotation:0,layout:this.parseNode2DLayout(r),flow:this.parseNode2DFlow(r),opacity:this.asNumber(r.opacity,void 0),size:this.asNumber(r.size,void 0),checked:typeof r.checked=="boolean"?r.checked:void 0,uncheckedColor:this.asString(r.uncheckedColor),checkedColor:this.asString(r.checkedColor),checkmarkColor:this.asString(r.checkmarkColor),checkmarkAction:this.asString(r.checkmarkAction),label:this.asString(r.label),labelKey:this.asString(r.labelKey),...this.readLabelStyle(r),labelAlign:this.asString(r.labelAlign),texturePath:this.asString(r.texturePath),enabled:typeof r.enabled=="boolean"?r.enabled:void 0,textureBox:D(r.textureBox??null),textureBoxChecked:D(r.textureBoxChecked??null),textureMark:D(r.textureMark??null)});for(let s of["box","boxChecked","mark"]){let a=o.getSlotTexturePath(s);if(a)try{o.setSlotTexture(s,await this.assetLoader.loadTexture(a))}catch(l){console.warn(`[SceneLoader] Error loading ${s} texture for Checkbox2D "${o.nodeId}":`,l)}}return o}case"InventorySlot2D":{let r=t.properties,i=this.asRecord(r.transform);return new Pr({...t,position:this.readVector2(i?.position??r.position,ee),scale:this.readVector2(i?.scale??r.scale,he),rotation:typeof(i?.rotation??r.rotation)=="number"?i?.rotation??r.rotation:0,layout:this.parseNode2DLayout(r),flow:this.parseNode2DFlow(r),opacity:this.asNumber(r.opacity,void 0),width:this.asNumber(r.width,void 0),height:this.asNumber(r.height,void 0),backdropColor:this.asString(r.backdropColor),borderColor:this.asString(r.borderColor),borderWidth:this.asNumber(r.borderWidth,void 0),quantity:this.asNumber(r.quantity,void 0),showQuantity:typeof r.showQuantity=="boolean"?r.showQuantity:void 0,quantityFontSize:this.asNumber(r.quantityFontSize,void 0),selectionColor:this.asString(r.selectionColor),selectedAction:this.asString(r.selectedAction),label:this.asString(r.label),labelKey:this.asString(r.labelKey),...this.readLabelStyle(r),labelAlign:this.asString(r.labelAlign),texturePath:this.asString(r.texturePath),enabled:typeof r.enabled=="boolean"?r.enabled:void 0})}case"GeometryMesh":{let r=this.parseNode3DTransforms(t.properties),i=t.properties,o=this.asString(i.geometry)??"box",s=this.readVector3(i.size,Lb),a=typeof i.castShadow=="boolean"?i.castShadow:!0,l=typeof i.receiveShadow=="boolean"?i.receiveShadow:!0,c=this.asRecord(i.material),d={color:this.asString(c?.color)??"#4e8df5"},h=this.asString(c?.type);h&&(d.type=h),typeof c?.roughness=="number"&&(d.roughness=c.roughness),typeof c?.metalness=="number"&&(d.metalness=c.metalness);let p=this.asString(c?.aoMap);p&&(d.aoMap=p),typeof c?.aoMapIntensity=="number"&&(d.aoMapIntensity=c.aoMapIntensity);let f=this.asString(c?.map);f&&(d.map=f);let m=this.parseGeometryMeshEffects(c?.effects);m&&(d.effects=m);let g=new yt({...t,properties:r.restProps,position:r.position,rotation:r.rotation,rotationOrder:r.rotationOrder,scale:r.scale,geometry:o,size:[s.x,s.y,s.z],castShadow:a,receiveShadow:l,material:d});if(p)try{let y=await this.assetLoader.loadTexture(p,{atlas:!1});g.setAOMap(y)}catch(y){console.warn(`[SceneLoader] Error loading AO map for GeometryMesh "${g.nodeId}":`,y)}if(f)try{let y=await this.assetLoader.loadTexture(f,{atlas:!1});g.setMap(y)}catch(y){console.warn(`[SceneLoader] Error loading albedo map for GeometryMesh "${g.nodeId}":`,y)}return g}case"InstancedMesh3D":{let r=this.parseNode3DTransforms(t.properties),i=t.properties,o=this.asPositiveInteger(i.maxInstances),s=this.asRecord(i.material),a={type:this.asString(s?.type),color:this.asString(s?.color),roughness:typeof s?.roughness=="number"?s.roughness:void 0,metalness:typeof s?.metalness=="number"?s.metalness:void 0};if(o===null)throw new ve(`Node "${e.id}" has invalid InstancedMesh3D.maxInstances value.`,["maxInstances must be a positive integer."]);return new bt({...t,properties:r.restProps,position:r.position,rotation:r.rotation,rotationOrder:r.rotationOrder,scale:r.scale,maxInstances:o,castShadow:typeof i.castShadow=="boolean"?i.castShadow:!1,receiveShadow:typeof i.receiveShadow=="boolean"?i.receiveShadow:!1,enablePerInstanceColor:typeof i.enablePerInstanceColor=="boolean"?i.enablePerInstanceColor:!1,frustumCulled:typeof i.frustumCulled=="boolean"?i.frustumCulled:void 0,materialConfig:a})}case"DirectionalLightNode":{let r=this.parseNode3DTransforms(t.properties),i=t.properties;return new Ot({...t,properties:r.restProps,position:r.position,rotation:r.rotation,rotationOrder:r.rotationOrder,scale:r.scale,color:i.color??"#ffffff",intensity:i.intensity??1,castShadow:typeof i.castShadow=="boolean"?i.castShadow:!0,shadowCameraSize:typeof i.shadowCameraSize=="number"?i.shadowCameraSize:20,shadowMapSize:typeof i.shadowMapSize=="number"?i.shadowMapSize:2048})}case"PointLightNode":{let r=this.parseNode3DTransforms(t.properties),i=t.properties;return new Lt({...t,properties:r.restProps,position:r.position,rotation:r.rotation,rotationOrder:r.rotationOrder,scale:r.scale,color:i.color??"#ffffff",intensity:i.intensity??1,distance:i.distance??0,decay:i.decay??2,castShadow:typeof i.castShadow=="boolean"?i.castShadow:!0})}case"SpotLightNode":{let r=this.parseNode3DTransforms(t.properties),i=t.properties;return new Ft({...t,properties:r.restProps,position:r.position,rotation:r.rotation,rotationOrder:r.rotationOrder,scale:r.scale,color:i.color??"#ffffff",intensity:i.intensity??1,distance:i.distance??0,angle:typeof i.angle=="number"?i.angle*Math.PI/180:Math.PI/3,penumbra:i.penumbra??0,decay:i.decay??2,castShadow:typeof i.castShadow=="boolean"?i.castShadow:!0})}case"AmbientLightNode":{let r=this.parseNode3DTransforms(t.properties),i=t.properties;return new _t({...t,properties:r.restProps,position:r.position,rotation:r.rotation,rotationOrder:r.rotationOrder,scale:r.scale,color:i.color??"#ffffff",intensity:i.intensity??.5})}case"HemisphereLightNode":{let r=this.parseNode3DTransforms(t.properties),i=t.properties;return new zt({...t,properties:r.restProps,position:r.position,rotation:r.rotation,rotationOrder:r.rotationOrder,scale:r.scale,skyColor:i.skyColor??"#ffffff",groundColor:i.groundColor??"#444444",intensity:i.intensity??.5})}case"Camera3D":{let r=this.parseNode3DTransforms(t.properties),i=t.properties;return new fe({...t,properties:r.restProps,position:r.position,rotation:r.rotation,rotationOrder:r.rotationOrder,scale:r.scale,projection:i.projection??"perspective",fov:i.fov??60,near:i.near??.1,far:i.far??1e3,orthographicSize:i.orthographicSize??5})}case"VirtualCamera3D":{let r=this.parseNode3DTransforms(t.properties),i=t.properties;return new vt({...t,properties:r.restProps,position:r.position,rotation:r.rotation,rotationOrder:r.rotationOrder,scale:r.scale,priority:this.asNumber(i.priority,ze.priority),fov:this.asNumber(i.fov,ze.fov),orthographicSize:this.asNumber(i.orthographicSize,ze.orthographicSize),followTargetId:this.asString(i.followTargetId)??"",followDamping:this.asNumber(i.followDamping,ze.followDamping),followOffset:this.readVector3(i.followOffset,Pi),deadzone:this.readVector3(i.deadzone,Pi),lookAtTargetId:this.asString(i.lookAtTargetId)??"",lookAtWeight:this.asNumber(i.lookAtWeight,ze.lookAtWeight),rotationDamping:this.asNumber(i.rotationDamping,ze.rotationDamping),confinerEnabled:typeof i.confinerEnabled=="boolean"?i.confinerEnabled:!1,confinerCenter:this.readVector3(i.confinerCenter,Pi),confinerSize:this.readVector3(i.confinerSize,new S(10,10,10)),blendDuration:this.asNumber(i.blendDuration,ze.blendDuration),blendEasing:_e(i.blendEasing)?i.blendEasing:ze.blendEasing})}case"MeshInstance":{let r=this.parseNode3DTransforms(t.properties),i=t.properties,o=this.asString(i.src)??null,s=typeof i.castShadow=="boolean"?i.castShadow:!0,a=typeof i.receiveShadow=="boolean"?i.receiveShadow:!0,l=this.asString(i.initialAnimation)??null,c=typeof i.isPlaying=="boolean"?i.isPlaying:!0,u=typeof i.isLoop=="boolean"?i.isLoop:!0,d=new ct({...t,properties:r.restProps,position:r.position,rotation:r.rotation,rotationOrder:r.rotationOrder,scale:r.scale,src:o,castShadow:s,receiveShadow:a,initialAnimation:l,isPlaying:c,isLoop:u});if(o)try{let p=(await this.assetLoader.loadAsset(o)).node;if(p.children&&p.children.length>0)for(let f of p.children)d.add(f);"animations"in p&&Array.isArray(p.animations)&&(d.animations=p.animations),d.applyLoadedShadowProperties(),d.showDefaultPose()}catch(h){console.warn(`[SceneLoader] Error loading GLB model from "${o}":`,h)}return d}case"AnimatedSprite3D":{let r=this.parseNode3DTransforms(t.properties),i=t.properties,o=Array.isArray(i.frames)?i.frames.map(D):[],s=new yr({...t,properties:r.restProps,position:r.position,rotation:r.rotation,rotationOrder:r.rotationOrder,scale:r.scale,frames:o,width:this.asNumber(i.width,1),height:this.asNumber(i.height,1),color:this.asString(i.color)??"#ffffff",fps:typeof i.fps=="number"?i.fps:void 0,playing:typeof i.playing=="boolean"?i.playing:void 0,loop:typeof i.loop=="boolean"?i.loop:void 0,freeOnFinish:typeof i.freeOnFinish=="boolean"?i.freeOnFinish:void 0,billboard:typeof i.billboard=="boolean"?i.billboard:!1,opacity:this.asNumber(i.opacity,void 0)});return o.forEach(async(a,l)=>{if(a?.url)try{let c=await this.assetLoader.loadTexture(a.url);s.setTextureForFrame(l,c)}catch(c){console.warn(`[SceneLoader] Error loading texture for AnimatedSprite3D "${s.nodeId}":`,c)}}),s}case"Sprite3D":{let r=this.parseNode3DTransforms(t.properties),i=t.properties,o=D(i.texture??i.texturePath??null),s=new ht({...t,properties:r.restProps,position:r.position,rotation:r.rotation,rotationOrder:r.rotationOrder,scale:r.scale,texture:o,width:this.asNumber(i.width,1),height:this.asNumber(i.height,1),color:this.asString(i.color)??"#ffffff",billboard:typeof i.billboard=="boolean"?i.billboard:!1,billboardRoll:this.asNumber(i.billboardRoll,0),opacity:this.asNumber(i.opacity,void 0)});if(s.texturePath)try{let a=await this.assetLoader.loadTexture(s.texturePath);s.setTexture(a)}catch(a){console.warn(`[SceneLoader] Error loading texture for Sprite3D "${s.nodeId}":`,a)}return s}case"Particles3D":{let r=this.parseNode3DTransforms(t.properties),i=t.properties,o=D(i.texture??i.texturePath??null),s=this.readVector3(i.emitterBoxSize,new S(1,1,1)),a=this.readVector3(i.gravity,new S(0,0,0)),l=new pt({...t,properties:r.restProps,position:r.position,rotation:r.rotation,rotationOrder:r.rotationOrder,scale:r.scale,texture:o,emitterShape:i.emitterShape,emitterRadius:this.asNumber(i.emitterRadius,.5),emitterBoxSize:{x:s.x,y:s.y,z:s.z},particleShape:i.particleShape,emissionRate:this.asNumber(i.emissionRate,24),maxParticles:this.asNumber(i.maxParticles,512),lifetime:this.asNumber(i.lifetime,2),speed:this.asNumber(i.speed,2),speedSpread:this.asNumber(i.speedSpread,.5),gravity:{x:a.x,y:a.y,z:a.z},particleSize:this.asNumber(i.particleSize,.2),sizeRandomness:this.asNumber(i.sizeRandomness,.2),startColor:this.asString(i.startColor)??"#ffffff",endColor:this.asString(i.endColor)??"#ffd24d",startAlpha:this.asNumber(i.startAlpha,1),endAlpha:this.asNumber(i.endAlpha,0),billboard:typeof i.billboard=="boolean"?i.billboard:!0,disableRotation:typeof i.disableRotation=="boolean"?i.disableRotation:!1,playing:typeof i.playing=="boolean"?i.playing:!0,loop:typeof i.loop=="boolean"?i.loop:!0,prewarm:typeof i.prewarm=="boolean"?i.prewarm:!1,preview:typeof i.preview=="boolean"?i.preview:!1,simulationSpace:i.simulationSpace==="world"?"world":"local",trailEnabled:typeof i.trailEnabled=="boolean"?i.trailEnabled:!1,trailLifetime:this.asNumber(i.trailLifetime,.3),trailWidth:this.asNumber(i.trailWidth,.05),trailSegments:this.asNumber(i.trailSegments,16),trailFade:this.asNumber(i.trailFade,1),subEmitterId:this.asString(i.subEmitterId)??"",subEmitterBurstCount:this.asNumber(i.subEmitterBurstCount,8),subEmitterInheritVelocity:this.asNumber(i.subEmitterInheritVelocity,0)});if(l.texturePath)try{let c=await this.assetLoader.loadTexture(l.texturePath);l.setTexture(c)}catch(c){console.warn(`[SceneLoader] Error loading texture for Particles3D "${l.nodeId}":`,c)}return l}default:return new V({...t,type:e.type})}}async loadSpineSkeleton2DAsset(e){let t=e.getAssetRequest();if(!t){e.setSpineAsset(null);return}try{let r=await this.assetLoader.loadSpineAsset(t),i=e.getAssetRequest();if(!i||i.skeletonPath!==t.skeletonPath||i.atlasPath!==t.atlasPath||i.texturePath!==t.texturePath)return;e.setSpineAsset(r)}catch(r){console.warn(`[SceneLoader] Error loading Spine asset for SpineSkeleton2D "${e.nodeId}":`,r)}}async loadAnimatedSprite2DAsset(e,t){try{let r=await this.assetLoader.loadAnimationResource(t);e.setAnimationResource(r);let i=new Map;for(let o of r.clips)o.frames.forEach((s,a)=>{let l=Ql(r,s);l&&i.set(a,l)});if(await Promise.all(Array.from(i.entries()).map(async([o,s])=>{try{let a=await this.assetLoader.loadTexture(s);e.setFrameTexture(o,a)}catch(a){console.warn(`[SceneLoader] Error loading frame texture for AnimatedSprite2D "${e.nodeId}":`,a)}})),!r.texturePath)return;try{let o=await this.assetLoader.loadTexture(r.texturePath);e.setSpritesheetTexture(o)}catch(o){console.warn(`[SceneLoader] Error loading spritesheet for AnimatedSprite2D "${e.nodeId}":`,o)}}catch(r){console.warn(`[SceneLoader] Error loading animation resource for AnimatedSprite2D "${e.nodeId}":`,r)}}parseNode3DTransforms(e){let{position:t,rotation:r,scale:i,transform:o,...s}=e,a=this.readVector3(t,Pi),l=this.readVector3(r,Pi),c=this.readVector3(i,Lb),u=this.asRecord(o),d=a,h=l,p=c,f="XYZ";if(u){f=this.readRotationOrder(u.rotationOrder)??f,d=this.readVector3(u.position??u.translate,a),h=this.readVector3(u.rotationEuler??u.rotation??u.euler,l),p=this.readVector3(u.scale,c);let g=Object.entries(u).filter(([y])=>!["position","translate","rotation","rotationEuler","euler","scale","rotationOrder"].includes(y));g.length>0&&(s.transform=Object.fromEntries(g))}let m=new Yr(E.degToRad(h.x),E.degToRad(h.y),E.degToRad(h.z),f);return{position:d,rotation:m,rotationOrder:f,scale:p,restProps:s}}readVector3(e,t){if(!e)return t.clone();if(e instanceof S)return e.clone();if(Array.isArray(e))return new S(this.asNumber(e[0],t.x),this.asNumber(e[1],t.y),this.asNumber(e[2],t.z));if(typeof e=="object"){let r=e;return new S(this.asNumber(r.x,t.x),this.asNumber(r.y,t.y),this.asNumber(r.z,t.z))}return t.clone()}readLabelStyle(e){let t=e.labelFontWeight;return{labelFontFamily:this.asString(e.labelFontFamily),labelFontSize:this.asNumber(e.labelFontSize,void 0),labelColor:this.asString(e.labelColor),labelFontWeight:typeof t=="number"||typeof t=="string"?t:void 0,labelOutlineWidth:this.asNumber(e.labelOutlineWidth,void 0),labelOutlineColor:this.asString(e.labelOutlineColor),labelShadowColor:this.asString(e.labelShadowColor),labelShadowOffsetX:this.asNumber(e.labelShadowOffsetX,void 0),labelShadowOffsetY:this.asNumber(e.labelShadowOffsetY,void 0),labelLetterSpacing:this.asNumber(e.labelLetterSpacing,void 0)}}readSliceBorder(e){return{left:this.asNumber(e.sliceBorderLeft,0),right:this.asNumber(e.sliceBorderRight,0),top:this.asNumber(e.sliceBorderTop,0),bottom:this.asNumber(e.sliceBorderBottom,0)}}readVector2(e,t){if(!e)return t.clone();if(e instanceof I)return e.clone();if(Array.isArray(e))return new I(this.asNumber(e[0],t.x),this.asNumber(e[1],t.y));if(typeof e=="object"){let r=e;return new I(this.asNumber(r.x,t.x),this.asNumber(r.y,t.y))}return t.clone()}parseGeometryMeshEffects(e){if(!Array.isArray(e))return;let t=[];for(let r of e){let i=this.asRecord(r),o=this.asString(i?.type);if(!o)continue;let s={type:o};i&&typeof i.enabled=="boolean"&&(s.enabled=i.enabled);let a=this.asRecord(i?.params);a&&(s.params={...a}),t.push(s)}return t.length>0?t:void 0}readRotationOrder(e){if(typeof e!="string")return;let t=e.trim().toUpperCase();return["XYZ","XZY","YXZ","YZX","ZXY","ZYX"].includes(t)?t:void 0}asNumber(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}asPositiveInteger(e){if(typeof e!="number"||!Number.isFinite(e))return null;let t=Math.floor(e);return t>0?t:null}asRecord(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}asString(e){return typeof e=="string"?e:void 0}parseNode2DFlow(e){let t=e.flow;if(!t||typeof t!="object")return;let r=t;if(r.enabled!==!0)return;let i=a=>typeof a=="number"&&Number.isFinite(a)?a:void 0,o=r.direction==="horizontal"?"horizontal":"vertical",s=r.align==="center"||r.align==="end"?r.align:"start";return{enabled:!0,direction:o,gap:i(r.gap),paddingX:i(r.paddingX),paddingY:i(r.paddingY),align:s,autoSize:r.autoSize===!0}}parseNode2DLayout(e){let t=this.asRecord(e.layout);if(!t)return;let r=["left","center","right","stretch"],i=["top","center","bottom","stretch"],o=r.find(a=>a===t.horizontalAlign),s=i.find(a=>a===t.verticalAlign);return{enabled:typeof t.enabled=="boolean"?t.enabled:void 0,horizontalAlign:o,verticalAlign:s}}};var wT=new Set(["AmbientLight","DirectionalLight","HemisphereLight","PointLight","SpotLight"]),_b=new Set(["GeometryMesh","MeshInstance","InstancedMesh3D"]),xT=new Set([..._b,"Sprite3D","AnimatedSprite3D","Particles3D"]),PT=new Set(["Camera3D","VirtualCamera3D"]),Un=8,kT=(n,e={})=>{let t=[],r=[],i=[],o=0,s=0,a=!1,l=0,c=h=>{if(h.visible===!1)return;let p=TT(h);p?(wT.has(p.type)&&o++,PT.has(p.type)&&s++,xT.has(p.type)&&r.push(p),_b.has(p.type)&&t.push(p),zb(p)&&i.push(p)):NT(h)&&(a=!0,DT(h)&&l++);for(let f of h.children)c(f)};for(let h of n)c(h);let u=[];if((a||t.some(h=>!ET(h)))&&t.length>0&&o===0&&u.push({code:"lit-material-no-light",severity:"blocking",message:`${t.length} 3D mesh node(s) use lit materials but the scene has no enabled light \u2014 they will render black. Add a HemisphereLightNode (plus a DirectionalLightNode for shading), or give the meshes an unlit material.`,nodeIds:t.slice(0,Un).map(h=>h.nodeId),nodeCount:t.length}),r.length>0&&s===0&&u.push({code:"no-camera-3d",severity:"blocking",message:`The scene has ${r.length} 3D node(s) but no enabled Camera3D \u2014 nothing 3D will be drawn. Add a Camera3D and position it to look at the content.`,nodeIds:r.slice(0,Un).map(h=>h.nodeId),nodeCount:r.length}),l>0&&e.targetPlatform&&e.targetPlatform!=="desktop"&&u.push({code:"pbr-on-mobile",severity:"advice",message:`${l} material(s) use PBR (standard/physical) in a ${e.targetPlatform} project. PBR shading is a desktop-class per-pixel cost; set the meshes' materialType to 'lambert' (or 'basic' for unlit) unless the user asked for a high-end look.`,nodeIds:t.slice(0,Un).map(h=>h.nodeId),nodeCount:l}),i.length>0){let h=i.slice(0,Un).map(p=>ou(p.name,p.type)).join(" ");u.push({code:"inert-nodes",severity:"blocking",message:`${i.length} node(s) have an unrecognised type and do nothing. ${h}`,nodeIds:i.slice(0,Un).map(p=>p.nodeId),nodeCount:i.length})}return u},AT=n=>n.length===0?"":n.map(e=>e.message).join(" "),TT=n=>n instanceof V?n:null,zb=n=>Object.getPrototypeOf(n)===V.prototype&&!nu(n.type),CT=["isMeshStandardMaterial","isMeshPhysicalMaterial"],MT=["isMeshStandardMaterial","isMeshPhysicalMaterial","isMeshLambertMaterial","isMeshPhongMaterial","isMeshToonMaterial"],dh=n=>{let e=n.material;return e?Array.isArray(e)?e:[e]:[]},DT=n=>dh(n).some(e=>CT.some(t=>e[t]===!0)),NT=n=>dh(n).some(e=>MT.some(t=>e[t]===!0)),ET=n=>{let e=!1;return n.traverse(t=>{!e&&dh(t).length>0&&(e=!0)}),e};var IT="1.0.0",RT=["version","description","metadata","root"],BT=["id","type","name","instance","instancePath","groups","properties","metadata","children","components","overrides"],VT=["id","type","enabled","config"],OT={kind:"record",nested:{position:{schemaName:"position"},scale:{schemaName:"scale"},rotation:{schemaName:"rotation"}}},LT=["XYZ","XZY","YXZ","YZX","ZXY","ZYX"],FT={kind:"record",nested:{position:{schemaName:"position"},translate:{schemaName:"position",preferred:"transform.position"},rotationEuler:{schemaName:"rotation"},rotation:{schemaName:"rotation",preferred:"transform.rotationEuler"},euler:{schemaName:"rotation",preferred:"transform.rotationEuler"},scale:{schemaName:"scale"},rotationOrder:{kind:"enum",options:LT}}},_T={kind:"record",nested:{enabled:{schemaName:"layoutEnabled"},horizontalAlign:{schemaName:"horizontalAlign"},verticalAlign:{schemaName:"verticalAlign"}}},zT={kind:"record",nested:{enabled:{schemaName:"flowEnabled"},direction:{schemaName:"flowDirection"},gap:{schemaName:"flowGap"},paddingX:{schemaName:"flowPaddingX"},paddingY:{schemaName:"flowPaddingY"},align:{schemaName:"flowAlign"},autoSize:{schemaName:"flowAutoSize"}}},Oa={kind:"array"},UT={id:"the node id is the entry's own `id:`, not a property",name:"the node name is the entry's own `name:`, not a property",type:"the node type is the entry's own `type:`, not a property",groups:"groups are the entry's own `groups:` list, not a property"},Ub=["position","rotation","scale"],Wb={Group:{family:"base",classExport:"NodeBase"},Node2D:{family:"2d"},Node3D:{family:"3d"},ColorRect2D:{family:"2d"},Sprite2D:{family:"2d",extras:{effects:Oa,texturePath:{kind:"resource-path",preferred:"texture"},color:{kind:"color"}}},TiledSprite2D:{family:"2d",extras:{texturePath:{kind:"resource-path",preferred:"texture"},color:{kind:"color"}}},AnimatedSprite2D:{family:"2d",extras:{effects:Oa}},SpineSkeleton2D:{family:"2d",extras:{texturePath:{kind:"resource-path",preferred:"texture"}}},Label2D:{family:"2d",writeOnly:["texturePath"],extras:{labelOutlineWidth:{schemaName:"outlineWidth",preferred:"outlineWidth"},labelOutlineColor:{schemaName:"outlineColor",preferred:"outlineColor"}}},Group2D:{family:"2d"},CanvasLayer2D:{family:"2d"},Camera2D:{family:"2d"},Button2D:{family:"2d",extras:{effects:Oa,stateTextureKeys:{kind:"record",nested:{normal:{schemaName:"textureNormalKey"},hover:{schemaName:"textureHoverKey"},pressed:{schemaName:"texturePressedKey"},disabled:{schemaName:"textureDisabledKey"}}}}},Slider2D:{family:"2d"},Bar2D:{family:"2d",extras:{borderWidth:{kind:"number"}}},Checkbox2D:{family:"2d"},Joystick2D:{family:"2d",extras:{handleRadius:{kind:"number"},baseColor:{kind:"color"},handleColor:{kind:"color"}}},ScrollContainer2D:{family:"2d"},InventorySlot2D:{family:"2d",extras:{borderWidth:{kind:"number"},quantityFontSize:{kind:"number"}}},GeometryMesh:{family:"3d",extras:{material:{kind:"record",nested:{type:{schemaName:"materialType"},color:{schemaName:"color"},roughness:{schemaName:"roughness"},metalness:{schemaName:"metalness"},aoMap:{kind:"resource-path"},aoMapIntensity:{schemaName:"aoMapIntensity"},map:{kind:"resource-path"},effects:Oa}}},relocated:{map:"material.map"}},MeshInstance:{family:"3d",extras:{src:{kind:"resource-path"}}},InstancedMesh3D:{family:"3d",extras:{material:{kind:"record",nested:{type:{schemaName:"materialType"},color:{schemaName:"color"},roughness:{kind:"number"},metalness:{kind:"number"}}},frustumCulled:{kind:"boolean"}},notStored:{visibleInstanceCount:"computed at runtime from the instance buffer"}},Sprite3D:{family:"3d",extras:{texturePath:{kind:"resource-path",preferred:"texture"},color:{kind:"color"}},notStored:{textureAspectRatio:"derived from the loaded texture",aspectRatioLocked:"an inspector-only toggle on Sprite3D"}},AnimatedSprite3D:{family:"3d",extras:{frames:{kind:"array"}},notStored:{currentFrame:"playback state, not saved on AnimatedSprite3D"}},Particles3D:{family:"3d",extras:{texturePath:{kind:"resource-path",preferred:"texture"}}},AmbientLightNode:{family:"3d"},DirectionalLightNode:{family:"3d"},HemisphereLightNode:{family:"3d"},PointLightNode:{family:"3d"},SpotLightNode:{family:"3d"},Camera3D:{family:"3d"},VirtualCamera3D:{family:"3d"},PostProcess:{family:"base"},AudioPlayer:{family:"base"}},WT=Object.keys(Wb),GT=(n,e,t)=>{for(let[r,i]of Object.entries(n.nested??{}))i.schemaName&&!i.preferred&&!(i.schemaName in t)&&(t[i.schemaName]=`${e}.${r}`)},qT=(n,e)=>{let r={...e.family==="2d"?{transform:OT,layout:_T,flow:zT}:e.family==="3d"?{transform:FT}:{},...e.extras},i={};for(let[o,s]of Object.entries(r))GT(s,o,i);for(let o of Ub)delete i[o];return Object.assign(i,e.relocated),{type:n,classExport:e.classExport??n,family:e.family,extras:r,relocated:i,notStored:{...UT,...e.notStored},writeOnly:e.writeOnly??[]}},HT=new Map(Object.entries(Wb).map(([n,e])=>[n,qT(n,e)])),jT=n=>HT.get(n)??null,YT=(n,e,t)=>{let r=n.extras[t];if(r)return{kind:"extra",rule:r};let i=e.find(a=>a.name===t);if(!i)return{kind:"unknown"};let o=n.notStored[t];if(o!==void 0)return{kind:"not-stored",property:i,reason:o};let s=n.relocated[t];if(s!==void 0)return{kind:"relocated",property:i,diskPath:s};if(n.writeOnly.includes(t))return{kind:"write-only",property:i};if(n.family!=="base"&&Ub.includes(t)){let a=n.family==="3d"&&t==="rotation"?"transform.rotationEuler":`transform.${t}`;return{kind:"schema",property:i,preferred:a}}return{kind:"schema",property:i}},$T={position:"position",translate:"position",rotationEuler:"rotation",rotation:"rotation",euler:"rotation",scale:"scale"};var KT=new RegExp("\\p{Extended_Pictographic}","u"),XT=new RegExp("\\p{Extended_Pictographic}","gu"),QT=new RegExp("\\s|\\u{FE0F}|\\u{200D}|\\u{20E3}|\\u{FE0E}|\\p{Emoji_Modifier}|\\p{Emoji_Component}","gu"),hh=new Set(["label","text","placeholder","title","caption","buttonText","labelText","content"]),Gb=n=>KT.test(n)?n.replace(XT,"").replace(QT,"").trim().length===0:!1,JT=n=>hh.has(n.split(".").pop()??n),ZT=new RegExp(`^\\s*(${[...hh].join("|")}):\\s*(?:"([^"]*)"|'([^']*)'|(.+?))\\s*$`,"gmu"),eC=n=>{let e=[];for(let t of n.matchAll(ZT)){let r=t[2]??t[3]??t[4]??"";Gb(r)&&e.push({property:t[1],value:r.trim()})}return e};var qb=["scripts","src/scripts"],Hb=/extends\s+Script\b/,jb="user:",Yb=n=>`${jb}${n}`,$b=n=>n.replace(/\\/g,"/").replace(/^res:\/\//,"").replace(/^\.?\/+/,""),Kb=n=>{let e=$b(n);return qb.some(t=>e===t||e.startsWith(`${t}/`))},tC=(n,e)=>{let t=$b(n);return(t.endsWith(".ts")||t.endsWith(".js"))&&Kb(t)&&Hb.test(e)},Xb=(n,e=O)=>{if(typeof n!="function"||typeof n.getPropertySchema!="function")return!1;if(n===e)return!0;let t=e.prototype,r=n.prototype;for(;r;){if(r===t)return!0;r=Object.getPrototypeOf(r)}return!1},rC=(n,e,t)=>{let r=[];for(let[i,o]of Object.entries(e)){if(!Xb(o))continue;let s=Yb(i);n.registerComponent({id:s,displayName:i,description:`Project component from ${t}`,category:"Project",componentClass:o,keywords:["project","component",i.toLowerCase(),t.toLowerCase()]}),r.push(s)}return r};var Qb=_p(ch(),1);var ph=class{constructor(){}serializeSceneDocument(e){let t=e.rootNodes.map(r=>this.serializeNode(r));return{version:e.version??"1.0.0",description:e.description,metadata:e.metadata,root:t}}serializeScene(e){let t=this.serializeSceneDocument(e),r=(0,Qb.stringify)(t,{indent:2});return r=r.replace(/position:\s*\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)/g,"position: [$1, $2, $3]"),r=r.replace(/position:\s*\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)(?!\s*-)/g,"position: [$1, $2]"),r=r.replace(/rotationEuler:\s*\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)/g,"rotationEuler: [$1, $2, $3]"),r=r.replace(/scale:\s*\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)/g,"scale: [$1, $2, $3]"),r=r.replace(/scale:\s*\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)(?!\s*-)/g,"scale: [$1, $2]"),r=r.replace(/rotation:\s*\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)\n\s*- (\w+)/g,"rotation: [$1, $2, $3, $4]"),r=r.replace(/rotation:\s*\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)(?!\s*-)/g,"rotation: [$1, $2]"),r=r.replace(/size:\s*\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)/g,"size: [$1, $2, $3]"),r=r.replace(/size:\s*\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)(?!\s*-)/g,"size: [$1, $2]"),r=r.replace(/pivot:\s*\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)/g,"pivot: [$1, $2]"),r=r.replace(/emitterBoxSize:\s*\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)/g,"emitterBoxSize: [$1, $2, $3]"),r=r.replace(/gravity:\s*\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)/g,"gravity: [$1, $2, $3]"),r}serializeNode(e){if(e.instancePath)return this.serializeInstanceNode(e);let t=this.serializeNodeProperties(e),r={id:e.nodeId,type:e.type!=="Group"?e.type:void 0,name:e.name,groups:e.groups.size>0?Array.from(e.groups.values()):void 0,properties:t,metadata:this.serializeMetadata(e.metadata)};e instanceof Ot?r.type="DirectionalLightNode":e instanceof Lt?r.type="PointLightNode":e instanceof Ft?r.type="SpotLightNode":e instanceof _t?r.type="AmbientLightNode":e instanceof zt&&(r.type="HemisphereLightNode");let i=Yi(e);return i.length>0&&(r.components=i.map(o=>({...o,config:o.config&&Object.keys(o.config).length>0?o.config:void 0}))),e.children&&e.children.length>0&&(r.children=e.children.filter(o=>o instanceof V).map(o=>this.serializeNode(o))),Object.keys(r).forEach(o=>{r[o]===void 0&&delete r[o]}),r}serializeInstanceNode(e){let t={id:e.nodeId,type:e.type!=="Group"?e.type:void 0,name:e.name,instance:e.instancePath??void 0,groups:e.groups.size>0?Array.from(e.groups.values()):void 0,metadata:this.serializeMetadata(e.metadata)},r=this.getPrefabMarker(e),i=r?.basePropertiesByLocalId??{},o=this.captureInstanceComparableMap(e),s=r?r.effectiveLocalId:this.normalizeLocalId(e.nodeId),a=o[s]??{},l=i[s]??{},c=this.diffRecord(l,a);Object.keys(c).length>0&&(t.properties=c);let u={};for(let[d,h]of Object.entries(o)){if(d===s)continue;let p=i[d]??{},f=this.diffRecord(p,h);if(Object.keys(f).length===0)continue;let m=d.startsWith(`${s}/`)?d.slice(s.length+1):d;u[m]={properties:f}}if(Object.keys(u).length>0){let d={byLocalId:u};t.overrides=d}return Object.keys(t).forEach(d=>{t[d]===void 0&&delete t[d]}),t}serializeMetadata(e){let t=Object.entries(e).filter(([r])=>r!=="__pix3Prefab");if(t.length!==0)return Object.fromEntries(t)}serializeNodeProperties(e){let t={...e.properties};if(delete t.position,delete t.rotation,delete t.scale,delete t.rotationEuler,delete t.rotationOrder,delete t.transform,e instanceof U){let r=e.rotation,i={position:[e.position.x,e.position.y,e.position.z],rotationEuler:[E.radToDeg(r.x),E.radToDeg(r.y),E.radToDeg(r.z)],scale:[e.scale.x,e.scale.y,e.scale.z]};r.order&&r.order!=="XYZ"&&(i.rotationOrder=r.order),t.transform=i,e.opacity!==1?t.opacity=e.opacity:delete t.opacity}else if(e instanceof Je){t.width=e.width,t.height=e.height;let r={position:[e.position.x,e.position.y],scale:[e.scale.x,e.scale.y],rotation:E.radToDeg(e.rotation.z)};t.transform=r;let i=e.serializeLayout();i?t.layout=i:delete t.layout;let o=e.serializeFlow();o?t.flow=o:delete t.flow}else if(e instanceof Ae){t.width=e.width,t.height=e.height;let r={position:[e.position.x,e.position.y],scale:[e.scale.x,e.scale.y],rotation:E.radToDeg(e.rotation.z)};t.transform=r;let i=e.serializeLayout();i?t.layout=i:delete t.layout;let o=e.serializeFlow();o?t.flow=o:delete t.flow}else if(e instanceof M){let r={position:[e.position.x,e.position.y],scale:[e.scale.x,e.scale.y],rotation:E.radToDeg(e.rotation.z)};t.transform=r;let i=e.serializeLayout();i?t.layout=i:delete t.layout;let o=e.serializeFlow();o?t.flow=o:delete t.flow,e.opacity!==1?t.opacity=e.opacity:delete t.opacity}if(e instanceof dr)t.width=e.width,t.height=e.height,t.color=e.color;else if(e instanceof Je)t.scrollY=e.scrollY,t.dragScrollEnabled=e.dragScrollEnabled,t.wheelScrollEnabled=e.wheelScrollEnabled,t.inertiaEnabled=e.inertiaEnabled,t.showScrollbar=e.showScrollbar,t.wheelSensitivity=e.wheelSensitivity,t.dragThreshold=e.dragThreshold,t.inertiaDamping=e.inertiaDamping,t.scrollbarWidth=e.scrollbarWidth,t.scrollbarMinHeight=e.scrollbarMinHeight,t.scrollbarInset=e.scrollbarInset,t.scrollbarColor=e.scrollbarColor,t.scrollbarTrackColor=e.scrollbarTrackColor,e.scrollbarThumbTexture?t.scrollbarThumbTexture={...e.scrollbarThumbTexture}:delete t.scrollbarThumbTexture,e.scrollbarTrackTexture?t.scrollbarTrackTexture={...e.scrollbarTrackTexture}:delete t.scrollbarTrackTexture;else if(e instanceof Le){e.texture&&(t.texture={...e.texture}),e.textureKey?t.textureKey=e.textureKey:delete t.textureKey,t.width=e.width,t.height=e.height,e.aspectRatioLocked&&(t.aspectRatioLocked=!0),(e.anchor.x!==.5||e.anchor.y!==.5)&&(t.anchor=[Math.round(e.anchor.x*1e3)/1e3,Math.round(e.anchor.y*1e3)/1e3]),delete t.effects;let r=e.getShaderEffectStack();r.isEmpty||(t.effects=r.serialize())}else if(e instanceof pr)e.texture&&(t.texture={...e.texture}),t.patchMode=e.patchMode,t.width=e.width,t.height=e.height,t.sliceBorderLeft=e.sliceBorder.left,t.sliceBorderRight=e.sliceBorder.right,t.sliceBorderTop=e.sliceBorder.top,t.sliceBorderBottom=e.sliceBorder.bottom,t.drawCenter=e.drawCenter,t.axisStretchHorizontal=e.axisStretchHorizontal,t.axisStretchVertical=e.axisStretchVertical,t.tileScale=[e.tileScale.x,e.tileScale.y],t.tileOffset=[e.tileOffset.x,e.tileOffset.y],(e.anchor.x!==.5||e.anchor.y!==.5)&&(t.anchor=[Math.round(e.anchor.x*1e3)/1e3,Math.round(e.anchor.y*1e3)/1e3]);else if(e instanceof ur)e.skeletonPath?t.skeletonPath=e.skeletonPath:delete t.skeletonPath,e.atlasPath?t.atlasPath=e.atlasPath:delete t.atlasPath,e.texture?t.texture={...e.texture}:delete t.texture,delete t.texturePath,e.animation?t.animation=e.animation:delete t.animation,e.skin?t.skin=e.skin:delete t.skin,t.loop=e.loop,t.isPlaying=e.isPlaying,t.timeScale=e.timeScale,t.defaultMix=e.defaultMix,t.color=e.color,e.twoColorTint?t.twoColorTint=!0:delete t.twoColorTint,e.freeOnFinish?t.freeOnFinish=!0:delete t.freeOnFinish,e.previewInEditor?t.previewInEditor=!0:delete t.previewInEditor;else if(e instanceof Ke){delete t.frames,delete t.fps,delete t.playing,delete t.loop,e.animationResourcePath?t.animationResourcePath=e.animationResourcePath:delete t.animationResourcePath,e.currentClip?t.currentClip=e.currentClip:delete t.currentClip,t.isPlaying=e.isPlaying,e.freeOnFinish?t.freeOnFinish=!0:delete t.freeOnFinish,t.currentFrame=e.currentFrame,t.width=e.width,t.height=e.height,t.color=e.color,e.sizeMode==="native"?t.sizeMode="native":delete t.sizeMode,e.anchor.x!==.5||e.anchor.y!==.5?t.anchor=[Math.round(e.anchor.x*1e3)/1e3,Math.round(e.anchor.y*1e3)/1e3]:delete t.anchor,delete t.effects;let r=e.getShaderEffectStack();r.isEmpty||(t.effects=r.serialize())}else if(e instanceof br)e.radius!==50&&(t.radius=e.radius),e.handleRadius!==20&&(t.handleRadius=e.handleRadius),e.axisHorizontal!=="Horizontal"&&(t.axisHorizontal=e.axisHorizontal),e.axisVertical!=="Vertical"&&(t.axisVertical=e.axisVertical),e.baseColor!=="#ffffff"&&(t.baseColor=e.baseColor),e.handleColor!=="#cccccc"&&(t.handleColor=e.handleColor),e.floating!==!1&&(t.floating=e.floating);else if(e instanceof mt){this.serializeCommonUIControlProps(e,t),t.width=e.width,t.height=e.height,t.backgroundColor=e.backgroundColor,t.hoverColor=e.hoverColor,t.pressedColor=e.pressedColor,t.buttonAction=e.buttonAction,e.textureNormal?t.textureNormal={...e.textureNormal}:delete t.textureNormal,e.textureHover?t.textureHover={...e.textureHover}:delete t.textureHover,e.texturePressed?t.texturePressed={...e.texturePressed}:delete t.texturePressed,e.textureDisabled?t.textureDisabled={...e.textureDisabled}:delete t.textureDisabled,e.hasLocalizedStateTextures()?t.stateTextureKeys={...e.stateTextureKeys}:delete t.stateTextureKeys,this.serializeSliceBorder(e.sliceBorder,t),delete t.effects;let r=e.getShaderEffectStack();r.isEmpty||(t.effects=r.serialize())}else if(e instanceof ft)this.serializeCommonUIControlProps(e,t),e.width>0&&(t.width=e.width),e.height>0&&(t.height=e.height),e.labelVAlign!=="middle"&&(t.labelVAlign=e.labelVAlign),e.typewriterSpeed>0&&(t.typewriterSpeed=e.typewriterSpeed),e.glowStrength>0?(t.glowStrength=e.glowStrength,e.glowColor!=="#ffffff"&&(t.glowColor=e.glowColor)):(delete t.glowStrength,delete t.glowColor),e.outlineWidth>0?(t.outlineWidth=e.outlineWidth,e.outlineColor!=="#000000"&&(t.outlineColor=e.outlineColor)):(delete t.outlineWidth,delete t.outlineColor),delete t.labelOutlineWidth,delete t.labelOutlineColor;else if(e instanceof vr)this.serializeCommonUIControlProps(e,t),t.width=e.width,t.height=e.height,t.handleSize=e.handleSize,t.trackBackgroundColor=e.trackBackgroundColor,t.trackFilledColor=e.trackFilledColor,t.handleColor=e.handleColor,t.minValue=e.minValue,t.maxValue=e.maxValue,t.value=e.value,t.axisName=e.axisName,this.serializeTextureRef(t,"textureTrack",e.textureTrack),this.serializeTextureRef(t,"textureFill",e.textureFill),this.serializeTextureRef(t,"textureThumb",e.textureThumb),this.serializeSliceBorder(e.sliceBorder,t);else if(e instanceof wr)this.serializeCommonUIControlProps(e,t),t.width=e.width,t.height=e.height,t.backBackgroundColor=e.backBackgroundColor,t.barColor=e.barColor,t.minValue=e.minValue,t.maxValue=e.maxValue,t.value=e.value,t.showBorder=e.showBorder,t.borderColor=e.borderColor,t.borderWidth=e.borderWidth,this.serializeTextureRef(t,"textureTrough",e.textureTrough),this.serializeTextureRef(t,"textureFill",e.textureFill),this.serializeSliceBorder(e.sliceBorder,t);else if(e instanceof xr)this.serializeCommonUIControlProps(e,t),t.size=e.size,t.checked=e.checked,t.uncheckedColor=e.uncheckedColor,t.checkedColor=e.checkedColor,t.checkmarkColor=e.checkmarkColor,t.checkmarkAction=e.checkmarkAction,this.serializeTextureRef(t,"textureBox",e.textureBox),this.serializeTextureRef(t,"textureBoxChecked",e.textureBoxChecked),this.serializeTextureRef(t,"textureMark",e.textureMark);else if(e instanceof Pr)this.serializeCommonUIControlProps(e,t),t.width=e.width,t.height=e.height,t.backdropColor=e.backdropColor,t.borderColor=e.borderColor,t.borderWidth=e.borderWidth,t.quantity=e.quantity,t.showQuantity=e.showQuantity,t.quantityFontSize=e.quantityFontSize,t.selectionColor=e.selectionColor,t.selectedAction=e.selectedAction;else if(e instanceof yt)Object.assign(t,e.serializeConfig());else if(e instanceof bt){t.maxInstances=e.maxInstances;let r=e.serializeMaterialConfig();r?t.material=r:delete t.material,t.castShadow=e.mesh.castShadow,t.receiveShadow=e.mesh.receiveShadow,t.enablePerInstanceColor=e.enablePerInstanceColor,e.mesh.frustumCulled?t.frustumCulled=!0:delete t.frustumCulled,delete t.visibleInstanceCount}else if(e instanceof Ot)t.color="#"+e.light.color.getHexString(),t.intensity=e.light.intensity,t.castShadow=e.light.castShadow,t.shadowCameraSize=e.light.shadow.camera.right,t.shadowMapSize=e.light.shadow.mapSize.width;else if(e instanceof Lt)t.color="#"+e.light.color.getHexString(),t.intensity=e.light.intensity,t.distance=e.light.distance,t.decay=e.light.decay,t.castShadow=e.light.castShadow;else if(e instanceof Ft)t.color="#"+e.light.color.getHexString(),t.intensity=e.light.intensity,t.distance=e.light.distance,t.angle=e.light.angle*180/Math.PI,t.penumbra=e.light.penumbra,t.decay=e.light.decay,t.castShadow=e.light.castShadow;else if(e instanceof _t)t.color="#"+e.light.color.getHexString(),t.intensity=e.light.intensity;else if(e instanceof zt)t.skyColor="#"+e.light.color.getHexString(),t.groundColor="#"+e.light.groundColor.getHexString(),t.intensity=e.light.intensity;else if(e instanceof fe)e.camera instanceof ye?(t.projection="perspective",t.fov=e.fov,t.near=e.near,t.far=e.far):e.camera instanceof me&&(t.projection="orthographic",t.orthographicSize=e.orthographicSize,t.near=e.near,t.far=e.far);else if(e instanceof vt)Object.assign(t,e.serializeConfig());else if(e instanceof Vt)Object.assign(t,e.serializeConfig());else if(e instanceof et)Object.assign(t,e.serializeConfig());else if(e instanceof gt)Object.assign(t,e.serializeConfig());else if(e instanceof ct){let r=e;r.src&&(t.src=r.src),r.initialAnimation&&(t.initialAnimation=r.initialAnimation),t.isPlaying=r.isPlaying,t.isLoop=r.isLoop,t.castShadow=r.castShadow,t.receiveShadow=r.receiveShadow}else e instanceof ht?(e.texture&&(t.texture={...e.texture}),t.width=e.width,t.height=e.height,t.color=e.color,t.billboard=e.billboard,t.billboardRoll=e.billboardRoll):e instanceof pt&&(e.texture&&(t.texture={...e.texture}),t.emitterShape=e.emitterShape,t.emitterRadius=e.emitterRadius,t.emitterBoxSize=[e.emitterBoxSize.x,e.emitterBoxSize.y,e.emitterBoxSize.z],t.particleShape=e.particleShape,t.emissionRate=e.emissionRate,t.maxParticles=e.maxParticles,t.lifetime=e.lifetime,t.speed=e.speed,t.speedSpread=e.speedSpread,t.gravity=[e.gravity.x,e.gravity.y,e.gravity.z],t.particleSize=e.particleSize,t.sizeRandomness=e.sizeRandomness,t.startColor=e.startColor,t.endColor=e.endColor,t.startAlpha=e.startAlpha,t.endAlpha=e.endAlpha,t.billboard=e.billboard,t.disableRotation=e.disableRotation,t.playing=e.playing,t.loop=e.loop,t.prewarm=e.prewarm,t.preview=e.preview,t.simulationSpace=e.simulationSpace,t.trailEnabled=e.trailEnabled,t.trailLifetime=e.trailLifetime,t.trailWidth=e.trailWidth,t.trailSegments=e.trailSegments,t.trailFade=e.trailFade,t.subEmitterId=e.subEmitterId,t.subEmitterBurstCount=e.subEmitterBurstCount,t.subEmitterInheritVelocity=e.subEmitterInheritVelocity);return t}captureInstanceComparableMap(e){let t={},r=[e];for(;r.length>0;){let i=r.pop();if(!i)continue;let o=this.getPrefabMarker(i);o&&(t[o.effectiveLocalId]=this.captureComparableProperties(i));for(let s of i.children)s instanceof V&&r.push(s)}return t}captureComparableProperties(e){let t=ke(e),r={};for(let i of t.properties)i.ui?.hidden||i.ui?.readOnly===!0||(r[i.name]=this.cloneValue(i.getValue(e)));return r}diffRecord(e,t){let r={},i=new Set([...Object.keys(e),...Object.keys(t)]);for(let o of i){let s=e[o],a=t[o];this.isEqualValue(s,a)||(r[o]=this.cloneValue(a))}return r}isEqualValue(e,t){return JSON.stringify(e)===JSON.stringify(t)}getPrefabMarker(e){let r=e.metadata.__pix3Prefab;if(!r||typeof r!="object")return null;let i=r;return typeof i.localId!="string"||typeof i.effectiveLocalId!="string"||typeof i.instanceRootId!="string"||typeof i.sourcePath!="string"?null:i}normalizeLocalId(e){return e.replace(/\\/g,"/").replace(/^\/+/,"").trim()}cloneValue(e){return e==null||typeof e!="object"?e:JSON.parse(JSON.stringify(e))}serializeCommonUIControlProps(e,t){e.enabled!==!0&&(t.enabled=e.enabled),e.label!==""&&(t.label=e.label),e.labelKey!==""&&(t.labelKey=e.labelKey),e.labelFontFamily!=="Arial"&&(t.labelFontFamily=e.labelFontFamily),e.labelFontSize!==16&&(t.labelFontSize=e.labelFontSize),e.labelColor!=="#ffffff"&&(t.labelColor=e.labelColor),e.labelAlign!=="center"&&(t.labelAlign=e.labelAlign),e.labelFontWeight!=="normal"&&e.labelFontWeight!==400&&(t.labelFontWeight=e.labelFontWeight),e.labelOutlineWidth!==0&&(t.labelOutlineWidth=e.labelOutlineWidth),e.labelOutlineColor!=="#000000"&&(t.labelOutlineColor=e.labelOutlineColor),e.labelShadowColor?t.labelShadowColor=e.labelShadowColor:delete t.labelShadowColor,e.labelShadowOffsetX!==0&&(t.labelShadowOffsetX=e.labelShadowOffsetX),e.labelShadowOffsetY!==0&&(t.labelShadowOffsetY=e.labelShadowOffsetY),e.labelLetterSpacing!==0&&(t.labelLetterSpacing=e.labelLetterSpacing),e.texturePath&&(t.texturePath=e.texturePath)}serializeTextureRef(e,t,r){r?e[t]={...r}:delete e[t]}serializeSliceBorder(e,t){let r=[["sliceBorderLeft",e.left],["sliceBorderRight",e.right],["sliceBorderTop",e.top],["sliceBorderBottom",e.bottom]];for(let[i,o]of r)o>0?t[i]=o:delete t[i]}};var mh=class{sceneLoader;sceneSaver;sceneGraphs=new Map;groupMaps=new Map;activeSceneId=null;constructor(e,t){this.sceneLoader=e,this.sceneSaver=t??null}async instantiatePrefab(e,t){return await this.sceneLoader.instantiatePrefab(e,t)}resolvePendingComponents(){let e=0;for(let t of this.sceneGraphs.values())e+=this.sceneLoader.resolvePendingComponents(t.rootNodes);return e}async parseScene(e,t={}){return await this.sceneLoader.parseScene(e,t)}serializeScene(e){if(!this.sceneSaver)throw new Error("[SceneManager] No SceneSaver was provided \u2014 this host cannot serialize scenes. Pass a SceneSaver to the SceneManager constructor if you need to save or clone scenes.");return this.sceneSaver.serializeScene(e)}serializeSceneDocument(e){if(!this.sceneSaver)throw new Error("[SceneManager] No SceneSaver was provided \u2014 this host cannot serialize scenes.");return this.sceneSaver.serializeSceneDocument(e)}setActiveSceneGraph(e,t,r={}){let i=this.sceneGraphs.get(e);i&&i!==t&&r.disposePrevious!==!1&&this.disposeSceneGraph(i),this.sceneGraphs.set(e,t),this.groupMaps.set(e,this.buildGroupMap(t)),this.activeSceneId=e,console.debug("[SceneManager] setActiveSceneGraph",{sceneId:e,rootCount:t.rootNodes.length})}setActiveScene(e){return this.sceneGraphs.has(e)?(this.activeSceneId=e,!0):!1}getSceneGraph(e){return this.sceneGraphs.get(e)??null}getActiveSceneGraph(){return this.activeSceneId?this.sceneGraphs.get(this.activeSceneId)??null:null}resizeRoot(e,t,r=!1){let i=this.getActiveSceneGraph();if(i)for(let o of i.rootNodes)o instanceof M&&o.applyAnchoredLayoutRecursive({width:e,height:t},{width:e,height:t})}removeSceneGraph(e){let t=this.sceneGraphs.get(e);t&&this.disposeSceneGraph(t),this.sceneGraphs.delete(e),this.groupMaps.delete(e),this.activeSceneId===e&&(this.activeSceneId=null)}addNodeToGroup(e,t,r){let i=r??this.activeSceneId;if(!i)return;let o=this.ensureGroupMap(i),s=o.get(t)??new Set;s.add(e),o.set(t,s)}removeNodeFromGroup(e,t,r){let i=r??this.activeSceneId;if(!i)return;let o=this.ensureGroupMap(i),s=o.get(t);s&&(s.delete(e),s.size===0&&o.delete(t))}getNodesInGroup(e,t){let r=t??this.activeSceneId;if(!r)return[];let i=this.sceneGraphs.get(r);if(!i)return[];let o=this.ensureGroupMap(r),s=Array.from(o.get(e)??[]),a=s.filter(l=>i.nodeMap.has(l.nodeId));return a.length!==s.length?(this.groupMaps.set(r,this.buildGroupMap(i)),Array.from(this.groupMaps.get(r)?.get(e)??[])):a}callGroup(e,t,...r){let i=this.getNodesInGroup(e),o=0;for(let s of i)for(let a of s.components){let l=a[t];typeof l=="function"&&(l.apply(a,r),o+=1)}i.length>0&&o===0&&console.warn(`[SceneManager] callGroup("${e}", "${t}") found no callable methods.`)}dispose(){for(let e of this.sceneGraphs.values())this.disposeSceneGraph(e);this.sceneGraphs.clear(),this.groupMaps.clear(),this.activeSceneId=null}disposeSceneGraph(e){for(let t of e.rootNodes)t.dispose();e.nodeMap.clear()}ensureGroupMap(e){let t=this.sceneGraphs.get(e);if(!t)return new Map;let r=this.groupMaps.get(e);return r||(r=this.buildGroupMap(t),this.groupMaps.set(e,r)),r}buildGroupMap(e){let t=new Map;for(let r of e.nodeMap.values())for(let i of r.groups){let o=t.get(i)??new Set;o.add(r),t.set(i,o)}return t}};var iC=64,Wn=class{axes=new Map;buttons=new Map;pointerPosition=new I;isPointerDown=!1;activePointerId=null;wheelDelta=new I;pointerEvents=[];keyEvents=[];width=0;height=0;hoveredUIElements=new Set;hoveredUIPointers=new Set;activePointers=new Map;pendingWheelDelta=new I;pendingPointerEvents=[];pendingKeyEvents=[];element=null;previousTouchAction=null;lockDepth=0;polledActions=null;pollsTruncated=!1;lockedDuringPollWindow=!1;beginFrame(){this.hoveredUIElements.clear(),this.hoveredUIPointers.clear(),this.wheelDelta.copy(this.pendingWheelDelta),this.pendingWheelDelta.set(0,0),this.pointerEvents=this.pendingPointerEvents,this.pendingPointerEvents=[],this.keyEvents=this.pendingKeyEvents,this.pendingKeyEvents=[]}registerHover(e,t){this.hoveredUIElements.add(e);let r=t??this.activePointerId;r!=null&&this.hoveredUIPointers.add(r)}get isHoveringUI(){return this.hoveredUIElements.size>0}isPointerOverUI(e){return this.hoveredUIPointers.has(e)}getActivePointers(){return[...this.activePointers.values()]}getPointer(e){return this.activePointers.get(e)??null}get pointerDownCount(){return this.activePointers.size}lock(){this.lockDepth+=1,this.polledActions!==null&&(this.lockedDuringPollWindow=!0),this.lockDepth===1&&(this.pendingPointerEvents=[],this.pendingKeyEvents=[],this.pendingWheelDelta.set(0,0),this.wheelDelta.set(0,0),this.cancelActivePointers(!0),this.isPointerDown=!1,this.activePointerId=null,this.setButton("Action_Primary",!1),this.clearHeldKeyButtons())}cancelActivePointers(e){for(let t of this.activePointers.values())this.releasePointer(t.pointerId),e&&this.pendingPointerEvents.push({type:"cancel",pointerId:t.pointerId,x:t.x,y:t.y});this.activePointers.clear(),this.syncDerivedPointerState()}clearHeldKeyButtons(){for(let e of this.buttons.keys())e.startsWith("Key_")&&this.buttons.set(e,!1)}unlock(){this.lockDepth>0&&(this.lockDepth-=1)}get isLocked(){return this.lockDepth>0}setAxis(e,t){this.axes.set(e,t)}getAxis(e){return this.polledActions!==null&&this.recordPoll(e),this.axes.get(e)||0}setButton(e,t){this.buttons.set(e,t)}getButton(e){return this.polledActions!==null&&this.recordPoll(e),this.buttons.get(e)||!1}startPollRecording(){this.polledActions=new Set,this.pollsTruncated=!1,this.lockedDuringPollWindow=this.lockDepth>0}stopPollRecording(){this.polledActions=null,this.pollsTruncated=!1,this.lockedDuringPollWindow=!1}get isPollRecording(){return this.polledActions!==null}getObservedPolls(){return{observedPolls:this.polledActions?[...this.polledActions]:[],locked:this.lockDepth>0,lockedDuringWindow:this.lockedDuringPollWindow||this.lockDepth>0,truncated:this.pollsTruncated}}takeObservedPolls(){let e=this.getObservedPolls();return this.polledActions!==null&&(this.polledActions.clear(),this.pollsTruncated=!1,this.lockedDuringPollWindow=this.lockDepth>0),e}recordPoll(e){let t=this.polledActions;if(!(!t||t.has(e))){if(t.size>=iC){this.pollsTruncated=!0;return}t.add(e)}}attach(e){this.detach(),this.element=e,this.previousTouchAction=e.style.touchAction,e.style.touchAction="none";let t=this.getInputDimensions();this.width=t.width,this.height=t.height,console.log(`[InputService] Attached to element. Dimensions: ${this.width}x${this.height}`),e.addEventListener("pointerdown",this.onPointerDown),e.addEventListener("pointermove",this.onPointerMove),e.addEventListener("pointerup",this.onPointerUp),e.addEventListener("pointercancel",this.onPointerCancel),e.addEventListener("pointerleave",this.onPointerLeave),e.addEventListener("wheel",this.onWheel,{passive:!1}),window.addEventListener("keydown",this.onKeyDown),window.addEventListener("keyup",this.onKeyUp),window.addEventListener("blur",this.onWindowBlur),e.addEventListener("contextmenu",this.onContextMenu)}detach(){this.element&&(this.element.removeEventListener("pointerdown",this.onPointerDown),this.element.removeEventListener("pointermove",this.onPointerMove),this.element.removeEventListener("pointerup",this.onPointerUp),this.element.removeEventListener("pointercancel",this.onPointerCancel),this.element.removeEventListener("pointerleave",this.onPointerLeave),this.element.removeEventListener("wheel",this.onWheel),this.element.removeEventListener("contextmenu",this.onContextMenu),window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp),window.removeEventListener("blur",this.onWindowBlur),this.cancelActivePointers(!1),this.previousTouchAction!==null&&(this.element.style.touchAction=this.previousTouchAction,this.previousTouchAction=null),this.element=null,this.isPointerDown=!1,this.activePointerId=null,this.wheelDelta.set(0,0),this.pendingWheelDelta.set(0,0),this.pointerEvents=[],this.pendingPointerEvents=[],this.keyEvents=[],this.pendingKeyEvents=[],this.setButton("Action_Primary",!1),this.lockDepth=0,this.stopPollRecording())}onPointerDown=e=>{if(this.lockDepth>0||this.activePointers.has(e.pointerId))return;let t=this.computePointerPosition(e),r=this.activePointers.size===0;this.activePointers.set(e.pointerId,{pointerId:e.pointerId,x:t.x,y:t.y,isPrimary:r}),this.syncDerivedPointerState(),this.pendingPointerEvents.push({type:"down",pointerId:e.pointerId,x:t.x,y:t.y}),this.capturePointer(e.pointerId),r&&this.setButton("Action_Primary",!0)};onPointerMove=e=>{if(this.lockDepth>0)return;let t=this.activePointers.get(e.pointerId),r=this.computePointerPosition(e);if(!t){this.activePointers.size===0&&this.pointerPosition.set(r.x,r.y);return}t.x=r.x,t.y=r.y,t.isPrimary&&this.pointerPosition.set(r.x,r.y),this.pendingPointerEvents.push({type:"move",pointerId:e.pointerId,x:r.x,y:r.y})};onPointerUp=e=>{this.endPointer(e,"up")};onPointerCancel=e=>{this.endPointer(e,"cancel")};onPointerLeave=e=>{this.endPointer(e,"cancel")};onWindowBlur=()=>{this.activePointers.size!==0&&(this.cancelActivePointers(!0),this.setButton("Action_Primary",!1))};endPointer(e,t){if(this.lockDepth>0)return;let r=this.activePointers.get(e.pointerId);if(!r)return;let i=this.computePointerPosition(e);r.isPrimary&&this.pointerPosition.set(i.x,i.y),this.activePointers.delete(e.pointerId),this.syncDerivedPointerState(),this.pendingPointerEvents.push({type:t,pointerId:e.pointerId,x:i.x,y:i.y}),this.releasePointer(e.pointerId),this.activePointers.size===0&&this.setButton("Action_Primary",!1)}syncDerivedPointerState(){let e=null;for(let t of this.activePointers.values()){let r=e===null;t.isPrimary=r,r&&(e=t)}this.isPointerDown=this.activePointers.size>0,this.activePointerId=e?e.pointerId:null,e&&this.pointerPosition.set(e.x,e.y)}capturePointer(e){try{this.element?.setPointerCapture?.(e)}catch{}}releasePointer(e){try{this.element?.releasePointerCapture?.(e)}catch{}}onContextMenu=e=>{e.preventDefault()};onWheel=e=>{e.preventDefault(),!(this.lockDepth>0)&&(this.pendingWheelDelta.x+=e.deltaX,this.pendingWheelDelta.y+=e.deltaY)};onKeyDown=e=>{this.lockDepth>0||(this.setButton(`Key_${e.code}`,!0),this.setButton(`Key_${e.key.toUpperCase()}`,!0),this.pendingKeyEvents.push({type:"down",code:e.code,key:e.key,repeat:e.repeat}))};onKeyUp=e=>{this.lockDepth>0||(this.setButton(`Key_${e.code}`,!1),this.setButton(`Key_${e.key.toUpperCase()}`,!1),this.pendingKeyEvents.push({type:"up",code:e.code,key:e.key,repeat:e.repeat}))};computePointerPosition(e){if(!this.element)return{x:this.pointerPosition.x,y:this.pointerPosition.y};let t=this.element.getBoundingClientRect(),r=this.getInputDimensions();this.width=r.width,this.height=r.height;let i=t.width>0?t.width:1,o=t.height>0?t.height:1,s=this.width/i,a=this.height/o,l=(e.clientX-t.left)*s,c=(e.clientY-t.top)*a;return{x:l,y:c}}getInputDimensions(){if(!this.element)return{width:0,height:0};if(this.element instanceof HTMLCanvasElement){let t=this.element.width,r=this.element.height;if(t>0&&r>0)return{width:t,height:r}}let e=this.element.getBoundingClientRect();return{width:e.width,height:e.height}}};var pF=3,mF=512;function Qt(n,e,t,r,i,o){return(t-n)*(o-e)-(r-e)*(i-n)}function Fa(n){let e=n.length;if(e<3)return 0;let t=0;for(let r=0,i=e-1;r<e;i=r++)t+=n[i].x*n[r].y-n[r].x*n[i].y;return t/2}function gh(n){return Math.abs(Fa(n))}function Gn(n){let e=n.length;if(e===0)return{x:0,y:0};let t=Fa(n);if(Math.abs(t)<1e-9){let o=0,s=0;for(let a of n)o+=a.x,s+=a.y;return{x:o/e,y:s/e}}let r=0,i=0;for(let o=0,s=e-1;o<e;s=o++){let a=n[s],l=n[o],c=a.x*l.y-l.x*a.y;r+=(a.x+l.x)*c,i+=(a.y+l.y)*c}return{x:r/(6*t),y:i/(6*t)}}function eS(n){let e=n.length;if(e<3)return!1;let t=0;for(let r=0;r<e;r++){let i=n[r],o=n[(r+1)%e],s=n[(r+2)%e],a=Qt(i.x,i.y,o.x,o.y,s.x,s.y);if(Math.abs(a)<1e-9)continue;let l=a>0?1:-1;if(t===0)t=l;else if(t!==l)return!1}return!0}function ki(n){let e=n.map(t=>({x:t.x,y:t.y}));return Fa(e)<0&&e.reverse(),e}function yh(n,e=1e-6){let t=[];for(let o of n){if(!Number.isFinite(o?.x)||!Number.isFinite(o?.y))continue;let s=t[t.length-1];s&&Math.abs(s.x-o.x)<=e&&Math.abs(s.y-o.y)<=e||t.push({x:o.x,y:o.y})}for(;t.length>1;){let o=t[0],s=t[t.length-1];if(Math.abs(o.x-s.x)<=e&&Math.abs(o.y-s.y)<=e)t.pop();else break}if(t.length<3)return t;let r=[],i=t.length;for(let o=0;o<i;o++){let s=t[(o-1+i)%i],a=t[o],l=t[(o+1)%i];Math.abs(Qt(s.x,s.y,a.x,a.y,l.x,l.y))<=e||r.push(a)}return r.length>=3?r:t}function La(n){let e=n.filter(o=>Number.isFinite(o?.x)&&Number.isFinite(o?.y)).map(o=>({x:o.x,y:o.y})).sort((o,s)=>o.x===s.x?o.y-s.y:o.x-s.x);if(e.length<3)return e;let t=o=>{let s=[];for(let a of o){for(;s.length>=2;){let l=s[s.length-2],c=s[s.length-1];if(Qt(l.x,l.y,c.x,c.y,a.x,a.y)>1e-9)break;s.pop()}s.push(a)}return s.pop(),s},r=t(e),i=t([...e].reverse());return[...r,...i]}function bh(n){if(n.length===0)return{minX:0,minY:0,maxX:0,maxY:0};let e=1/0,t=1/0,r=-1/0,i=-1/0;for(let o of n)o.x<e&&(e=o.x),o.y<t&&(t=o.y),o.x>r&&(r=o.x),o.y>i&&(i=o.y);return{minX:e,minY:t,maxX:r,maxY:i}}function Rr(n,e){let t=Math.cos(e.rotation),r=Math.sin(e.rotation),i=new Array(n.length);for(let o=0;o<n.length;o++){let s=n[o].x*e.scaleX,a=n[o].y*e.scaleY;i[o]={x:e.x+s*t-a*r,y:e.y+s*r+a*t}}return e.scaleX*e.scaleY<0&&i.reverse(),i}function Ai(n,e,t){let r=t?.x??0,i=t?.y??0,o=Math.abs(n),s=Math.abs(e);return[{x:r-o,y:i-s},{x:r+o,y:i-s},{x:r+o,y:i+s},{x:r-o,y:i+s}]}function tS(n,e=16,t){let r=t?.x??0,i=t?.y??0,o=Math.max(3,Math.floor(e)),s=new Array(o);for(let a=0;a<o;a++){let l=a/o*Math.PI*2;s[a]={x:r+Math.cos(l)*n,y:i+Math.sin(l)*n}}return s}function Sh(n,e,t=8,r){let i=Math.abs(e),o=r?.x??0,s=r?.y??0;if(i<=0)return[];let a=Math.max(0,Math.abs(n)/2-i);if(a<=1e-6)return tS(i,t*2,r);let l=Math.max(2,Math.floor(t)),c=[];for(let u=0;u<=l;u++){let d=Math.PI*(u/l);c.push({x:o+Math.cos(d)*i,y:s+a+Math.sin(d)*i})}for(let u=0;u<=l;u++){let d=Math.PI+Math.PI*(u/l);c.push({x:o+Math.cos(d)*i,y:s-a+Math.sin(d)*i})}return ki(yh(c))}function kt(n,e,t){let r=t.length;if(r<3)return!1;let i=!1;for(let o=0,s=r-1;o<r;s=o++){let a=t[s],l=t[o];if(a.y>e!=l.y>e){let c=(e-a.y)/(l.y-a.y);n<a.x+c*(l.x-a.x)&&(i=!i)}}return i}function nC(n,e,t,r){let i=r.x-t.x,o=r.y-t.y,s=i*i+o*o,a=s>1e-9?((n-t.x)*i+(e-t.y)*o)/s:0;a=a<0?0:a>1?1:a;let l=t.x+i*a-n,c=t.y+o*a-e;return l*l+c*c}function rS(n,e,t){let r=1/0,i=t.length;for(let o=0,s=i-1;o<i;s=o++){let a=nC(n,e,t[s],t[o]);a<r&&(r=a)}return Math.sqrt(r)}function qn(n,e,t,r){return r.length<3?!1:kt(n,e,r)?!0:rS(n,e,r)<=Math.abs(t)}function vh(n,e,t,r,i){let o=i.length;if(o<3)return!1;let s=Math.abs(t),a=Math.abs(r),l=n-s,c=n+s,u=e-a,d=e+a;for(let p of i)if(p.x>=l&&p.x<=c&&p.y>=u&&p.y<=d)return!0;let h=Ai(s,a,{x:n,y:e});if(kt(h[0].x,h[0].y,i))return!0;for(let p=0,f=o-1;p<o;f=p++){let m=i[f],g=i[p],y=g.x-m.x,b=g.y-m.y;for(let v=0,w=3;v<4;w=v++)if(nS(m.x,m.y,y,b,h[w],h[v])!==null)return!0}return!1}function oC(n,e,t,r,i){return iS(Ai(t,r,{x:n,y:e}),i)}function iS(n,e){return n.length<3||e.length<3?!1:!Jb(n,e)&&!Jb(e,n)}function Jb(n,e){let t=n.length;for(let r=0,i=t-1;r<t;i=r++){let o=n[r].x-n[i].x,s=n[r].y-n[i].y,a=Math.hypot(o,s);if(a<1e-9)continue;let l=s/a,c=-o/a,u=1/0,d=-1/0;for(let f of n){let m=f.x*l+f.y*c;m<u&&(u=m),m>d&&(d=m)}let h=1/0,p=-1/0;for(let f of e){let m=f.x*l+f.y*c;m<h&&(h=m),m>p&&(p=m)}if(d<h-1e-9||p<u-1e-9)return!0}return!1}function wh(n,e,t,r,i){let o=i.length;if(o<3)return null;if(kt(n,e,i))return 0;let s=null;for(let a=0,l=o-1;a<o;l=a++){let c=nS(n,e,t,r,i[l],i[a]);c!==null&&(s===null||c<s)&&(s=c)}return s}function nS(n,e,t,r,i,o){let s=o.x-i.x,a=o.y-i.y,l=t*a-r*s;if(Math.abs(l)<1e-9)return null;let c=i.x-n,u=i.y-e,d=(c*a-u*s)/l,h=(c*r-u*t)/l;return d<0||d>1||h<0||h>1?null:d}function _a(n){let e=yh(n);if(e.length<3)return[];if(e.length>512){let r=La(e);return r.length>=3?[ki(r)]:[]}let t=[];return fh(ki(e),t,0),t}var sC=512;function fh(n,e,t){if(n.length<3)return;if(n.length===3||eS(n)){e.push(n);return}if(t>=sC){let o=La(n);o.length>=3&&e.push(ki(o));return}let r=n.length;for(let o=0;o<r;o++){if(!aC(n,o))continue;let s=-1,a=1/0;for(let l=2;l<=r-2;l++){let c=(o+l)%r;if(!lC(n,o,c))continue;let u=n[c].x-n[o].x,d=n[c].y-n[o].y,h=u*u+d*d;h<a&&(a=h,s=c)}if(!(s<0)){fh(Zb(n,o,s),e,t+1),fh(Zb(n,s,o),e,t+1);return}}let i=La(n);i.length>=3&&e.push(ki(i))}function aC(n,e){let t=n.length,r=n[(e-1+t)%t],i=n[e],o=n[(e+1)%t];return Qt(r.x,r.y,i.x,i.y,o.x,o.y)<-1e-9}function lC(n,e,t){let r=n.length,i=n[e],o=n[t];for(let s=0,a=r-1;s<r;a=s++)if(!(a===e||a===t||s===e||s===t)&&cC(i,o,n[a],n[s]))return!1;return kt((i.x+o.x)/2,(i.y+o.y)/2,n)}function cC(n,e,t,r){let i=Qt(t.x,t.y,r.x,r.y,n.x,n.y),o=Qt(t.x,t.y,r.x,r.y,e.x,e.y),s=Qt(n.x,n.y,e.x,e.y,t.x,t.y),a=Qt(n.x,n.y,e.x,e.y,r.x,r.y);return(i>1e-9&&o<-1e-9||i<-1e-9&&o>1e-9)&&(s>1e-9&&a<-1e-9||s<-1e-9&&a>1e-9)}function Zb(n,e,t){let r=n.length,i=[];for(let o=e;i.push({x:n[o].x,y:n[o].y}),o!==t;o=(o+1)%r);return i}var oS=new ae,xh=new S,sS=new _,Ph=new S;function it(n,e){let t=e??{x:0,y:0,rotation:0,scaleX:1,scaleY:1};return n.updateWorldMatrix(!0,!1),oS.copy(n.matrixWorld),oS.decompose(xh,sS,Ph),t.x=xh.x,t.y=xh.y,t.rotation=aS(sS),t.scaleX=Ph.x||1,t.scaleY=Ph.y||1,t}function aS(n){return Math.atan2(2*(n.w*n.z+n.x*n.y),1-2*(n.y*n.y+n.z*n.z))}var kh=new S,Ah=new S,lS={x:0,y:0,rotation:0,scaleX:1,scaleY:1},Hn=class{sources=new Set;register(e){this.sources.add(e)}unregister(e){this.sources.delete(e)}get count(){return this.sources.size}overlapPoint(e,t,r){let i=[];for(let o of this.resolve(r))(o.polygon?kt(e,t,o.polygon):o.shape==="circle"?Ua(e,t,o.cx,o.cy)<=o.r*o.r:Math.abs(e-o.cx)<=o.hw&&Math.abs(t-o.cy)<=o.hh)&&i.push(Th(o));return i}overlapCircle(e,t,r,i){let o=[];for(let s of this.resolve(i)){let a;if(s.polygon)a=qn(e,t,r,s.polygon);else if(s.shape==="circle"){let l=s.r+r;a=Ua(e,t,s.cx,s.cy)<=l*l}else{let l=za(e,s.cx-s.hw,s.cx+s.hw),c=za(t,s.cy-s.hh,s.cy+s.hh);a=Ua(e,t,l,c)<=r*r}a&&o.push(Th(s))}return o}overlapRect(e,t,r,i,o){let s=Math.abs(r)/2,a=Math.abs(i)/2,l=[];for(let c of this.resolve(o)){let u;if(c.polygon)u=vh(e,t,s,a,c.polygon);else if(c.shape==="circle"){let d=za(c.cx,e-s,e+s),h=za(c.cy,t-a,t+a);u=Ua(c.cx,c.cy,d,h)<=c.r*c.r}else u=Math.abs(c.cx-e)<=c.hw+s&&Math.abs(c.cy-t)<=c.hh+a;u&&l.push(Th(c))}return l}raycast(e,t,r,i,o){let s=r-e,a=i-t,l=Math.hypot(s,a);if(l<=1e-6){let d=this.overlapPoint(e,t,o);return d.length>0?{...d[0],distance:0,x:e,y:t}:null}let c=null,u=1/0;for(let d of this.resolve(o)){let h=d.polygon?wh(e,t,s,a,d.polygon):d.shape==="circle"?uC(e,t,s,a,d.cx,d.cy,d.r):dC(e,t,s,a,d.cx-d.hw,d.cy-d.hh,d.cx+d.hw,d.cy+d.hh);h!==null&&h<u&&(u=h,c={node:d.node,source:d.source,group:d.group,x:e+s*h,y:t+a*h,distance:l*h})}return c}*resolve(e){for(let t of this.sources){let r=t.node;if(!r||!t.enabled||!r.visible)continue;let i=t.getHitboxGroup();if(e!==void 0&&i!==e)continue;let o=t.getHitboxOffset(),s=t.getHitboxSize(),a=t.getHitboxShape();if(a==="polygon"){let u=t.getHitboxPolygon?.();if(!u||u.length<3)continue;it(r,lS);let d=Rr(u.map(p=>({x:p.x+o.x,y:p.y+o.y})),lS),h=Gn(d);yield{source:t,node:r,group:i,shape:a,cx:h.x,cy:h.y,hw:0,hh:0,r:0,polygon:d};continue}r.getWorldPosition(kh),r.getWorldScale(Ah);let l=Math.abs(Ah.x)||1,c=Math.abs(Ah.y)||1;yield{source:t,node:r,group:i,shape:a,cx:kh.x+o.x*l,cy:kh.y+o.y*c,hw:Math.abs(s.width)/2*l,hh:Math.abs(s.height)/2*c,r:Math.abs(s.radius)*Math.max(l,c),polygon:null}}}};function Th(n){return{node:n.node,source:n.source,group:n.group,x:n.cx,y:n.cy}}function za(n,e,t){return n<e?e:n>t?t:n}function Ua(n,e,t,r){let i=t-n,o=r-e;return i*i+o*o}function uC(n,e,t,r,i,o,s){let a=n-i,l=e-o,c=t*t+r*r,u=2*(a*t+l*r),d=a*a+l*l-s*s;if(d<=0)return 0;let h=u*u-4*c*d;if(h<0||c<=1e-12)return null;let p=Math.sqrt(h),f=(-u-p)/(2*c);return f>=0&&f<=1?f:null}function dC(n,e,t,r,i,o,s,a){let l=0,c=1;for(let[u,d,h,p]of[[n,t,i,s],[e,r,o,a]])if(Math.abs(d)<1e-12){if(u<h||u>p)return null}else{let f=(h-u)/d,m=(p-u)/d;if(f>m){let g=f;f=m,m=g}if(l=Math.max(l,f),c=Math.min(c,m),l>c)return null}return l}var Te=1e-9,Br=.5;function Ch(n,e,t,r,i,o){let s=r-n,a=i-e,l=s*s+a*a,c=t+o,u=c+Br;if(l>u*u)return null;let d=Math.sqrt(l),h=d>Te?s/d:1,p=d>Te?a/d:0,f=c-d;return{normalX:h,normalY:p,contacts:[{x:n+h*(t-f/2),y:e+p*(t-f/2),penetration:f,featureId:0}]}}function Wa(n,e,t,r){let i=r.length;if(i<3)return null;let o=-1/0,s=0;for(let w=0,k=i-1;w<i;k=w++){let T=r[w].x-r[k].x,N=r[w].y-r[k].y,A=Math.hypot(T,N);if(A<Te)continue;let F=N/A,Z=-T/A,ne=(n-r[k].x)*F+(e-r[k].y)*Z;ne>o&&(o=ne,s=k)}if(o>t+Br)return null;let a=r[s],l=r[(s+1)%i];if(o<Te){let w=l.x-a.x,k=l.y-a.y,T=Math.hypot(w,k)||1,N=k/T,A=-w/T;return{normalX:-N,normalY:-A,contacts:[{x:n+N*-o,y:e+A*-o,penetration:t-o,featureId:s}]}}let c=l.x-a.x,u=l.y-a.y,d=c*c+u*u,h=d>Te?((n-a.x)*c+(e-a.y)*u)/d:0;h=h<0?0:h>1?1:h;let p=a.x+c*h,f=a.y+u*h,m=p-n,g=f-e,y=Math.hypot(m,g);if(y>t+Br)return null;let b=y>Te?m/y:0,v=y>Te?g/y:1;return{normalX:b,normalY:v,contacts:[{x:p,y:f,penetration:t-y,featureId:s}]}}function cS(n,e){let t=-1/0,r=0,i=n.length;for(let o=0;o<i;o++){let s=n[o],a=n[(o+1)%i],l=a.x-s.x,c=a.y-s.y,u=Math.hypot(l,c);if(u<Te)continue;let d=c/u,h=-l/u,p=1/0;for(let f of e){let m=(f.x-s.x)*d+(f.y-s.y)*h;m<p&&(p=m)}p>t&&(t=p,r=o)}return{separation:t,edgeIndex:r}}function hC(n,e,t){let r=n.length,i=1/0,o=0;for(let s=0;s<r;s++){let a=n[s],l=n[(s+1)%r],c=l.x-a.x,u=l.y-a.y,d=Math.hypot(c,u);if(d<Te)continue;let h=u/d*e+-c/d*t;h<i&&(i=h,o=s)}return o}function uS(n,e,t,r,i){let o=[],s=e*n[0].x+t*n[0].y-r,a=e*n[1].x+t*n[1].y-r;if(s<=0&&o.push(n[0]),a<=0&&o.push(n[1]),s*a<0){let l=s/(s-a);o.push({x:n[0].x+l*(n[1].x-n[0].x),y:n[0].y+l*(n[1].y-n[0].y),id:i})}return o}function Mh(n,e){if(n.length<3||e.length<3)return null;let t=cS(n,e);if(t.separation>Br)return null;let r=cS(e,n);if(r.separation>Br)return null;let i=r.separation>t.separation+1e-5,o=i?e:n,s=i?n:e,a=i?r.edgeIndex:t.edgeIndex,l=o.length,c=o[a],u=o[(a+1)%l],d=u.x-c.x,h=u.y-c.y,p=Math.hypot(d,h);if(p<Te)return null;let f=d/p,m=h/p,g=m,y=-f,b=hC(s,g,y),v=s.length,w=s[b],k=s[(b+1)%v],T=[{x:w.x,y:w.y,id:b*4+0},{x:k.x,y:k.y,id:b*4+1}];if(T=uS(T,-f,-m,-(f*c.x+m*c.y),a*4+2),T.length<2||(T=uS(T,f,m,f*u.x+m*u.y,a*4+3),T.length<2))return null;let N=g*c.x+y*c.y,A=[];for(let F of T){let Z=g*F.x+y*F.y-N;Z<=Br&&A.push({x:F.x,y:F.y,penetration:-Z,featureId:F.id})}return A.length===0?null:i?{normalX:-g,normalY:-y,contacts:A}:{normalX:g,normalY:y,contacts:A}}function jn(n,e,t,r,i,o){let s=o.length;if(s<3)return null;if(qn(n,e,i,o))return 0;let a=null,l=c=>{c>=0&&c<=1&&(a===null||c<a)&&(a=c)};for(let c=0,u=s-1;c<s;u=c++){let d=o[u],h=o[c],p=h.x-d.x,f=h.y-d.y,m=Math.hypot(p,f);if(m<Te)continue;let g=f/m,y=-p/m,b=t*g+r*y;if(b<-Te){let k=-((n-d.x)*g+(e-d.y)*y-i)/b;if(k>=0&&k<=1){let T=n+t*k-g*i,N=e+r*k-y*i,A=((T-d.x)*p+(N-d.y)*f)/(m*m);A>=0&&A<=1&&l(k)}}let v=pC(n,e,t,r,d.x,d.y,i);v!==null&&l(v)}return a}function pC(n,e,t,r,i,o,s){let a=n-i,l=e-o,c=t*t+r*r;if(c<Te)return null;let u=2*(a*t+l*r),d=a*a+l*l-s*s;if(d<=0)return 0;let h=u*u-4*c*d;if(h<0)return null;let p=(-u-Math.sqrt(h))/(2*c);return p>=0&&p<=1?p:null}var dS=-1960,mC=8,fC=3,Dh=.05,gC=.2,hS=4,yC=.2,bC=40,SC=4,vC=.15,wC=.5,xC=8,Ga=128,Yn=class{gravityX=0;gravityY=dS;bodies=new Map;colliders=new Map;staticBody;contacts=new Map;joints=new Map;jointedPairs=new Set;touching=new Map;signalQueue=[];orderCounter=0;constructor(){this.staticBody=PC()}setGravity(e,t){this.gravityX=Number.isFinite(e)?e:0,this.gravityY=Number.isFinite(t)?t:dS}getGravity(){return{x:this.gravityX,y:this.gravityY}}get bodyCount(){return this.bodies.size}get colliderCount(){return this.colliders.size}registerBody(e){let t=e.node;if(!t)return;let r=this.bodies.get(t);if(r){r.source=e;return}let i=it(t);this.bodies.set(t,{node:t,source:e,bodyType:e.getBodyType(),x:i.x,y:i.y,rotation:i.rotation,vx:0,vy:0,w:0,forceX:0,forceY:0,torque:0,mass:1,invMass:1,inertia:1,invInertia:1,prevX:i.x,prevY:i.y,prevRotation:i.rotation,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,canSleep:!0,emitContacts:!1,sleepTimer:0,sleeping:!1,colliders:[],order:this.orderCounter++,transformDirty:!1}),this.rebindColliders()}unregisterBody(e){let t=e.node;t&&(this.bodies.delete(t),this.rebindColliders())}registerCollider(e){if(!e.node)return;let t={source:e,body:this.staticBody,shape:qa(),friction:.4,restitution:0,density:1,sensor:!1,group:"default",revision:"",bounds:{minX:0,minY:0,maxX:0,maxY:0},order:this.orderCounter++};this.colliders.set(e,t),this.rebindColliders()}unregisterCollider(e){let t=this.colliders.get(e);if(t){this.colliders.delete(e),t.body.colliders=t.body.colliders.filter(r=>r!==t);for(let[r,i]of this.contacts)(i.a===t||i.b===t)&&this.contacts.delete(r);for(let[r,i]of this.touching)i[0]!==t&&i[1]!==t||(this.wakeBody(i[0].body),this.wakeBody(i[1].body),this.touching.delete(r))}}registerJoint(e){let t=e.node;if(!t||this.joints.has(e))return;let r=this.bodies.get(t);if(!r)return;let i=e.getConnectedNode(),o=(i?this.bodies.get(i):null)??this.staticBody,s=r,a=e.getJointAnchor(),l=it(t),c=Math.cos(l.rotation),u=Math.sin(l.rotation),d=l.x+a.x*c-a.y*u,h=l.y+a.x*u+a.y*c,p=gS(o,d,h),f=gS(s,d,h);this.joints.set(e,{source:e,bodyA:o,bodyB:s,localAX:p.x,localAY:p.y,localBX:f.x,localBY:f.y,referenceAngle:s.rotation-o.rotation,rax:0,ray:0,rbx:0,rby:0,massXX:0,massXY:0,massYY:0,angularMass:0,impulseX:0,impulseY:0,motorImpulse:0,lowerImpulse:0,upperImpulse:0,order:this.orderCounter++}),this.refreshJointedPairs()}unregisterJoint(e){this.joints.delete(e),this.refreshJointedPairs()}refreshJointedPairs(){this.jointedPairs=new Set;for(let e of this.joints.values())e.source.getJointConfig().collideConnected||this.jointedPairs.add(Ih(e.bodyA,e.bodyB))}get jointCount(){return this.joints.size}getBody(e){let t=e?this.bodies.get(e):null;return t?MC(t):null}step(e){if(!Number.isFinite(e)||e<=0||this.colliders.size===0)return;this.syncFromNodes();for(let r of this.bodies.values())r.prevX=r.x,r.prevY=r.y,r.prevRotation=r.rotation;this.refreshShapes(),this.integrateVelocities(e);let t=this.broadphase();this.narrowphase(t),this.prepareJoints(),this.warmStart(),this.warmStartJoints();for(let r=0;r<mC;r++)this.solveJointVelocities(e),this.solveVelocities(e);this.integratePositions(e),this.applyContinuousCollision(e);for(let r=0;r<fC;r++)this.solvePositions(),this.solveJointPositions();this.writeBackToNodes(),this.updateSleep(e),this.flushSignals()}interpolate(e){if(!Number.isFinite(e)||this.bodies.size===0)return;let t=e<0?0:e>1?1:e;for(let r of this.orderedBodies()){if(r.bodyType!=="dynamic"||r.sleeping)continue;let i=r.x,o=r.y,s=r.rotation;r.x=r.prevX+(i-r.prevX)*t,r.y=r.prevY+(o-r.prevY)*t,r.rotation=r.prevRotation+CC(r.prevRotation,s)*t,this.writeBodyToNode(r),r.x=i,r.y=o,r.rotation=s}}raycast(e,t,r,i,o={}){this.refreshShapes();let s=r-e,a=i-t,l=Math.hypot(s,a);if(l<1e-6)return null;let c=null,u=1/0;for(let d of this.orderedColliders(o)){let h=AC(d.shape,e,t,s,a);h!==null&&h<u&&(u=h,c={node:d.source.node,group:d.group,x:e+s*h,y:t+a*h,distance:l*h})}return c}overlapCircle(e,t,r,i={}){this.refreshShapes();let o=pS(0,0,Math.abs(r));return o.worldCx=e,o.worldCy=t,this.orderedColliders(i).filter(s=>mS(o,s.shape)).map(s=>s.source.node)}overlapRect(e,t,r,i,o={}){this.refreshShapes();let s=Ha([Ai(Math.abs(r)/2,Math.abs(i)/2)]);return s.worldParts=s.parts.map(a=>Rr(a,{x:e,y:t,rotation:0,scaleX:1,scaleY:1})),s.worldCx=e,s.worldCy=t,this.orderedColliders(o).filter(a=>mS(s,a.shape)).map(a=>a.source.node)}moveAndCollide(e,t,r,i={}){let o={movedX:0,movedY:0,collided:!1,normalX:0,normalY:0,collider:null},s=e?this.bodies.get(e):null;if(!s||!Number.isFinite(t)||!Number.isFinite(r))return o;this.refreshShapes();let a=s.x,l=s.y,c=Math.hypot(t,r),u=Math.max(1,Math.ceil(c/Math.max(1,this.bodyStepLimit(s)))),d=!1,h=0,p=0,f=-1/0,m=null;for(let g=0;g<u;g++){s.x+=t/u,s.y+=r/u;let y=this.depenetrate(s,i);y&&(d=!0,y.depth>f&&(f=y.depth,h=y.normalX,p=y.normalY,m=y.collider))}return this.writeBodyToNode(s),{movedX:s.x-a,movedY:s.y-l,collided:d,normalX:h,normalY:p,collider:m}}moveAndSlide(e,t,r,i,o={}){let s=o.upX??0,a=o.upY??1,l=Math.hypot(s,a)||1,c=s/l,u=a/l,d=Math.cos((o.floorMaxAngle??45)*Math.PI/180),h=Math.max(1,Math.floor(o.maxSlides??4)),p=t,f=r,m=t*i,g=r*i,y={velocityX:p,velocityY:f,isOnFloor:!1,isOnWall:!1,isOnCeiling:!1,floorNormalX:0,floorNormalY:0,collider:null};for(let v=0;v<h&&!(Math.hypot(m,g)<1e-6);v++){let w=this.moveAndCollide(e,m,g,o);if(!w.collided)break;let k=w.normalX,T=w.normalY,N=k*c+T*u;N>=d?(y.isOnFloor=!0,y.floorNormalX=k,y.floorNormalY=T):N<=-d?y.isOnCeiling=!0:y.isOnWall=!0,y.collider=w.collider,m-=w.movedX,g-=w.movedY;let A=m*k+g*T;A<0&&(m-=k*A,g-=T*A);let F=p*k+f*T;F<0&&(p-=k*F,f-=T*F)}y.velocityX=p,y.velocityY=f;let b=e?this.bodies.get(e):null;return b&&(b.vx=p,b.vy=f),y}bodyStepLimit(e){let t=1/0;for(let r of e.colliders){if(r.sensor||r.shape.kind==="empty")continue;let i=r.shape.kind==="circle"?r.shape.radius*2:Math.min(r.bounds.maxX-r.bounds.minX,r.bounds.maxY-r.bounds.minY);t=Math.min(t,i)}return Number.isFinite(t)?Math.max(1,t/2):1/0}depenetrate(e,t){let r=null;for(let i=0;i<4;i++){for(let s of e.colliders)this.refreshColliderWorldShape(s);let o=null;for(let s of e.colliders)if(!(s.sensor||s.shape.kind==="empty")){for(let a of this.orderedColliders(t))if(!(a.body===e||a.shape.kind==="empty"))for(let l of Rh(s.shape,a.shape))for(let c of l.manifold.contacts)c.penetration<=Dh||(!o||c.penetration>o.depth)&&(o={normalX:-l.manifold.normalX,normalY:-l.manifold.normalY,depth:c.penetration,collider:a.source.node})}if(!o)break;e.x+=o.normalX*o.depth,e.y+=o.normalY*o.depth,(!r||o.depth>r.depth)&&(r=o)}return r}writeBodyToNode(e){let t=e.node,r=t.parentNode;if(!r){t.position.set(e.x,e.y,t.position.z),t.rotation.z=e.rotation;return}let i=it(r),o=e.x-i.x,s=e.y-i.y,a=Math.cos(-i.rotation),l=Math.sin(-i.rotation),c=i.scaleX||1,u=i.scaleY||1;t.position.set((o*a-s*l)/c,(o*l+s*a)/u,t.position.z),t.rotation.z=e.rotation-i.rotation}buildDebugBuffers(){this.refreshShapes();let e=[],t=[];for(let r of this.orderedColliders({includeSensors:!0})){let i=r.shape.kind==="circle"?[bS(r.shape)]:r.shape.worldParts,o=r.sensor?[.5,.95,.4]:r.body.sleeping?[.45,.5,.55]:[.12,.74,.89];for(let s of i)for(let a=0,l=s.length-1;a<s.length;l=a++)e.push(s[l].x,s[l].y,0,s[a].x,s[a].y,0),t.push(o[0],o[1],o[2],1,o[0],o[1],o[2],1)}return{vertices:new Float32Array(e),colors:new Float32Array(t)}}clear(){this.bodies.clear(),this.colliders.clear(),this.contacts.clear(),this.touching.clear(),this.joints.clear(),this.jointedPairs.clear(),this.signalQueue.length=0,this.staticBody.colliders=[]}rebindColliders(){this.staticBody.colliders=[];for(let e of this.bodies.values())e.colliders=[];for(let e of this.colliders.values()){let t=this.findOwningBody(e.source.node)??this.staticBody;e.body=t,t.colliders.push(e)}for(let e of this.bodies.values())e.colliders.sort((t,r)=>t.order-r.order),this.recomputeMass(e);this.staticBody.colliders.sort((e,t)=>e.order-t.order)}findOwningBody(e){let t=e;for(;t;){let r=this.bodies.get(t);if(r)return r;t=t.parentNode??null}return null}syncFromNodes(){for(let e of this.bodies.values()){let t=e.source;if(t){let r=t.getBodyConfig(),i=t.getBodyType();i!==e.bodyType&&(e.bodyType=i,this.recomputeMass(e),e.sleeping=!1),e.gravityScale=r.gravityScale,e.linearDamping=r.linearDamping,e.angularDamping=r.angularDamping,e.bullet=r.bullet,e.canSleep=r.canSleep,e.emitContacts=r.emitContacts,r.fixedRotation!==e.fixedRotation&&(e.fixedRotation=r.fixedRotation,this.recomputeMass(e),r.fixedRotation&&(e.w=0))}if(e.bodyType!=="dynamic"||e.transformDirty){let r=it(e.node);e.bodyType==="kinematic"&&!e.transformDirty&&(e.vx=0,e.vy=0),e.x=r.x,e.y=r.y,e.rotation=r.rotation,e.transformDirty=!1}}}refreshShapes(){for(let e of this.colliders.values()){let t=e.source;if(!t.node)continue;let i=t.getColliderRevision();if(i!==e.revision){e.revision=i;let o=t.getColliderMaterial();e.friction=o.friction,e.restitution=o.restitution,e.density=o.density,e.sensor=t.isSensor(),e.group=t.getColliderGroup(),e.shape=this.bakeShape(e),this.recomputeMass(e.body)}this.refreshColliderWorldShape(e)}}refreshColliderWorldShape(e){let t=e.body,r=this.colliderLocalTransform(e),i=Math.cos(t.rotation),o=Math.sin(t.rotation),s=r.x*i-r.y*o,a=r.x*o+r.y*i,l={x:t.x+s,y:t.y+a,rotation:t.rotation+r.rotation,scaleX:1,scaleY:1};if(e.shape.kind==="circle"){let p=Rr([{x:e.shape.cx,y:e.shape.cy}],l);e.shape.worldCx=p[0].x,e.shape.worldCy=p[0].y,e.bounds={minX:e.shape.worldCx-e.shape.radius,minY:e.shape.worldCy-e.shape.radius,maxX:e.shape.worldCx+e.shape.radius,maxY:e.shape.worldCy+e.shape.radius};return}e.shape.worldParts=e.shape.parts.map(p=>Rr(p,l));let c=1/0,u=1/0,d=-1/0,h=-1/0;for(let p of e.shape.worldParts){let f=bh(p);c=Math.min(c,f.minX),u=Math.min(u,f.minY),d=Math.max(d,f.maxX),h=Math.max(h,f.maxY)}e.bounds={minX:c,minY:u,maxX:d,maxY:h},e.shape.worldCx=(c+d)/2,e.shape.worldCy=(u+h)/2}colliderLocalTransform(e){let t=e.source.node,r=e.body;if(!t||t===r.node)return{x:0,y:0,rotation:0,scaleX:1,scaleY:1};let i=it(t),o=i.x-r.x,s=i.y-r.y,a=Math.cos(-r.rotation),l=Math.sin(-r.rotation);return{x:o*a-s*l,y:o*l+s*a,rotation:i.rotation-r.rotation,scaleX:1,scaleY:1}}bakeShape(e){let t=e.source,r=t.node,i=t.getColliderSize(),o=t.getColliderOffset(),s=r?it(r):{scaleX:1,scaleY:1},a=Math.abs(s.scaleX)||1,l=Math.abs(s.scaleY)||1;switch(t.getColliderShape()){case"circle":return pS(o.x*a,o.y*l,Math.abs(i.radius)*Math.max(a,l));case"capsule":{let c=_a(Sh(Math.abs(i.height)*l,Math.abs(i.radius)*Math.max(a,l),xC,{x:o.x*a,y:o.y*l}));return c.length>0?Ha(c):qa()}case"polygon":{let u=t.getColliderPolygon().map(h=>({x:(h.x+o.x)*a,y:(h.y+o.y)*l})),d=_a(u);return d.length>0?Ha(d):qa()}default:{let c=Math.abs(i.width)/2*a,u=Math.abs(i.height)/2*l;return c<=0||u<=0?qa():Ha([Ai(c,u,{x:o.x*a,y:o.y*l})])}}}recomputeMass(e){if(e.bodyType!=="dynamic"){e.mass=0,e.invMass=0,e.inertia=0,e.invInertia=0;return}let t=0,r=0;for(let o of e.colliders)o.sensor||(t+=o.shape.area*o.density,r+=o.shape.inertiaPerDensity*o.density);let i=e.source?.getBodyConfig().mass??0;if(i>0){let o=t>0?i/t:0;r=o>0?r*o:i,t=i}t<=0&&(t=1,r=1),e.mass=t,e.invMass=1/t,e.inertia=e.fixedRotation?0:r,e.invInertia=e.fixedRotation||r<=0?0:1/r}integrateVelocities(e){for(let t of this.orderedBodies()){if(t.bodyType!=="dynamic"||t.sleeping){t.forceX=0,t.forceY=0,t.torque=0;continue}t.vx+=(this.gravityX*t.gravityScale+t.forceX*t.invMass)*e,t.vy+=(this.gravityY*t.gravityScale+t.forceY*t.invMass)*e,t.fixedRotation||(t.w+=t.torque*t.invInertia*e),t.vx*=1/(1+e*t.linearDamping),t.vy*=1/(1+e*t.linearDamping),t.w*=1/(1+e*t.angularDamping),t.forceX=0,t.forceY=0,t.torque=0}}broadphase(){let e=new Map,t=[...this.colliders.values()].sort((o,s)=>o.order-s.order);for(let o of t){if(!o.source.enabled||!o.source.node||o.shape.kind==="empty")continue;let s=Math.floor(o.bounds.minX/Ga),a=Math.floor(o.bounds.maxX/Ga),l=Math.floor(o.bounds.minY/Ga),c=Math.floor(o.bounds.maxY/Ga);for(let u=s;u<=a;u++)for(let d=l;d<=c;d++){let h=`${u},${d}`,p=e.get(h);p?p.push(o):e.set(h,[o])}}let r=new Set,i=[];for(let o of e.values())for(let s=0;s<o.length;s++)for(let a=s+1;a<o.length;a++){let l=o[s],c=o[a];if(!this.shouldCollide(l,c)||!TC(l.bounds,c.bounds))continue;let u=fS(l,c);r.has(u)||(r.add(u),i.push(l.order<c.order?[l,c]:[c,l]))}return i.sort((o,s)=>o[0].order-s[0].order||o[1].order-s[1].order),i}shouldCollide(e,t){return!(e.body===t.body||this.jointedPairs.has(Ih(e.body,t.body))||e.body.bodyType!=="dynamic"&&t.body.bodyType!=="dynamic")}narrowphase(e){let t=new Map,r=new Map;for(let[i,o]of e){let s=Rh(i.shape,o.shape),a=fS(i,o);if(!(s.length===0||(t.set(a,[i,o]),i.sensor||o.sensor))){for(let c of s){let u=c.manifold,d=a+":"+c.partA+":"+c.partB,h=this.contacts.get(d),p={a:i,b:o,partA:c.partA,partB:c.partB,normalX:u.normalX,normalY:u.normalY,friction:Math.sqrt(Math.max(0,i.friction)*Math.max(0,o.friction)),restitution:Math.max(i.restitution,o.restitution),points:u.contacts.map(f=>{let m=h?.points.find(g=>g.featureId===f.featureId);return{featureId:f.featureId,normalImpulse:m?.normalImpulse??0,tangentImpulse:m?.tangentImpulse??0,rax:0,ray:0,rbx:0,rby:0,normalMass:0,tangentMass:0,bias:0,penetration:f.penetration,x:f.x,y:f.y}}),approachSpeed:[],prepAx:0,prepAy:0,prepBx:0,prepBy:0};this.prepareContact(p),r.set(d,p)}this.touching.has(a)||(this.wakeBody(i.body),this.wakeBody(o.body)),this.wakeIfTouchedByAwake(i.body,o.body)}}this.emitTransitions(t),this.contacts.clear();for(let[i,o]of r)this.contacts.set(i,o);this.touching=t}emitTransitions(e){for(let[t,r]of e)this.touching.has(t)||this.queueContactSignal(r[0],r[1],!0);for(let[t,r]of this.touching)e.has(t)||this.queueContactSignal(r[0],r[1],!1)}queueContactSignal(e,t,r){let i=e.source.node,o=t.source.node;if(!i||!o)return;let s=e.sensor||t.sensor,a=s?r?"body-entered":"body-exited":r?"contact-started":"contact-ended",l=(c,u,d)=>{!s&&!c.body.emitContacts||s&&!c.sensor||this.signalQueue.push({node:u,name:a,args:[d]})};l(e,i,o),l(t,o,i)}prepareContact(e){let t=e.a.body,r=e.b.body,i=e.normalX,o=e.normalY,s=-o,a=i;e.approachSpeed=[],e.prepAx=t.x,e.prepAy=t.y,e.prepBx=r.x,e.prepBy=r.y;for(let l of e.points){l.rax=l.x-t.x,l.ray=l.y-t.y,l.rbx=l.x-r.x,l.rby=l.y-r.y;let c=l.rax*o-l.ray*i,u=l.rbx*o-l.rby*i,d=t.invMass+r.invMass+t.invInertia*c*c+r.invInertia*u*u;l.normalMass=d>0?1/d:0;let h=l.rax*a-l.ray*s,p=l.rbx*a-l.rby*s,f=t.invMass+r.invMass+t.invInertia*h*h+r.invInertia*p*p;l.tangentMass=f>0?1/f:0;let m=Ya(t,r,l,i,o);e.approachSpeed.push(m<-bC?m:0),l.bias=0}}warmStart(){for(let e of this.orderedContacts()){if(Eh(e))continue;let t=e.a.body,r=e.b.body,i=-e.normalY,o=e.normalX;for(let s of e.points){let a=e.normalX*s.normalImpulse+i*s.tangentImpulse,l=e.normalY*s.normalImpulse+o*s.tangentImpulse;we(t,-a,-l,s.rax,s.ray),we(r,a,l,s.rbx,s.rby)}}}solveVelocities(e){for(let t of this.orderedContacts()){if(Eh(t))continue;let r=t.a.body,i=t.b.body,o=t.normalX,a=-t.normalY,l=o;for(let c of t.points){let d=-SS(r,i,c,a,l)*c.tangentMass,h=t.friction*c.normalImpulse,p=yS(c.tangentImpulse+d,-h,h);d=p-c.tangentImpulse,c.tangentImpulse=p,we(r,-a*d,-l*d,c.rax,c.ray),we(i,a*d,l*d,c.rbx,c.rby)}if(!(t.points.length===2&&this.solveNormalBlock(t,e)))for(let c=0;c<t.points.length;c++)this.solveNormalPoint(t,t.points[c],Nh(t,c,e))}}solveNormalPoint(e,t,r){let i=e.a.body,o=e.b.body,s=e.normalX,a=e.normalY,c=-(Ya(i,o,t,s,a)-r)*t.normalMass,u=Math.max(0,t.normalImpulse+c);c=u-t.normalImpulse,t.normalImpulse=u,we(i,-s*c,-a*c,t.rax,t.ray),we(o,s*c,a*c,t.rbx,t.rby)}solveNormalBlock(e,t){let r=e.a.body,i=e.b.body,[o,s]=e.points,a=e.normalX,l=e.normalY,c=o.rax*l-o.ray*a,u=o.rbx*l-o.rby*a,d=s.rax*l-s.ray*a,h=s.rbx*l-s.rby*a,p=r.invMass+i.invMass,f=p+r.invInertia*c*c+i.invInertia*u*u,m=p+r.invInertia*d*d+i.invInertia*h*h,g=p+r.invInertia*c*d+i.invInertia*u*h,y=f*m-g*g;if(!(f*f<1e3*y)||y===0)return!1;let b=o.normalImpulse,v=s.normalImpulse,w=Ya(r,i,o,a,l)-Nh(e,0,t),k=Ya(r,i,s,a,l)-Nh(e,1,t);w-=f*b+g*v,k-=g*b+m*v;let T=[[(-m*w+g*k)/y,(g*w-f*k)/y],[-w/f,0],[0,-k/m],[0,0]];for(let N=0;N<T.length;N++){let[A,F]=T[N];if(A<0||F<0||N===1&&g*A+k<0||N===2&&g*F+w<0||N===3&&(w<0||k<0))continue;let Z=A-b,ne=F-v;return we(r,-a*Z,-l*Z,o.rax,o.ray),we(i,a*Z,l*Z,o.rbx,o.rby),we(r,-a*ne,-l*ne,s.rax,s.ray),we(i,a*ne,l*ne,s.rbx,s.rby),o.normalImpulse=A,s.normalImpulse=F,!0}return!1}orderedJoints(){return[...this.joints.values()].sort((e,t)=>e.order-t.order)}prepareJoints(){for(let e of this.orderedJoints()){let t=e.bodyA,r=e.bodyB,i=Math.cos(t.rotation),o=Math.sin(t.rotation),s=Math.cos(r.rotation),a=Math.sin(r.rotation);e.rax=e.localAX*i-e.localAY*o,e.ray=e.localAX*o+e.localAY*i,e.rbx=e.localBX*s-e.localBY*a,e.rby=e.localBX*a+e.localBY*s;let l=t.invMass,c=r.invMass,u=t.invInertia,d=r.invInertia,h=l+c+u*e.ray*e.ray+d*e.rby*e.rby,p=-u*e.rax*e.ray-d*e.rbx*e.rby,f=l+c+u*e.rax*e.rax+d*e.rbx*e.rbx,m=h*f-p*p;Math.abs(m)>1e-12?(e.massXX=f/m,e.massXY=-p/m,e.massYY=h/m):(e.massXX=0,e.massXY=0,e.massYY=0);let g=u+d;e.angularMass=g>0?1/g:0;let y=e.source.getJointConfig();this.syncJointedPair(e,y.collideConnected),y.motorEnabled&&y.motorSpeed!==0&&(this.wakeBody(t),this.wakeBody(r))}}syncJointedPair(e,t){let r=Ih(e.bodyA,e.bodyB);t?this.jointedPairs.delete(r):this.jointedPairs.add(r)}warmStartJoints(){for(let e of this.orderedJoints()){let t=e.bodyA,r=e.bodyB,i=e.motorImpulse+e.lowerImpulse-e.upperImpulse;we(t,-e.impulseX,-e.impulseY,e.rax,e.ray),we(r,e.impulseX,e.impulseY,e.rbx,e.rby),Jt(t,-i),Jt(r,i)}}solveJointVelocities(e){for(let t of this.orderedJoints()){let r=t.bodyA,i=t.bodyB;if(!t.source.enabled)continue;let o=t.source.getJointConfig();if(o.motorEnabled&&t.angularMass>0){let f=i.w-r.w-o.motorSpeed,m=-t.angularMass*f,g=o.maxMotorTorque*e,y=yS(t.motorImpulse+m,-g,g);m=y-t.motorImpulse,t.motorImpulse=y,Jt(r,-m),Jt(i,m)}else t.motorImpulse=0;if(o.limitEnabled&&t.angularMass>0){let f=i.rotation-r.rotation-t.referenceAngle;{let m=f-o.lowerAngle,g=-t.angularMass*(i.w-r.w+Math.max(m,0)/e),y=Math.max(t.lowerImpulse+g,0);g=y-t.lowerImpulse,t.lowerImpulse=y,Jt(r,-g),Jt(i,g)}{let m=o.upperAngle-f,g=-t.angularMass*(r.w-i.w+Math.max(m,0)/e),y=Math.max(t.upperImpulse+g,0);g=y-t.upperImpulse,t.upperImpulse=y,Jt(r,g),Jt(i,-g)}}else t.lowerImpulse=0,t.upperImpulse=0;let s=r.vx-r.w*t.ray,a=r.vy+r.w*t.rax,l=i.vx-i.w*t.rby,c=i.vy+i.w*t.rbx,u=l-s,d=c-a,h=-(t.massXX*u+t.massXY*d),p=-(t.massXY*u+t.massYY*d);t.impulseX+=h,t.impulseY+=p,we(r,-h,-p,t.rax,t.ray),we(i,h,p,t.rbx,t.rby)}}solveJointPositions(){for(let e of this.orderedJoints()){let t=e.bodyA,r=e.bodyB,i=t.invMass+r.invMass;if(i<=0)continue;let o=Math.cos(t.rotation),s=Math.sin(t.rotation),a=Math.cos(r.rotation),l=Math.sin(r.rotation),c=t.x+e.localAX*o-e.localAY*s,u=t.y+e.localAX*s+e.localAY*o,d=r.x+e.localBX*a-e.localBY*l,h=r.y+e.localBX*l+e.localBY*a,p=d-c,f=h-u,m=Math.hypot(p,f);if(m<Dh)continue;let g=Math.min(m,hS)*yC,y=p/m,b=f/m;t.x+=y*g*t.invMass/i,t.y+=b*g*t.invMass/i,r.x-=y*g*r.invMass/i,r.y-=b*g*r.invMass/i}}integratePositions(e){for(let t of this.orderedBodies())t.bodyType!=="dynamic"||t.sleeping||(t.x+=t.vx*e,t.y+=t.vy*e,t.fixedRotation||(t.rotation+=t.w*e))}applyContinuousCollision(e){for(let t of this.orderedBodies()){if(t.bodyType!=="dynamic"||!t.bullet||t.sleeping)continue;let r=t.vx*e,i=t.vy*e,o=Math.hypot(r,i),s=t.colliders.find(u=>!u.sensor&&u.shape.kind==="circle");if(!s||o<s.shape.radius)continue;let a=t.x-r,l=t.y-i,c=null;for(let u of this.colliders.values())if(!(u.body===t||u.sensor||u.body.bodyType==="dynamic"))for(let d of u.shape.worldParts){let h=jn(a,l,r,i,s.shape.radius,d);h!==null&&(c===null||h<c)&&(c=h)}c!==null&&c<1&&(t.x=a+r*c,t.y=l+i*c)}}solvePositions(){for(let e of this.orderedContacts()){if(Eh(e))continue;let t=e.a.body,r=e.b.body,i=t.invMass+r.invMass;if(i<=0)continue;let o=r.x-e.prepBx-(t.x-e.prepAx),s=r.y-e.prepBy-(t.y-e.prepAy),a=o*e.normalX+s*e.normalY;for(let l of e.points){let c=l.penetration-a,u=Math.min(Math.max(c-Dh,0)*gC/i,hS/i);u<=0||(t.x-=e.normalX*u*t.invMass,t.y-=e.normalY*u*t.invMass,r.x+=e.normalX*u*r.invMass,r.y+=e.normalY*u*r.invMass)}}}updateSleep(e){let t=this.orderedBodies().filter(s=>s.bodyType==="dynamic");if(t.length===0)return;let r=new Map;for(let s of t)r.set(s,s);let i=s=>{let a=s;for(;r.get(a)!==a;)a=r.get(a);let l=s;for(;r.get(l)!==a;){let c=r.get(l);r.set(l,a),l=c}return a};for(let s of this.contacts.values()){let a=s.a.body,l=s.b.body;if(a.bodyType!=="dynamic"||l.bodyType!=="dynamic")continue;let c=i(a),u=i(l);c!==u&&r.set(c,u)}let o=new Map;for(let s of t){let a=i(s),l=o.get(a);l?l.push(s):o.set(a,[s])}for(let s of o.values()){if(!(s.every(u=>u.canSleep)&&s.every(u=>Math.hypot(u.vx,u.vy)<SC&&Math.abs(u.w)<vC))){for(let u of s)u.sleepTimer=0,u.sleeping=!1;continue}let c=1/0;for(let u of s)u.sleepTimer+=e,c=Math.min(c,u.sleepTimer);if(!(c<wC))for(let u of s)u.sleeping=!0,u.vx=0,u.vy=0,u.w=0}}wakeIfTouchedByAwake(e,t){let r=e.bodyType==="dynamic"&&!e.sleeping,i=t.bodyType==="dynamic"&&!t.sleeping;r&&t.sleeping&&this.wakeBody(t),i&&e.sleeping&&this.wakeBody(e)}wakeBody(e){e.bodyType==="dynamic"&&(e.sleeping=!1,e.sleepTimer=0)}writeBackToNodes(){for(let e of this.orderedBodies())e.bodyType!=="dynamic"||e.sleeping||this.writeBodyToNode(e)}flushSignals(){if(this.signalQueue.length===0)return;let e=this.signalQueue.splice(0,this.signalQueue.length);for(let t of e)t.node.emit(t.name,...t.args)}orderedBodies(){return[...this.bodies.values()].sort((e,t)=>e.order-t.order)}orderedContacts(){return[...this.contacts.values()].sort((e,t)=>e.a.order-t.a.order||e.b.order-t.b.order||e.partA-t.partA||e.partB-t.partB)}orderedColliders(e){return[...this.colliders.values()].filter(t=>!t.source.enabled||!t.source.node||t.shape.kind==="empty"||!e.includeSensors&&t.sensor?!1:e.group===void 0||t.group===e.group).sort((t,r)=>t.order-r.order)}};function PC(){return{node:null,source:null,bodyType:"static",x:0,y:0,rotation:0,vx:0,vy:0,w:0,forceX:0,forceY:0,torque:0,mass:0,invMass:0,inertia:0,invInertia:0,prevX:0,prevY:0,prevRotation:0,gravityScale:0,linearDamping:0,angularDamping:0,fixedRotation:!0,bullet:!1,canSleep:!1,emitContacts:!1,sleepTimer:0,sleeping:!1,colliders:[],order:-1,transformDirty:!1}}function qa(){return{kind:"empty",cx:0,cy:0,radius:0,parts:[],worldParts:[],worldCx:0,worldCy:0,area:0,inertiaPerDensity:0,centroidX:0,centroidY:0}}function pS(n,e,t){let r=Math.PI*t*t;return{kind:"circle",cx:n,cy:e,radius:t,parts:[],worldParts:[],worldCx:n,worldCy:e,area:r,inertiaPerDensity:r*(.5*t*t+n*n+e*e),centroidX:n,centroidY:e}}function Ha(n){let e=0,t=0,r=0,i=0;for(let o of n){let s=gh(o),a=Gn(o);e+=s,r+=a.x*s,i+=a.y*s,t+=kC(o)}return{kind:"polygon",cx:0,cy:0,radius:0,parts:n,worldParts:n.map(o=>o.map(s=>({x:s.x,y:s.y}))),worldCx:0,worldCy:0,area:e,inertiaPerDensity:t,centroidX:e>0?r/e:0,centroidY:e>0?i/e:0}}function kC(n){let e=0,t=0,r=n.length;for(let i=0,o=r-1;i<r;o=i++){let s=n[o],a=n[i],l=Math.abs(s.x*a.y-a.x*s.y);e+=l*(s.x*s.x+s.x*a.x+a.x*a.x+s.y*s.y+s.y*a.y+a.y*a.y),t+=l}return t>0?e/12:0}function Rh(n,e){let t=[];if(n.kind==="circle"&&e.kind==="circle"){let r=Ch(n.worldCx,n.worldCy,n.radius,e.worldCx,e.worldCy,e.radius);return r&&t.push({manifold:r,partA:0,partB:0}),t}return n.kind==="circle"?(e.worldParts.forEach((r,i)=>{let o=Wa(n.worldCx,n.worldCy,n.radius,r);o&&!ja(o,e,i)&&t.push({manifold:o,partA:0,partB:i})}),t):e.kind==="circle"?(n.worldParts.forEach((r,i)=>{let o=Wa(e.worldCx,e.worldCy,e.radius,r);o&&!ja(o,n,i)&&t.push({manifold:{...o,normalX:-o.normalX,normalY:-o.normalY},partA:i,partB:0})}),t):(n.worldParts.forEach((r,i)=>{e.worldParts.forEach((o,s)=>{let a=Mh(r,o);a&&!ja(a,n,i)&&!ja(a,e,s)&&t.push({manifold:a,partA:i,partB:s})})}),t)}function ja(n,e,t){return e.worldParts.length<2?!1:n.contacts.every(r=>{for(let i=0;i<e.worldParts.length;i++)if(i!==t&&kt(r.x,r.y,e.worldParts[i]))return!0;return!1})}function mS(n,e){return Rh(n,e).length>0}function AC(n,e,t,r,i){if(n.kind==="circle")return jn(e,t,r,i,0,bS(n));let o=null;for(let s of n.worldParts){let a=jn(e,t,r,i,0,s);a!==null&&(o===null||a<o)&&(o=a)}return o}function bS(n){let t=new Array(16);for(let r=0;r<16;r++){let i=r/16*Math.PI*2;t[r]={x:n.worldCx+Math.cos(i)*n.radius,y:n.worldCy+Math.sin(i)*n.radius}}return t}function Nh(n,e,t){let r=-n.points[e].penetration;return r>0?-r/t:-n.restitution*n.approachSpeed[e]}function Eh(n){let e=n.a.body,t=n.b.body,r=e.bodyType!=="dynamic"||e.sleeping,i=t.bodyType!=="dynamic"||t.sleeping;return r&&i}function TC(n,e){return n.minX<=e.maxX&&n.maxX>=e.minX&&n.minY<=e.maxY&&n.maxY>=e.minY}function Ih(n,e){return n.order<e.order?`${n.order}/${e.order}`:`${e.order}/${n.order}`}function fS(n,e){return n.order<e.order?`${n.order}:${e.order}`:`${e.order}:${n.order}`}function SS(n,e,t,r,i){let o=n.vx-n.w*t.ray,s=n.vy+n.w*t.rax,a=e.vx-e.w*t.rby,l=e.vy+e.w*t.rbx;return(a-o)*r+(l-s)*i}function Ya(n,e,t,r,i){return SS(n,e,t,r,i)}function we(n,e,t,r,i){n.sleeping||n.invMass<=0&&n.invInertia<=0||(n.vx+=e*n.invMass,n.vy+=t*n.invMass,n.w+=(r*t-i*e)*n.invInertia)}function gS(n,e,t){let r=e-n.x,i=t-n.y,o=Math.cos(-n.rotation),s=Math.sin(-n.rotation);return{x:r*o-i*s,y:r*s+i*o}}function Jt(n,e){n.sleeping||n.invInertia<=0||(n.w+=e*n.invInertia)}function CC(n,e){let t=(e-n)%(Math.PI*2);return t>Math.PI?t-=Math.PI*2:t<-Math.PI&&(t+=Math.PI*2),t}function yS(n,e,t){return n<e?e:n>t?t:n}function MC(n){return{node:n.node,get bodyType(){return n.bodyType},get velocityX(){return n.vx},get velocityY(){return n.vy},get angularVelocity(){return n.w},get isSleeping(){return n.sleeping},setVelocity(e,t){n.vx=e,n.vy=t,n.sleeping=!1,n.sleepTimer=0},setAngularVelocity(e){n.w=e,n.sleeping=!1,n.sleepTimer=0},applyImpulse(e,t){n.vx+=e*n.invMass,n.vy+=t*n.invMass,n.sleeping=!1,n.sleepTimer=0},applyForce(e,t){n.forceX+=e,n.forceY+=t,n.sleeping=!1,n.sleepTimer=0},teleport(e,t,r){n.x=e,n.y=t,typeof r=="number"&&(n.rotation=r),n.vx=0,n.vy=0,n.w=0,n.prevX=n.x,n.prevY=n.y,n.prevRotation=n.rotation,n.sleeping=!1,n.sleepTimer=0},wake(){n.sleeping=!1,n.sleepTimer=0}}}var q={None:0,ProtocolVersionMismatch:1,InvalidToken:2,TokenExpired:3,TokenRoomMismatch:4,RoomNotFound:5,RoomFull:6,RoomClosing:7,RateLimited:8,PayloadTooLarge:9,QuotaExceeded:10,ServerShuttingDown:11,IdleTimeout:12,BadRequest:13,SessionReplaced:14,EntityLimitReached:15,NotEntityOwner:16,InternalError:17,KindNotAllowed:18,SendQueueOverflow:19};var $n={Server:0,AllPeers:1,SinglePeer:2,AoiPeers:3};var wS={Relay:0,Authoritative:1};var j={None:0,X:1,Y:2,Rot:4,Vx:8,Vy:16,Flags:32,ColdDirty:64,Teleport:128,TwoByteFieldBits:27,OneByteFieldBits:36,PayloadBits:63,SignalBits:192,MaxPayloadSize:10};function Bh(n){return(vS(n&j.TwoByteFieldBits)<<1)+vS(n&j.OneByteFieldBits)}function vS(n){let e=n&255,t=0;for(;e!==0;)e&=e-1,t+=1;return t}var DC=j.PayloadBits|j.Teleport,MF=~DC&255;var NC={None:0,Final:1,ReservedBits:254};function Vh(n){return(n&NC.Final)!==0}var NF=65535;function xS(n){let e=n.trim().replace(/\\/g,"/");return(e.startsWith("res://")?e.slice(6):e).replace(/^\.\//,"").replace(/^\/+/,"")}var Kn=class{entries=[];byKey=new Map;authoredCount=0;constructor(e){e&&this.replaceAll(e)}get size(){return this.entries.length}get prefabCount(){return this.entries.length-this.authoredCount}get isEmpty(){return this.entries.length===0}replaceAll(e){let t=Array.isArray(e),r=t?e:e.prefabs,i=t?[]:e.authored??[];this.entries.length=0,this.byKey.clear(),this.authoredCount=0;for(let o of r)this.append(o);for(let o of i){if(this.entries.length>65535)break;this.entries.push(o),this.authoredCount+=1}}register(e){let t=this.kindOf(e);if(t!==null)return t;if(this.authoredCount>0)throw new RangeError("Cannot register a prefab into a net kind table that already carries an authored-binding segment: appending would shift every authored index.");return this.append(e)}kindOf(e){return this.byKey.get(xS(e))??null}prefabPathOf(e){return!Number.isInteger(e)||e<0||e>=this.prefabCount?null:this.entries[e]}toArray(){return[...this.entries]}clear(){this.entries.length=0,this.byKey.clear(),this.authoredCount=0}append(e){let t=xS(e),r=this.byKey.get(t);if(r!==void 0)return r;if(this.entries.length>65535)throw new RangeError("A net kind table holds at most 65536 entries.");let i=this.entries.length;return this.entries.push(e.trim()),this.byKey.set(t,i),i}},$a=new Kn;function Oh(){return $a}function EC(n){$a.replaceAll(n)}function IC(n){return $a.register(n)}function RC(){$a=new Kn}var BC={initialDelayMs:500,maxDelayMs:15e3,factor:2,jitterRatio:.25,maxAttempts:8},Lh=4007,Ka=1e3;function VC(n){if(typeof WebSocket>"u")throw new Error("WsTransport: no global WebSocket in this environment. Pass options.socketFactory.");return new WebSocket(n)}var Xn=class{url;socketFactory;now;random;backoff;shouldReconnect;socket=null;currentState="idle";retryTimer=null;attempt=0;disposed=!1;closingLocally=!1;lastClose=null;lastFrameAtMs=0;counters={framesSent:0,framesReceived:0,bytesSent:0,bytesReceived:0,framesDropped:0,textFramesReceived:0,unusableFramesReceived:0,reconnectAttempts:0,opens:0};onFrame=null;onStateChange=null;constructor(e){this.url=e.url,this.socketFactory=e.socketFactory??VC,this.now=e.now??Date.now,this.random=e.random??Math.random,this.backoff={...BC,...e.backoff},this.shouldReconnect=e.shouldReconnect??(()=>!0)}get state(){return this.currentState}get isOpen(){return this.currentState==="open"}get closeInfo(){return this.currentState==="closed"?this.lastClose:null}get lastCloseInfo(){return this.lastClose}get stats(){return{...this.counters}}get attemptCount(){return this.attempt}get msSinceLastFrame(){return this.lastFrameAtMs===0?null:Math.max(0,this.now()-this.lastFrameAtMs)}connect(){this.disposed||this.currentState==="connecting"||this.currentState==="open"||this.retryTimer===null&&(this.attempt=0,this.openSocket("connecting"))}send(e){let t=this.socket;if(this.disposed||this.currentState!=="open"||!t)return this.counters.framesDropped+=1,!1;try{t.send(e)}catch{return this.counters.framesDropped+=1,!1}return this.counters.framesSent+=1,this.counters.bytesSent+=e.byteLength,!0}close(e=Ka,t=""){this.currentState==="closed"||this.disposed||(this.closingLocally=!0,this.cancelRetry(),this.closeSocket(e,t),this.finish({reason:"client",code:e,message:t,wasClean:!0}))}dispose(){this.disposed||(this.closingLocally=!0,this.cancelRetry(),this.closeSocket(Ka,"disposed"),this.disposed=!0,this.currentState!=="closed"&&this.finish({reason:"client",code:Ka,message:"disposed",wasClean:!0}),this.onFrame=null,this.onStateChange=null)}openSocket(e){this.closingLocally=!1,this.setState(e);let t;try{t=this.socketFactory(this.url)}catch(r){let i=r instanceof Error?r.message:String(r);this.finish({reason:"error",code:null,message:i,wasClean:!1});return}this.socket=t,t.binaryType="arraybuffer",t.onopen=()=>this.handleOpen(),t.onmessage=r=>this.handleMessage(r),t.onerror=()=>this.handleError(),t.onclose=r=>this.handleClose(r)}handleOpen(){this.disposed||(this.attempt=0,this.counters.opens+=1,this.setState("open"))}handleMessage(e){if(this.disposed)return;let t=e.data;if(typeof t=="string"){this.counters.textFramesReceived+=1,this.closingLocally=!0,this.cancelRetry(),this.closeSocket(Lh,"text frame"),this.finish({reason:"protocol-violation",code:Lh,message:"The server sent a text frame; this protocol is binary-only.",wasClean:!1});return}let r;if(t instanceof ArrayBuffer)r=new Uint8Array(t);else if(ArrayBuffer.isView(t))r=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);else{this.counters.unusableFramesReceived+=1;return}this.counters.framesReceived+=1,this.counters.bytesReceived+=r.byteLength,this.lastFrameAtMs=this.now(),this.onFrame?.(r)}handleError(){}handleClose(e){if(this.detachSocket(),!(this.disposed||this.currentState==="closed")){if(this.closingLocally){this.closingLocally=!1;return}this.handleUnexpectedClose({reason:"server",code:typeof e.code=="number"?e.code:null,message:typeof e.reason=="string"?e.reason:"",wasClean:!!e.wasClean})}}handleUnexpectedClose(e){if(this.lastClose=e,!this.shouldReconnect(e)){this.finish(e);return}if(this.attempt>=this.backoff.maxAttempts){this.finish({...e,reason:"attempts-exhausted"});return}let t=this.nextDelay(this.attempt);this.attempt+=1,this.counters.reconnectAttempts+=1,this.setState("reconnecting"),this.retryTimer=setTimeout(()=>{this.retryTimer=null,!(this.disposed||this.currentState==="closed")&&this.openSocket("reconnecting")},t)}nextDelay(e){let t=Math.min(this.backoff.maxDelayMs,this.backoff.initialDelayMs*Math.pow(this.backoff.factor,e)),r=t*this.backoff.jitterRatio*(this.random()*2-1);return Math.max(0,Math.round(t+r))}cancelRetry(){this.retryTimer!==null&&(clearTimeout(this.retryTimer),this.retryTimer=null)}closeSocket(e,t){let r=this.socket;if(r){this.detachSocket();try{r.close(e,t)}catch{}}}detachSocket(){let e=this.socket;e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.onclose=null,this.socket=null)}finish(e){this.lastClose=e,this.cancelRetry(),this.setState("closed",e)}setState(e,t=null){this.currentState===e&&e!=="closed"||(this.currentState=e,this.onStateChange?.(e,t))}};var P={HelloCommand:1,WelcomeEvent:2,RejectedEvent:3,PingCommand:4,PongEvent:5,PeerJoinedEvent:6,PeerLeftEvent:7,RoomInfoEvent:8,SendChatCommand:9,ChatMessageEvent:10,LeaveCommand:11,SetRoomVarCommand:12,RoomVarsChangedEvent:13,ResyncCommand:14,SetClientPrefsCommand:15,HostChangedEvent:16,RoomRosterEvent:17,SpawnEntityRequest:64,SpawnEntityResponse:65,DespawnEntityCommand:66,EntityUpdatePacket:67,SnapshotPacket:68,DeltaPacket:69,SetEntityPropsCommand:70,EntityPropsChangedEvent:71,EmitSignalCommand:128,SignalEvent:129,SignalBatchPacket:130};var RF=new Map(Object.entries(P).map(([n,e])=>[e,n]));function PS(n,e){let t=new Uint8Array(e.length+1);return t[0]=n,t.set(e,1),t}function kS(n){return n.length===0?-1:n[0]}function AS(n){return n.subarray(1)}var Xa=class{counts=new Map;total=0;get count(){return this.total}record(e){return this.counts.set(e,(this.counts.get(e)??0)+1),this.total+=1,this.total}countFor(e){return this.counts.get(e)??0}seenTypeIds(){return[...this.counts.keys()]}reset(){this.counts.clear(),this.total=0}};var Jn=20,Qn=3,LF=Qn+j.MaxPayloadSize,Uh=5,FF=Uh+j.MaxPayloadSize,Wh=2,Ti=2,Fh=10,OC=7,LC=8,CS=7,FC=CS+Ti*3,Qa=6,zh=5,_C=255,_h=8,zC=7;var MS=6,DS=1,UC=64;var NS=MS+DS;function Zn(){return{qx:0,qy:0,qrot:0,qvx:0,qvy:0,kind:0,ownerId:0,flags:0}}function eo(n){n.qx=0,n.qy=0,n.qrot=0,n.qvx=0,n.qvy=0,n.kind=0,n.ownerId=0,n.flags=0}function ES(n,e,t){(e&j.X)!==0&&(n.qx=t.qx),(e&j.Y)!==0&&(n.qy=t.qy),(e&j.Rot)!==0&&(n.qrot=t.qrot),(e&j.Vx)!==0&&(n.qvx=t.qvx),(e&j.Vy)!==0&&(n.qvy=t.qvy),(e&j.Flags)!==0&&(n.flags=t.flags)}function IS(){return{netId:0,state:Zn()}}function RS(n,e,t){return t.netId=0,eo(t.state),e<0||n.byteLength-e<Jn?!1:(t.netId=n.getUint32(e,!0),t.state.kind=n.getUint16(e+4,!0),t.state.ownerId=n.getUint32(e+6,!0),t.state.qx=n.getUint16(e+10,!0),t.state.qy=n.getUint16(e+12,!0),t.state.qrot=n.getUint8(e+14),t.state.qvx=n.getInt16(e+15,!0),t.state.qvy=n.getInt16(e+17,!0),t.state.flags=n.getUint8(e+19),!0)}function BS(){return{slot:0,mask:0,state:Zn(),bytesRead:0}}function WC(n){return Qn+Bh(n)}function GC(n,e,t){if(t.slot=0,t.mask=0,t.bytesRead=0,eo(t.state),e<0||n.byteLength-e<Qn)return!1;let r=n.getUint8(e+2),i=WC(r);return n.byteLength-e<i?!1:(t.slot=n.getUint16(e,!0),t.mask=r,HC(n,e+Qn,r,t.state),t.bytesRead=i,!0)}function Gh(n){return Uh+Bh(n)}function VS(n,e,t,r,i){let o=Gh(r);return n.byteLength-e<o?0:(n.setUint32(e,t,!0),n.setUint8(e+4,r),qC(n,e+Uh,r,i),o)}function qC(n,e,t,r){let i=e;(t&j.X)!==0&&(n.setUint16(i,r.qx,!0),i+=2),(t&j.Y)!==0&&(n.setUint16(i,r.qy,!0),i+=2),(t&j.Rot)!==0&&(n.setUint8(i,r.qrot),i+=1),(t&j.Vx)!==0&&(n.setInt16(i,r.qvx,!0),i+=2),(t&j.Vy)!==0&&(n.setInt16(i,r.qvy,!0),i+=2),(t&j.Flags)!==0&&n.setUint8(i,r.flags)}function HC(n,e,t,r){let i=e;(t&j.X)!==0&&(r.qx=n.getUint16(i,!0),i+=2),(t&j.Y)!==0&&(r.qy=n.getUint16(i,!0),i+=2),(t&j.Rot)!==0&&(r.qrot=n.getUint8(i),i+=1),(t&j.Vx)!==0&&(r.qvx=n.getInt16(i,!0),i+=2),(t&j.Vy)!==0&&(r.qvy=n.getInt16(i,!0),i+=2),(t&j.Flags)!==0&&(r.flags=n.getUint8(i))}function jC(n,e){return e<0||n.byteLength-e<Wh?-1:n.getUint16(e,!0)}function OS(){return{seq:0,serverTick:0,frameFlags:0,count:0,recordsOffset:0,recordsLength:0}}function LS(n,e){if(e.seq=0,e.serverTick=0,e.frameFlags=0,e.count=0,e.recordsOffset=0,e.recordsLength=0,n.byteLength<Fh||n.getUint8(0)!==P.SnapshotPacket)return!1;let t=n.getUint16(LC,!0),r=t*Jn;return n.byteLength-Fh<r?!1:(e.seq=n.getUint16(1,!0),e.serverTick=n.getUint32(3,!0),e.frameFlags=n.getUint8(OC),e.count=t,e.recordsOffset=Fh,e.recordsLength=r,!0)}function FS(n,e,t,r){return t<0||t>=e.count?(r.netId=0,eo(r.state),!1):RS(n,e.recordsOffset+t*Jn,r)}function _S(){return{seq:0,serverTick:0,removedCount:0,removedOffset:0,enterCount:0,enterOffset:0,updateCount:0,updatesOffset:0,updatesLength:0}}function zS(n,e){if(e.seq=0,e.serverTick=0,e.removedCount=0,e.removedOffset=0,e.enterCount=0,e.enterOffset=0,e.updateCount=0,e.updatesOffset=0,e.updatesLength=0,n.byteLength<FC||n.getUint8(0)!==P.DeltaPacket)return!1;let t=n.getUint16(1,!0),r=n.getUint32(3,!0),i=CS,o=n.getUint16(i,!0);i+=Ti;let s=o*Wh;if(n.byteLength-i<s)return!1;let a=i;if(i+=s,n.byteLength-i<Ti)return!1;let l=n.getUint16(i,!0);i+=Ti;let c=l*Jn;if(n.byteLength-i<c)return!1;let u=i;if(i+=c,n.byteLength-i<Ti)return!1;let d=n.getUint16(i,!0);i+=Ti;let h=n.byteLength-i;return h<d*Qn?!1:(e.seq=t,e.serverTick=r,e.removedCount=o,e.removedOffset=a,e.enterCount=l,e.enterOffset=u,e.updateCount=d,e.updatesOffset=i,e.updatesLength=h,!0)}function US(n,e,t){return t<0||t>=e.removedCount?-1:jC(n,e.removedOffset+t*Wh)}function WS(n,e,t,r){return t<0||t>=e.enterCount?(r.netId=0,eo(r.state),!1):RS(n,e.enterOffset+t*Jn,r)}function GS(n,e,t,r){return t<0||t>=e.updatesLength?(r.slot=0,r.mask=0,r.bytesRead=0,eo(r.state),!1):GC(n,e.updatesOffset+t,r)}function qS(n,e,t){return n.byteLength-e<Qa?0:(n.setUint8(e,P.EntityUpdatePacket),n.setUint32(e+1,t,!0),n.setUint8(e+zh,0),Qa)}function HS(n,e){return e<0||e>_C||n.byteLength<=zh?!1:(n.setUint8(zh,e),!0)}function jS(){return{seq:0,serverTick:0,count:0,entriesOffset:0,entriesLength:0}}var Ci=new Uint8Array(0);function YS(){return{senderClientId:0,name:Ci,payload:Ci,bytesRead:0}}function YC(n,e,t){if(t.senderClientId=0,t.name=Ci,t.payload=Ci,t.bytesRead=0,e<0||n.byteLength-e<NS)return!1;let r=n.getUint8(e+4);if(r<DS||r>UC)return!1;let i=e+5+r;if(n.byteLength<=i)return!1;let o=n.getUint8(i),s=MS+r+o;return n.byteLength-e<s?!1:(t.senderClientId=n.getUint32(e,!0),t.name=TS(n,e+5,r),t.payload=TS(n,i+1,o),t.bytesRead=s,!0)}function $S(n,e){if(e.seq=0,e.serverTick=0,e.count=0,e.entriesOffset=0,e.entriesLength=0,n.byteLength<_h||n.getUint8(0)!==P.SignalBatchPacket)return!1;let t=n.getUint8(zC),r=n.byteLength-_h;return r<t*NS?!1:(e.seq=n.getUint16(1,!0),e.serverTick=n.getUint32(3,!0),e.count=t,e.entriesOffset=_h,e.entriesLength=r,!0)}function KS(n,e,t,r){return t<0||t>=e.entriesLength?(r.senderClientId=0,r.name=Ci,r.payload=Ci,r.bytesRead=0,!1):YC(n,e.entriesOffset+t,r)}function TS(n,e,t){return new Uint8Array(n.buffer,n.byteOffset+e,t)}var X=class n{static MAX_MEMBER_COUNT=249;static NULL_OBJECT_MARKER=255;bytes;view;memberOffsets=[];cursor=0;static utf8=new TextDecoder("utf-8",{fatal:!1});static utf16=new TextDecoder("utf-16le",{fatal:!1});memberCount;constructor(e){if(this.bytes=e,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),e.length===0)throw new RangeError("A version-tolerant object needs at least its member-count byte.");let t=e[0];if(t===n.NULL_OBJECT_MARKER)throw new RangeError("Unexpected null object (memberCount 0xFF) on the control plane.");if(t>n.MAX_MEMBER_COUNT)throw new RangeError(`Illegal member count ${t}; the maximum is ${n.MAX_MEMBER_COUNT}.`);this.memberCount=t;let r=1,i=[];for(let o=0;o<t;o++){let[s,a]=$C(this.bytes,this.view,r);i.push(s),r=a}for(let o of i){if(o<0)throw new RangeError(`Negative member byte-length ${o}.`);this.memberOffsets.push(r),r+=o}if(this.memberOffsets.push(r),r>e.length)throw new RangeError(`Truncated object: members declare ${r} bytes but the payload is ${e.length}.`)}hasMember(e){return e>=0&&e<this.memberCount}memberLength(e){return this.requireMember(e),this.memberOffsets[e+1]-this.memberOffsets[e]}seekMember(e){this.requireMember(e),this.cursor=this.memberOffsets[e]}requireMember(e){if(!this.hasMember(e))throw new RangeError(`Member ${e} was not written; the object declares ${this.memberCount}.`)}require(e){let t=this.cursor;if(t+e>this.bytes.length)throw new RangeError(`Truncated value: ${e} bytes needed at offset ${t}.`);return this.cursor=t+e,t}readBool(){return this.bytes[this.require(1)]!==0}readUint8(){return this.bytes[this.require(1)]}readInt8(){return this.view.getInt8(this.require(1))}readUint16(){return this.view.getUint16(this.require(2),!0)}readInt16(){return this.view.getInt16(this.require(2),!0)}readUint32(){return this.view.getUint32(this.require(4),!0)}readInt32(){return this.view.getInt32(this.require(4),!0)}readFloat32(){return this.view.getFloat32(this.require(4),!0)}readInt64(){return this.view.getBigInt64(this.require(8),!0)}readInt64AsNumber(){let e=this.readInt64();if(e>BigInt(Number.MAX_SAFE_INTEGER)||e<BigInt(Number.MIN_SAFE_INTEGER))throw new RangeError(`i64 value ${e} does not fit a JavaScript number exactly.`);return Number(e)}readString(){let e=this.readInt32();if(e===-1)return null;if(e===0)return"";if(e<0){let r=~e;this.readInt32();let i=this.require(r);return n.utf8.decode(this.bytes.subarray(i,i+r))}let t=this.require(e*2);return n.utf16.decode(this.bytes.subarray(t,t+e*2))}readBytes(){let e=this.readInt32();if(e===-1)return null;if(e<0)throw new RangeError(`Illegal array element count ${e}.`);let t=this.require(e);return this.bytes.slice(t,t+e)}readUint32Array(){let e=this.readInt32();if(e===-1)return null;if(e<0)throw new RangeError(`Illegal array element count ${e}.`);let t=[];for(let r=0;r<e;r++)t.push(this.readUint32());return t}readStringArray(){let e=this.readInt32();if(e===-1)return null;if(e<0)throw new RangeError(`Illegal array element count ${e}.`);let t=[];for(let r=0;r<e;r++)t.push(this.readString());return t}readBytesArray(){let e=this.readInt32();if(e===-1)return null;if(e<0)throw new RangeError(`Illegal array element count ${e}.`);let t=[];for(let r=0;r<e;r++)t.push(this.readBytes());return t}};function $C(n,e,t){if(t>=n.length)throw new RangeError(`Truncated member length at offset ${t}.`);let r=n[t];if(r<=127)return[r,t+1];if(r===132){if(t+3>n.length)throw new RangeError(`Truncated u16 member length at offset ${t}.`);return[e.getUint16(t+1,!0),t+3]}if(r===130){if(t+5>n.length)throw new RangeError(`Truncated i32 member length at offset ${t}.`);return[e.getInt32(t+1,!0),t+5]}throw new RangeError(`Unsupported member-length marker 0x${r.toString(16).toUpperCase().padStart(2,"0")} at offset ${t}.`)}var Q=class n{static MAX_MEMBER_COUNT=249;bytes;view;length=0;boundaries=[];static utf8=new TextEncoder;constructor(e=128){this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}endMember(){this.boundaries.push(this.length)}finish(){let e=this.boundaries.length;if(e>n.MAX_MEMBER_COUNT)throw new RangeError(`A version-tolerant object may declare at most ${n.MAX_MEMBER_COUNT} members, got ${e}.`);if((e===0?0:this.boundaries[e-1])!==this.length)throw new Error("The last member was never closed \u2014 call endMember() after every member.");let r=1,i=0;for(let l of this.boundaries)r+=KC(l-i),i=l;let o=new Uint8Array(r+this.length),s=new DataView(o.buffer);o[0]=e;let a=1;i=0;for(let l of this.boundaries)a=XC(o,s,a,l-i),i=l;return o.set(this.bytes.subarray(0,this.length),a),o}writeBool(e){this.reserve(1),this.bytes[this.length]=e?1:0,this.length+=1}writeUint8(e){this.reserve(1),this.bytes[this.length]=e&255,this.length+=1}writeInt8(e){this.reserve(1),this.view.setInt8(this.length,e),this.length+=1}writeUint16(e){this.reserve(2),this.view.setUint16(this.length,e,!0),this.length+=2}writeInt16(e){this.reserve(2),this.view.setInt16(this.length,e,!0),this.length+=2}writeUint32(e){this.reserve(4),this.view.setUint32(this.length,e,!0),this.length+=4}writeInt32(e){this.reserve(4),this.view.setInt32(this.length,e,!0),this.length+=4}writeFloat32(e){this.reserve(4),this.view.setFloat32(this.length,e,!0),this.length+=4}writeInt64(e){this.reserve(8),this.view.setBigInt64(this.length,typeof e=="bigint"?e:BigInt(Math.trunc(e)),!0),this.length+=8}writeString(e){if(e===null){this.writeInt32(-1);return}if(e.length===0){this.writeInt32(0);return}let t=n.utf8.encode(e);this.writeInt32(~t.length),this.writeInt32(e.length),this.writeRaw(t)}writeBytes(e){if(e===null){this.writeInt32(-1);return}this.writeInt32(e.length),this.writeRaw(e)}writeUint32Array(e){if(e===null){this.writeInt32(-1);return}this.writeInt32(e.length);for(let t of e)this.writeUint32(t)}writeStringArray(e){if(e===null){this.writeInt32(-1);return}this.writeInt32(e.length);for(let t of e)this.writeString(t)}writeBytesArray(e){if(e===null){this.writeInt32(-1);return}this.writeInt32(e.length);for(let t of e)this.writeBytes(t)}writeRaw(e){this.reserve(e.length),this.bytes.set(e,this.length),this.length+=e.length}reserve(e){let t=this.length+e;if(t<=this.bytes.length)return;let r=this.bytes.length===0?32:this.bytes.length;for(;r<t;)r*=2;let i=new Uint8Array(r);i.set(this.bytes.subarray(0,this.length)),this.bytes=i,this.view=new DataView(i.buffer)}};function KC(n){return n>=0&&n<=127?1:n>=0&&n<=65535?3:5}function XC(n,e,t,r){return r>=0&&r<=127?(n[t]=r,t+1):r>=0&&r<=65535?(n[t]=132,e.setUint16(t+1,r,!0),t+3):(n[t]=130,e.setInt32(t+1,r,!0),t+5)}var Ce=new Uint8Array(0);function QC(){return{protocolVersion:0,token:"",roomId:"",displayName:"",capabilities:0,resumeKey:null}}function JC(n){let e=new Q;return e.writeUint16(n.protocolVersion),e.endMember(),e.writeString(n.token),e.endMember(),e.writeString(n.roomId),e.endMember(),e.writeString(n.displayName),e.endMember(),e.writeUint16(n.capabilities),e.endMember(),e.writeBytes(n.resumeKey),e.endMember(),e.finish()}function ZC(n){let e=new X(n),t=QC();return e.hasMember(0)&&(e.seekMember(0),t.protocolVersion=e.readUint16()),e.hasMember(1)&&(e.seekMember(1),t.token=e.readString()??""),e.hasMember(2)&&(e.seekMember(2),t.roomId=e.readString()??""),e.hasMember(3)&&(e.seekMember(3),t.displayName=e.readString()??""),e.hasMember(4)&&(e.seekMember(4),t.capabilities=e.readUint16()),e.hasMember(5)&&(e.seekMember(5),t.resumeKey=e.readBytes()),t}function eM(){return{clientId:0,roomId:"",tickHz:0,serverTimeMs:0,serverTick:0,aoiRadius:0,maxPlayers:0,protocolVersion:0,worldOriginX:0,worldOriginY:0,worldSize:0,mode:0,maxVisibleEntities:0,hostClientId:0,resumeKey:Ce,resumed:!1}}function tM(n){let e=new Q;return e.writeUint32(n.clientId),e.endMember(),e.writeString(n.roomId),e.endMember(),e.writeUint8(n.tickHz),e.endMember(),e.writeInt64(n.serverTimeMs),e.endMember(),e.writeUint32(n.serverTick),e.endMember(),e.writeFloat32(n.aoiRadius),e.endMember(),e.writeUint16(n.maxPlayers),e.endMember(),e.writeUint16(n.protocolVersion),e.endMember(),e.writeFloat32(n.worldOriginX),e.endMember(),e.writeFloat32(n.worldOriginY),e.endMember(),e.writeFloat32(n.worldSize),e.endMember(),e.writeUint8(n.mode),e.endMember(),e.writeUint16(n.maxVisibleEntities),e.endMember(),e.writeUint32(n.hostClientId),e.endMember(),e.writeBytes(n.resumeKey),e.endMember(),e.writeBool(n.resumed),e.endMember(),e.finish()}function rM(n){let e=new X(n),t=eM();return e.hasMember(0)&&(e.seekMember(0),t.clientId=e.readUint32()),e.hasMember(1)&&(e.seekMember(1),t.roomId=e.readString()??""),e.hasMember(2)&&(e.seekMember(2),t.tickHz=e.readUint8()),e.hasMember(3)&&(e.seekMember(3),t.serverTimeMs=e.readInt64AsNumber()),e.hasMember(4)&&(e.seekMember(4),t.serverTick=e.readUint32()),e.hasMember(5)&&(e.seekMember(5),t.aoiRadius=e.readFloat32()),e.hasMember(6)&&(e.seekMember(6),t.maxPlayers=e.readUint16()),e.hasMember(7)&&(e.seekMember(7),t.protocolVersion=e.readUint16()),e.hasMember(8)&&(e.seekMember(8),t.worldOriginX=e.readFloat32()),e.hasMember(9)&&(e.seekMember(9),t.worldOriginY=e.readFloat32()),e.hasMember(10)&&(e.seekMember(10),t.worldSize=e.readFloat32()),e.hasMember(11)&&(e.seekMember(11),t.mode=e.readUint8()),e.hasMember(12)&&(e.seekMember(12),t.maxVisibleEntities=e.readUint16()),e.hasMember(13)&&(e.seekMember(13),t.hostClientId=e.readUint32()),e.hasMember(14)&&(e.seekMember(14),t.resumeKey=e.readBytes()??Ce),e.hasMember(15)&&(e.seekMember(15),t.resumed=e.readBool()),t}function iM(){return{code:0,message:""}}function nM(n){let e=new Q;return e.writeUint16(n.code),e.endMember(),e.writeString(n.message),e.endMember(),e.finish()}function oM(n){let e=new X(n),t=iM();return e.hasMember(0)&&(e.seekMember(0),t.code=e.readUint16()),e.hasMember(1)&&(e.seekMember(1),t.message=e.readString()??""),t}function sM(){return{clientTimeMs:0}}function aM(n){let e=new Q;return e.writeInt64(n.clientTimeMs),e.endMember(),e.finish()}function lM(n){let e=new X(n),t=sM();return e.hasMember(0)&&(e.seekMember(0),t.clientTimeMs=e.readInt64AsNumber()),t}function cM(){return{clientTimeMs:0,serverTimeMs:0,serverTick:0}}function uM(n){let e=new Q;return e.writeInt64(n.clientTimeMs),e.endMember(),e.writeInt64(n.serverTimeMs),e.endMember(),e.writeUint32(n.serverTick),e.endMember(),e.finish()}function dM(n){let e=new X(n),t=cM();return e.hasMember(0)&&(e.seekMember(0),t.clientTimeMs=e.readInt64AsNumber()),e.hasMember(1)&&(e.seekMember(1),t.serverTimeMs=e.readInt64AsNumber()),e.hasMember(2)&&(e.seekMember(2),t.serverTick=e.readUint32()),t}function hM(){return{clientId:0,displayName:""}}function pM(n){let e=new Q;return e.writeUint32(n.clientId),e.endMember(),e.writeString(n.displayName),e.endMember(),e.finish()}function mM(n){let e=new X(n),t=hM();return e.hasMember(0)&&(e.seekMember(0),t.clientId=e.readUint32()),e.hasMember(1)&&(e.seekMember(1),t.displayName=e.readString()??""),t}function fM(){return{clientId:0,reason:0}}function gM(n){let e=new Q;return e.writeUint32(n.clientId),e.endMember(),e.writeUint8(n.reason),e.endMember(),e.finish()}function yM(n){let e=new X(n),t=fM();return e.hasMember(0)&&(e.seekMember(0),t.clientId=e.readUint32()),e.hasMember(1)&&(e.seekMember(1),t.reason=e.readUint8()),t}function bM(){return{playerCount:0,entityCount:0,serverTick:0}}function SM(n){let e=new Q;return e.writeUint16(n.playerCount),e.endMember(),e.writeUint16(n.entityCount),e.endMember(),e.writeUint32(n.serverTick),e.endMember(),e.finish()}function vM(n){let e=new X(n),t=bM();return e.hasMember(0)&&(e.seekMember(0),t.playerCount=e.readUint16()),e.hasMember(1)&&(e.seekMember(1),t.entityCount=e.readUint16()),e.hasMember(2)&&(e.seekMember(2),t.serverTick=e.readUint32()),t}function wM(){return{text:""}}function xM(n){let e=new Q;return e.writeString(n.text),e.endMember(),e.finish()}function PM(n){let e=new X(n),t=wM();return e.hasMember(0)&&(e.seekMember(0),t.text=e.readString()??""),t}function kM(){return{clientId:0,text:""}}function AM(n){let e=new Q;return e.writeUint32(n.clientId),e.endMember(),e.writeString(n.text),e.endMember(),e.finish()}function TM(n){let e=new X(n),t=kM();return e.hasMember(0)&&(e.seekMember(0),t.clientId=e.readUint32()),e.hasMember(1)&&(e.seekMember(1),t.text=e.readString()??""),t}function XS(){return new Q(1).finish()}function QS(n){return new X(n),{}}function CM(){return{key:"",value:Ce}}function MM(n){let e=new Q;return e.writeString(n.key),e.endMember(),e.writeBytes(n.value),e.endMember(),e.finish()}function DM(n){let e=new X(n),t=CM();return e.hasMember(0)&&(e.seekMember(0),t.key=e.readString()??""),e.hasMember(1)&&(e.seekMember(1),t.value=e.readBytes()??Ce),t}function NM(){return{keys:[],values:[]}}function EM(n){let e=new Q;return e.writeStringArray(n.keys),e.endMember(),e.writeBytesArray(n.values),e.endMember(),e.finish()}function IM(n){let e=new X(n),t=NM();return e.hasMember(0)&&(e.seekMember(0),t.keys=(e.readStringArray()??[]).map(r=>r??"")),e.hasMember(1)&&(e.seekMember(1),t.values=(e.readBytesArray()??[]).map(r=>r??Ce)),t}function RM(){return{hidden:!1,sendRateDivisor:0}}function BM(n){let e=new Q;return e.writeBool(n.hidden),e.endMember(),e.writeUint8(n.sendRateDivisor),e.endMember(),e.finish()}function VM(n){let e=new X(n),t=RM();return e.hasMember(0)&&(e.seekMember(0),t.hidden=e.readBool()),e.hasMember(1)&&(e.seekMember(1),t.sendRateDivisor=e.readUint8()),t}function OM(){return{hostClientId:0,previousHostClientId:0}}function LM(n){let e=new Q;return e.writeUint32(n.hostClientId),e.endMember(),e.writeUint32(n.previousHostClientId),e.endMember(),e.finish()}function FM(n){let e=new X(n),t=OM();return e.hasMember(0)&&(e.seekMember(0),t.hostClientId=e.readUint32()),e.hasMember(1)&&(e.seekMember(1),t.previousHostClientId=e.readUint32()),t}function _M(){return{clientIds:[],displayNames:[],frameFlags:0}}function zM(n){let e=new Q;return e.writeUint32Array(n.clientIds),e.endMember(),e.writeStringArray(n.displayNames),e.endMember(),e.writeUint8(n.frameFlags),e.endMember(),e.finish()}function UM(n){let e=new X(n),t=_M();return e.hasMember(0)&&(e.seekMember(0),t.clientIds=e.readUint32Array()??[]),e.hasMember(1)&&(e.seekMember(1),t.displayNames=(e.readStringArray()??[]).map(r=>r??"")),e.hasMember(2)&&(e.seekMember(2),t.frameFlags=e.readUint8()),t}function WM(){return{requestId:0,kind:0,qx:0,qy:0,qrot:0,qvx:0,qvy:0,flags:0,props:null}}function GM(n){let e=new Q;return e.writeUint32(n.requestId),e.endMember(),e.writeUint16(n.kind),e.endMember(),e.writeUint16(n.qx),e.endMember(),e.writeUint16(n.qy),e.endMember(),e.writeUint8(n.qrot),e.endMember(),e.writeInt16(n.qvx),e.endMember(),e.writeInt16(n.qvy),e.endMember(),e.writeUint8(n.flags),e.endMember(),e.writeBytes(n.props),e.endMember(),e.finish()}function qM(n){let e=new X(n),t=WM();return e.hasMember(0)&&(e.seekMember(0),t.requestId=e.readUint32()),e.hasMember(1)&&(e.seekMember(1),t.kind=e.readUint16()),e.hasMember(2)&&(e.seekMember(2),t.qx=e.readUint16()),e.hasMember(3)&&(e.seekMember(3),t.qy=e.readUint16()),e.hasMember(4)&&(e.seekMember(4),t.qrot=e.readUint8()),e.hasMember(5)&&(e.seekMember(5),t.qvx=e.readInt16()),e.hasMember(6)&&(e.seekMember(6),t.qvy=e.readInt16()),e.hasMember(7)&&(e.seekMember(7),t.flags=e.readUint8()),e.hasMember(8)&&(e.seekMember(8),t.props=e.readBytes()),t}function HM(){return{requestId:0,netId:0,rejectCode:0}}function jM(n){let e=new Q;return e.writeUint32(n.requestId),e.endMember(),e.writeUint32(n.netId),e.endMember(),e.writeUint16(n.rejectCode),e.endMember(),e.finish()}function YM(n){let e=new X(n),t=HM();return e.hasMember(0)&&(e.seekMember(0),t.requestId=e.readUint32()),e.hasMember(1)&&(e.seekMember(1),t.netId=e.readUint32()),e.hasMember(2)&&(e.seekMember(2),t.rejectCode=e.readUint16()),t}function $M(){return{netId:0}}function KM(n){let e=new Q;return e.writeUint32(n.netId),e.endMember(),e.finish()}function XM(n){let e=new X(n),t=$M();return e.hasMember(0)&&(e.seekMember(0),t.netId=e.readUint32()),t}function QM(){return{netId:0,json:Ce}}function JM(n){let e=new Q;return e.writeUint32(n.netId),e.endMember(),e.writeBytes(n.json),e.endMember(),e.finish()}function ZM(n){let e=new X(n),t=QM();return e.hasMember(0)&&(e.seekMember(0),t.netId=e.readUint32()),e.hasMember(1)&&(e.seekMember(1),t.json=e.readBytes()??Ce),t}function eD(){return{netId:0,json:Ce}}function tD(n){let e=new Q;return e.writeUint32(n.netId),e.endMember(),e.writeBytes(n.json),e.endMember(),e.finish()}function rD(n){let e=new X(n),t=eD();return e.hasMember(0)&&(e.seekMember(0),t.netId=e.readUint32()),e.hasMember(1)&&(e.seekMember(1),t.json=e.readBytes()??Ce),t}function iD(){return{name:"",target:0,targetClientId:0,payload:Ce}}function nD(n){let e=new Q;return e.writeString(n.name),e.endMember(),e.writeUint8(n.target),e.endMember(),e.writeUint32(n.targetClientId),e.endMember(),e.writeBytes(n.payload),e.endMember(),e.finish()}function oD(n){let e=new X(n),t=iD();return e.hasMember(0)&&(e.seekMember(0),t.name=e.readString()??""),e.hasMember(1)&&(e.seekMember(1),t.target=e.readUint8()),e.hasMember(2)&&(e.seekMember(2),t.targetClientId=e.readUint32()),e.hasMember(3)&&(e.seekMember(3),t.payload=e.readBytes()??Ce),t}function sD(){return{senderClientId:0,name:"",payload:Ce}}function aD(n){let e=new Q;return e.writeUint32(n.senderClientId),e.endMember(),e.writeString(n.name),e.endMember(),e.writeBytes(n.payload),e.endMember(),e.finish()}function lD(n){let e=new X(n),t=sD();return e.hasMember(0)&&(e.seekMember(0),t.senderClientId=e.readUint32()),e.hasMember(1)&&(e.seekMember(1),t.name=e.readString()??""),e.hasMember(2)&&(e.seekMember(2),t.payload=e.readBytes()??Ce),t}var HF=new Set([P.HelloCommand,P.WelcomeEvent,P.RejectedEvent,P.PingCommand,P.PongEvent,P.PeerJoinedEvent,P.PeerLeftEvent,P.RoomInfoEvent,P.SendChatCommand,P.ChatMessageEvent,P.LeaveCommand,P.SetRoomVarCommand,P.RoomVarsChangedEvent,P.ResyncCommand,P.SetClientPrefsCommand,P.HostChangedEvent,P.RoomRosterEvent,P.SpawnEntityRequest,P.SpawnEntityResponse,P.DespawnEntityCommand,P.SetEntityPropsCommand,P.EntityPropsChangedEvent,P.EmitSignalCommand,P.SignalEvent]);function JS(n,e){switch(n){case P.HelloCommand:return{typeId:n,body:ZC(e)};case P.WelcomeEvent:return{typeId:n,body:rM(e)};case P.RejectedEvent:return{typeId:n,body:oM(e)};case P.PingCommand:return{typeId:n,body:lM(e)};case P.PongEvent:return{typeId:n,body:dM(e)};case P.PeerJoinedEvent:return{typeId:n,body:mM(e)};case P.PeerLeftEvent:return{typeId:n,body:yM(e)};case P.RoomInfoEvent:return{typeId:n,body:vM(e)};case P.SendChatCommand:return{typeId:n,body:PM(e)};case P.ChatMessageEvent:return{typeId:n,body:TM(e)};case P.LeaveCommand:return{typeId:n,body:QS(e)};case P.SetRoomVarCommand:return{typeId:n,body:DM(e)};case P.RoomVarsChangedEvent:return{typeId:n,body:IM(e)};case P.ResyncCommand:return{typeId:n,body:QS(e)};case P.SetClientPrefsCommand:return{typeId:n,body:VM(e)};case P.HostChangedEvent:return{typeId:n,body:FM(e)};case P.RoomRosterEvent:return{typeId:n,body:UM(e)};case P.SpawnEntityRequest:return{typeId:n,body:qM(e)};case P.SpawnEntityResponse:return{typeId:n,body:YM(e)};case P.DespawnEntityCommand:return{typeId:n,body:XM(e)};case P.SetEntityPropsCommand:return{typeId:n,body:ZM(e)};case P.EntityPropsChangedEvent:return{typeId:n,body:rD(e)};case P.EmitSignalCommand:return{typeId:n,body:oD(e)};case P.SignalEvent:return{typeId:n,body:lD(e)};default:return}}function ZS(n){return PS(n.typeId,cD(n))}function cD(n){switch(n.typeId){case P.HelloCommand:return JC(n.body);case P.WelcomeEvent:return tM(n.body);case P.RejectedEvent:return nM(n.body);case P.PingCommand:return aM(n.body);case P.PongEvent:return uM(n.body);case P.PeerJoinedEvent:return pM(n.body);case P.PeerLeftEvent:return gM(n.body);case P.RoomInfoEvent:return SM(n.body);case P.SendChatCommand:return xM(n.body);case P.ChatMessageEvent:return AM(n.body);case P.LeaveCommand:return XS();case P.SetRoomVarCommand:return MM(n.body);case P.RoomVarsChangedEvent:return EM(n.body);case P.ResyncCommand:return XS();case P.SetClientPrefsCommand:return BM(n.body);case P.HostChangedEvent:return LM(n.body);case P.RoomRosterEvent:return zM(n.body);case P.SpawnEntityRequest:return GM(n.body);case P.SpawnEntityResponse:return jM(n.body);case P.DespawnEntityCommand:return KM(n.body);case P.SetEntityPropsCommand:return JM(n.body);case P.EntityPropsChangedEvent:return tD(n.body);case P.EmitSignalCommand:return nD(n.body);case P.SignalEvent:return aD(n.body)}}function qh(n){return n&65535}var Ja=Math.PI*2;function ev(){return{qx:0,qy:0}}function tv(n,e,t){return Number.isFinite(n)&&Number.isFinite(e)&&Number.isFinite(t)&&t>=1&&rv(n,e,t)}function rv(n,e,t){let r=Math.fround(128*t);return Math.abs(n)<r&&Math.abs(e)<r&&Math.abs(Math.fround(n+t))<r&&Math.abs(Math.fround(e+t))<r}function Hh(n){return Math.floor(n+.5)}var Za=class{originX;originY;size;constructor(e,t,r){if(!Number.isFinite(e))throw new RangeError(`World origin X must be finite, got ${e}.`);if(!Number.isFinite(t))throw new RangeError(`World origin Y must be finite, got ${t}.`);if(!Number.isFinite(r)||r<1)throw new RangeError(`World size must be finite and at least 1, got ${r}.`);if(!rv(e,t,r))throw new RangeError("World bounds are too far from the origin for their size: every coordinate magnitude must stay below 128 \xD7 size, or float32 round-tripping stops being a fixed point and positions oscillate by a quantum forever.");this.originX=e,this.originY=t,this.size=r}get maxX(){return this.originX+this.size}get maxY(){return this.originY+this.size}tryQuantizePosition(e,t,r){return!Number.isFinite(e)||!Number.isFinite(t)?(r.qx=0,r.qy=0,!1):(r.qx=this.quantizeAxis(e,this.originX),r.qy=this.quantizeAxis(t,this.originY),!0)}dequantizeX(e){return Math.fround(this.originX+e*this.size/65535)}dequantizeY(e){return Math.fround(this.originY+e*this.size/65535)}quantizeAxis(e,t){let r=Hh((e-t)*65535/this.size);return r<=0?0:r>=65535?65535:r}};function el(n){if(!Number.isFinite(n))return null;let e=n%Ja;return e<0&&(e+=Ja),Hh(e/Ja*256)&255}function iv(n){return Math.fround(n*Ja/256)}function to(n){if(!Number.isFinite(n))return null;let e=Hh(n*8);return e<=-32768?-32768:e>=32767?32767:e}var Yh={owned:0,shared:1,transferable:2},$h=3,cv=3;function Kh(n){switch(n&$h){case Yh.shared:return"shared";case Yh.transferable:return"transferable";default:return"owned"}}function uv(n,e=0){return Yh[n]&$h|(e&31)<<cv}function Xh(n){return(n&j.Teleport)!==0}var ge=class extends Error{kind;prefabPath;rejectCode;constructor(e,t,r,i=0){super(r),this.name="NetworkSpawnError",this.kind=e,this.prefabPath=t,this.rejectCode=i}},nt=class extends Error{kind;rejectCode;closeCode;constructor(e,t,r=0,i=null){super(t),this.name="NetworkConnectError",this.kind=e,this.rejectCode=r,this.closeCode=i}},nv=8,dD=2,hD=1e3,ov=240,pD=6e4,sv=64,mD=4294967296,fD=65536,gD=new Set([4001,4002,4003,4007,4008]),yD=new Set([q.ProtocolVersionMismatch,q.InvalidToken,q.TokenExpired,q.TokenRoomMismatch,q.RoomNotFound,q.RoomFull,q.RoomClosing,q.BadRequest,q.SessionReplaced]),bD=new Map([[q.None,"No error."],[q.ProtocolVersionMismatch,"This build speaks an unsupported protocol version \u2014 update the game."],[q.InvalidToken,"The room token is missing, malformed or not signed by pix3-cloud."],[q.TokenExpired,"The room token has expired \u2014 request a new one and rejoin."],[q.TokenRoomMismatch,"The room token was minted for a different room."],[q.RoomNotFound,"No such room on this server."],[q.RoomFull,"The room is full."],[q.RoomClosing,"The room is shutting down and is not accepting members."],[q.RateLimited,"Rate limit tripped \u2014 this client sent too much, too fast."],[q.PayloadTooLarge,"A frame exceeded the 4 KiB control-frame limit."],[q.QuotaExceeded,"A room or connection quota was exceeded."],[q.ServerShuttingDown,"The server is draining and closed the session."],[q.IdleTimeout,"The connection was idle for too long."],[q.BadRequest,"The server refused a malformed or out-of-order frame."],[q.SessionReplaced,"This session was displaced by a newer connection for the same identity."],[q.EntityLimitReached,"The room is holding as many entities as it can."],[q.NotEntityOwner,"That entity belongs to someone else."],[q.InternalError,"The server hit an internal error."],[q.KindNotAllowed,"That entity kind is not on the room allowlist."],[q.SendQueueOverflow,"The send queue overflowed \u2014 this client could not keep up."]]);function tl(n){return bD.get(n)??`The server refused the session (code ${n}).`}var Qh=new TextEncoder,Jh=new TextDecoder,rl=class{constructor(e){this.send=e}values=new Map;get(e){return this.values.get(e)}getText(e){let t=this.values.get(e);return t===void 0?void 0:Jh.decode(t)}getJson(e){let t=this.getText(e);if(t!==void 0)try{return JSON.parse(t)}catch{return}}has(e){return this.values.has(e)}keys(){return[...this.values.keys()]}get size(){return this.values.size}set(e,t){let r=typeof t=="string"?Qh.encode(t):t;return this.send(e,r)}replaceAll(e,t){let r=new Set(this.values.keys());this.values.clear();for(let i=0;i<e.length;i+=1)this.values.set(e[i],t[i]??new Uint8Array(0)),r.add(e[i]);return[...r]}merge(e,t){for(let r=0;r<e.length;r+=1)this.values.set(e[r],t[r]??new Uint8Array(0));return[...e]}clear(){this.values.clear()}},ro=class{sendIntervalMs;pingIntervalMs;now;socketFactory;backoffOptions;random;visibility;transport=null;credentials=null;disposed=!1;currentStatus="offline";session=null;worldQuantizer=null;resumeKey=null;hasWelcomed=!1;lastRejectCode=null;rttMs=0;clockOffsetMs=0;lastPingSentAtMs=0;lastPingClientTimeMs=0;pumpTimer=null;clientTick=0;peerMap=new Map;entityMap=new Map;slotToNetId=new Map;publishStates=new Map;pendingSpawns=new Map;nextRequestId=1;spawnTimestamps=[];ownedNetIds=new Set;kindTableOverride;roomVars;receivedRoomVarsForSession=!1;pendingSnapshot=new Map;snapshotInProgress=!1;snapshotComplete=!1;pendingRoster=[];rosterInProgress=!1;lastSeq=null;desynced=!1;resyncTimestamps=[];unknownTypeIds=new Xa;counters={framesReceived:0,unknownTypeIds:0,malformedFrames:0,seqGaps:0,resyncsSent:0,resyncsSuppressed:0,entityPacketsSent:0,entityRecordsSent:0,unknownSlotUpdates:0,nonFiniteRejected:0,signalHandlerErrors:0,spawnsSent:0,spawnsRejected:0,spawnsThrottled:0,despawnsSent:0};signalHandlers=new Map;statusListeners=new Set;peerListeners=new Set;entityListeners=new Set;roomVarListeners=new Set;errorListeners=new Set;pendingConnect=null;connectPromise=null;hidden=!1;onVisibilityChange=()=>this.handleVisibilityChange();snapshotView=OS();deltaSections=_S();fullRecord=IS();updateRecord=BS();signalSections=jS();signalEntry=YS();quantizedPosition=ev();scratchChanges=[];constructor(e={}){let t=e.sendRateHz&&e.sendRateHz>0?e.sendRateHz:20;this.sendIntervalMs=Math.max(1,Math.round(1e3/t)),this.pingIntervalMs=e.pingIntervalMs??2e3,this.now=e.now??Date.now,this.socketFactory=e.socketFactory,this.backoffOptions=e.backoff,this.random=e.random,this.visibility=e.visibility===void 0?xD():e.visibility,this.kindTableOverride=e.kindTable??null,this.roomVars=new rl((r,i)=>this.sendSetRoomVar(r,i))}get status(){return this.currentStatus}get isOnline(){return this.currentStatus==="online"}get clientId(){return this.session?.clientId??0}get roomId(){return this.session?.roomId??""}get tickHz(){return this.session?.tickHz??0}get mode(){return this.session?.mode??wS.Relay}get hostClientId(){return this.session?.hostClientId??0}get isHost(){let e=this.session?.hostClientId??0;return e!==0&&e===this.clientId}get maxVisibleEntities(){return this.session?.maxVisibleEntities??0}get maxPlayers(){return this.session?.maxPlayers??0}get aoiRadius(){return this.session?.aoiRadius??0}get sessionInfo(){return this.session}get quantizer(){return this.worldQuantizer}get rtt(){return this.rttMs}get clockOffset(){return this.clockOffsetMs}get serverTimeMs(){return this.now()+this.clockOffsetMs}get peers(){return[...this.peerMap.values()]}get entities(){return this.entityMap}get entityCount(){return this.entityMap.size}get hasCompleteSnapshot(){return this.snapshotComplete&&!this.desynced}get isDesynced(){return this.desynced}get vars(){return this.roomVars}get stats(){return{...this.counters}}get transportStats(){return this.transport?this.transport.stats:null}getEntity(e){return this.entityMap.get(e)}resolveSlot(e){return this.slotToNetId.get(e)??0}connect(e){if(this.disposed)return Promise.reject(new nt("cancelled","This NetworkService has been disposed."));if(!e.url||!e.roomId)return Promise.reject(new nt("invalid","connect() needs both a url and a roomId."));if(this.connectPromise)return this.connectPromise;if(this.session)return Promise.resolve(this.session);if(this.transport)return Promise.reject(new nt("invalid","This session is still reconnecting; call disconnect() before joining another room."));this.credentials={url:e.url,token:e.token??"",roomId:e.roomId,displayName:e.displayName??"",capabilities:e.capabilities??0},this.lastRejectCode=null,this.hasWelcomed=!1,this.resumeKey=null;let t=new Promise((r,i)=>{this.pendingConnect={resolve:r,reject:i}});return this.connectPromise=t,this.transport=new Xn({url:this.credentials.url,socketFactory:this.socketFactory,now:this.now,random:this.random,backoff:this.backoffOptions,shouldReconnect:r=>this.shouldReconnect(r)}),this.transport.onFrame=r=>this.handleFrame(r),this.transport.onStateChange=(r,i)=>this.handleTransportState(r,i),this.attachVisibility(),this.startPump(),this.transport.connect(),t}disconnect(){this.transport&&(this.sendControl({typeId:P.LeaveCommand,body:{}}),this.transport.onFrame=null,this.transport.onStateChange=null,this.transport.dispose(),this.transport=null),this.rejectPendingConnect(new nt("cancelled","The session was disconnected locally.")),this.rejectPendingSpawns("cancelled","The session was disconnected locally."),this.stopPump(),this.detachVisibility(),this.resetSessionState(),this.session=null,this.worldQuantizer=null,this.hasWelcomed=!1,this.resumeKey=null,this.credentials=null,this.setStatus("offline")}dispose(){this.disposed||(this.disconnect(),this.disposed=!0,this.signalHandlers.clear(),this.statusListeners.clear(),this.peerListeners.clear(),this.entityListeners.clear(),this.roomVarListeners.clear(),this.errorListeners.clear())}onStatusChange(e){return this.statusListeners.add(e),()=>this.statusListeners.delete(e)}onPeersChange(e){return this.peerListeners.add(e),()=>this.peerListeners.delete(e)}onEntitiesChange(e){return this.entityListeners.add(e),()=>this.entityListeners.delete(e)}onRoomVarsChange(e){return this.roomVarListeners.add(e),()=>this.roomVarListeners.delete(e)}onError(e){return this.errorListeners.add(e),()=>this.errorListeners.delete(e)}on(e,t){let r=this.signalHandlers.get(e);return r||(r=new Set,this.signalHandlers.set(e,r)),r.add(t),()=>this.off(e,t)}off(e,t){let r=this.signalHandlers.get(e);r&&(t?r.delete(t):r.clear(),r.size===0&&this.signalHandlers.delete(e))}emit(e,t=null,r={}){if(!this.isOnline)return!1;let i=r.to??"peers",o=$n.AllPeers,s=0;return typeof i=="number"?(o=$n.SinglePeer,s=i):i==="server"?o=$n.Server:i==="aoi"&&(o=$n.AoiPeers),this.sendControl({typeId:P.EmitSignalCommand,body:{name:e,target:o,targetClientId:s,payload:dv(t)}})}publish(e,t){let r=this.worldQuantizer;if(!this.isOnline||!r)return!1;let i=this.getPublishEntry(e),o=i.mask;if(t.x!==void 0||t.y!==void 0){let s=t.x??r.dequantizeX(i.next.qx),a=t.y??r.dequantizeY(i.next.qy);if(!r.tryQuantizePosition(s,a,this.quantizedPosition))return this.counters.nonFiniteRejected+=1,!1;t.x!==void 0&&(!i.hasSent||this.quantizedPosition.qx!==i.sent.qx)&&(i.next.qx=this.quantizedPosition.qx,o|=j.X),t.y!==void 0&&(!i.hasSent||this.quantizedPosition.qy!==i.sent.qy)&&(i.next.qy=this.quantizedPosition.qy,o|=j.Y)}if(t.rotation!==void 0){let s=el(t.rotation);if(s===null)return this.counters.nonFiniteRejected+=1,!1;(!i.hasSent||s!==i.sent.qrot)&&(i.next.qrot=s,o|=j.Rot)}if(t.vx!==void 0){let s=to(t.vx);if(s===null)return this.counters.nonFiniteRejected+=1,!1;(!i.hasSent||s!==i.sent.qvx)&&(i.next.qvx=s,o|=j.Vx)}if(t.vy!==void 0){let s=to(t.vy);if(s===null)return this.counters.nonFiniteRejected+=1,!1;(!i.hasSent||s!==i.sent.qvy)&&(i.next.qvy=s,o|=j.Vy)}if(t.flags!==void 0){let s=t.flags&255;(!i.hasSent||s!==i.sent.flags)&&(i.next.flags=s,o|=j.Flags)}return t.teleport&&(o|=j.Teleport),i.mask=o,!0}clearPublished(e){this.publishStates.delete(e)}get kinds(){return this.kindTableOverride??Oh()}get ownedEntityCount(){return this.ownedNetIds.size}ownsEntity(e){return this.ownedNetIds.has(e)}spawn(e,t={}){let r=this.kinds.kindOf(e);if(r===null)return Promise.reject(new ge("unknown-kind",e,`"${e}" is not in this build's netKindTable, so it has no wire kind. Export the project (the exporter emits the table) or call registerNetworkPrefab() on every client.`));let i=this.worldQuantizer;if(!this.isOnline||!i)return Promise.reject(new ge("offline",e,"Cannot spawn: this session is not in a room."));if(this.ownedNetIds.size>=sv)return this.counters.spawnsThrottled+=1,Promise.reject(new ge("quota",e,`This client already owns ${sv} entities \u2014 despawn one first.`,q.QuotaExceeded));let o=this.now();for(;this.spawnTimestamps.length>0&&o-this.spawnTimestamps[0]>=pD;)this.spawnTimestamps.shift();if(this.spawnTimestamps.length>=ov)return this.counters.spawnsThrottled+=1,Promise.reject(new ge("rate-limited",e,`Spawn rate limit: ${ov} spawns per minute per connection.`,q.RateLimited));let s=t.position;if(!i.tryQuantizePosition(s?.x??0,s?.y??0,this.quantizedPosition))return this.counters.nonFiniteRejected+=1,Promise.reject(new ge("invalid",e,"Spawn position must be finite."));let a=el(t.rotation??0),l=to(t.velocity?.x??0),c=to(t.velocity?.y??0);if(a===null||l===null||c===null)return this.counters.nonFiniteRejected+=1,Promise.reject(new ge("invalid",e,"Spawn rotation and velocity must be finite."));let u=this.nextRequestId;return this.nextRequestId=(this.nextRequestId+1)%mD||1,this.sendControl({typeId:P.SpawnEntityRequest,body:{requestId:u,kind:r,qx:this.quantizedPosition.qx,qy:this.quantizedPosition.qy,qrot:a,qvx:l,qvy:c,flags:uv(t.ownership??"owned",t.appFlags??0),props:vD(t.props)}})?(this.spawnTimestamps.push(o),this.counters.spawnsSent+=1,new Promise((h,p)=>{this.pendingSpawns.set(u,{prefabPath:e,resolve:h,reject:p})})):Promise.reject(new ge("invalid",e,"The spawn request could not be sent."))}despawn(e){return!this.isOnline||!this.sendControl({typeId:P.DespawnEntityCommand,body:{netId:e}})?!1:(this.counters.despawnsSent+=1,this.ownedNetIds.delete(e),this.publishStates.delete(e),!0)}snapPosition(e,t,r){let i=this.worldQuantizer;return!i||!i.tryQuantizePosition(e,t,this.quantizedPosition)?!1:(r.x=i.dequantizeX(this.quantizedPosition.qx),r.y=i.dequantizeY(this.quantizedPosition.qy),!0)}snapRotation(e){let t=el(e);return t===null?null:iv(t)}flush(){this.pump()}requestResync(){if(!this.isOnline)return!1;let e=this.now();for(;this.resyncTimestamps.length>0&&e-this.resyncTimestamps[0]>=hD;)this.resyncTimestamps.shift();return this.resyncTimestamps.length>=dD?(this.counters.resyncsSuppressed+=1,!1):this.sendControl({typeId:P.ResyncCommand,body:{}})?(this.resyncTimestamps.push(e),this.counters.resyncsSent+=1,!0):!1}sendChat(e){return this.isOnline?this.sendControl({typeId:P.SendChatCommand,body:{text:e}}):!1}shouldReconnect(e){return!(!this.hasWelcomed||e.code!==null&&gD.has(e.code)||this.lastRejectCode!==null&&yD.has(this.lastRejectCode))}handleTransportState(e,t){switch(e){case"connecting":this.setStatus("connecting");break;case"open":this.sendHello();break;case"reconnecting":this.session=null,this.rejectPendingSpawns("transport","The room connection dropped before the spawn was answered."),this.setStatus("reconnecting");break;case"closed":{let r=this.describeClose(t);this.session=null,this.rejectPendingSpawns("transport",`The room connection closed: ${r.message}`),this.setStatus("offline"),this.rejectPendingConnect(r),this.notifyError(r);break}default:break}}describeClose(e){if(this.lastRejectCode!==null)return new nt("rejected",tl(this.lastRejectCode),this.lastRejectCode,e?.code??null);let t=e?`${e.reason}${e.message?`: ${e.message}`:""}`:"connection closed";return new nt("transport",`The room connection closed (${t}).`,0,e?.code??null)}sendHello(){let e=this.credentials;e&&this.sendControl({typeId:P.HelloCommand,body:{protocolVersion:2,token:e.token,roomId:e.roomId,displayName:e.displayName,capabilities:e.capabilities,resumeKey:this.resumeKey}})}sendControl(e){let t=this.transport;return t?t.send(ZS(e)):!1}sendSetRoomVar(e,t){return this.isOnline?this.sendControl({typeId:P.SetRoomVarCommand,body:{key:e,value:t}}):!1}handleFrame(e){this.counters.framesReceived+=1;let t=kS(e);if(t<0){this.counters.malformedFrames+=1;return}switch(t){case P.SnapshotPacket:this.applySnapshotPacket(e);return;case P.DeltaPacket:this.applyDeltaPacket(e);return;case P.SignalBatchPacket:this.applySignalBatchPacket(e);return;default:break}let r;try{r=JS(t,AS(e))}catch{this.counters.malformedFrames+=1;return}if(!r){this.unknownTypeIds.record(t),this.counters.unknownTypeIds+=1;return}this.dispatchControl(r)}dispatchControl(e){switch(e.typeId){case P.WelcomeEvent:this.handleWelcome(e.body);break;case P.RejectedEvent:this.handleRejected(e.body.code,e.body.message);break;case P.PongEvent:this.handlePong(e.body.clientTimeMs,e.body.serverTimeMs);break;case P.PeerJoinedEvent:this.peerMap.set(e.body.clientId,{clientId:e.body.clientId,displayName:e.body.displayName,isLocal:e.body.clientId===this.clientId}),this.notifyPeers();break;case P.PeerLeftEvent:this.peerMap.delete(e.body.clientId)&&this.notifyPeers();break;case P.HostChangedEvent:this.session&&(this.session={...this.session,hostClientId:e.body.hostClientId}),this.notifyPeers();break;case P.RoomVarsChangedEvent:this.handleRoomVars(e.body.keys,e.body.values);break;case P.RoomRosterEvent:this.handleRoomRoster(e.body);break;case P.SignalEvent:this.dispatchSignal(e.body.name,e.body.payload,e.body.senderClientId);break;case P.SpawnEntityResponse:this.handleSpawnResponse(e.body);break;default:break}}handleWelcome(e){let t=e.resumed&&this.hasWelcomed;t||this.resetSessionState(),this.slotToNetId.clear(),this.pendingSnapshot.clear(),this.snapshotInProgress=!1,this.snapshotComplete=!1,this.lastSeq=null,this.desynced=!1,this.lastRejectCode=null,this.pendingRoster.length=0,this.rosterInProgress=!1,this.receivedRoomVarsForSession=!1,this.worldQuantizer=tv(e.worldOriginX,e.worldOriginY,e.worldSize)?new Za(e.worldOriginX,e.worldOriginY,e.worldSize):null,this.resumeKey=e.resumeKey.length>0?e.resumeKey.slice():null,this.hasWelcomed=!0,this.session={clientId:e.clientId,roomId:e.roomId,tickHz:e.tickHz,mode:e.mode,protocolVersion:e.protocolVersion,maxPlayers:e.maxPlayers,maxVisibleEntities:e.maxVisibleEntities,aoiRadius:e.aoiRadius,hostClientId:e.hostClientId,resumed:t,world:{originX:e.worldOriginX,originY:e.worldOriginY,size:e.worldSize}},this.peerMap.set(e.clientId,{clientId:e.clientId,displayName:this.credentials?.displayName??"",isLocal:!0}),this.clockOffsetMs=e.serverTimeMs-this.now(),this.setStatus("online"),this.notifyPeers(),this.hidden&&this.sendClientPrefs();let r=this.pendingConnect?.resolve;this.pendingConnect=null,this.connectPromise=null,r?.(this.session)}handleSpawnResponse(e){let t=this.pendingSpawns.get(e.requestId);if(t){if(this.pendingSpawns.delete(e.requestId),e.rejectCode!==q.None||e.netId===0){this.counters.spawnsRejected+=1,t.reject(new ge(SD(e.rejectCode),t.prefabPath,tl(e.rejectCode),e.rejectCode));return}this.ownedNetIds.add(e.netId),t.resolve(e.netId)}}rejectPendingSpawns(e,t){if(this.pendingSpawns.size===0)return;let r=[...this.pendingSpawns.values()];this.pendingSpawns.clear();for(let i of r)i.reject(new ge(e,i.prefabPath,t))}handleRejected(e,t){this.lastRejectCode=e;let r=new nt("rejected",t&&t.length>0?t:tl(e),e,null);this.rejectPendingConnect(r),this.notifyError(r)}handlePong(e,t){if(e!==this.lastPingClientTimeMs){this.clockOffsetMs=t-this.now();return}let r=this.now();this.rttMs=Math.max(0,r-e),this.clockOffsetMs=t+this.rttMs/2-r}handleRoomVars(e,t){let r=!this.receivedRoomVarsForSession;this.receivedRoomVarsForSession=!0;let i=r?this.roomVars.replaceAll(e,t.map(lv)):this.roomVars.merge(e,t.map(lv));if(i.length>0)for(let o of[...this.roomVarListeners])o(i)}handleRoomRoster(e){this.rosterInProgress||(this.pendingRoster.length=0,this.rosterInProgress=!0);let t=Math.min(e.clientIds.length,e.displayNames.length);(t!==e.clientIds.length||t!==e.displayNames.length)&&(this.counters.malformedFrames+=1);for(let r=0;r<t;r+=1){let i=e.clientIds[r];this.pendingRoster.push({clientId:i,displayName:e.displayNames[r],isLocal:i===this.clientId})}Vh(e.frameFlags)&&this.commitRoster()}commitRoster(){let e=this.peerMap.get(this.clientId);this.peerMap.clear();for(let t of this.pendingRoster)t.isLocal&&this.peerMap.set(t.clientId,t);this.peerMap.size===0&&e&&this.peerMap.set(e.clientId,e);for(let t of this.pendingRoster)t.isLocal||this.peerMap.set(t.clientId,t);this.pendingRoster.length=0,this.rosterInProgress=!1,this.notifyPeers()}applySnapshotPacket(e){let t=jh(e);if(!LS(t,this.snapshotView)){this.counters.malformedFrames+=1;return}if(this.acceptHotFrame(this.snapshotView.seq,!0)){this.snapshotInProgress||(this.pendingSnapshot.clear(),this.snapshotInProgress=!0);for(let r=0;r<this.snapshotView.count;r+=1){if(!FS(t,this.snapshotView,r,this.fullRecord)){this.counters.malformedFrames+=1;break}this.pendingSnapshot.set(this.fullRecord.netId,av(this.fullRecord.netId,this.fullRecord.state))}Vh(this.snapshotView.frameFlags)&&this.commitSnapshot()}}commitSnapshot(){let e=this.beginChanges();for(let[t,r]of this.entityMap)this.pendingSnapshot.has(t)||e.push({kind:"leave",netId:t,entity:r,mask:0});this.entityMap.clear(),this.slotToNetId.clear();for(let[t,r]of this.pendingSnapshot)this.entityMap.set(t,r),this.slotToNetId.set(qh(t),t),e.push({kind:"enter",netId:t,entity:r,mask:0});this.pendingSnapshot.clear(),this.snapshotInProgress=!1,this.snapshotComplete=!0,this.desynced=!1,this.flushChanges(e)}applyDeltaPacket(e){let t=jh(e);if(!zS(t,this.deltaSections)){this.counters.malformedFrames+=1;return}if(!this.acceptHotFrame(this.deltaSections.seq,!1))return;let r=this.beginChanges();for(let o=0;o<this.deltaSections.removedCount;o+=1){let s=US(t,this.deltaSections,o);if(s<0){this.counters.malformedFrames+=1;break}let a=this.slotToNetId.get(s);if(a===void 0)continue;let l=this.entityMap.get(a);this.slotToNetId.delete(s),this.entityMap.delete(a),this.publishStates.delete(a),l&&r.push({kind:"leave",netId:a,entity:l,mask:0})}for(let o=0;o<this.deltaSections.enterCount;o+=1){if(!WS(t,this.deltaSections,o,this.fullRecord)){this.counters.malformedFrames+=1;break}let s=this.fullRecord.netId,a=av(s,this.fullRecord.state);this.entityMap.set(s,a),this.slotToNetId.set(qh(s),s),r.push({kind:"enter",netId:s,entity:a,mask:0})}let i=0;for(let o=0;o<this.deltaSections.updateCount;o+=1){if(!GS(t,this.deltaSections,i,this.updateRecord)){this.counters.malformedFrames+=1;break}i+=this.updateRecord.bytesRead;let s=this.slotToNetId.get(this.updateRecord.slot),a=s===void 0?void 0:this.entityMap.get(s);if(!a){this.counters.unknownSlotUpdates+=1;continue}ES(a,this.updateRecord.mask,this.updateRecord.state),r.push({kind:"update",netId:a.netId,entity:a,mask:this.updateRecord.mask})}this.flushChanges(r)}applySignalBatchPacket(e){let t=jh(e);if(!$S(t,this.signalSections)){this.counters.malformedFrames+=1;return}if(!this.acceptHotFrame(this.signalSections.seq,!1))return;let r=0;for(let i=0;i<this.signalSections.count;i+=1){if(!KS(t,this.signalSections,r,this.signalEntry)){this.counters.malformedFrames+=1;break}r+=this.signalEntry.bytesRead,this.dispatchSignal(Jh.decode(this.signalEntry.name),this.signalEntry.payload,this.signalEntry.senderClientId)}}acceptHotFrame(e,t){if(this.desynced&&!t)return!1;let r=this.lastSeq===null?e:(this.lastSeq+1)%fD;if(e!==r){if(this.counters.seqGaps+=1,!t)return this.desynced=!0,this.snapshotComplete=!1,this.requestResync(),!1;this.pendingSnapshot.clear(),this.snapshotInProgress=!1}return t&&(this.desynced=!1),this.lastSeq=e,!0}dispatchSignal(e,t,r){let i=this.signalHandlers.get(e);if(!(!i||i.size===0))for(let o of[...i])try{o(t,r)}catch(s){this.counters.signalHandlerErrors+=1,console.error(`[NetworkService] Signal handler for "${e}" threw:`,s)}}startPump(){this.pumpTimer===null&&(this.pumpTimer=setInterval(()=>this.pump(),this.sendIntervalMs))}stopPump(){this.pumpTimer!==null&&(clearInterval(this.pumpTimer),this.pumpTimer=null)}pump(){this.isOnline&&(this.flushDirtyEntities(),this.maybePing())}maybePing(){let e=this.now();this.lastPingSentAtMs!==0&&e-this.lastPingSentAtMs<this.pingIntervalMs||(this.lastPingSentAtMs=e,this.lastPingClientTimeMs=e,this.sendControl({typeId:P.PingCommand,body:{clientTimeMs:e}}))}flushDirtyEntities(){let e=[];for(let t of this.publishStates.values())t.mask!==0&&e.push(t);if(e.length!==0){this.clientTick=this.clientTick+1>>>0;for(let t=0;t<e.length;t+=nv){let r=e.slice(t,t+nv),i=Qa;for(let l of r)i+=Gh(l.mask);let o=new ArrayBuffer(i),s=new DataView(o),a=qS(s,0,this.clientTick);for(let l of r)a+=VS(s,a,l.netId,l.mask,l.next);if(HS(s,r.length),!this.transport?.send(new Uint8Array(o)))return;this.counters.entityPacketsSent+=1,this.counters.entityRecordsSent+=r.length;for(let l of r)l.sent.qx=l.next.qx,l.sent.qy=l.next.qy,l.sent.qrot=l.next.qrot,l.sent.qvx=l.next.qvx,l.sent.qvy=l.next.qvy,l.sent.flags=l.next.flags,l.mask=0,l.hasSent=!0}}}getPublishEntry(e){let t=this.publishStates.get(e);return t||(t={netId:e,sent:Zn(),next:Zn(),mask:0,hasSent:!1},this.publishStates.set(e,t)),t}attachVisibility(){this.visibility&&(this.hidden=this.visibility.hidden,this.visibility.addEventListener("visibilitychange",this.onVisibilityChange))}detachVisibility(){this.visibility?.removeEventListener("visibilitychange",this.onVisibilityChange)}handleVisibilityChange(){let e=this.visibility?.hidden??!1;e!==this.hidden&&(this.hidden=e,this.sendClientPrefs())}sendClientPrefs(){this.sendControl({typeId:P.SetClientPrefsCommand,body:{hidden:this.hidden,sendRateDivisor:0}})}resetSessionState(){this.entityMap.clear(),this.slotToNetId.clear(),this.pendingSnapshot.clear(),this.publishStates.clear(),this.peerMap.clear(),this.pendingRoster.length=0,this.rosterInProgress=!1,this.roomVars.clear(),this.receivedRoomVarsForSession=!1,this.snapshotInProgress=!1,this.snapshotComplete=!1,this.desynced=!1,this.lastSeq=null,this.resyncTimestamps.length=0,this.clientTick=0,this.lastPingSentAtMs=0,this.lastPingClientTimeMs=0,this.rttMs=0,this.ownedNetIds.clear(),this.spawnTimestamps.length=0,this.rejectPendingSpawns("transport","The session was reset before the spawn was answered.")}setStatus(e){if(this.currentStatus!==e){this.currentStatus=e;for(let t of[...this.statusListeners])t(e)}}notifyPeers(){let e=this.peers;for(let t of[...this.peerListeners])t(e)}notifyError(e){for(let t of[...this.errorListeners])t(e)}rejectPendingConnect(e){let t=this.pendingConnect?.reject;this.pendingConnect=null,this.connectPromise=null,t?.(e)}beginChanges(){return this.scratchChanges.length=0,this.scratchChanges}flushChanges(e){for(let r of e)r.kind==="leave"&&(this.ownedNetIds.delete(r.netId),this.publishStates.delete(r.netId));if(e.length===0||this.entityListeners.size===0){e.length=0;return}let t=[...e];e.length=0;for(let r of[...this.entityListeners])r(t)}};function jh(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function av(n,e){return{netId:n,qx:e.qx,qy:e.qy,qrot:e.qrot,qvx:e.qvx,qvy:e.qvy,kind:e.kind,ownerId:e.ownerId,flags:e.flags}}function SD(n){switch(n){case q.QuotaExceeded:return"quota";case q.EntityLimitReached:return"entity-limit";case q.KindNotAllowed:return"kind-not-allowed";default:return"rejected"}}function vD(n){return n==null?null:n instanceof Uint8Array?n:Qh.encode(JSON.stringify(n))}function lv(n){return n.slice()}function dv(n){return n===null?new Uint8Array(0):n instanceof Uint8Array?n:Qh.encode(JSON.stringify(n))}function wD(n){if(n.length!==0)try{return JSON.parse(Jh.decode(n))}catch{return}}function xD(){let n=globalThis.document;return n&&typeof n.addEventListener=="function"?n:null}var io=class{constructor(e){this.host=e;this.unsubscribe=e.network.onEntitiesChange(t=>this.applyChanges(t))}byNetId=new Map;byNode=new WeakMap;inFlight=new Set;pending=new Set;unsubscribe=null;disposed=!1;counters={remoteSpawned:0,remoteFreed:0,unknownKinds:0,instantiateFailures:0};get stats(){return{...this.counters}}get boundCount(){return this.byNetId.size}get pendingCount(){return this.pending.size+this.inFlight.size}bind(e,t,r=null){this.adopt({netId:e,node:t,remote:!1,listener:r})}setListener(e,t){let r=this.byNetId.get(e);r&&(r.listener=t)}unbind(e){let t=this.byNetId.get(e);t&&(this.byNetId.delete(e),this.byNode.get(t.node)===e&&this.byNode.delete(t.node))}getNode(e){return this.byNetId.get(e)?.node??null}getNetId(e){return this.byNode.get(e)??0}isRemote(e){return this.byNetId.get(e)?.remote??!1}reconcile(){if(!this.disposed)for(let[e,t]of this.host.network.entities)this.byNetId.has(e)||this.inFlight.has(e)||this.isLocallyOwned(e)||(this.pending.add(e),this.instantiateRemote(e,t.kind))}handleSceneStopped(){for(let e of this.byNetId.values())e.remote&&this.pending.add(e.netId);this.byNetId.clear(),this.inFlight.clear()}dispose(){this.disposed||(this.disposed=!0,this.unsubscribe?.(),this.unsubscribe=null,this.byNetId.clear(),this.inFlight.clear(),this.pending.clear())}adopt(e){let t=this.byNetId.get(e.netId);t&&t.node!==e.node&&this.byNode.delete(t.node),this.byNetId.set(e.netId,e),this.byNode.set(e.node,e.netId),this.pending.delete(e.netId)}applyChanges(e){if(!this.disposed)for(let t of e){let r=this.byNetId.get(t.netId);if(r?.listener)try{r.listener(t)}catch(i){console.error(`[NetworkNodeBinder] Listener for entity ${t.netId} threw:`,i)}if(t.kind==="leave"){this.releaseEntity(t.netId);continue}t.kind!=="enter"||r||this.inFlight.has(t.netId)||this.isLocallyOwned(t.netId)||(this.pending.add(t.netId),this.instantiateRemote(t.netId,t.entity.kind))}}releaseEntity(e){this.pending.delete(e);let t=this.byNetId.get(e);t&&(this.byNetId.delete(e),this.byNode.delete(t.node),t.remote&&(t.node.queueFree(),this.counters.remoteFreed+=1))}isLocallyOwned(e){let t=this.host.network;if(t.ownsEntity(e))return!0;let r=t.entities.get(e);return r!==void 0&&r.ownerId!==0&&r.ownerId===t.clientId}async instantiateRemote(e,t){if(this.host.isSceneRunning&&!this.host.isSceneRunning())return;let r=this.host.network.kinds.prefabPathOf(t);if(!r){this.pending.delete(e),this.counters.unknownKinds+=1;return}this.inFlight.add(e);let i;try{i=await this.host.instantiate(r,{instanceId:`net:${e}`})}catch(o){this.inFlight.delete(e),this.counters.instantiateFailures+=1,console.warn(`[NetworkNodeBinder] Could not instantiate "${r}":`,o);return}if(this.inFlight.delete(e),this.disposed||!this.host.network.entities.has(e)){i.queueFree(),this.pending.delete(e);return}this.adopt({netId:e,node:i,remote:!0,listener:null}),this.counters.remoteSpawned+=1}};var Vr=class{effectiveScale=1;blendedScale=1;blendFrom=1;blendTo=1;blendDurationSec=0;blendElapsedSec=0;autoRelease=!1;holdRemainingSec=1/0;releaseBlendSec=0;hitstopRemainingSec=0;hitstopWindowSec=0;frameIndex=0;lastHitstopFrame=-1;hitstopFrameStreak=0;warnedAboutHitstopStreak=!1;get scale(){return this.effectiveScale}get baseScale(){return Math.max(0,this.blendedScale)}get isFrozen(){return this.hitstopRemainingSec>0}hitstop(e){let t=Number.isFinite(e)?Math.max(0,e)/1e3:0;if(this.noteHitstopRequest(),!(t<=0)){if(this.hitstopRemainingSec>0){t>this.hitstopWindowSec&&(this.hitstopRemainingSec=t,this.hitstopWindowSec=t);return}this.hitstopRemainingSec=t,this.hitstopWindowSec=t}}slowMotion(e,t={}){let r=this.sanitizeScale(e,.3),i=this.sanitizeMs(t.blendMs,150)/1e3;this.startBlend(r,i),t.durationMs!=null&&Number.isFinite(t.durationMs)?(this.autoRelease=!0,this.holdRemainingSec=Math.max(0,t.durationMs)/1e3,this.releaseBlendSec=i):(this.autoRelease=!1,this.holdRemainingSec=1/0)}setScale(e){let t=this.sanitizeScale(e,1);this.blendedScale=t,this.blendFrom=t,this.blendTo=t,this.blendDurationSec=0,this.blendElapsedSec=0,this.autoRelease=!1,this.holdRemainingSec=1/0,this.updateEffective()}reset(){this.hitstopRemainingSec=0,this.hitstopWindowSec=0,this.lastHitstopFrame=-1,this.hitstopFrameStreak=0,this.setScale(1)}advance(e){let t=Number.isFinite(e)&&e>0?e:0;if(this.frameIndex+=1,this.hitstopRemainingSec>0&&(this.hitstopRemainingSec=Math.max(0,this.hitstopRemainingSec-t),this.hitstopRemainingSec===0&&(this.hitstopWindowSec=0)),this.blendElapsedSec<this.blendDurationSec){this.blendElapsedSec=Math.min(this.blendDurationSec,this.blendElapsedSec+t);let i=this.blendDurationSec>0?this.blendElapsedSec/this.blendDurationSec:1;this.blendedScale=this.blendFrom+(this.blendTo-this.blendFrom)*i}else this.blendedScale=this.blendTo;let r=this.blendElapsedSec>=this.blendDurationSec;this.autoRelease&&r&&this.blendTo!==1&&(this.holdRemainingSec-=t,this.holdRemainingSec<=0&&(this.autoRelease=!1,this.holdRemainingSec=1/0,this.startBlend(1,this.releaseBlendSec))),this.updateEffective()}noteHitstopRequest(){this.hitstopFrameStreak=this.lastHitstopFrame>=this.frameIndex-1?this.hitstopFrameStreak+1:1,this.lastHitstopFrame=this.frameIndex,this.hitstopFrameStreak>=30&&!this.warnedAboutHitstopStreak&&(this.warnedAboutHitstopStreak=!0,console.warn(`[GameTime] hitstop() has been called on ${this.hitstopFrameStreak} consecutive frames. Hitstop is edge-triggered juice: call it once when a contact BEGINS (a signal handler, or a "was overlapping last frame" guard), not every frame while an overlap lasts. Requests during a freeze are ignored, so the game runs slowly instead of freezing.`))}startBlend(e,t){this.blendFrom=this.blendedScale,this.blendTo=e,this.blendDurationSec=Math.max(0,t),this.blendElapsedSec=0,this.blendDurationSec===0&&(this.blendedScale=e),this.updateEffective()}updateEffective(){this.effectiveScale=this.hitstopRemainingSec>0?0:Math.max(0,this.blendedScale)}sanitizeScale(e,t){return!Number.isFinite(e)||e<0?t:e}sanitizeMs(e,t){return typeof e!="number"||!Number.isFinite(e)||e<0?t:e}};var PD=50,il=8,kD=32,hv=64,AD=200,pv=6,TD=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*(?:\.[a-z][a-z0-9]*(?:-[a-z0-9]+)*)*$/;function Zh(n,e,t,r){if(n===null)return null;let i=typeof n;if(i==="string"||i==="boolean")return null;if(i==="number")return Number.isFinite(n)?null:`${e} is ${String(n)}, which JSON cannot carry`;if(i==="undefined")return`${e} is undefined \u2014 use null for an absent value`;if(i!=="object")return`${e} is a ${i}, which is not JSON-serialisable`;let o=n;if(r.has(o))return`${e} is a circular reference`;if(t>pv)return`${e} nests deeper than ${pv} levels`;let s=Object.getPrototypeOf(o),a=s===Object.prototype||s===null;if(!Array.isArray(o)&&!a){let l=o.constructor?.name??"object";return`${e} is a ${l} instance \u2014 pass plain data, not live objects`}r.add(o);try{if(Array.isArray(o)){for(let l=0;l<o.length;l++){let c=Zh(o[l],`${e}[${l}]`,t+1,r);if(c)return c}return null}for(let[l,c]of Object.entries(o)){let u=Zh(c,`${e}.${l}`,t+1,r);if(u)return u}return null}finally{r.delete(o)}}var no=class{constructor(e=()=>0){this.frameProvider=e}commands=new Map;entries=[];undoStack=[];depth=0;dropped=0;register(e,t,r){let i=()=>{};if(typeof e!="string"||e.length===0||e.length>hv)return this.reject(String(e),`command names are 1..${hv} characters of kebab-case, optionally namespaced (e.g. "settings.toggle-music")`),i;if(!TD.test(e))return this.reject(e,`"${e}" is not a valid command name \u2014 use kebab-case, optionally namespaced with dots (e.g. "settings.toggle-music")`),i;if(typeof t!="function")return this.reject(e,`"${e}" was registered without a handler function`),i;if(this.commands.has(e))return this.reject(e,`"${e}" is already registered \u2014 command names are unique per scene`),i;let o={name:e,handler:t,meta:r};return this.commands.set(e,o),()=>{this.commands.get(e)===o&&this.commands.delete(e)}}dispatch(e,t){let r=this.commands.get(e);if(!r)return this.push({frame:this.frame(),name:String(e),status:"unknown",error:`no command named "${String(e)}" is registered`}),console.warn(`[commands] No command named "${String(e)}" is registered.`),!1;if(t!==void 0){let o=typeof t!="object"||t===null||Array.isArray(t)?"args must be a plain object of JSON values":Zh(t,"args",0,new Set);if(o)return this.reject(e,o),!1}if(this.depth>=il)return this.reject(e,`dispatch nested deeper than ${il} commands \u2014 a command is dispatching itself, directly or in a cycle`),!1;let i=this.push({frame:this.frame(),name:e,status:"ok",...this.describeArgs(t)});this.depth+=1;try{let o=r.handler(t);return o&&typeof o.undo=="function"&&(this.undoStack.push({name:e,undo:()=>o.undo()}),this.undoStack.length>kD&&this.undoStack.shift()),!0}catch(o){let{message:s,stack:a}=Nt(o);return i.status="error",i.error=s,console.error(`[commands] Command "${e}" failed:`,o),Dt({phase:"command",message:`command "${e}": ${s}`,stack:a}),!1}finally{this.depth-=1}}undo(){let e=this.undoStack.pop();if(!e)return this.reject("(undo)","nothing to undo \u2014 no dispatched command declared a reverse step"),!1;if(this.depth>=il)return this.reject(e.name,`undo nested deeper than ${il} commands`),!1;let t=this.push({frame:this.frame(),name:e.name,status:"undo"});this.depth+=1;try{return e.undo(),!0}catch(r){let{message:i,stack:o}=Nt(r);return t.status="error",t.error=i,console.error(`[commands] Undo of "${e.name}" failed:`,r),Dt({phase:"command",message:`undo of command "${e.name}": ${i}`,stack:o}),!1}finally{this.depth-=1}}list(){return[...this.commands.values()].map(e=>({name:e.name,...e.meta?.description?{description:e.meta.description}:{},...e.meta?.params?{params:e.meta.params}:{},undoable:e.meta?.undoable===!0})).sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}get log(){return this.entries}get droppedLogEntries(){return this.dropped}get canUndo(){return this.undoStack.length>0}clear(){this.commands.clear(),this.entries.length=0,this.undoStack.length=0,this.depth=0,this.dropped=0}frame(){let e=this.frameProvider();return Number.isFinite(e)?e:0}reject(e,t){this.push({frame:this.frame(),name:e,status:"rejected",error:t}),console.error(`[commands] ${t}`)}describeArgs(e){if(e===void 0)return{};let t=JSON.stringify(e);return t===void 0||t.length>AD?{argsOmitted:!0}:{args:JSON.parse(t)}}push(e){for(this.entries.push(e);this.entries.length>PD;)this.entries.shift(),this.dropped+=1;return e}};var Zt=class n extends O{active=!1;elapsed=0;baseScale=new S(1,1,1);onTriggerSignal=()=>{this.trigger()};constructor(e,t){super(e,t),this.config={amount:.3,duration:.35,vibrato:3,triggerEvent:"",playOnStart:!1}}static getPropertySchema(){return{nodeType:"PunchScaleBehavior",properties:[{name:"amount",type:"number",ui:{label:"Amount",description:"Peak scale delta (0.3 = +30%)",group:"Punch Scale",min:0,step:.05,precision:2},getValue:e=>e.getAmount(),setValue:(e,t)=>{e.config.amount=n.num(t,.3,0)}},{name:"duration",type:"number",ui:{label:"Duration",group:"Punch Scale",min:0,step:.05,precision:2,unit:"s"},getValue:e=>e.getDuration(),setValue:(e,t)=>{e.config.duration=n.num(t,.35,0)}},{name:"vibrato",type:"number",ui:{label:"Vibrato",description:"Oscillations before settling",group:"Punch Scale",min:0,step:1},getValue:e=>e.getVibrato(),setValue:(e,t)=>{e.config.vibrato=n.num(t,3,0)}},{name:"triggerEvent",type:"string",ui:{label:"Trigger Event",description:"Node signal that triggers the punch (empty = manual/API only)",group:"Punch Scale"},getValue:e=>e.getTriggerEvent(),setValue:(e,t)=>{e.setTriggerEvent(t)}},{name:"playOnStart",type:"boolean",ui:{label:"Play On Start",group:"Punch Scale"},getValue:e=>!!e.config.playOnStart,setValue:(e,t)=>{e.config.playOnStart=!!t}}],groups:{"Punch Scale":{label:"Punch Scale",expanded:!0}}}}onStart(){this.bindTrigger(),this.config.playOnStart&&this.trigger()}onDetach(){this.unbindTrigger(),this.restore(),this.active=!1,super.onDetach()}play(e={}){e.amount!=null&&(this.config.amount=n.num(e.amount,.3,0)),e.duration!=null&&(this.config.duration=n.num(e.duration,.35,0)),e.vibrato!=null&&(this.config.vibrato=n.num(e.vibrato,3,0)),this.trigger()}trigger(){this.node&&(this.active||this.baseScale.copy(this.node.scale),this.elapsed=0,this.active=!0)}onUpdate(e){if(!this.active||!this.node)return;this.elapsed+=e;let t=this.getDuration();if(t<=0||this.elapsed>=t){this.node.scale.copy(this.baseScale),this.active=!1;return}let r=this.elapsed/t,i=Math.pow(1-r,2),o=Math.cos(r*this.getVibrato()*Math.PI*2),s=1+this.getAmount()*i*o;this.node.scale.set(this.baseScale.x*s,this.baseScale.y*s,this.baseScale.z*s)}restore(){this.node&&this.active&&this.node.scale.copy(this.baseScale)}bindTrigger(){let e=this.getTriggerEvent();this.node&&e&&this.node.connect(e,this,this.onTriggerSignal)}unbindTrigger(){let e=this.getTriggerEvent();this.node&&e&&this.node.disconnect(e,this,this.onTriggerSignal)}getAmount(){return n.num(this.config.amount,.3,0)}getDuration(){return n.num(this.config.duration,.35,0)}getVibrato(){return n.num(this.config.vibrato,3,0)}getTriggerEvent(){return typeof this.config.triggerEvent=="string"?this.config.triggerEvent.trim():""}setTriggerEvent(e){let t=!!this.node;t&&this.unbindTrigger(),this.config.triggerEvent=typeof e=="string"?e.trim():"",t&&this.bindTrigger()}static num(e,t,r){let i=typeof e=="number"?e:Number(e);return Number.isFinite(i)?Math.max(r,i):t}};var ep="backOut",er=class n extends O{active=!1;elapsed=0;captured=!1;baseScale=new S(1,1,1);onTriggerSignal=()=>{this.trigger()};constructor(e,t){super(e,t),this.config={from:0,duration:.4,easing:ep,triggerEvent:"",playOnStart:!0}}static getPropertySchema(){return{nodeType:"PopInBehavior",properties:[{name:"from",type:"number",ui:{label:"From Scale",description:"Starting fraction of the authored scale",group:"Pop In",min:0,step:.05,precision:2},getValue:e=>e.getFrom(),setValue:(e,t)=>{e.config.from=n.num(t,0,0)}},{name:"duration",type:"number",ui:{label:"Duration",group:"Pop In",min:0,step:.05,precision:2,unit:"s"},getValue:e=>e.getDuration(),setValue:(e,t)=>{e.config.duration=n.num(t,.4,0)}},{name:"easing",type:"select",ui:{label:"Easing",group:"Pop In",options:["backOut","elasticOut","bounceOut","cubicOut","quadOut","linear"]},getValue:e=>e.getEasing(),setValue:(e,t)=>{e.config.easing=_e(t)?t:ep}},{name:"triggerEvent",type:"string",ui:{label:"Trigger Event",description:"Node signal that triggers the pop (empty = manual/API only)",group:"Pop In"},getValue:e=>e.getTriggerEvent(),setValue:(e,t)=>{e.setTriggerEvent(t)}},{name:"playOnStart",type:"boolean",ui:{label:"Play On Start",group:"Pop In"},getValue:e=>!!e.config.playOnStart,setValue:(e,t)=>{e.config.playOnStart=!!t}}],groups:{"Pop In":{label:"Pop In",expanded:!0}}}}onStart(){this.captureBase(),this.bindTrigger(),this.config.playOnStart&&this.trigger()}onDetach(){this.unbindTrigger(),this.node&&this.captured&&this.node.scale.copy(this.baseScale),this.active=!1,super.onDetach()}play(e={}){e.from!=null&&(this.config.from=n.num(e.from,0,0)),e.duration!=null&&(this.config.duration=n.num(e.duration,.4,0)),e.easing!=null&&_e(e.easing)&&(this.config.easing=e.easing),this.trigger()}trigger(){if(!this.node)return;this.captureBase(),this.elapsed=0,this.active=!0;let e=this.getFrom();this.node.scale.set(this.baseScale.x*e,this.baseScale.y*e,this.baseScale.z*e)}onUpdate(e){if(!this.active||!this.node)return;this.elapsed+=e;let t=this.getDuration(),r=t>0?Math.min(this.elapsed/t,1):1,i=this.getFrom(),o=i+(1-i)*St(this.getEasing(),r);this.node.scale.set(this.baseScale.x*o,this.baseScale.y*o,this.baseScale.z*o),r>=1&&(this.node.scale.copy(this.baseScale),this.active=!1)}captureBase(){!this.node||this.captured||(this.baseScale.copy(this.node.scale),this.captured=!0)}bindTrigger(){let e=this.getTriggerEvent();this.node&&e&&this.node.connect(e,this,this.onTriggerSignal)}unbindTrigger(){let e=this.getTriggerEvent();this.node&&e&&this.node.disconnect(e,this,this.onTriggerSignal)}getFrom(){return n.num(this.config.from,0,0)}getDuration(){return n.num(this.config.duration,.4,0)}getEasing(){return _e(this.config.easing)?this.config.easing:ep}getTriggerEvent(){return typeof this.config.triggerEvent=="string"?this.config.triggerEvent.trim():""}setTriggerEvent(e){let t=!!this.node;t&&this.unbindTrigger(),this.config.triggerEvent=typeof e=="string"?e.trim():"",t&&this.bindTrigger()}static num(e,t,r){let i=typeof e=="number"?e:Number(e);return Number.isFinite(i)?Math.max(r,i):t}};var Or={count:14,speed:260,spread:Math.PI*2,direction:Math.PI/2,lifeSec:.5,sizePx:10,gravityY:-600},yv=512,nl={fontSizePx:28,driftPx:60,durationSec:.8,glowStrength:1.5},mv=.22,tp=.45,CD=[[-.5,.5],[.5,.5],[-.5,-.5],[.5,-.5]],fv=[[0,1],[1,1],[0,0],[1,0]],gv=[0,1,2,2,1,3],ol;function MD(){return ol!==void 0||(ol=DD()),ol}function DD(){if(typeof document>"u")return null;try{let e=document.createElement("canvas");e.width=64,e.height=64;let t=e.getContext("2d");if(!t||typeof t.createRadialGradient!="function")return null;let r=64/2,i=t.createRadialGradient(r,r,0,r,r,r);i.addColorStop(0,"rgba(255,255,255,1)"),i.addColorStop(.4,"rgba(255,255,255,0.9)"),i.addColorStop(1,"rgba(255,255,255,0)"),t.fillStyle=i,t.fillRect(0,0,64,64);let o=new Mt(e);return Y(o),o}catch{return null}}function Re(n,e,t,r){let i=typeof n=="number"?n:Number(n);return Number.isFinite(i)?Math.min(r,Math.max(t,i)):e}function ND(n){let t=(Array.isArray(n.colors)?n.colors:[]).filter(r=>typeof r=="string"&&!!r.trim());return t.length===0&&typeof n.color=="string"&&n.color.trim()&&t.push(n.color),t.length===0&&t.push("#ffffff"),t.map(r=>{try{return new L(r)}catch{return new L("#ffffff")}})}var oo=class extends M{particles=[];geometry;positionAttribute;colorAttribute;gravityY;fadeOut;aliveParticles;constructor(e,t={}){super(e,"ParticleBurst2D"),this.isContainer=!1;let r=Math.round(Re(t.count,Or.count,1,yv)),i=Re(t.speed,Or.speed,0,2e4),o=Re(t.spread,Or.spread,0,Math.PI*2),s=Re(t.direction,Or.direction,-1e6,1e6),a=Re(t.lifeSec,Or.lifeSec,.05,10),l=Re(t.sizePx,Or.sizePx,.5,1024);this.gravityY=Re(t.gravityY,Or.gravityY,-1e5,1e5),this.fadeOut=t.fadeOut!==!1,t.zIndex!==void 0&&(this.zIndex=Re(t.zIndex,0,-4096,4096));let c=ND(t);this.geometry=new le,this.positionAttribute=new J(new Float32Array(r*4*3),3),this.colorAttribute=new J(new Float32Array(r*4*4),4);let u=new J(new Float32Array(r*4*2),2),d=new Uint16Array(r*6);for(let f=0;f<r;f++){let m=s+(Math.random()-.5)*o,g=i*(.55+Math.random()*.45),y={x:0,y:0,vx:Math.cos(m)*g,vy:Math.sin(m)*g,age:0,life:a*(.7+Math.random()*.6),size:l*(.7+Math.random()*.6)};this.particles.push(y);let b=c[Math.floor(Math.random()*c.length)]??c[0];for(let v=0;v<4;v++){let w=f*4+v;u.setXY(w,fv[v][0],fv[v][1]),this.colorAttribute.setXYZW(w,b.r,b.g,b.b,1)}for(let v=0;v<gv.length;v++)d[f*6+v]=f*4+gv[v];this.writeQuad(f,y.x,y.y,y.size)}this.geometry.setAttribute("position",this.positionAttribute),this.geometry.setAttribute("uv",u),this.geometry.setAttribute("color",this.colorAttribute),this.geometry.setIndex(new qo(d,1)),this.aliveParticles=r;let h=new R({map:MD(),transparent:!0,depthTest:!1,depthWrite:!1,vertexColors:!0,blending:t.additive===!1?st:at});this.registerOpacityMaterial(h,1);let p=new B(this.geometry,h);p.frustumCulled=!1,p.userData[Fe]=!0,this.add(p)}get particleCount(){return this.particles.length}get aliveCount(){return this.aliveParticles}tick(e){if(super.tick(e),this.aliveParticles===0)return;let t=Math.max(0,e),r=0;for(let i=0;i<this.particles.length;i++){let o=this.particles[i];if(o.age>=o.life)continue;o.age+=t;let s=o.age/o.life;if(s>=1){this.writeQuad(i,o.x,o.y,0),this.writeAlpha(i,0);continue}o.vy+=this.gravityY*t,o.x+=o.vx*t,o.y+=o.vy*t,this.writeQuad(i,o.x,o.y,o.size*(1-.6*s)),this.writeAlpha(i,this.fadeOut?1-s*s:1),r++}this.positionAttribute.needsUpdate=!0,this.colorAttribute.needsUpdate=!0,this.aliveParticles=r,r===0&&this.queueFree()}writeQuad(e,t,r,i){for(let o=0;o<4;o++){let[s,a]=CD[o];this.positionAttribute.setXYZ(e*4+o,t+s*i,r+a*i,0)}}writeAlpha(e,t){let r=this.colorAttribute.array;for(let i=0;i<4;i++)r[(e*4+i)*4+3]=t}};function ED(n){return 1-Math.pow(1-n,3)}function ID(n){return 1+2.70158*Math.pow(n-1,3)+1.70158*Math.pow(n-1,2)}var so=class extends ft{totalDuration;driftPx;elapsed=0;captured=!1;baseY=0;baseScaleX=1;baseScaleY=1;finished=!1;constructor(e,t,r={}){let i=typeof r.color=="string"&&r.color.trim()?r.color:"#ffffff",o=r.glow===!0?i:typeof r.glow=="string"&&r.glow.trim()?r.glow:"";super({...e,label:t,labelColor:i,labelFontFamily:typeof r.fontFamily=="string"&&r.fontFamily.trim()?r.fontFamily:"Arial",labelFontSize:Re(r.fontSizePx,nl.fontSizePx,1,512),glowColor:o||void 0,glowStrength:o?Re(r.glowStrength,nl.glowStrength,0,4):0,zIndex:r.zIndex}),this.isContainer=!1,this.totalDuration=Re(r.durationSec,nl.durationSec,.05,30),this.driftPx=Re(r.driftPx,nl.driftPx,-1e4,1e4)}isPointInBounds(){return!1}tick(e){if(super.tick(e),this.finished)return;this.captured||(this.baseY=this.position.y,this.baseScaleX=this.scale.x,this.baseScaleY=this.scale.y,this.captured=!0),this.elapsed+=Math.max(0,e);let t=Math.min(1,this.elapsed/this.totalDuration);this.position.y=this.baseY+this.driftPx*ED(t);let r=t<mv?ID(t/mv):1;this.scale.set(this.baseScaleX*r,this.baseScaleY*r,1),this.opacity=t<tp?1:Math.max(0,1-(t-tp)/(1-tp)),t>=1&&(this.finished=!0,this.queueFree())}};var rp={lifeSec:.35,widthPx:14,maxPoints:48},bv=256,RD=1e-4;function sl(n,e,t,r){let i=typeof n=="number"?n:Number(n);return Number.isFinite(i)?Math.min(r,Math.max(t,i)):e}function BD(n){let t=(Array.isArray(n.colors)?n.colors:Array.isArray(n.color)?n.color:typeof n.color=="string"?[n.color]:[]).filter(r=>typeof r=="string"&&r.trim().length>0);return t.length===0&&t.push("#ffffff"),t.map(r=>{try{return new L(r)}catch{return new L("#ffffff")}})}var ao=class extends M{points=[];geometry;positionAttribute;colorAttribute;palette;lifeSec;halfWidth;maxPoints;scratchWorld=new S;scratchColor=new L;target;following=!0;freed=!1;constructor(e,t,r={}){super(e,"Trail2D"),this.isContainer=!1,this.target=t,this.lifeSec=sl(r.lifeSec,rp.lifeSec,.02,10),this.halfWidth=sl(r.widthPx,rp.widthPx,.1,4096)/2,this.maxPoints=Math.round(sl(r.maxPoints,rp.maxPoints,2,bv)),this.palette=BD(r),r.zIndex!==void 0&&(this.zIndex=sl(r.zIndex,0,-4096,4096)),this.geometry=new le,this.positionAttribute=new J(new Float32Array(this.maxPoints*2*3),3),this.colorAttribute=new J(new Float32Array(this.maxPoints*2*4),4);let i=new Uint16Array((this.maxPoints-1)*6);for(let a=0;a<this.maxPoints-1;a++){let l=a*2,c=a*6;i[c]=l,i[c+1]=l+1,i[c+2]=l+2,i[c+3]=l+2,i[c+4]=l+1,i[c+5]=l+3}this.geometry.setAttribute("position",this.positionAttribute),this.geometry.setAttribute("color",this.colorAttribute),this.geometry.setIndex(new qo(i,1)),this.geometry.setDrawRange(0,0);let o=new R({transparent:!0,depthTest:!1,depthWrite:!1,vertexColors:!0,side:xe,blending:r.additive===!1?st:at});this.registerOpacityMaterial(o,1);let s=new B(this.geometry,o);s.frustumCulled=!1,s.userData[Fe]=!0,this.add(s)}get pointCount(){return this.points.length}get isFollowing(){return this.following}stop(){this.following=!1,this.target=null}tick(e){if(super.tick(e),this.freed)return;let t=Math.max(0,e);for(let i of this.points)i.age+=t;for(;this.points.length>0&&this.points[this.points.length-1].age>=this.lifeSec;)this.points.pop();let r=this.target;r&&r.isDisposed?this.stop():r&&this.following&&this.sample(r),this.rebuild(),!this.following&&this.points.length===0&&(this.freed=!0,this.queueFree())}sample(e){e.updateWorldMatrix(!0,!1),e.getWorldPosition(this.scratchWorld),this.updateWorldMatrix(!0,!1);let t=this.worldToLocal(this.scratchWorld);for(this.points.unshift({x:t.x,y:t.y,age:0});this.points.length>this.maxPoints;)this.points.pop()}rebuild(){let e=this.points.length;if(e<2){this.geometry.setDrawRange(0,0);return}let t=0,r=1;for(let i=0;i<e;i++){let o=this.points[i],s=this.points[i-1]??o,a=this.points[i+1]??o,l=s.x-a.x,c=s.y-a.y,u=Math.hypot(l,c);u>RD&&(t=-c/u,r=l/u);let d=e>1?i/(e-1):0,h=1-d,p=this.halfWidth*h,f=Math.max(0,1-o.age/this.lifeSec)*h;this.sampleRamp(d);let m=i*2;this.positionAttribute.setXYZ(m,o.x+t*p,o.y+r*p,0),this.positionAttribute.setXYZ(m+1,o.x-t*p,o.y-r*p,0),this.colorAttribute.setXYZW(m,this.scratchColor.r,this.scratchColor.g,this.scratchColor.b,f),this.colorAttribute.setXYZW(m+1,this.scratchColor.r,this.scratchColor.g,this.scratchColor.b,f)}this.positionAttribute.needsUpdate=!0,this.colorAttribute.needsUpdate=!0,this.geometry.setDrawRange(0,(e-1)*6)}sampleRamp(e){let t=this.palette;if(t.length===1){this.scratchColor.copy(t[0]);return}let r=e*(t.length-1),i=Math.min(t.length-2,Math.floor(r));this.scratchColor.copy(t[i]).lerp(t[i+1],r-i)}};function Sv(n){return typeof n=="object"&&n!==null&&typeof n.x=="number"&&typeof n.y=="number"&&!(n instanceof V)}var lo=class{constructor(e){this.scene=e}transientCounter=0;warned=new Set;shake(e,t={}){if(typeof e=="string"){let o=e.toLowerCase();if(o==="camera2d"){let s=this.scene.getActiveCamera2D();return s?(s.shake(t),null):(this.warnOnce("camera2d","juice.shake('camera2d') found no active Camera2D \u2014 nothing shook. Add a Camera2D to the scene, or shake a node instead."),null)}if(o==="camera"&&!this.scene.getActiveCamera()){let s=this.scene.getActiveCamera2D();if(s)return s.shake(t),null}}let r=this.resolveNode(e);if(!r)return null;let i=r.getComponent(Bt);return i||(i=new Bt("core:Shake","core:Shake"),i.config.playOnStart=!1,i.config.triggerEvent="",r.addComponent(i)),i.play(t),i}punchScale(e,t={}){let r=this.resolveNode(e);if(!r)return null;let i=r.getComponent(Zt);return i||(i=new Zt("core:PunchScale","core:PunchScale"),i.config.playOnStart=!1,i.config.triggerEvent="",r.addComponent(i)),i.play(t),i}popIn(e,t={}){let r=this.resolveNode(e);if(!r)return null;let i=r.getComponent(er);return i||(i=new er("core:PopIn","core:PopIn"),i.config.playOnStart=!1,i.config.triggerEvent="",r.addComponent(i)),i.play(t),i}flash(e={}){this.scene.flash(e)}burst(e,t={}){let r=this.resolveAnchorNode(e,"burst");if(r===void 0)return null;let i=this.resolve2DHost(r);if(!i)return console.warn("[JuiceApi] burst: the scene has no 2D node to host the effect."),null;let o=new oo({id:this.nextTransientId("burst"),name:"JuiceBurst"},t);i.adoptChild(o);let s=this.resolveHostLocalPoint(i,r,e);return o.position.set(s.x,s.y,0),o}floatText(e,t={}){let r=typeof e=="string"?e:String(e??"");if(r.length===0)return null;let i=t.at===void 0?null:this.resolveAnchorNode(t.at,"floatText");if(i===void 0)return null;let o=this.resolve2DHost(i);if(!o)return console.warn("[JuiceApi] floatText: the scene has no 2D node to host the popup."),null;let s=new so({id:this.nextTransientId("float-text"),name:"JuiceFloatText"},r,t);if(o.adoptChild(s),t.at!==void 0){let a=this.resolveHostLocalPoint(o,i,t.at);s.position.set(a.x,a.y,0)}return s}trail(e,t={}){let r=this.resolveNode(e);if(!r)return null;let i=this.resolve2DHost(r);if(!i)return console.warn("[JuiceApi] trail: the scene has no 2D node to host the ribbon."),null;let o=new ao({id:this.nextTransientId("trail"),name:"JuiceTrail"},r,t);return i.adoptChild(o),o}resolveAnchorNode(e,t){if(Sv(e))return null;let r=this.resolveNode(e);if(!r){console.warn(`[JuiceApi] ${t}: target "${String(e)}" not found.`);return}return r}resolve2DHost(e){if(e){let i=null,o=e;for(;o;)o instanceof M&&(i=o),o=o.parent;if(i)return i}let t=null,r=null;for(let i of this.scene.getRootNodes())i instanceof M&&(r=i,i.isCanvasLayer||(t=i));return t??r}resolveHostLocalPoint(e,t,r){let i=new S;return t?(t.updateWorldMatrix(!0,!1),t.getWorldPosition(i)):Sv(r)&&i.set(r.x,r.y,0),e.updateWorldMatrix(!0,!1),e.worldToLocal(i)}nextTransientId(e){return this.transientCounter+=1,`juice:${e}:${this.transientCounter}`}resolveNode(e){if(e instanceof V)return e;if(typeof e=="string"){let t=e.toLowerCase()==="camera"?this.scene.getActiveCamera():this.scene.findNode(e);return t||this.warnOnce(e,`juice: no node named "${e}" \u2014 the effect did nothing.`),t}return null}warnOnce(e,t){this.warned.has(e)||(this.warned.add(e),console.warn(`[Juice] ${t}`))}};var al=.3,VD="cubicOut",OD={x:"position.x",y:"position.y",rotation:"rotation.z"},LD=1024,FD=1e-6;function tr(n){return typeof n=="number"&&Number.isFinite(n)}function _D(n){return typeof n=="object"&&n!==null}function zD(n,e){let t=e.split(".").filter(i=>i.length>0);if(t.length===0)return null;let r=n;for(let i=0;i<t.length-1;i++){if(typeof r!="object"||r===null)return null;r=r[t[i]]}return typeof r!="object"||r===null?null:{owner:r,key:t[t.length-1]}}function ip(n){return{cancel:()=>{},finished:Promise.resolve(n),isRunning:!1}}var np=class{constructor(e,t,r,i){this.target=e;this.props=t;this.warn=i;let o=tr(r.durationSec)?r.durationSec:al;this.duration=Math.max(0,o),this.ease=r.ease??VD,this.yoyo=r.yoyo===!0;let s=tr(r.repeat)?Math.trunc(r.repeat):0;this.totalIterations=s<0?Number.POSITIVE_INFINITY:Math.max(0,s)+1,this.delayRemaining=tr(r.delaySec)?Math.max(0,r.delaySec):0,this.onUpdate=r.onUpdate,this.onComplete=r.onComplete,this.finished=new Promise(a=>{this.resolveFinished=a})}finished;resolveFinished;duration;ease;yoyo;totalIterations;onUpdate;onComplete;channels=[];delayRemaining;elapsed=0;iteration=0;captured=!1;running=!0;get isRunning(){return this.running}cancel(){this.end("cancelled")}advance(e){if(!this.running)return!1;if(this.target instanceof V&&this.target.isDisposed)return this.end("cancelled"),!1;let t=Math.max(0,e);if(this.delayRemaining>0){let c=Math.min(this.delayRemaining,t);if(this.delayRemaining-=c,t-=c,this.delayRemaining>0)return!0}if(!this.captured&&(this.captureChannels(),this.captured=!0,this.channels.length===0))return this.end("completed"),!1;if(this.elapsed+=t,this.duration<=0)return this.applyProgress(1),this.end("completed"),!1;let r=this.duration-FD,i=0;for(;this.elapsed>=r&&this.iteration+1<this.totalIterations&&i<LD;)this.elapsed-=this.duration,this.iteration+=1,i+=1;let o=this.elapsed>=r&&this.iteration+1>=this.totalIterations,s=o?1:Math.min(1,Math.max(0,this.elapsed/this.duration)),l=this.yoyo&&this.iteration%2===1?1-s:s;return this.applyProgress(l),this.onUpdate?.(l),o?(this.end("completed"),!1):!0}applyProgress(e){let t=St(this.ease,e);for(let r of this.channels)r.owner[r.key]=r.from+(r.to-r.from)*t}end(e){this.running&&(this.running=!1,e==="completed"&&this.onComplete?.(),this.resolveFinished(e))}captureChannels(){let e=this.target instanceof V;for(let[t,r]of Object.entries(this.props))if(r!=null){if(e&&t==="scale"&&tr(r)){this.addChannel("scale.x",r),this.addChannel("scale.y",r);continue}if(tr(r)){this.addChannel(e?OD[t]??t:t,r);continue}if(_D(r))for(let i of["x","y","z"]){let o=r[i];tr(o)&&this.addChannel(`${t}.${i}`,o)}}}addChannel(e,t){let r=zD(this.target,e);if(!r){this.warn(e,`tween: "${e}" is not a property path on the target \u2014 skipped.`);return}let i=r.owner[r.key];if(!tr(i)){this.warn(e,`tween: "${e}" is not a finite number on the target (got ${typeof i}) \u2014 skipped.`);return}this.channels.push({owner:r.owner,key:r.key,from:i,to:t})}},op=class{constructor(e){this.parts=e;this.finished=Promise.all(e.map(t=>t.finished)).then(t=>t.some(r=>r==="cancelled")?"cancelled":"completed")}finished;cancel(){for(let e of this.parts)e.cancel()}get isRunning(){return this.parts.some(e=>e.isRunning)}};function vv(n){return tr(n.opacity)}var co=class{constructor(e){this.scene=e}active=new Set;warned=new Set;get activeCount(){return this.active.size}to(e,t,r={}){let i=this.resolveTarget(e);if(!i)return ip("cancelled");let o=new np(i,t,r,(s,a)=>this.warnOnce(s,a));return this.active.add(o),o}fadeIn(e,t=al){let r=this.resolveTarget(e);if(!r||!vv(r))return this.warnOpacityless(e,"fadeIn"),ip("cancelled");let i=r.opacity>0?r.opacity:1;return r.visible=!0,r.opacity=0,this.to(r,{opacity:i},{durationSec:t,ease:"quadOut"})}fadeOut(e,t=al,r={}){let i=this.resolveTarget(e);if(!i||!vv(i))return this.warnOpacityless(e,"fadeOut"),ip("cancelled");let o=r.hide!==!1;return this.to(i,{opacity:0},{durationSec:t,ease:"quadIn",onComplete:o?()=>{i.visible=!1}:void 0})}crossFade(e,t,r=al){return new op([this.fadeOut(e,r),this.fadeIn(t,r)])}killAll(e){if(e===void 0){for(let r of[...this.active])r.cancel();this.active.clear();return}let t=this.resolveTarget(e);if(t)for(let r of[...this.active])r.target===t&&(r.cancel(),this.active.delete(r))}update(e){if(this.active.size!==0)for(let t of[...this.active])t.advance(e)||this.active.delete(t)}cancelAll(){for(let e of[...this.active])e.cancel();this.active.clear(),this.warned.clear()}resolveTarget(e){if(e instanceof V)return e;if(typeof e=="string"){let t=this.scene.findNode(e);return t||(this.warnOnce(e,`tween: no node named "${e}" \u2014 the tween did nothing.`),null)}return typeof e=="object"&&e!==null?e:null}warnOpacityless(e,t){typeof e!="string"&&this.warnOnce(`${t}:no-opacity`,`tween.${t}: the target has no \`opacity\` \u2014 nothing faded.`)}warnOnce(e,t){this.warned.has(e)||(this.warned.add(e),console.warn(`[Tween] ${t}`))}};var ll=["tap","score","bounce","explosion","powerup","win","lose","laser","tick"],UD={tap:[{wave:"sine",freq:880,freqEnd:620,duration:.09,decay:3,gain:.7},{wave:"square",freq:1320,duration:.035,decay:4,gain:.15}],tick:[{wave:"square",freq:2200,freqEnd:1700,duration:.035,decay:5,gain:.35}],bounce:[{wave:"sine",freq:420,freqEnd:140,duration:.18,decay:2.5,gain:.9},{wave:"triangle",freq:840,freqEnd:280,duration:.1,decay:3,gain:.3}],score:[{wave:"square",freq:880,duration:.08,decay:2.5,gain:.35},{wave:"square",freq:1174,start:.06,duration:.08,decay:2.5,gain:.35},{wave:"triangle",freq:1568,start:.12,duration:.18,decay:2,gain:.45}],powerup:[{wave:"square",freq:440,freqEnd:1760,duration:.3,decay:1.2,gain:.35},{wave:"sine",freq:880,freqEnd:3520,duration:.3,decay:1.6,gain:.25}],laser:[{wave:"saw",freq:1800,freqEnd:180,duration:.22,decay:2,gain:.45},{wave:"square",freq:900,freqEnd:90,duration:.22,decay:2.5,gain:.18}],explosion:[{wave:"noise",duration:.55,decay:1.6,gain:.9,lowpassHz:900,attack:.002},{wave:"noise",duration:.12,decay:3,gain:.45,lowpassHz:3500,attack:.001},{wave:"sine",freq:120,freqEnd:40,duration:.45,decay:2,gain:.6}],win:[{wave:"triangle",freq:523,duration:.22,decay:2,gain:.4},{wave:"triangle",freq:659,start:.1,duration:.22,decay:2,gain:.4},{wave:"triangle",freq:784,start:.2,duration:.24,decay:2,gain:.4},{wave:"square",freq:1046,start:.3,duration:.34,decay:1.6,gain:.3}],lose:[{wave:"square",freq:392,duration:.22,decay:2,gain:.3},{wave:"square",freq:311,start:.12,duration:.22,decay:2,gain:.3},{wave:"square",freq:233,start:.24,duration:.3,decay:1.8,gain:.3},{wave:"sine",freq:160,freqEnd:60,start:.24,duration:.4,decay:1.6,gain:.5}]},WD=.02,GD=64,wv=.9;function Mi(n){return typeof n=="string"&&ll.includes(n)}function Lr(n){let e=typeof n=="number"?n:Number(n);return!Number.isFinite(e)||e<=0?1:Math.min(4,Math.max(.25,e))}var uo=class{cache=new Map;get size(){return this.cache.size}getBuffer(e,t,r=1){let i=e.getSampleRate();if(!i||!Number.isFinite(i)||i<=0)return null;let o=Lr(r),s=`${t}|${o.toFixed(2)}|${Math.round(i)}`,a=this.cache.get(s);if(a)return a;let l=null;try{l=this.render(e,t,o,i)}catch(c){return console.warn(`[SfxSynth] Failed to render preset "${t}":`,c),null}if(!l)return null;if(this.cache.size>=GD){let c=this.cache.keys().next();c.done||this.cache.delete(c.value)}return this.cache.set(s,l),l}clear(){this.cache.clear()}render(e,t,r,i){let o=UD[t],s=0;for(let d of o)s=Math.max(s,(d.start??0)+d.duration);let a=Math.max(1,Math.ceil((s+WD)*i)),l=e.createBuffer(a,1);if(!l)return null;let c=l.getChannelData(0);c.fill(0);for(let d of o)qD(c,d,r,i);let u=0;for(let d=0;d<c.length;d++){let h=Math.abs(c[d]);h>u&&(u=h)}if(u>wv){let d=wv/u;for(let h=0;h<c.length;h++)c[h]*=d}return l}};function qD(n,e,t,r){let i=Math.max(0,Math.floor((e.start??0)*r)),o=Math.max(1,Math.floor(e.duration*r)),s=e.gain??.7,a=Math.max(1/r,e.attack??.004),l=e.decay??2,c=Math.max(1,(e.freq??440)*t),d=Math.max(1,(e.freqEnd??e.freq??440)*t)/c,h=e.lowpassHz?e.lowpassHz*t:0,p=h>0?1-Math.exp(-2*Math.PI*h/r):1,f=0,m=0;for(let g=0;g<o;g++){let y=i+g;if(y>=n.length)break;let b=g/r,v=g/o,w;if(e.wave==="noise"){let T=Math.random()*2-1;f+=p*(T-f),w=f}else{let T=c*Math.pow(d,v);m+=2*Math.PI*T/r,w=HD(e.wave,m)}let k=Math.min(1,b/a)*Math.pow(Math.max(0,1-v),Math.max(.1,l));n[y]+=w*k*s}}function HD(n,e){switch(n){case"sine":return Math.sin(e);case"square":return Math.sin(e)>=0?1:-1;case"saw":{let t=e/(Math.PI*2)%1;return 2*(t<0?t+1:t)-1}case"triangle":{let t=e/(Math.PI*2)%1,r=t<0?t+1:t;return 2*Math.abs(2*r-1)-1}}}var ho=class{constructor(e){this.scene=e}sfxSynth=null;async play(e,t={}){let r=this.scene.getAssetLoader();if(!r||!this.scene.getAudioService())return null;let i=await r.loadAudio(e),o=this.scene.getAudioService();return o?o.play(i,{...t,resourcePath:e,sizeBytes:r.getAudioMetadata(e)?.sizeBytes}):null}sfx(e,t={}){let r=this.scene.getAudioService();if(!r)return null;if(!Mi(e))return console.warn(`[AudioApi] sfx: unknown preset "${String(e)}".`),null;let i=Lr(t.pitch);this.sfxSynth??=new uo;let o=this.sfxSynth.getBuffer(r,e,i);if(!o)return null;let s=typeof t.volume=="number"?t.volume:1;return r.play(o,{bus:"sfx",label:`sfx:${e}`,volume:Math.min(1,Math.max(0,Number.isFinite(s)?s:1))})}setBusVolume(e,t,r){this.scene.getAudioService()?.setBusVolume(e,t,r)}getBusVolume(e){return this.scene.getAudioService()?.getBusVolume(e)??1}applySnapshot(e,t){this.scene.getAudioService()?.applySnapshot(e,t)}resetSnapshot(e){this.scene.getAudioService()?.resetSnapshot(e)}registerSnapshot(e){this.scene.getAudioService()?.registerSnapshot(e)}getActiveSnapshotName(){return this.scene.getAudioService()?.getActiveSnapshotName()??"default"}stopAll(){this.scene.getAudioService()?.stopAll()}};function At(n,e,t){return n+(e-n)*t}function xv(n){let e=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.exec(n.trim());if(!e)return null;let t=e[1];return t.length===3&&(t=t.split("").map(r=>r+r).join("")),[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]}function jD(n,e,t){let r=o=>Math.min(255,Math.max(0,Math.round(o))),i=o=>r(o).toString(16).padStart(2,"0");return`#${i(n)}${i(e)}${i(t)}`}function Pv(n,e,t,r){switch(n){case"number":return At(e,t,r);case"vector2":{let i=e,o=t;return[At(i[0],o[0],r),At(i[1],o[1],r)]}case"vector3":case"euler":{let i=e,o=t;return[At(i[0],o[0],r),At(i[1],o[1],r),At(i[2],o[2],r)]}case"color":{let i=xv(e),o=xv(t);return!i||!o?e:jD(At(i[0],o[0],r),At(i[1],o[1],r),At(i[2],o[2],r))}case"boolean":case"string":return e}}function kv(n,e){let t=n.keys;if(t.length===0)return null;if(e<=t[0].time)return t[0].value;let r=t[t.length-1];if(e>=r.time)return r.value;let i=0,o=t.length-1;for(;o-i>1;){let u=i+o>>1;t[u].time<=e?i=u:o=u}let s=t[i],a=t[o];if(s.easing==="step"||n.valueType==="boolean"||n.valueType==="string")return s.value;let l=a.time-s.time,c=l>0?(e-s.time)/l:1;return Pv(n.valueType,s.value,a.value,St(s.easing,c))}function ap(n,e,t,r={}){if(n.length===0)return[];let i=r.includeStart===!0,o=(s,a,l,c)=>(c?s>=a:s>a)&&s<=l;if(r.wrapDuration!==void 0&&t<e){let s=r.wrapDuration;return n.filter(a=>o(a.time,e,s,i)||o(a.time,0,t,!0))}return n.filter(s=>o(s.time,e,t,i))}function lp(n,e,t,r={}){return n.enabled?ap(n.keys,e,t,r):[]}function cp(n,e,t,r={}){return n.enabled?ap(n.keys,e,t,r):[]}function up(n,e){e.signal.length!==0&&n.emit(e.signal,...en(e.args))}function Av(n,e){switch(n){case"vector2":{let t=e;return{x:t[0],y:t[1]}}case"vector3":case"euler":{let t=e;return{x:t[0],y:t[1],z:t[2]}}default:return e}}function YD(n,e){switch(n){case"number":return typeof e=="number"&&Number.isFinite(e)?e:null;case"boolean":return typeof e=="boolean"?e:null;case"string":case"color":return typeof e=="string"?e:null;case"vector2":{let t=e;return t&&typeof t.x=="number"&&typeof t.y=="number"?[t.x,t.y]:null}case"vector3":case"euler":{let t=e;return t&&typeof t.x=="number"&&typeof t.y=="number"&&typeof t.z=="number"?[t.x,t.y,t.z]:null}}}function sp(n,e){let t=e.trim();return t.length===0||t==="."?n:n.findByPath(t)}function dp(n,e){let t=[],r=[],i=[],o=[];for(let s of e.tracks){if(s.kind==="audio"){r.push(s);continue}if(s.kind==="event"){let c=sp(n,s.targetPath);if(!c){o.push(`${s.targetPath||"."} \u2192 ${s.name} (node not found)`);continue}i.push({track:s,node:c});continue}let a=sp(n,s.targetPath);if(!a){o.push(`${s.targetPath||"."} \u2192 ${s.property} (node not found)`);continue}let l=It(ke(a),s.property);if(!l){o.push(`${s.targetPath||"."} \u2192 ${s.property} (property not found)`);continue}t.push({track:s,node:a,propDef:l})}return{clip:e,entries:t,audioTracks:r,eventEntries:i,missingTargets:o}}function Fr(n,e){let t=Math.min(Math.max(0,e),n.clip.duration);for(let r of n.entries){if(!r.track.enabled)continue;let i=kv(r.track,t);i!==null&&r.propDef.setValue(r.node,Av(r.track.valueType,i))}}var Cv=.01,hp=1,$D=["number","vector2","vector3","euler","color","boolean","string"];function Mv(n){return typeof n=="string"&&$D.includes(n)}function Dv(){return`track-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function _r(n,e){let t=typeof n=="number"?n:Number(n);return Number.isFinite(t)?t:e}function rr(n,e){if(typeof n!="string")return e;let t=n.trim();return t.length>0?t:e}function pp(n,e){return typeof n=="boolean"?n:e}function KD(n){return typeof n=="string"&&/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(n.trim())?n.trim().toLowerCase():"#ffffff"}function Tv(n,e){let t=Array.isArray(n)?n:[],r=[];for(let i=0;i<e;i+=1)r.push(_r(t[i],0));return r}function Nv(n,e){switch(n){case"number":return _r(e,0);case"boolean":return pp(e,!1);case"string":return typeof e=="string"?e:String(e??"");case"color":return KD(e);case"vector2":return Tv(e,2);case"vector3":case"euler":return Tv(e,3)}}function XD(n,e){let t=typeof n=="object"&&n!==null?n:{},r=t.easing;return{time:Math.max(0,_r(t.time,0)),value:Nv(e,t.value),easing:_e(r)?r:"linear"}}function QD(n){let e=typeof n=="object"&&n!==null?n:{};return{time:Math.max(0,_r(e.time,0)),audioPath:rr(e.audioPath,""),volume:Math.min(1,Math.max(0,_r(e.volume,1)))}}function JD(n){let e=typeof n=="object"&&n!==null?n:{};return{time:Math.max(0,_r(e.time,0)),signal:rr(e.signal,""),args:typeof e.args=="string"?e.args:""}}function ZD(n,e){let t=typeof n=="object"&&n!==null?n:{},r=rr(t.id,"");(r.length===0||e.has(r))&&(r=Dv()),e.add(r);let i=pp(t.enabled,!0),o=Array.isArray(t.keys)?t.keys:[];if(t.kind==="audio"){let u=o.map(QD).filter(d=>d.audioPath.length>0);return u.sort((d,h)=>d.time-h.time),{id:r,kind:"audio",name:rr(t.name,"Audio"),enabled:i,keys:u}}if(t.kind==="event"){let u=o.map(JD).filter(h=>h.signal.length>0);u.sort((h,p)=>h.time-p.time);let d=typeof t.targetPath=="string"?t.targetPath.trim():"";return{id:r,kind:"event",name:rr(t.name,"Events"),targetPath:d==="."?"":d,enabled:i,keys:u}}let s=rr(t.property,"");if(s.length===0)return null;let a=Mv(t.valueType)?t.valueType:"number",l=typeof t.targetPath=="string"?t.targetPath.trim():"",c=o.map(u=>XD(u,a));return c.sort((u,d)=>u.time-d.time),{id:r,kind:"property",targetPath:l==="."?"":l,property:s,valueType:a,enabled:i,keys:c}}function eN(n,e,t){let r=typeof n=="object"&&n!==null?n:{},i=rr(r.name,`clip-${e+1}`);if(t.has(i)){let l=2;for(;t.has(`${i}-${l}`);)l+=1;i=`${i}-${l}`}t.add(i);let o=new Set,a=(Array.isArray(r.tracks)?r.tracks:[]).map(l=>ZD(l,o)).filter(l=>l!==null);return{name:i,duration:Math.max(Cv,_r(r.duration,hp)),loop:pp(r.loop,!1),tracks:a}}function cl(n){let e=typeof n=="object"&&n!==null?n:{},t=Array.isArray(e.clips)?e.clips:[],r=new Set;return{version:rr(e.version,"1.0.0"),clips:t.map((i,o)=>eN(i,o,r))}}function mp(){return{version:"1.0.0",clips:[]}}function tN(n){return{name:n,duration:hp,loop:!1,tracks:[]}}function zr(n,e){return!n||n.clips.length===0?null:e?n.clips.find(t=>t.name===e)??null:n.clips[0]??null}var ir=class extends O{cachedSet=null;activeClipName=null;binding=null;time=0;playing=!1;paused=!1;pendingStartAudio=!1;missingTargetsWarned=!1;constructor(e,t){super(e,t),this.config={autoplay:"",speed:1,animations:mp()}}static getPropertySchema(){return{nodeType:"AnimationPlayerBehavior",properties:[{name:"autoplay",type:"string",ui:{label:"Autoplay Clip",description:"Clip name to play automatically on start (empty = none)",group:"Animation"},getValue:e=>e.getAutoplay(),setValue:(e,t)=>{e.config.autoplay=typeof t=="string"?t.trim():""}},{name:"speed",type:"number",ui:{label:"Speed",description:"Playback speed multiplier",group:"Animation",min:0,step:.1,precision:2},getValue:e=>e.getSpeed(),setValue:(e,t)=>{let r=typeof t=="number"?t:Number(t);e.config.speed=Number.isFinite(r)?Math.max(0,r):1}},{name:"animations",type:"object",ui:{label:"Animations",group:"Animation",hidden:!0},getValue:e=>e.getAnimationSet(),setValue:(e,t)=>{let r=e;r.config.animations=cl(t),r.invalidateBindings()}}],groups:{Animation:{label:"Animation",expanded:!0}}}}onStart(){this.warmUpAudio();let e=this.getAutoplay();e.length>0&&this.play(e)}onUpdate(e){if(!this.playing||this.paused)return;let t=this.getActiveClip();if(!t){this.playing=!1;return}let r=this.ensureBinding(t),i=this.pendingStartAudio;this.pendingStartAudio=!1;let o=this.time,s=o+e*this.getSpeed();if(s>=t.duration){t.loop&&t.duration>0?(this.fireTimeWindow(r,o,t.duration,i),s=s%t.duration,this.time=s,Fr(r,s),this.fireTimeWindow(r,0,s,!0)):(this.fireTimeWindow(r,o,t.duration,i),this.time=t.duration,Fr(r,t.duration),this.playing=!1,this.node?.emit("animation_finished",t.name));return}this.time=s,Fr(r,s),this.fireTimeWindow(r,o,s,i)}onDetach(){this.playing=!1,this.paused=!1,this.binding=null,super.onDetach()}play(e){let t=this.getAnimationSet(),r=e??(this.getAutoplay()||void 0),i=zr(t,r)??(r?null:t.clips[0]??null);return i?(this.activeClipName=i.name,this.binding=null,this.time=0,this.playing=!0,this.paused=!1,this.pendingStartAudio=!0,this.node?.emit("animation_started",i.name),!0):!1}stop(){this.playing=!1,this.paused=!1,this.pendingStartAudio=!1}finish(e=!0){if(!this.playing)return;let t=this.getActiveClip();if(!t){this.playing=!1,this.paused=!1,this.pendingStartAudio=!1;return}if(t.loop){this.playing=!1,this.paused=!1,this.pendingStartAudio=!1,this.node?.emit("animation_finished",t.name);return}let r=this.ensureBinding(t);e&&this.fireTimeWindow(r,this.time,t.duration,this.pendingStartAudio),this.pendingStartAudio=!1,this.time=t.duration,Fr(r,t.duration),this.playing=!1,this.paused=!1,this.node?.emit("animation_finished",t.name)}pause(){this.playing&&(this.paused=!0)}resume(){this.paused=!1}seek(e,t=!0){let r=this.getActiveClip();r&&(this.time=Math.min(Math.max(0,e),r.duration),t&&Fr(this.ensureBinding(r),this.time))}get currentTime(){return this.time}get duration(){return this.getActiveClip()?.duration??0}get isPlaying(){return this.playing&&!this.paused}get isPaused(){return this.playing&&this.paused}get currentClipName(){return this.activeClipName}getAnimationSet(){return this.cachedSet||(this.cachedSet=cl(this.config.animations)),this.cachedSet}invalidateBindings(){this.cachedSet=null,this.binding=null,this.missingTargetsWarned=!1}getActiveClip(){return this.activeClipName?zr(this.getAnimationSet(),this.activeClipName):null}ensureBinding(e){if(!this.binding||this.binding.clip!==e){let t=this.node;if(!t)return{clip:e,entries:[],audioTracks:[],eventEntries:[],missingTargets:[]};this.binding=dp(t,e),this.binding.missingTargets.length>0&&!this.missingTargetsWarned&&(this.missingTargetsWarned=!0,console.warn(`[AnimationPlayer] Clip "${e.name}" has unresolved tracks on node "${t.name}":`,this.binding.missingTargets))}return this.binding}fireTimeWindow(e,t,r,i){for(let o of e.audioTracks){let s=lp(o,t,r,{wrapDuration:e.clip.duration,includeStart:i});for(let a of s)this.playAudioKey(a)}for(let o of e.eventEntries){let s=cp(o.track,t,r,{wrapDuration:e.clip.duration,includeStart:i});for(let a of s)up(o.node,a)}}async playAudioKey(e){let t=this.scene;if(!t||e.audioPath.length===0)return;let r=t.getAssetLoader(),i=t.getAudioService();if(!(!r||!i))try{let o=await r.loadAudio(e.audioPath),s=t.getAudioService();if(!s)return;let a=r.getAudioMetadata(e.audioPath);s.play(o,{resourcePath:e.audioPath,sizeBytes:a?.sizeBytes,volume:e.volume})}catch(o){console.warn(`[AnimationPlayer] Failed to play audio key "${e.audioPath}":`,o)}}warmUpAudio(){let e=this.scene?.getAssetLoader();if(!e)return;let t=new Set;for(let r of this.getAnimationSet().clips)for(let i of r.tracks)if(i.kind==="audio")for(let o of i.keys)o.audioPath.length>0&&t.add(o.audioPath);for(let r of t)e.loadAudio(r).catch(i=>{console.warn(`[AnimationPlayer] Failed to preload audio "${r}":`,i)})}getAutoplay(){let e=this.config.autoplay;return typeof e=="string"?e.trim():""}getSpeed(){let e=this.config.speed,t=typeof e=="number"?e:Number(e);return Number.isFinite(t)&&t>=0?t:1}};var Ur=class extends O{currentActiveId=null;blending=!1;blendElapsed=0;blendDuration=0;blendEasing="linear";pendingBlendOverride=null;blendFromPos=new S;blendFromQuat=new _;blendFromFov=60;blendFromOrtho=5;targetPos=new S;targetQuat=new _;outPos=new S;outQuat=new _;parentQuat=new _;localPos=new S;constructor(e,t){super(e,t),this.config={blendEnabled:!0}}static getPropertySchema(){return{nodeType:"CameraBrainBehavior",properties:[{name:"blendEnabled",type:"boolean",ui:{label:"Blend On Switch",description:"Ease between cameras on activation. Off = hard cut.",group:"Camera Brain"},getValue:e=>e.config.blendEnabled!==!1,setValue:(e,t)=>{e.config.blendEnabled=!!t}}],groups:{"Camera Brain":{label:"Camera Brain",expanded:!0}}}}onStart(){this.currentActiveId=null,this.blending=!1,this.pendingBlendOverride=null}overrideNextBlend(e,t){this.pendingBlendOverride={duration:Math.max(0,e),easing:t}}onUpdate(e){let t=this.node;if(!(t instanceof fe))return;let r=this.collectVirtualCameras();for(let a of r)a.solve(e);let i=this.pickActive(r);if(!i){this.currentActiveId=null,this.blending=!1;return}i.nodeId!==this.currentActiveId&&(this.beginBlend(t,i),this.currentActiveId=i.nodeId),i.getDesiredWorldPosition(this.targetPos),i.getDesiredWorldQuaternion(this.targetQuat);let o=i.fov,s=i.orthographicSize;if(this.blending){this.blendElapsed+=Math.max(0,e);let a=this.blendDuration>0?this.blendElapsed/this.blendDuration:1,l=St(this.blendEasing,a);this.outPos.copy(this.blendFromPos).lerp(this.targetPos,l),this.outQuat.copy(this.blendFromQuat).slerp(this.targetQuat,l);let c=this.blendFromFov+(o-this.blendFromFov)*l,u=this.blendFromOrtho+(s-this.blendFromOrtho)*l;this.applyToHost(t,this.outPos,this.outQuat,c,u),a>=1&&(this.blending=!1)}else this.applyToHost(t,this.targetPos,this.targetQuat,o,s)}beginBlend(e,t){let r=this.pendingBlendOverride;this.pendingBlendOverride=null;let i=this.config.blendEnabled!==!1,o=r?r.duration:i?t.blendDuration:0;if(o<=0){this.blending=!1;return}e.getWorldPosition(this.blendFromPos),e.getWorldQuaternion(this.blendFromQuat),this.blendFromFov=e.fov,this.blendFromOrtho=e.orthographicSize,this.blendElapsed=0,this.blendDuration=o,this.blendEasing=r?.easing??t.blendEasing,this.blending=!0}applyToHost(e,t,r,i,o){this.localPos.copy(t),e.parent?(e.parent.updateWorldMatrix(!0,!1),e.parent.worldToLocal(this.localPos),e.parent.getWorldQuaternion(this.parentQuat),this.parentQuat.invert().multiply(r),e.quaternion.copy(this.parentQuat)):e.quaternion.copy(r),e.position.copy(this.localPos),e.fov=i,e.orthographicSize=o}pickActive(e){let t=null;for(let r of e)r.visible&&(t===null||r.priority>t.priority)&&(t=r);return t}collectVirtualCameras(){let e=this.scene?.getRootNodes()??this.rootsFromHost(),t=[],r=[...e];for(;r.length>0;){let i=r.pop();if(i){i instanceof vt&&t.push(i);for(let o of i.children)o instanceof V&&r.push(o)}}return t}rootsFromHost(){let e=this.node;for(;e?.parentNode;)e=e.parentNode;return e?[e]:[]}};var rN=["Escape","Space","Enter"],iN=.1,nN=.4,oN=.45;function sN(n){let e=typeof n.letterboxSize=="number"&&Number.isFinite(n.letterboxSize)?Math.max(0,Math.min(oN,n.letterboxSize)):iN,t=typeof n.letterboxEnterSec=="number"&&Number.isFinite(n.letterboxEnterSec)?Math.max(0,n.letterboxEnterSec):nN;return{skippableAfter:typeof n.skippableAfter=="number"&&Number.isFinite(n.skippableAfter)?Math.max(0,n.skippableAfter):null,blendDuration:typeof n.blendDuration=="number"&&Number.isFinite(n.blendDuration)?Math.max(0,n.blendDuration):null,blendEasing:n.blendEasing,letterbox:n.letterbox!==!1,letterboxSize:e,letterboxEnterSec:t,lockInput:n.lockInput!==!1,fireSkippedEvents:n.fireSkippedEvents!==!1,skipKeys:Array.isArray(n.skipKeys)&&n.skipKeys.length>0?n.skipKeys.slice():rN}}function aN(n){let e=n.getComponent(ir);if(e)return e;let t=Ev(n);for(;t.length>0;){let r=t.pop();if(!r)continue;let i=r.getComponent(ir);if(i)return i;t.push(...Ev(r))}return null}function Ev(n){return n.children.filter(e=>e instanceof V)}function lN(n,e){let t=n.getAnimationSet();if(e)return zr(t,e);let r=typeof n.config.autoplay=="string"?n.config.autoplay.trim():"";return(r?zr(t,r):null)??t.clips[0]??null}var fp=class{constructor(e,t,r,i,o){this.scene=e;this.hostNode=t;this.player=r;this.clip=i;this.opts=o;this.done=new Promise(s=>{this.resolveDone=s})}done;resolveDone;settled=!1;input=null;holdsLock=!1;topBar=null;bottomBar=null;barAnimId=null;barT=0;startedAtMs=0;finishConnected=!1;get isActive(){return!this.settled}start(){if(this.opts.lockInput){let e=this.scene.getInputService();e&&(e.lock(),this.input=e,this.holdsLock=!0)}this.opts.letterbox&&(this.ensureBars(),this.animateBars(0,1,this.opts.letterboxEnterSec)),this.startedAtMs=performance.now(),this.attachSkipListeners(),this.armBlendOverride(),this.clip.loop?console.warn(`[Cutscene] clip "${this.clip.name}" loops \u2014 cutscene will only end via skip()/stop().`):(this.hostNode.connect("animation_finished",this,this.onFinished),this.finishConnected=!0),this.player.play(this.clip.name)||this.hardSettle("stopped")}skip(){this.settled||(this.detachFinishSignal(),this.player.finish(this.opts.fireSkippedEvents),this.settleSoft("skipped"))}stop(){this.hardSettle("stopped")}forceStop(e){this.hardSettle(e)}onSkipPointer=()=>{this.onSkipGesture()};onSkipKey=e=>{this.opts.skipKeys.includes(e.code)&&this.onSkipGesture()};onSkipGesture(){this.opts.skippableAfter!==null&&(performance.now()-this.startedAtMs<this.opts.skippableAfter*1e3||this.skip())}attachSkipListeners(){this.scene.getCanvas()?.addEventListener("pointerdown",this.onSkipPointer),typeof window<"u"&&window.addEventListener("keydown",this.onSkipKey)}detachSkipListeners(){this.scene.getCanvas()?.removeEventListener("pointerdown",this.onSkipPointer),typeof window<"u"&&window.removeEventListener("keydown",this.onSkipKey)}onFinished=(...e)=>{e[0]===this.clip.name&&this.settleSoft("finished")};detachFinishSignal(){this.finishConnected&&(this.hostNode.disconnect("animation_finished",this,this.onFinished),this.finishConnected=!1)}armBlendOverride(){if(this.opts.blendDuration===null)return;(this.scene.getActiveCamera()?.getComponent(Ur)??null)?.overrideNextBlend(this.opts.blendDuration,this.opts.blendEasing)}ensureBars(){let e=this.scene.getCanvas()?.parentElement;if(!e){console.warn("[Cutscene] Cannot create letterbox bars: canvas has no parent element.");return}getComputedStyle(e).position==="static"&&(e.style.position="relative");let r=["position: absolute","left: 0","right: 0","height: 0%","background: #000","pointer-events: none","z-index: 9998"];this.topBar=document.createElement("div"),this.topBar.style.cssText=[...r,"top: 0"].join("; "),this.bottomBar=document.createElement("div"),this.bottomBar.style.cssText=[...r,"bottom: 0"].join("; "),e.appendChild(this.topBar),e.appendChild(this.bottomBar)}animateBars(e,t,r,i){if(this.cancelBarAnim(),!this.topBar||!this.bottomBar){this.barT=t,i?.();return}let o=Math.max(0,r*1e3);if(o===0){this.setBarHeight(t),i?.();return}let s=performance.now(),a=l=>{let c=Math.min((l-s)/o,1);this.setBarHeight(e+(t-e)*c),c<1?this.barAnimId=requestAnimationFrame(a):(this.barAnimId=null,i?.())};this.barAnimId=requestAnimationFrame(a)}setBarHeight(e){this.barT=e;let t=`${(this.opts.letterboxSize*e*100).toFixed(4)}%`;this.topBar&&(this.topBar.style.height=t),this.bottomBar&&(this.bottomBar.style.height=t)}cancelBarAnim(){this.barAnimId!==null&&(cancelAnimationFrame(this.barAnimId),this.barAnimId=null)}removeBars(){this.cancelBarAnim(),this.topBar?.remove(),this.bottomBar?.remove(),this.topBar=null,this.bottomBar=null}settleSoft(e){this.settled||(this.settled=!0,this.armBlendOverride(),this.detachSkipListeners(),this.detachFinishSignal(),this.releaseLock(),this.animateBars(this.barT,0,this.opts.letterboxEnterSec,()=>this.removeBars()),this.resolveDone(e))}hardSettle(e){this.settled||(this.settled=!0,this.player.stop(),this.resolveDone(e)),this.teardownResources()}teardownResources(){this.removeBars(),this.detachSkipListeners(),this.detachFinishSignal(),this.releaseLock()}releaseLock(){this.holdsLock&&(this.input?.unlock(),this.holdsLock=!1)}};function Iv(){return{done:Promise.resolve("stopped"),isActive:!1,skip:()=>{},stop:()=>{}}}var po=class{constructor(e){this.scene=e}active=null;playCinematic(e,t={}){this.active?.stop(),this.active=null;let r=this.scene.findNode(e),i=r?aN(r):null,o=i?.node??null;if(!r||!i||!o)return console.warn(`[Cutscene] playCinematic: no AnimationPlayer found for "${e}".`),Iv();let s=lN(i,t.clip);if(!s)return console.warn(`[Cutscene] playCinematic: clip "${t.clip??"(default)"}" not found on "${e}".`),Iv();let a=new fp(this.scene,o,i,s,sN(t));return this.active=a,a.start(),a}stopAll(e="stopped"){this.active?.forceStop(e),this.active=null}dispose(){this.stopAll("stopped"),this.active=null}};var cN="res://locales/{locale}.json";function uN(n,e){return n.replace(/\{(\w+)\}/g,(t,r)=>r in e?String(e[r]):t)}function Rv(n){if(!n||typeof n!="object")return{};let e={};for(let[t,r]of Object.entries(n))typeof r=="string"&&(e[t]=r);return e}function Bv(n){return{locale:n.locale,strings:Rv(n.strings),sprites:Rv(n.sprites),meta:n.meta}}var Wr=class{config={defaultLocale:"en"};resources=null;tables=new Map;currentLocale="en";listeners=new Set;configure(e){this.config={...e},this.currentLocale=e.defaultLocale}attachResources(e){this.resources=e}get locale(){return this.currentLocale}get locales(){return this.config.locales??[...this.tables.keys()]}get fallbackLocale(){return this.config.fallbackLocale??this.config.defaultLocale}async setLocale(e){!this.tables.has(e)&&this.resources&&await this.loadTable(e),this.currentLocale=e,this.notify()}setTable(e){this.tables.set(e.locale,Bv(e)),this.notify()}async loadTable(e){if(!this.resources)return;let t=(this.config.tablePathTemplate??cN).replace("{locale}",e);try{let r=await this.resources.readText(t),i=JSON.parse(r);this.tables.set(e,Bv({locale:e,strings:i.strings,sprites:i.sprites,meta:i.$meta??i.meta}))}catch(r){console.warn(`[Localization] Failed to load locale "${e}" from ${t}`,r),this.tables.set(e,{locale:e,strings:{},sprites:{}})}}tr(e,t){if(!e)return"";let r=this.lookupString(e)??e;return t?uN(r,t):r}lookupString(e){let t=this.tables.get(this.currentLocale)?.strings[e];return t||this.tables.get(this.fallbackLocale)?.strings[e]||void 0}trPlural(e,t,r){let i={count:t,...r},o=this.pluralCategory(t);return this.has(`${e}.${o}`)?this.tr(`${e}.${o}`,i):this.has(`${e}.other`)?this.tr(`${e}.other`,i):this.tr(e,i)}pluralRulesCache=new Map;pluralCategory(e){let t=this.pluralRulesCache.get(this.currentLocale);if(t===void 0){try{t=new Intl.PluralRules(this.currentLocale)}catch{t=null}this.pluralRulesCache.set(this.currentLocale,t)}return t?t.select(e):"other"}trSprite(e){if(!e)return null;let t=this.tables.get(this.currentLocale)?.sprites[e];return t||this.tables.get(this.fallbackLocale)?.sprites[e]||null}has(e){return this.lookupString(e)!==void 0}onChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(){for(let e of[...this.listeners])try{e()}catch(t){console.error("[Localization] onChange listener threw",t)}}dispose(){this.listeners.clear(),this.tables.clear(),this.resources=null}};var mo=class{delegate=null;fadeOverlay=null;fadeAnimationId=null;flashOverlay=null;flashAnimationId=null;juiceApi=null;tweenApi=null;audioApi=null;inertLocalization=null;cutsceneApi=null;collision2dService=null;physics2dService=null;commandRegistry=null;networkService=null;networkNodeBinder=null;sceneRunning=!1;scratchPointerUnproject=new S;changeScenePromise=null;fallbackGameTime=null;canvas=null;viewportWidth=0;viewportHeight=0;viewportListeners=new Set;setDelegate(e){this.delegate=e,e||(this.sceneRunning=!1,this.networkNodeBinder?.handleSceneStopped())}handleSceneStarted(){this.sceneRunning=!0,this.networkNodeBinder?.reconcile()}attachCanvas(e){this.canvas=e}dispose(){this.cancelFade(),this.cancelFlash(),this.changeScenePromise=null,this.cutsceneApi?.dispose(),this.cutsceneApi=null,this.clearTweens(),this.collision2dService=null,this.commandRegistry?.clear(),this.networkNodeBinder?.dispose(),this.networkNodeBinder=null,this.fadeOverlay?.remove(),this.fadeOverlay=null,this.flashOverlay?.remove(),this.flashOverlay=null,this.canvas=null,this.delegate=null,this.viewportListeners.clear()}get time(){let e=this.delegate?.getGameTime();return e||(this.fallbackGameTime||(this.fallbackGameTime=new Vr),this.fallbackGameTime)}get juice(){return this.juiceApi||(this.juiceApi=new lo(this)),this.juiceApi}get tween(){return this.tweenApi||(this.tweenApi=new co(this)),this.tweenApi}updateTweens(e){this.tweenApi?.update(e)}clearTweens(){this.tweenApi?.cancelAll()}get audio(){return this.audioApi||(this.audioApi=new ho(this)),this.audioApi}get localization(){let e=this.delegate?.getLocalizationService?.()??null;if(e)return e;let t=Ye();return t||(this.inertLocalization??=new Wr)}get cutscene(){return this.cutsceneApi||(this.cutsceneApi=new po(this)),this.cutsceneApi}cancelActiveCutscene(){this.cutsceneApi?.stopAll("stopped")}get commands(){return this.commandRegistry||(this.commandRegistry=new no(()=>this.delegate?.getFrameNumber?.()??0)),this.commandRegistry}clearCommands(){this.commandRegistry?.clear()}get collision2d(){return this.collision2dService||(this.collision2dService=new Hn),this.collision2dService}get physics2d(){return this.physics2dService||(this.physics2dService=new Yn),this.physics2dService}stepPhysics2D(e){this.physics2dService?.step(e)}buildPhysics2DDebugBuffers(){return this.physics2dService?this.physics2dService.buildDebugBuffers():null}interpolatePhysics2D(e){this.physics2dService?.interpolate(e)}clearPhysics2D(){this.physics2dService?.clear(),this.physics2dService=null}get network(){return this.networkService||(this.networkService=new ro),this.networkService}setNetworkService(e){e!==null&&e===this.networkService||(this.networkService=e,this.networkNodeBinder?.dispose(),this.networkNodeBinder=null,e&&this.netNodes)}get netNodes(){return this.networkNodeBinder||(this.networkNodeBinder=new io({network:this.network,instantiate:(e,t)=>this.instantiate(e,t),isSceneRunning:()=>this.sceneRunning})),this.networkNodeBinder}getPointer2DWorldPosition(e,t){let r=typeof e=="number"?e:null,i=(typeof e=="number"?t:e)??new I,o=this.delegate?.getInputService();if(!o)return null;let s=r===null?o.pointerPosition:o.getPointer(r);if(!s)return null;let a=Math.max(1,o.width),l=Math.max(1,o.height),c=this.delegate?.getUICamera();if(c){let p=s.x/a*2-1,f=-(s.y/l*2-1);return this.scratchPointerUnproject.set(p,f,0).unproject(c),i.set(this.scratchPointerUnproject.x,this.scratchPointerUnproject.y),i}let u=this.delegate?.getLogicalCameraSize(),d=u&&Number.isFinite(u.width)&&u.width>0?u.width:a,h=u&&Number.isFinite(u.height)&&u.height>0?u.height:l;return i.set(s.x/a*d-d/2,h/2-s.y/l*h),i}async instantiate(e,t={}){if(!this.delegate?.instantiatePrefab)throw new Error("[SceneService] instantiate requires a running scene.");let r=null;if(typeof t.parent=="string"){if(r=this.findNode(t.parent),!r)throw new Error(`[SceneService] instantiate: parent "${t.parent}" not found.`)}else r=t.parent??null;return this.delegate.instantiatePrefab(e,r,t.instanceId)}getInputService(){return this.delegate?.getInputService()??null}getCanvas(){return this.canvas}setActiveCamera(e){if(!this.delegate){console.warn("[SceneService] setActiveCamera: no scene delegate.");return}let t=this.delegate.findNodeById(e);if(!t){console.warn(`[SceneService] setActiveCamera: node "${e}" not found.`);return}if(!(t instanceof fe)){console.warn(`[SceneService] setActiveCamera: node "${e}" is not a Camera3D.`);return}t.camera.layers.disableAll(),t.camera.layers.enable(0),this.delegate.setActiveCameraNode(t)}getActiveCamera(){return this.delegate?.getActiveCameraNode()??null}getActiveCamera2D(){return this.delegate?.getActiveCamera2DNode()??null}getRootNodes(){return this.delegate?.getRootNodes()??[]}findNodeById(e){return this.delegate?.findNodeById(e)??null}findNodeByName(e){for(let t of this.getRootNodes()){let r=t.findByName(e);if(r)return r}return null}findNodeByPath(e){let t=e.split("/").map(s=>s.trim()).filter(s=>s.length>0);if(t.length===0)return null;let[r,...i]=t,o=this.getRootNodes().find(s=>s.name===r)??null;return o?i.length===0?o:o.findByPath(i.join("/")):null}findNode(e){return e.includes("/")?this.findNodeByPath(e):this.findNodeById(e)??this.findNodeByName(e)}getUICamera(){return this.delegate?.getUICamera()??null}getAudioService(){return this.delegate?.getAudioService()??null}getAssetLoader(){return this.delegate?.getAssetLoader()??null}getResourceManager(){return this.delegate?.getResourceManager()??null}getECSService(){return this.delegate?.getECSService()??null}raycastViewport(e,t){return this.delegate?.raycastViewport(e,t)??null}reportFrameProfilerActivities(e){this.delegate?.reportFrameProfilerActivities(e)}setViewportSize(e,t){let r=Number.isFinite(e)?Math.max(0,Math.round(e)):0,i=Number.isFinite(t)?Math.max(0,Math.round(t)):0;if(this.viewportWidth===r&&this.viewportHeight===i)return;this.viewportWidth=r,this.viewportHeight=i;let o=this.getViewportInfo();for(let s of this.viewportListeners)s(o)}getViewportInfo(){let e=this.resolveViewportDimensions(),t=e.width>=e.height?"landscape":"portrait";return{width:e.width,height:e.height,orientation:t,aspect:e.height>0?e.width/e.height:1}}getViewportSize(){let e=this.getViewportInfo();return{width:e.width,height:e.height}}getLogicalCameraSize(){return this.delegate?.getLogicalCameraSize()??this.getViewportSize()}getOrientation(){return this.getViewportInfo().orientation}isPortrait(){return this.getOrientation()==="portrait"}isLandscape(){return this.getOrientation()==="landscape"}onViewportChanged(e){return this.viewportListeners.add(e),e(this.getViewportInfo()),()=>{this.viewportListeners.delete(e)}}switchCameraWithFade(e,t=.5,r=.5,i){this.fadeToBlack(t,()=>{this.setActiveCamera(e),this.fadeFromBlack(r,i)})}async changeScene(e,t={}){let r=this.delegate;if(!r)throw new Error("[SceneService] changeScene: no scene is running.");if(this.changeScenePromise)return console.warn("[SceneService] changeScene ignored: a scene change is already in progress."),this.changeScenePromise;let i=t.transition??"fade",o=Math.max(0,t.durationSec??.3),s=async()=>{i==="fade"&&await this.awaitFade("out",o);try{await r.loadAndStartScene(e)}catch(a){throw console.error("[SceneService] changeScene failed:",a),i==="fade"&&this.fadeFromBlack(o),a}t.onLoaded?.(),i==="fade"&&await this.awaitFade("in",o)};return this.changeScenePromise=s().finally(()=>{this.changeScenePromise=null}),this.changeScenePromise}awaitFade(e,t){return new Promise(r=>{let i=!1,o=()=>{i||(i=!0,r())};e==="out"?this.fadeToBlack(t,o):this.fadeFromBlack(t,o),setTimeout(o,t*1e3+100)})}fadeToBlack(e,t){if(this.ensureFadeOverlay(),!this.fadeOverlay)return;let r=parseFloat(this.fadeOverlay.style.opacity??"0");this.cancelFade(),this.animateFade(r,1,e,t)}fadeFromBlack(e,t){if(this.ensureFadeOverlay(),!this.fadeOverlay)return;let r=parseFloat(this.fadeOverlay.style.opacity??"1");this.cancelFade(),this.animateFade(r,0,e,t)}setFadeOpacity(e){this.ensureFadeOverlay(),this.fadeOverlay&&(this.cancelFade(),this.fadeOverlay.style.opacity=String(Math.max(0,Math.min(1,e))))}flash(e={}){let t=typeof e.color=="string"&&e.color.trim()?e.color.trim():"#ffffff",r=Math.max(0,Math.min(1,e.intensity??1)),i=Math.max(0,e.durationSec??.2);this.ensureFlashOverlay();let o=this.flashOverlay;if(!o)return;if(this.cancelFlash(),o.style.background=t,r<=0){o.style.opacity="0";return}o.style.opacity=String(r);let s=i*1e3;if(s===0){o.style.opacity="0";return}let a=performance.now(),l=c=>{let u=Math.min((c-a)/s,1);o.style.opacity=String(r*(1-u)),u<1?this.flashAnimationId=requestAnimationFrame(l):this.flashAnimationId=null};this.flashAnimationId=requestAnimationFrame(l)}ensureFlashOverlay(){if(this.flashOverlay)return;let e=this.canvas?.parentElement;if(!e){console.warn("[SceneService] Cannot create flash overlay: canvas has no parent element.");return}getComputedStyle(e).position==="static"&&(e.style.position="relative"),this.flashOverlay=document.createElement("div"),this.flashOverlay.style.cssText=["position: absolute","inset: 0","background: #ffffff","opacity: 0","pointer-events: none","z-index: 10000"].join("; "),e.appendChild(this.flashOverlay)}cancelFlash(){this.flashAnimationId!==null&&(cancelAnimationFrame(this.flashAnimationId),this.flashAnimationId=null)}ensureFadeOverlay(){if(this.fadeOverlay)return;let e=this.canvas?.parentElement;if(!e){console.warn("[SceneService] Cannot create fade overlay: canvas has no parent element.");return}getComputedStyle(e).position==="static"&&(e.style.position="relative"),this.fadeOverlay=document.createElement("div"),this.fadeOverlay.style.cssText=["position: absolute","inset: 0","background: #000000","opacity: 0","pointer-events: none","z-index: 9999"].join("; "),e.appendChild(this.fadeOverlay)}cancelFade(){this.fadeAnimationId!==null&&(cancelAnimationFrame(this.fadeAnimationId),this.fadeAnimationId=null)}animateFade(e,t,r,i){if(!this.fadeOverlay)return;let o=this.fadeOverlay,s=Math.max(0,r*1e3);if(s===0){o.style.opacity=String(t),i?.();return}let a=performance.now(),l=c=>{let u=c-a,d=Math.min(u/s,1);o.style.opacity=String(e+(t-e)*d),d<1?this.fadeAnimationId=requestAnimationFrame(l):(this.fadeAnimationId=null,i?.())};this.fadeAnimationId=requestAnimationFrame(l)}resolveViewportDimensions(){if(this.viewportWidth>0&&this.viewportHeight>0)return{width:this.viewportWidth,height:this.viewportHeight};let e=this.canvas?.width??0,t=this.canvas?.height??0;if(e>0&&t>0)return{width:e,height:t};if(typeof window<"u"){let r=Number.isFinite(window.devicePixelRatio)?window.devicePixelRatio:1,i=Math.max(0,Math.round(window.innerWidth*r)),o=Math.max(0,Math.round(window.innerHeight*r));return{width:i,height:o}}return{width:0,height:0}}};var ul=null,gp=()=>import("./build-AUGKXER3.js");function dN(n){gp!==n&&(gp=n,ul=null)}function hN(){return ul||(ul=gp()),ul}var go=class{renderer;pp=null;loadingStarted=!1;composer=null;render3DPass=null;normalPass=null;depthDownsampling=null;ssaoPass=null;clearDepthPass=null;render2DPass=null;effectPass=null;bloom=null;vignette=null;chromaticAberration=null;ssao=null;caOffset=new I;structuralSignature="";lastCamera3D=null;lastOrthoCamera=null;width=0;height=0;sizeScratch=new I;constructor(e){this.renderer=e}ensureLoading(){this.pp||this.loadingStarted||(this.loadingStarted=!0,hN().then(e=>{this.pp=e}))}isReady(){return this.pp!==null}syncSizeFromRenderer(){let e=this.renderer.getSize(this.sizeScratch),t=Math.max(1,Math.round(e.width)),r=Math.max(1,Math.round(e.height));t===this.width&&r===this.height||(this.width=t,this.height=r,this.composer?.setSize(t,r,!1))}render(e,t,r,i){let o=this.pp;if(!o)return;this.syncSizeFromRenderer(),this.sync(o,e,t,r,i);let s=this.renderer.getSize(this.sizeScratch);this.renderer.setScissorTest(!1),this.renderer.setViewport(0,0,s.width,s.height),this.composer?.render()}sync(e,t,r,i,o){let s=this.computeSignature(o,r),a=this.lastCamera3D!==r||this.lastOrthoCamera!==i;(!this.composer||s!==this.structuralSignature||a)&&(this.rebuild(e,t,r,i,o),this.structuralSignature=s,this.lastCamera3D=r,this.lastOrthoCamera=i),this.applyLiveValues(o)}computeSignature(e,t){let r=e.bloom,i=e.lut.enabled&&e.lut.src.length>0;return[t?"3d":"no3d",e.affect2D?"2d":"2d-",r.enabled?`bloom:${r.threshold}:${r.smoothing}:${r.radius}`:"bloom-",e.vignette.enabled?"vig":"vig-",e.chromaticAberration.enabled?"ca":"ca-",e.ssao.enabled&&t?"ssao":"ssao-",i?`lut:${e.lut.src}`:"lut-"].join("|")}rebuild(e,t,r,i,o){this.composer||(this.composer=new e.EffectComposer(this.renderer,{frameBufferType:Kp}),this.composer.setSize(this.width,this.height,!1));let s=this.composer;if(s.removeAllPasses(),this.disposeEffects(),r?(this.render3DPass=new e.RenderPass(t,r),s.addPass(this.render3DPass)):this.render3DPass=null,o.ssao.enabled&&r?(this.normalPass=new e.NormalPass(t,r),this.depthDownsampling=new e.DepthDownsamplingPass({normalBuffer:this.normalPass.texture,resolutionScale:1}),s.addPass(this.normalPass),s.addPass(this.depthDownsampling),this.ssao=new e.SSAOEffect(r,this.normalPass.texture,{blendFunction:e.BlendFunction.MULTIPLY,distanceScaling:!0,depthAwareUpsampling:!0,normalDepthBuffer:this.depthDownsampling.texture,samples:30,rings:11,worldDistanceThreshold:40,worldDistanceFalloff:8,worldProximityThreshold:4,worldProximityFalloff:2,luminanceInfluence:.6,radius:o.ssao.radius,intensity:o.ssao.intensity,fade:.02,bias:.03}),this.ssaoPass=new e.EffectPass(r,this.ssao),s.addPass(this.ssaoPass)):(this.normalPass=null,this.depthDownsampling=null,this.ssaoPass=null,this.ssao=null),o.affect2D||!r){let u=!this.render3DPass;u?this.clearDepthPass=null:(this.clearDepthPass=new e.ClearPass(!1,!0,!1),s.addPass(this.clearDepthPass)),this.render2DPass=new e.RenderPass(t,i),this.render2DPass.clearPass.enabled=u,this.render2DPass.ignoreBackground=!u,s.addPass(this.render2DPass)}else this.clearDepthPass=null,this.render2DPass=null;let l=r??i,c=[];o.bloom.enabled&&(this.bloom=new e.BloomEffect({mipmapBlur:!0,intensity:o.bloom.intensity,luminanceThreshold:o.bloom.threshold,luminanceSmoothing:o.bloom.smoothing,radius:o.bloom.radius}),c.push(this.bloom)),o.vignette.enabled&&(this.vignette=new e.VignetteEffect({offset:o.vignette.offset,darkness:o.vignette.darkness}),c.push(this.vignette)),o.chromaticAberration.enabled&&(this.caOffset.set(o.chromaticAberration.offset,o.chromaticAberration.offset),this.chromaticAberration=new e.ChromaticAberrationEffect({offset:this.caOffset,radialModulation:!1,modulationOffset:0}),c.push(this.chromaticAberration)),c.length>0?(this.effectPass=new e.EffectPass(l,...c),s.addPass(this.effectPass)):this.effectPass=null}applyLiveValues(e){this.bloom&&(this.bloom.intensity=e.bloom.intensity),this.vignette&&(this.vignette.offset=e.vignette.offset,this.vignette.darkness=e.vignette.darkness),this.chromaticAberration&&(this.caOffset.set(e.chromaticAberration.offset,e.chromaticAberration.offset),this.chromaticAberration.offset=this.caOffset),this.ssao&&(this.ssao.intensity=e.ssao.intensity,this.ssao.radius=e.ssao.radius)}disposeEffects(){this.effectPass?.dispose(),this.bloom?.dispose(),this.vignette?.dispose(),this.chromaticAberration?.dispose(),this.ssaoPass?.dispose(),this.ssao?.dispose(),this.depthDownsampling?.dispose(),this.normalPass?.dispose(),this.effectPass=null,this.bloom=null,this.vignette=null,this.chromaticAberration=null,this.ssaoPass=null,this.ssao=null,this.depthDownsampling=null,this.normalPass=null}dispose(){this.disposeEffects(),this.composer?.dispose(),this.composer=null,this.render3DPass=null,this.clearDepthPass=null,this.render2DPass=null,this.structuralSignature="",this.lastCamera3D=null,this.lastOrthoCamera=null}};var pN=["normal","hover","pressed","disabled"];function dl(n,e){let t=r=>{r instanceof te&&r.labelKey&&r.refreshLocalizedLabel(),e&&(r instanceof Le&&r.textureKey?mN(r,e):r instanceof mt&&r.hasLocalizedStateTextures()&&fN(r,e));for(let i of r.children)t(i)};for(let r of n)t(r)}function mN(n,e){let t=n.getEffectiveTexturePath();t&&e.loadTexture(t).then(r=>{n.getEffectiveTexturePath()===t&&n.setTexture(r)}).catch(r=>{console.warn(`[Localization] Failed to load localized texture "${t}"`,r)})}function fN(n,e){for(let t of pN){if(!n.stateTextureKeys[t])continue;let r=n.getEffectiveStateTexturePath(t);r&&e.loadTexture(r).then(i=>{n.getEffectiveStateTexturePath(t)===r&&n.setStateTexture(t,i)}).catch(i=>{console.warn(`[Localization] Failed to load localized ${t} texture "${r}"`,i)})}}var gN=.016666666666666666,yN=4,yo=class{fixedTimeStep;maxFixedStepsPerFrame;registrations=[];scene=null;input=null;elapsedTime=0;frame=0;alpha=0;constructor(e={}){this.fixedTimeStep=typeof e.fixedTimeStep=="number"&&e.fixedTimeStep>0?e.fixedTimeStep:gN,this.maxFixedStepsPerFrame=typeof e.maxFixedStepsPerFrame=="number"&&e.maxFixedStepsPerFrame>0?Math.max(1,Math.floor(e.maxFixedStepsPerFrame)):yN}registerWorld(e){let t={world:e.world,systems:[...e.systems]};this.registrations.push(t);let r=this.tryCreateContext(0,this.elapsedTime,this.frame,this.alpha);return r&&t.world.initialize&&t.world.initialize(r),()=>{let i=this.registrations.indexOf(t);i!==-1&&(this.disposeRegistration(t),this.registrations.splice(i,1))}}clear(){for(;this.registrations.length>0;){let e=this.registrations.pop();e&&this.disposeRegistration(e)}}dispose(){this.clear(),this.scene=null,this.input=null,this.elapsedTime=0,this.frame=0,this.alpha=0}beginScene(e,t){this.scene=e,this.input=t,this.elapsedTime=0,this.frame=0,this.alpha=0;let r=this.tryCreateContext(0,0,0,0);if(r)for(let i of this.registrations)i.world.initialize?.(r)}endScene(){this.scene=null,this.input=null,this.elapsedTime=0,this.frame=0,this.alpha=0}setInterpolationAlpha(e){this.alpha=Number.isFinite(e)?Math.max(0,e):0}setFrameMetrics(e,t){this.elapsedTime=Number.isFinite(e)?Math.max(0,e):this.elapsedTime,this.frame=Number.isFinite(t)?Math.max(0,Math.floor(t)):this.frame}update(e,t=this.alpha){let r=Number.isFinite(e)?Math.max(0,e):0;this.alpha=Number.isFinite(t)?Math.max(0,t):this.alpha;let i=this.tryCreateContext(r,this.elapsedTime,this.frame,this.alpha);i&&this.runPhase("update",i)}fixedUpdate(e){let t=Number.isFinite(e)?Math.max(0,e):0,r=this.tryCreateContext(t,this.elapsedTime,this.frame,this.alpha);r&&this.runPhase("fixedUpdate",r)}runPhase(e,t){for(let r of this.registrations)for(let i of r.systems)i.phase===e&&i.update(t)}tryCreateContext(e,t,r,i){return!this.scene||!this.input?null:{dt:e,time:t,frame:r,fixedTimeStep:this.fixedTimeStep,alpha:i,scene:this.scene,input:this.input}}disposeRegistration(e){e.world.dispose?.()}};function yp(n,e,t,r){return!(t.width>0)||!(t.height>0)||!(r.width>0)||!(r.height>0)?null:{x:(n+t.width/2)/t.width*r.width,y:(t.height/2-e)/t.height*r.height}}function hl(n,e,t){return!(t.width>0)||!(t.height>0)||(n.project(e),!Number.isFinite(n.x)||!Number.isFinite(n.y))?null:{x:(n.x+1)/2*t.width,y:(1-n.y)/2*t.height}}var bp=.016666666666666666,Ov=240,Sp=Object.freeze({mode:"realtime",fixedDeltaSec:bp,ticksPerFrame:1,renderEveryNTicks:1,muteAudio:!0});function bN(n){return n==="realtime"||n==="fixed"||n==="manual"}function vp(n){if(!n||!bN(n.mode))throw new TypeError(`[RuntimeTime] mode must be one of 'realtime' | 'fixed' | 'manual' (got ${String(n?.mode)}).`);let e=n.fixedDeltaSec,t=bp;if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<=0)throw new RangeError(`[RuntimeTime] fixedDeltaSec must be a finite number > 0 (got ${String(e)}).`);t=e}let r=Vv(n.ticksPerFrame,1,1,Ov),i=n.mode==="fixed"?r:1,o=Vv(n.renderEveryNTicks,i,1,Number.MAX_SAFE_INTEGER);return{mode:n.mode,fixedDeltaSec:t,ticksPerFrame:r,renderEveryNTicks:o,muteAudio:n.muteAudio??!0}}function Vv(n,e,t,r){return n===void 0||typeof n!="number"||!Number.isFinite(n)?e:Math.min(r,Math.max(t,Math.round(n)))}var fl=null,Fv="",pl=!1,wp=new Set,xp=new Set,Lv=!1;function Pp(){let n=typeof window<"u"?window.innerWidth:0,e=typeof window<"u"?window.innerHeight:0;return{width:n,height:e,orientation:n>=e?"landscape":"portrait"}}function ml(){let n=Pp();for(let e of xp)try{e(n)}catch(t){console.warn("[PlayableSdk] resize listener failed:",t)}}function SN(){if(Lv||typeof window>"u")return;Lv=!0,window.addEventListener("resize",ml),window.addEventListener("orientationchange",ml),globalThis.mraid?.addEventListener?.("sizeChange",ml),globalThis.dapi?.addEventListener?.("adResized",ml)}function vN(n){fl=n}function wN(n){Fv=typeof n=="string"?n.trim():""}var kp={openStore(n){let e=(n??"").trim()||Fv;if(fl?.openStore){if(!e){console.warn("[PlayableSdk] openStore called without a store URL.");return}fl.openStore(e);return}let t=globalThis.dapi;if(t?.openStoreUrl){t.openStoreUrl();return}if(!e){console.warn("[PlayableSdk] openStore called without a store URL.");return}let r=globalThis.mraid;if(r?.open){r.open(e);return}typeof window<"u"&&window.open(e,"_blank","noopener")},getViewport(){return Pp()},getOrientation(){return Pp().orientation},onResize(n){return SN(),xp.add(n),()=>xp.delete(n)},gameEnd(){if(!pl){pl=!0,fl?.gameEnd?.();for(let n of wp)try{n()}catch(e){console.warn("[PlayableSdk] gameEnd listener failed:",e)}}},hasGameEnded(){return pl},onGameEnd(n){return wp.add(n),()=>wp.delete(n)},reset(){pl=!1}};function _v(n){let e={hasOverlay:!1};for(let t of n)t instanceof M&&zv(t,!1,e);return e.hasOverlay}function zv(n,e,t){n instanceof M&&n.isCanvasLayer&&(e=!0),e&&(t.hasOverlay=!0),n.layers.set(e?3:1);for(let r of n.children)zv(r,e,t)}var xN=57508,Di=.3,Ni=class{geometry=new le;material=new Ct({vertexColors:!0,transparent:!0,depthTest:!1,depthWrite:!1,toneMapped:!1});lines=new Qr(this.geometry,this.material);overlayScene=new Kr;positionAttr=null;colorAttr=null;constructor(){this.overlayScene.background=null,this.lines.frustumCulled=!1,this.lines.raycast=()=>{},this.overlayScene.add(this.lines)}sync(){let e=ql();if(!e)return!1;let t;try{t=e()}catch{return!1}return this.upload(t)}upload(e){if(!e?.vertices)return!1;let t=e.vertices,r=t.length;if(r<6)return this.geometry.setDrawRange(0,0),!1;(!this.positionAttr||this.positionAttr.array.length<r)&&(this.positionAttr=new J(new Float32Array(r),3),this.positionAttr.setUsage(se),this.geometry.setAttribute("position",this.positionAttr)),this.positionAttr.array.set(t),this.positionAttr.needsUpdate=!0;let i=Math.floor(r/3);this.geometry.setDrawRange(0,i);let o=e.colors,s=!!o&&o.length>=i*4;if(s&&o){(!this.colorAttr||this.colorAttr.array.length<o.length)&&(this.colorAttr=new J(new Float32Array(o.length),4),this.colorAttr.setUsage(se),this.geometry.setAttribute("color",this.colorAttr));let a=this.colorAttr.array,l=i*4;for(let c=0;c<l;c+=4)a[c]=Di+(1-Di)*o[c],a[c+1]=Di+(1-Di)*o[c+1],a[c+2]=Di+(1-Di)*o[c+2],a[c+3]=o[c+3];this.colorAttr.needsUpdate=!0}return this.material.vertexColors!==s&&(this.material.vertexColors=s,s||this.material.color.set(xN),this.material.needsUpdate=!0),!0}render(e,t){this.sync()&&e.render(this.overlayScene,t)}renderBuffers(e,t,r){this.upload(r)&&e.render(this.overlayScene,t)}dispose(){this.geometry.dispose(),this.material.dispose()}};var PN=[1,.23,.23],kN=[.35,.92,.35],AN=[.32,.55,1],Uv=.05,TN=1,CN=.28,MN=.14,gl=class{geometry=new le;material=new Ct({vertexColors:!0,transparent:!0,opacity:.95,depthTest:!1,depthWrite:!1,toneMapped:!1});lines=new Qr(this.geometry,this.material);overlayScene=new Kr;positionAttr=null;colorAttr=null;positions=[];colors=[];origin=new S;axis=new S;perp=new S;cameraPosition=new S;constructor(){this.overlayScene.background=null,this.lines.frustumCulled=!1,this.lines.layers.enableAll(),this.lines.raycast=()=>{},this.overlayScene.add(this.lines)}render(e,t,r,i){this.positions.length=0,this.colors.length=0;let o=t instanceof ye?t:null,s=o?Math.tan(E.degToRad(o.fov)/2):0;o&&this.cameraPosition.setFromMatrixPosition(o.matrixWorld);let a=t instanceof me?(t.top-t.bottom)/t.zoom*Uv:null;this.collect(r,i,o,s,a);let l=this.positions.length;if(l<6){this.geometry.setDrawRange(0,0);return}(!this.positionAttr||this.positionAttr.array.length<l)&&(this.positionAttr=new J(new Float32Array(l),3),this.positionAttr.setUsage(se),this.geometry.setAttribute("position",this.positionAttr),this.colorAttr=new J(new Float32Array(l),3),this.colorAttr.setUsage(se),this.geometry.setAttribute("color",this.colorAttr)),this.positionAttr.array.set(this.positions),this.positionAttr.needsUpdate=!0,this.colorAttr.array.set(this.colors),this.colorAttr.needsUpdate=!0,this.geometry.setDrawRange(0,Math.floor(l/3)),e.render(this.overlayScene,t)}collect(e,t,r,i,o){for(let s of e){if(!s.visible)continue;(t==="node2d"?s instanceof M:s instanceof U)&&this.emitForNode(s,t,r,i,o),s.children.length>0&&this.collect(s.children,t,r,i,o)}}emitForNode(e,t,r,i,o){let s=e.matrixWorld.elements;this.origin.set(s[12],s[13],s[14]);let a;r?a=2*this.cameraPosition.distanceTo(this.origin)*i*Uv:a=o??TN,!(a<=0)&&(this.axis.set(s[0],s[1],s[2]),this.emitArrow(t,a,PN),this.axis.set(s[4],s[5],s[6]),this.emitArrow(t,a,kN),t==="node3d"&&(this.axis.set(s[8],s[9],s[10]),this.emitArrow(t,a,AN)))}emitArrow(e,t,r){if(this.axis.lengthSq()<1e-12)return;this.axis.normalize();let i=this.origin.x,o=this.origin.y,s=this.origin.z,a=i+this.axis.x*t,l=o+this.axis.y*t,c=s+this.axis.z*t,u=t*CN,d=t*MN,h=a-this.axis.x*u,p=l-this.axis.y*u,f=c-this.axis.z*u;e==="node2d"?this.perp.set(-this.axis.y,this.axis.x,0):this.perpendicular3(this.axis,this.perp);let m=this.perp.x*d,g=this.perp.y*d,y=this.perp.z*d;this.pushSegment(i,o,s,a,l,c,r),this.pushSegment(a,l,c,h+m,p+g,f+y,r),this.pushSegment(a,l,c,h-m,p-g,f-y,r)}pushSegment(e,t,r,i,o,s,a){this.positions.push(e,t,r,i,o,s),this.colors.push(a[0],a[1],a[2],a[0],a[1],a[2])}perpendicular3(e,t){let r=Math.abs(e.x),i=Math.abs(e.y),o=Math.abs(e.z);r<=i&&r<=o?t.set(1,0,0):i<=o?t.set(0,1,0):t.set(0,0,1),t.cross(e).normalize()}dispose(){this.geometry.dispose(),this.material.dispose()}};var Wv={request:n=>requestAnimationFrame(n),cancel:n=>cancelAnimationFrame(n)},DN=.999,NN=100,Ap=Object.freeze([]);function EN(n){return n.trim().replace(/\\/g,"/").replace(/^res:\/\//i,"").replace(/^\/+/,"")}var Tp=class n{sceneManager;renderer;assetLoader;inputService;sceneService;ecsService;audioService;resourceManager;clock;gameTime=new Vr;audioMuffled=!1;raycaster=new vm;raycastPointer=new I;animationFrameId=null;frameScheduler=Wv;isRunning=!1;fixedTimeAccumulator=0;elapsedTime=0;frameNumber=0;timeConfig={...Sp};ticksSinceRender=0;inTick=!1;audioSilenced=!1;masterVolumeBeforeSilence=1;scene;activeCamera=null;activeCamera2D=null;scratchShake2D=new I;orthographicCamera;overlayCamera;overlay2DActive=!1;viewportSize={width:0,height:0};canvasCssSize=null;canvasSizeObserver=null;observedCanvas=null;logicalCameraSize={width:1,height:1};rootLayoutAuthoredSize;frameListeners=new Set;currentRafLatenessMs=0;currentFrameProfilerActivities=Ap;lastHeavySampleAtMs=Number.NEGATIVE_INFINITY;cachedRendererStats=null;cachedAudioPlaybacks=void 0;cachedAudioRevision=-1;physicsDebugOverlay=null;physics2DDebugOverlay=null;directionAxesOverlay=null;postFx=null;batch2D=null;batch2DEnabled=!1;localization=null;previousActiveLocalization=null;localizationUnsub=null;projectFonts=null;localizationConfig=null;seedLocale=null;ordered2DBuffer=[];ordered2DCount=0;collectOrdered2D=(e,t,r,i)=>{if(!e.isMesh)return;let o=this.ordered2DBuffer[this.ordered2DCount];o?(o.mesh=e,o.order=t,o.overlay=r,o.visible=i):this.ordered2DBuffer.push({mesh:e,order:t,overlay:r,visible:i}),this.ordered2DCount++};constructor(e,t,r,i,o={width:1920,height:1080}){this.sceneManager=e,this.renderer=t,this.assetLoader=i,this.inputService=new Wn,this.sceneService=new mo,this.ecsService=new yo,this.audioService=r,this.resourceManager=i.getResourceManager(),this.clock=new wm,this.scene=new Kr,this.rootLayoutAuthoredSize={width:Math.max(1,o.width),height:Math.max(1,o.height)},this.scene.background=new L("#202020"),this.orthographicCamera=new me(-1,1,1,-1,.1,1e3),this.orthographicCamera.position.z=100,this.orthographicCamera.layers.disableAll(),this.orthographicCamera.layers.enable(1),this.overlayCamera=new me(-1,1,1,-1,.1,1e3),this.overlayCamera.position.z=100,this.overlayCamera.layers.disableAll(),this.overlayCamera.layers.enable(3),this.bindSceneServiceDelegate()}setNetworkService(e){this.sceneService.setNetworkService(e)}setBatching2DEnabled(e){this.batch2DEnabled=e,!e&&this.batch2D&&(this.batch2D.dispose(),this.batch2D=null)}getBatch2DStats(){return this.batch2D?this.batch2D.stats:null}setProjectFonts(e){this.projectFonts=e&&e.length>0?e:null}setLocalizationConfig(e,t){this.localizationConfig=e,this.seedLocale=t??null}runtimeGraph=null;async startScene(e){let t=this.sceneManager.getSceneGraph(e);if(!t){console.warn(`[SceneRunner] Scene "${e}" not found.`);return}let r=this.stopEpoch,i;try{let o=this.sceneManager.serializeScene(t);i=await this.sceneManager.parseScene(o)}catch(o){throw console.error("[SceneRunner] Failed to clone scene for runtime:",o),o}this.abandonIfStopped(r,i)||await this.runGraph(i)}async loadAndStartScene(e){let t=this.stopEpoch,r=EN(e),i=await this.resourceManager.readText(`res://${r}`),o=await this.sceneManager.parseScene(i,{filePath:r});this.abandonIfStopped(t,o)||await this.runGraph(o)}abandonIfStopped(e,t){if(this.stopEpoch===e)return!1;for(let r of t.rootNodes)r.dispose();return!0}spawnCounter=0;async instantiatePrefab(e,t,r){if(!this.isRunning||!this.runtimeGraph)throw new Error("[SceneRunner] instantiatePrefab requires a running scene.");this.spawnCounter+=1;let i=r?.trim()||`spawn:${this.spawnCounter}`,o=await this.sceneManager.instantiatePrefab(e,i),s=t??this.runtimeGraph.rootNodes[0]??null;if(!s)throw o.dispose(),new Error("[SceneRunner] instantiatePrefab: no parent node available.");return s.adoptChild(o),this.stripEditorOnly(o.children.filter(a=>a instanceof V)),this.applyInitialVisibility([o]),o}async runGraph(e){this.stop(),this.bindSceneServiceDelegate(),kp.reset(),this.sceneService.attachCanvas(this.renderer.domElement),this.scene.clear(),this.activeCamera=null,this.activeCamera2D=null,this.lastTickErrorMessage=null,this.runtimeGraph=e;for(let t of this.runtimeGraph.rootNodes)t.input=this.inputService,t.scene=this.sceneService,this.scene.add(t);es(this.scene),ts((t,r,i)=>this.applyLivePropertyUpdate(t,r,i)),this.runtimeGraph.rootNodes=this.stripEditorOnly(this.runtimeGraph.rootNodes),this.applyInitialVisibility(this.runtimeGraph.rootNodes),this.applyEditorPeekMask(this.runtimeGraph.rootNodes),this.inputService.attach(this.renderer.domElement),this.activeCamera=this.findActiveCamera(this.runtimeGraph.rootNodes),this.activeCamera&&(this.activeCamera.camera.layers.disableAll(),this.activeCamera.camera.layers.enable(0)),this.viewportSize={width:0,height:0},this.logicalCameraSize={width:1,height:1},this.fixedTimeAccumulator=0,this.elapsedTime=0,this.frameNumber=0,this.ticksSinceRender=0,this.gameTime.reset(),this.audioMuffled=!1,this.audioSilenced=!1,this.applyTimeModeAudio(),this.projectFonts&&await Hc(this.projectFonts,this.resourceManager),await this.setupLocalization(this.runtimeGraph.rootNodes),this.ecsService.beginScene(this.sceneService,this.inputService),this.isRunning=!0,this.updateNodes(0),this.flushInstancedNodes(),this.sceneService.handleSceneStarted(),this.clock.start(),this.timeConfig.mode==="manual"?this.render():this.tick()}async setupLocalization(e){let t=new Wr;t.configure(this.localizationConfig??{defaultLocale:"en"}),t.attachResources(this.resourceManager),this.previousActiveLocalization=Ye(),this.localization=t,Ss(t),this.localizationUnsub=t.onChange(()=>{this.runtimeGraph&&dl(this.runtimeGraph.rootNodes,this.assetLoader)});let r=this.seedLocale??this.localizationConfig?.defaultLocale??"en";if(this.localizationConfig)try{await t.setLocale(r)}catch{}dl(e,this.assetLoader)}teardownLocalization(){this.localizationUnsub&&(this.localizationUnsub(),this.localizationUnsub=null),this.localization&&(Ss(this.previousActiveLocalization),this.localization.dispose(),this.localization=null),this.previousActiveLocalization=null}isPaused=!1;stopEpoch=0;stop(){if(this.stopEpoch+=1,this.isRunning=!1,this.sceneService.cancelActiveCutscene(),this.teardownLocalization(),es(null),ts(null),this.physicsDebugOverlay&&(this.physicsDebugOverlay.dispose(),this.physicsDebugOverlay=null),this.physics2DDebugOverlay&&(this.physics2DDebugOverlay.dispose(),this.physics2DDebugOverlay=null),this.directionAxesOverlay&&(this.directionAxesOverlay.dispose(),this.directionAxesOverlay=null),this.postFx&&(this.postFx.dispose(),this.postFx=null),this.batch2D&&(this.batch2D.dispose(),this.batch2D=null),this.ordered2DBuffer.length=0,this.ordered2DCount=0,this.clock.stop(),this.animationFrameId!==null&&(this.frameScheduler.cancel(this.animationFrameId),this.animationFrameId=null),this.audioSilenced&&(this.audioSilenced=!1,this.audioService.setBusVolume("master",this.masterVolumeBeforeSilence,.01)),this.ecsService.endScene(),this.ecsService.clear(),this.fixedTimeAccumulator=0,this.elapsedTime=0,this.frameNumber=0,this.ticksSinceRender=0,this.isPaused=!1,this.audioService.setPaused(!1),this.gameTime.reset(),this.currentFrameProfilerActivities=Ap,this.lastHeavySampleAtMs=Number.NEGATIVE_INFINITY,this.cachedRendererStats=null,this.cachedAudioPlaybacks=void 0,this.cachedAudioRevision=-1,this.lastAOSuppress=null,V.flushFreeQueue(),this.runtimeGraph){for(let e of this.runtimeGraph.rootNodes)this.detachScripts(e),this.stopAudioPlayers(e);this.audioService.stopAll(),this.audioService.resetBuses(),this.audioMuffled=!1,this.sceneService.setDelegate(null),this.scene.clear();for(let e of this.runtimeGraph.rootNodes)e.dispose();this.runtimeGraph=null}this.sceneService.clearCommands(),this.sceneService.clearTweens(),this.sceneService.clearPhysics2D(),this.activeCamera2D=null,this.overlay2DActive=!1,this.orthographicCamera.position.set(0,0,100),this.orthographicCamera.zoom!==1&&(this.orthographicCamera.zoom=1,this.orthographicCamera.updateProjectionMatrix()),this.canvasSizeObserver?.disconnect(),this.canvasSizeObserver=null,this.observedCanvas=null,this.canvasCssSize=null,this.inputService.detach()}setFrameScheduler(e){let t=e??Wv;if(t===this.frameScheduler)return;let r=this.animationFrameId!==null;this.animationFrameId!==null&&(this.frameScheduler.cancel(this.animationFrameId),this.animationFrameId=null),this.frameScheduler=t,r&&this.scheduleNextFrame()}pause(){!this.isRunning||this.isPaused||(this.isPaused=!0,this.audioService.setPaused(!0),this.animationFrameId!==null&&(this.frameScheduler.cancel(this.animationFrameId),this.animationFrameId=null))}resume(){!this.isRunning||!this.isPaused||(this.isPaused=!1,this.audioService.setPaused(!1),this.clock.getDelta(),this.timeConfig.mode!=="manual"&&this.tick())}get paused(){return this.isPaused}get running(){return this.isRunning}renderOnce(){return this.isRunning?(this.render(),!0):!1}getLiveNodeById(e){return this.findNodeById(e)}getLiveRootNodes(){return this.runtimeGraph?.rootNodes??[]}getActiveCamera3D(){return this.activeCamera}findLiveNodeByName(e){return this.findLiveNodesByName(e,1)[0]??null}findLiveNodesByName(e,t=Number.POSITIVE_INFINITY){let r=e.toLowerCase(),i=[],o=[...this.runtimeGraph?.rootNodes??[]].reverse();for(;o.length>0;){let s=o.pop();if(s){if(s.name.toLowerCase()===r&&(i.push(s),i.length>=t))return i;for(let a=s.children.length-1;a>=0;a-=1){let l=s.children[a];l instanceof V&&o.push(l)}}}return i}projectNodeToCanvas(e){let t=e.getWorldPosition(n.scratchProject);return e instanceof M?this.projectWorldPointToCanvas(t.x,t.y,{overlay:this.isInOverlayBand(e)}):this.activeCamera?hl(t,this.activeCamera.camera,this.canvasBackingSize()):null}projectWorldPointToCanvas(e,t,r){let i=this.canvasBackingSize();return!r?.overlay&&this.orthographicCamera?(n.scratchProject.set(e,t,0),hl(n.scratchProject,this.orthographicCamera,i)):yp(e,t,this.logicalCameraSize,i)}static scratchProject=new S;canvasBackingSize(){let e=this.renderer.domElement;return{width:e.width,height:e.height}}isInOverlayBand(e){let t=e,r=0;for(;t&&r++<128;){if(t instanceof M&&t.isCanvasLayer)return!0;t=t.parent instanceof V?t.parent:null}return!1}setTimeMode(e){let t=vp(e),r=this.timeConfig.mode;if(this.timeConfig=t,this.fixedTimeAccumulator=0,this.ticksSinceRender=0,t.mode==="realtime"&&r!=="realtime"&&this.clock.getDelta(),this.applyTimeModeAudio(),t.mode==="manual"){this.animationFrameId!==null&&(this.frameScheduler.cancel(this.animationFrameId),this.animationFrameId=null);return}this.scheduleNextFrame()}getTimeMode(){return{...this.timeConfig}}stepFrames(e=1){if(this.timeConfig.mode!=="manual")return console.warn(`[SceneRunner] stepFrames() is only available in 'manual' time mode (current: '${this.timeConfig.mode}').`),0;if(!this.isRunning||this.isPaused)return 0;if(this.inTick)return console.warn("[SceneRunner] stepFrames() called from inside a tick \u2014 ignored (reentrancy)."),0;let t=typeof e=="number"&&Number.isFinite(e)?Math.floor(e):0,r=0;for(let i=0;i<t&&!(!this.isRunning||this.isPaused);i+=1){try{this.runOneTick(this.timeConfig.fixedDeltaSec)}catch(o){console.error("[SceneRunner] stepFrames aborted by an error during the tick:",o);break}if(r+=1,this.timeConfig.mode!=="manual")break}return r}applyTimeModeAudio(){let e=this.timeConfig.muteAudio&&this.timeConfig.mode!=="realtime";e!==this.audioSilenced&&(this.audioSilenced=e,e?(this.masterVolumeBeforeSilence=this.audioService.getBusVolume("master"),this.audioService.setBusVolume("master",0,.01)):this.audioService.setBusVolume("master",this.masterVolumeBeforeSilence,.01))}scheduleNextFrame(){!this.isRunning||this.isPaused||this.timeConfig.mode!=="manual"&&this.animationFrameId===null&&(this.animationFrameId=this.frameScheduler.request(this.tick))}tick=e=>{if(this.currentRafLatenessMs=this.frameListeners.size>0&&typeof e=="number"&&Number.isFinite(e)?Math.max(0,performance.now()-e):0,this.animationFrameId=null,!this.isRunning||this.isPaused)return;let{mode:t,ticksPerFrame:r,fixedDeltaSec:i}=this.timeConfig;if(t!=="manual"){if(t==="realtime")this.runOneTick(this.clock.getDelta());else{this.clock.getDelta();for(let o=0;o<r&&!(!this.isRunning||this.isPaused||(this.runOneTick(i),this.timeConfig.mode!=="fixed"));o+=1);}this.scheduleNextFrame()}};runOneTick(e){this.inTick=!0;try{this.runFrameBody(e)}finally{this.inTick=!1}}runFrameBody(e){this.gameTime.advance(e);let t=this.gameTime.baseScale<DN;t!==this.audioMuffled&&(this.audioMuffled=t,this.audioService.applySnapshot(t?"muffled":"default"));let r=e*this.gameTime.scale,i=performance.now();this.currentFrameProfilerActivities=Ap,this.inputService.beginFrame(),this.frameNumber+=1,this.elapsedTime+=r,this.fixedTimeAccumulator+=r,this.runFixedUpdates();let o=this.ecsService.fixedTimeStep>0?Math.min(this.fixedTimeAccumulator/this.ecsService.fixedTimeStep,1):0;this.ecsService.setFrameMetrics(this.elapsedTime,this.frameNumber),this.ecsService.setInterpolationAlpha(o),this.ecsService.update(r,o),this.sceneService.interpolatePhysics2D(o),this.renderer.beginStatsFrame(),this.sceneService.updateTweens(r),this.updateGameLogicSafe(r),this.flushInstancedNodes();let s=performance.now()-i;this.ticksSinceRender+=1;let a=0;if(this.ticksSinceRender>=this.timeConfig.renderEveryNTicks){this.ticksSinceRender=0;let u=performance.now();this.render(),a=performance.now()-u}if(this.frameListeners.size===0)return;let l=performance.now(),c=l-this.lastHeavySampleAtMs>=NN;c&&(this.lastHeavySampleAtMs=l),this.notifyFrameListeners({dt:e,elapsedTime:this.elapsedTime,frameNumber:this.frameNumber,logicMs:s,renderMs:a,totalFrameMs:s+a,unaccountedMs:Math.max(0,e*1e3-(s+a)),rafLatenessMs:this.currentRafLatenessMs,rendererStats:this.getRendererStatsSample(c),profilerActivities:this.getFrameProfilerActivitiesSnapshot(),activeAudioPlaybacks:this.getActiveAudioPlaybackSnapshot(c)})}subscribeFrameStats(e){return this.frameListeners.add(e),()=>{this.frameListeners.delete(e)}}lastTickErrorMessage=null;updateGameLogicSafe(e){try{this.updateNodes(e),this.lastTickErrorMessage=null}catch(t){let{message:r,stack:i}=Nt(t);r!==this.lastTickErrorMessage&&(this.lastTickErrorMessage=r,console.error("[SceneRunner] Error during game update:",t),Dt({phase:"tick",message:r,stack:i}))}}observeCanvasSize(e){this.observedCanvas===e&&this.canvasSizeObserver!==null||(this.canvasSizeObserver?.disconnect(),this.canvasSizeObserver=null,this.observedCanvas=e,this.canvasCssSize=null,!(typeof ResizeObserver>"u")&&(this.canvasSizeObserver=new ResizeObserver(t=>{let r=t[t.length-1]?.contentRect;r&&(this.canvasCssSize={width:Math.round(r.width),height:Math.round(r.height)})}),this.canvasSizeObserver.observe(e)))}updateNodes(e){let t=this.runtimeGraph;if(t)for(let r of t.rootNodes)r.tick(e);V.flushFreeQueue()}render(){let e=this.renderer.domElement;this.observeCanvasSize(e);let t=this.canvasCssSize,r=t&&t.width>0?t.width:e.clientWidth>0?e.clientWidth:e.width,i=t&&t.height>0?t.height:e.clientHeight>0?e.clientHeight:e.height,o=this.viewportSize.width!==r||this.viewportSize.height!==i;if(o){this.viewportSize.width=r,this.viewportSize.height=i;let u=this.rootLayoutAuthoredSize.width,d=this.rootLayoutAuthoredSize.height,h=u/d,p=r/i,f=u,m=d;p>=h?(m=d,f=m*p):(f=u,m=f/p),this.logicalCameraSize={width:f,height:m}}if(!this.activeCamera){let u=this.runtimeGraph;u&&(this.activeCamera=this.findActiveCamera(u.rootNodes),this.activeCamera&&(this.activeCamera.camera.layers.disableAll(),this.activeCamera.camera.layers.enable(0)))}if(this.activeCamera){let u=r/i;this.activeCamera.updateAspectRatio(u)}if(this.orthographicCamera){let u=this.logicalCameraSize.width/2,d=this.logicalCameraSize.height/2;(this.orthographicCamera.left!==-u||this.orthographicCamera.right!==u||this.orthographicCamera.top!==d||this.orthographicCamera.bottom!==-d)&&(this.orthographicCamera.left=-u,this.orthographicCamera.right=u,this.orthographicCamera.top=d,this.orthographicCamera.bottom=-d,this.orthographicCamera.updateProjectionMatrix(),this.overlayCamera.left=-u,this.overlayCamera.right=u,this.overlayCamera.top=d,this.overlayCamera.bottom=-d,this.overlayCamera.updateProjectionMatrix()),this.activeCamera2D=ru(this.runtimeGraph?.rootNodes??[]);let h=0,p=0,f=1;if(this.activeCamera2D){let m=this.activeCamera2D.computeView(this.logicalCameraSize);this.activeCamera2D.getShakeOffset(this.scratchShake2D),h=m.x+this.scratchShake2D.x,p=m.y+this.scratchShake2D.y,f=m.zoom}this.orthographicCamera.position.x=h,this.orthographicCamera.position.y=p,this.orthographicCamera.zoom!==f&&(this.orthographicCamera.zoom=f,this.orthographicCamera.updateProjectionMatrix())}this.reflowRoot2DNodes(),o&&this.sceneService.setViewportSize(r,i),this.applyAOModeSuppression();let s=this.findActivePostProcessNode(),a=s?s.getConfig():null,l=!!a&&(!!this.activeCamera||a.affect2D);if(l?(this.postFx||(this.postFx=new go(this.renderer.getWebGLRenderer())),this.postFx.ensureLoading()):this.postFx&&(this.postFx.dispose(),this.postFx=null),l&&!!this.postFx&&this.postFx.isReady()&&a&&this.postFx){let u=this.activeCamera?.camera??null;u&&this.updateBillboardSprites(this.runtimeGraph?.rootNodes??[],u),this.postFx.render(this.scene,u,this.orthographicCamera,a),u&&zi()&&(this.physicsDebugOverlay||(this.physicsDebugOverlay=new Ni),this.renderer.setAutoClear(!1),this.physicsDebugOverlay.render(this.renderer,u)),u&&this.renderDirectionAxes("node3d",u),!a.affect2D&&u&&this.renderScene2D(),this.renderDirectionAxes("node2d",this.orthographicCamera)}else this.activeCamera?(this.updateBillboardSprites(this.runtimeGraph?.rootNodes??[],this.activeCamera.camera),this.renderer.setAutoClear(!0),this.renderer.render(this.scene,this.activeCamera.camera)):(this.renderer.setAutoClear(!0),this.renderer.clear()),this.activeCamera&&zi()&&(this.physicsDebugOverlay||(this.physicsDebugOverlay=new Ni),this.renderer.setAutoClear(!1),this.physicsDebugOverlay.render(this.renderer,this.activeCamera.camera)),this.activeCamera&&this.renderDirectionAxes("node3d",this.activeCamera.camera),this.renderScene2D(),this.renderDirectionAxes("node2d",this.orthographicCamera);this.overlay2DActive&&this.renderOverlay2D()}renderDirectionAxes(e,t){Yl()&&(this.directionAxesOverlay||(this.directionAxesOverlay=new gl),this.renderer.setAutoClear(!1),this.directionAxesOverlay.render(this.renderer,t,this.runtimeGraph?.rootNodes??[],e))}renderScene2D(){this.renderer.setAutoClear(!1),this.renderer.clearDepth();let e=this.scene.background;this.scene.background=null,this.renderer.render(this.scene,this.orthographicCamera),this.scene.background=e,this.renderPhysics2DDebug()}renderPhysics2DDebug(){if(!zi())return;let e=this.sceneService.buildPhysics2DDebugBuffers();e&&(this.physics2DDebugOverlay||(this.physics2DDebugOverlay=new Ni),this.renderer.setAutoClear(!1),this.physics2DDebugOverlay.renderBuffers(this.renderer,this.orthographicCamera,e))}renderOverlay2D(){this.renderer.setAutoClear(!1),this.renderer.clearDepth();let e=this.scene.background;this.scene.background=null,this.renderer.render(this.scene,this.overlayCamera),this.scene.background=e}lastAOSuppress=null;applyAOModeSuppression(){let e=this.runtimeGraph;if(!e)return;let t=null,r=[],i=[...e.rootNodes];for(;i.length>0;){let s=i.pop();if(s){s instanceof et&&!t?t=s:s instanceof yt&&r.push(s);for(let a of s.children)i.push(a)}}let o=t?t.getResolvedAOMode()!=="baked":!1;if(o!==this.lastAOSuppress){this.lastAOSuppress=o;for(let s of r)s.setAOSuppressed(o)}}findActivePostProcessNode(){let e=this.runtimeGraph;if(!e)return null;let t=[...e.rootNodes];for(;t.length>0;){let r=t.pop();if(r){if(r instanceof et&&r.isActive())return r;for(let i of r.children)t.push(i)}}return null}findActiveCamera(e){for(let t of e){if(t instanceof fe&&t.visible)return t;if(t.children&&t.children.length>0){let r=t.children.filter(o=>o instanceof V),i=this.findActiveCamera(r);if(i)return i}}return null}findNodeById(e){if(!this.runtimeGraph)return null;for(let t of this.runtimeGraph.rootNodes){let r=t.findById(e);if(r)return r}return null}applyLivePropertyUpdate(e,t,r){if(!this.isRunning||!this.runtimeGraph)return!1;let i=this.findNodeById(e);if(!i)return!1;let s=ke(i).properties.find(a=>a.name===t);if(!s){if(t==="opacity"&&i instanceof M){let a=Number(r);return Number.isFinite(a)?(i.opacity=Math.max(0,Math.min(1,a)),!0):!1}return!1}return s.setValue(i,r),this.afterLivePropertyApplied(i,t),!0}afterLivePropertyApplied(e,t){e instanceof M&&(["position","width","height","size","radius"].includes(t)&&e.captureAuthoredLayoutRectFromCurrent(),["width","height","size","radius","resolutionPreset"].includes(t)&&e.isContainer&&(e.reflowAnchoredChildren(),this.captureAnchoredDescendantRects(e)))}captureAnchoredDescendantRects(e){for(let t of e.children)t instanceof M&&t.captureAuthoredLayoutRectFromCurrent(),t instanceof V&&this.captureAnchoredDescendantRects(t)}bindSceneServiceDelegate(){let e=this;this.sceneService.setDelegate({getActiveCameraNode(){return e.activeCamera},getActiveCamera2DNode(){return e.activeCamera2D},getInputService(){return e.inputService},getUICamera(){return e.orthographicCamera},getLogicalCameraSize(){return{...e.logicalCameraSize}},setActiveCameraNode(t){e.activeCamera=t},findNodeById(t){return e.findNodeById(t)},getRootNodes(){return e.runtimeGraph?.rootNodes??[]},getAudioService(){return e.audioService},getLocalizationService(){return e.localization},getAssetLoader(){return e.assetLoader},getResourceManager(){return e.resourceManager},getECSService(){return e.runtimeGraph?e.ecsService:null},getGameTime(){return e.gameTime},getFrameNumber(){return e.frameNumber},raycastViewport(t,r){return e.raycastViewport(t,r)},reportFrameProfilerActivities(t){e.reportFrameProfilerActivities(t)},loadAndStartScene(t){return e.loadAndStartScene(t)},instantiatePrefab(t,r,i){return e.instantiatePrefab(t,r,i)}})}reportFrameProfilerActivities(e){this.currentFrameProfilerActivities=this.normalizeFrameProfilerActivities(e)}getFrameProfilerActivitiesSnapshot(){return this.currentFrameProfilerActivities.length===0?void 0:this.currentFrameProfilerActivities}getRendererStatsSample(e){return(e||!this.cachedRendererStats)&&(this.cachedRendererStats=this.renderer.getStatsSnapshot()),this.cachedRendererStats}getActiveAudioPlaybackSnapshot(e){let t=this.audioService.getActivePlaybackRevision();if(e||t!==this.cachedAudioRevision){this.cachedAudioRevision=t;let r=this.audioService.getActivePlaybackSnapshot();this.cachedAudioPlaybacks=r.length>0?r:void 0}return this.cachedAudioPlaybacks}normalizeFrameProfilerActivities(e){let t=[];for(let r of e){let i=typeof r.label=="string"?r.label.trim():"";if(!i)continue;let o=this.normalizeFrameProfilerValue(r.selfTimeMs);if(o===null)continue;let s=this.normalizeFrameProfilerValue(r.totalTimeMs);t.push(s===null?{label:i,selfTimeMs:o}:{label:i,selfTimeMs:o,totalTimeMs:Math.max(s,o)})}return t}normalizeFrameProfilerValue(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:e}runFixedUpdates(){let e=this.ecsService.fixedTimeStep;if(e<=0||this.fixedTimeAccumulator<e)return;let t=0,r=this.elapsedTime-this.fixedTimeAccumulator;for(;this.fixedTimeAccumulator>=e&&t<this.ecsService.maxFixedStepsPerFrame;)this.fixedTimeAccumulator-=e,r+=e,this.ecsService.setFrameMetrics(r,this.frameNumber),this.ecsService.fixedUpdate(e),this.sceneService.stepPhysics2D(e),t+=1;t===this.ecsService.maxFixedStepsPerFrame&&(this.fixedTimeAccumulator=Math.min(this.fixedTimeAccumulator,e))}flushInstancedNodes(){let e=this.runtimeGraph;if(!e)return;let t=[...e.rootNodes];for(;t.length>0;){let r=t.pop();if(r){r instanceof bt&&r.flush();for(let i of r.children)i instanceof V&&t.push(i)}}}raycastViewport(e,t){if(!this.runtimeGraph)return null;if(this.overlay2DActive){let i=this.raycastWithCamera(e,t,this.overlayCamera,3);if(i)return i}let r=this.raycastWithCamera(e,t,this.orthographicCamera,1);return r||(this.activeCamera?this.raycastWithCamera(e,t,this.activeCamera.camera,0):null)}raycastWithCamera(e,t,r,i){this.raycastPointer.set(e,t),this.raycaster.layers.set(i),this.raycaster.setFromCamera(this.raycastPointer,r);let o=this.raycaster.intersectObjects(this.scene.children,!0);for(let s of o){if(!this.isObjectVisibleInHierarchy(s.object))continue;let a=this.resolveNodeFromObject(s.object);if(a)return{node:a,distance:s.distance,point:s.point.clone(),object:s.object,instanceId:typeof s.instanceId=="number"?s.instanceId:void 0}}return null}resolveNodeFromObject(e){let t=e;for(;t;){if(t instanceof V)return t;t=t.parent}return null}isObjectVisibleInHierarchy(e){let t=e;for(;t;){if(!t.visible)return!1;t=t.parent}return!0}updateBillboardSprites(e,t){let r=t.getWorldQuaternion(new _),i=t.getWorldPosition(new S);for(let o of e)o instanceof pt?o.syncRenderState(r,i):(o instanceof ht||o instanceof yr)&&o.applyBillboard(r),o.children.length>0&&this.updateBillboardSprites(o.children,t)}stripEditorOnly(e){let t=[];for(let r of e){if(this.isEditorOnly(r)){r.removeFromParent(),r.dispose();continue}let i=r.children.filter(o=>o instanceof V);i.length>0&&this.stripEditorOnly(i),t.push(r)}return t}isEditorOnly(e){let t=e.properties;return this.toBooleanLike(t?.editorOnly)===!0}editorPeekMask=null;setEditorPeekMask(e){let t=e?new Set(e):null;this.editorPeekMask=t&&t.size>0?t:null,this.runtimeGraph&&this.applyEditorPeekMask(this.runtimeGraph.rootNodes)}applyEditorPeekMask(e){let t=this.editorPeekMask;for(let r of e){r.hiddenByEditor=t!==null&&t.has(r.nodeId);let i=r.children.filter(o=>o instanceof V);i.length>0&&this.applyEditorPeekMask(i)}}applyInitialVisibility(e){for(let t of e){let r=this.readInitialVisibility(t);r!==void 0&&(t.visible=r,t.properties.visible=r);let i=t.children.filter(o=>o instanceof V);i.length>0&&this.applyInitialVisibility(i)}}readInitialVisibility(e){let t=e.properties,r=t?.initiallyVisible,i=t?.initially_visible,o=e.userData.properties?.initiallyVisible;return this.toBooleanLike(r)??this.toBooleanLike(i)??this.toBooleanLike(o)}toBooleanLike(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();return t==="true"?!0:t==="false"?!1:void 0}}reflowRoot2DNodes(){if(!this.runtimeGraph)return;let e={width:Math.max(1,this.logicalCameraSize.width),height:Math.max(1,this.logicalCameraSize.height)};for(let t of this.runtimeGraph.rootNodes)t instanceof M&&t.applyAnchoredLayoutRecursive(e,this.rootLayoutAuthoredSize);if(this.overlay2DActive=_v(this.runtimeGraph.rootNodes),this.batch2DEnabled){this.batch2D||(this.batch2D=new Ji(this.scene)),this.ordered2DCount=0,Cs(this.runtimeGraph.rootNodes,this.collectOrdered2D);let t=this.ordered2DBuffer;t.length=this.ordered2DCount,this.scene.updateMatrixWorld(!0),this.batch2D.update(t)}else Cs(this.runtimeGraph.rootNodes)}stopAudioPlayers(e){e instanceof gt&&e.stop();for(let t of e.children)this.stopAudioPlayers(t)}detachScripts(e){for(let t of e.components){if(t.onDetach)try{t.onDetach()}catch(r){console.error("[SceneRunner] Component onDetach failed during stop()",{componentId:t.id,nodeId:e.nodeId,error:r})}ar(t),t.resetStartedState?t.resetStartedState():t._started=!1}for(let t of e.children)t instanceof V&&this.detachScripts(t)}notifyFrameListeners(e){for(let t of this.frameListeners)t(e)}};var Cp=class{renderer;canvas;resizeObserver=null;constructor(e={}){this.canvas=document.createElement("canvas"),this.canvas.style.display="block",this.canvas.style.width="100%",this.canvas.style.height="100%",this.renderer=new xm({canvas:this.canvas,antialias:e.antialias??!0,alpha:!1,powerPreference:"high-performance"}),this.renderer.info.autoReset=!1,this.renderer.setPixelRatio(e.pixelRatio??window.devicePixelRatio),this.renderer.setClearColor(e.clearColor??"#000000"),this.renderer.localClippingEnabled=!0,e.shadows&&(this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=zp)}get domElement(){return this.canvas}getWebGLRenderer(){return this.renderer}attachToDocument(e="app"){let t=document.getElementById(e);if(!(t instanceof HTMLElement))throw new Error(`Missing #${e} container`);this.attach(t)}attach(e){this.resizeObserver?.disconnect(),e.appendChild(this.canvas),this.resize(),this.resizeObserver=new ResizeObserver(()=>{this.resize()}),this.resizeObserver.observe(e)}resize(){let e=this.canvas.parentElement;if(e){let t=e.clientWidth,r=e.clientHeight;this.renderer.setSize(t,r,!1)}}render(e,t){this.renderer.render(e,t)}beginStatsFrame(){this.renderer.info.reset()}getStatsSnapshot(){return{calls:this.renderer.info.render.calls,triangles:this.renderer.info.render.triangles,points:this.renderer.info.render.points,lines:this.renderer.info.render.lines,geometries:this.renderer.info.memory.geometries,textures:this.renderer.info.memory.textures,programs:this.renderer.info.programs?.length??0}}setAutoClear(e){this.renderer.autoClear=e}clear(){this.renderer.clear()}clearDepth(){this.renderer.clearDepth()}dispose(){this.resizeObserver?.disconnect(),this.resizeObserver=null,this.renderer.dispose(),this.canvas.remove()}};var Gv="res://assets/.atlas/atlas-manifest.json",qv="res://assets/.atlas/";async function IN(n,e){try{let t=await e.readText(Gv),r=JSON.parse(t);if(!r||r.formatVersion!==1||!Array.isArray(r.sheets))return!1;let i=new Map(r.sheets.map(o=>[o.id,o.file]));return n.setAtlasResolver(lc(r,o=>`${qv}${i.get(o)??`${o}.png`}`)),!0}catch{return!1}}var bo=class extends O{rotationSpeed=1;constructor(e,t){super(e,t),this.config={rotationSpeed:this.rotationSpeed}}static getPropertySchema(){return{nodeType:"RotateBehavior",properties:[{name:"rotationSpeed",type:"number",ui:{label:"Rotation Speed",description:"Speed of rotation in radians per second",group:"Component",min:0,max:10,step:.1},getValue:e=>e.getRotationSpeed(),setValue:(e,t)=>{let r=e,i=Number(t);!Number.isFinite(i)||i<0||r.setRotationSpeed(i)}}],groups:{Component:{label:"Component Parameters",description:"Configuration for rotation component",expanded:!0}}}}onAttach(){this.setRotationSpeed(this.getRotationSpeed())}onUpdate(e){!this.node||!(this.node instanceof U)||(this.node.rotation.y+=this.rotationSpeed*e)}getRotationSpeed(){let e=this.config.rotationSpeed,t=typeof e=="number"?e:Number(e);return Number.isFinite(t)&&t>=0?t:1}setRotationSpeed(e){this.rotationSpeed=e,this.config.rotationSpeed=e}};var So=class extends O{constructor(e,t){super(e,t),this.config={speed:5,axisHorizontal:"Horizontal",axisVertical:"Vertical",movementPlane:"xz",invertVertical:!0}}static getPropertySchema(){return{nodeType:"SimpleMoveBehavior",properties:[{name:"speed",type:"number",ui:{label:"Speed",description:"Movement speed units per second",group:"Movement",min:0,max:50,step:.1},getValue:e=>e.getSpeed(),setValue:(e,t)=>{let r=e,i=Number(t);!Number.isFinite(i)||i<0||(r.config.speed=i)}},{name:"axisHorizontal",type:"string",ui:{label:"Horizontal Axis",description:"Input axis name for horizontal movement",group:"Input"},getValue:e=>e.getHorizontalAxis(),setValue:(e,t)=>{typeof t!="string"||t.trim().length===0||(e.config.axisHorizontal=t)}},{name:"axisVertical",type:"string",ui:{label:"Vertical Axis",description:"Input axis name for vertical movement",group:"Input"},getValue:e=>e.getVerticalAxis(),setValue:(e,t)=>{typeof t!="string"||t.trim().length===0||(e.config.axisVertical=t)}},{name:"movementPlane",type:"select",ui:{label:"Movement Plane",description:"Select whether vertical input moves on XY or XZ plane",group:"Movement",options:["xz","xy"]},getValue:e=>e.getMovementPlane(),setValue:(e,t)=>{(t==="xz"||t==="xy")&&(e.config.movementPlane=t)}},{name:"invertVertical",type:"boolean",ui:{label:"Invert Vertical",description:"Invert sign for vertical input axis",group:"Movement"},getValue:e=>e.isVerticalInverted(),setValue:(e,t)=>{typeof t=="boolean"&&(e.config.invertVertical=t)}}],groups:{Movement:{label:"Movement",description:"Movement settings",expanded:!0},Input:{label:"Input",description:"Input axis mapping",expanded:!0}}}}onUpdate(e){if(!this.input||!this.node)return;let t=this.input.getAxis(this.getHorizontalAxis()),r=this.input.getAxis(this.getVerticalAxis());if(t===0&&r===0)return;let i=this.isVerticalInverted()?-r:r,o=t*this.getSpeed()*e,s=i*this.getSpeed()*e;this.node.position.x+=o,this.getMovementPlane()==="xy"?this.node.position.y+=s:this.node.position.z+=s}getSpeed(){let e=this.config.speed,t=typeof e=="number"?e:Number(e);return Number.isFinite(t)&&t>=0?t:5}getHorizontalAxis(){let e=this.config.axisHorizontal;return typeof e=="string"&&e.length>0?e:"Horizontal"}getVerticalAxis(){let e=this.config.axisVertical;return typeof e=="string"&&e.length>0?e:"Vertical"}getMovementPlane(){let e=this.config.movementPlane;return e==="xy"||e==="xz"?e:"xz"}isVerticalInverted(){let e=this.config.invertVertical;return typeof e=="boolean"?e:!0}};var vo=class extends O{elapsedTime=0;initialPositionX=0;initialPositionY=0;initialPositionZ=0;constructor(e,t){super(e,t),this.config={amplitude:1,frequency:1,axis:"y"}}static getPropertySchema(){return{nodeType:"SineBehavior",properties:[{name:"amplitude",type:"number",ui:{label:"Amplitude",description:"Maximum displacement from the center",group:"Oscillation",min:0,step:.1},getValue:e=>e.getAmplitude(),setValue:(e,t)=>{let r=e,i=Number(t);!Number.isFinite(i)||i<0||(r.config.amplitude=i)}},{name:"frequency",type:"number",ui:{label:"Frequency (Hz)",description:"Oscillations per second",group:"Oscillation",min:0,step:.1},getValue:e=>e.getFrequency(),setValue:(e,t)=>{let r=e,i=Number(t);!Number.isFinite(i)||i<0||(r.config.frequency=i)}},{name:"axis",type:"select",ui:{label:"Axis",description:"The axis to oscillate along",group:"Oscillation",options:["x","y","z"]},getValue:e=>e.getAxis(),setValue:(e,t)=>{let r=e;(t==="x"||t==="y"||t==="z")&&(r.config.axis=t)}}],groups:{Oscillation:{label:"Oscillation Settings",expanded:!0}}}}onStart(){this.node&&(this.initialPositionX=this.node.position.x,this.initialPositionY=this.node.position.y,this.initialPositionZ=this.node.position.z)}onUpdate(e){if(!this.node)return;this.elapsedTime+=e;let t=Math.sin(this.elapsedTime*this.getFrequency()*Math.PI*2)*this.getAmplitude();this.node.position.set(this.initialPositionX,this.initialPositionY,this.initialPositionZ);let r=this.getAxis();r==="x"?this.node.position.x+=t:r==="y"?this.node.position.y+=t:this.node.position.z+=t}getAmplitude(){let e=this.config.amplitude,t=typeof e=="number"?e:Number(e);return Number.isFinite(t)&&t>=0?t:1}getFrequency(){let e=this.config.frequency,t=typeof e=="number"?e:Number(e);return Number.isFinite(t)&&t>=0?t:1}getAxis(){let e=this.config.axis;return e==="x"||e==="y"||e==="z"?e:"y"}};var wo=class extends O{targetNodeId="";yOffset=2;targetNode=null;cameraNode=null;_unsubscribeViewport=null;_tempWorldPos=new S;_tempPinnedWorldPos=new S;_tempPinnedLocalPos=new S;static getPropertySchema(){return{nodeType:"PinToNodeBehavior",properties:[x("targetNodeId","node",{ui:{label:"Target Model",nodeTypes:["MeshInstance","Node3D","Sprite3D"]},getValue:e=>e.targetNodeId,setValue:(e,t)=>{e.setTargetNodeId(String(t))}}),x("yOffset","number",{ui:{label:"Y Offset",step:.1},getValue:e=>e.yOffset,setValue:(e,t)=>{e.yOffset=Number(t)}})],groups:{}}}setTargetNodeId(e){this.targetNodeId=e,this.targetNode=null}getSceneRoot(){if(!this.node)return null;let e=this.node;for(;e.parent;)e=e.parent;return e}resolveProjectionCamera(e){let t=this.scene?.getActiveCamera()??null;return t?(this.cameraNode=t,t):this.cameraNode?this.cameraNode:(e&&this.findCamera(e),this.cameraNode)}onStart(){if(this.targetNode=null,this.cameraNode=null,this._unsubscribeViewport?.(),this._unsubscribeViewport=this.scene?.onViewportChanged(()=>{this.updatePinning()})??null,!this.node)return;let e=this.getSceneRoot();e&&(this.targetNodeId&&(this.targetNode=this.findNode(this.targetNodeId)),this.resolveProjectionCamera(e),this.updatePinning())}onDetach(){this._unsubscribeViewport?.(),this._unsubscribeViewport=null}findCamera(e){if(e instanceof fe){this.cameraNode=e;return}for(let t of e.children)if(this.findCamera(t),this.cameraNode)return}onUpdate(e){this.updatePinning()}updatePinning(){if(!this.node||!(this.node instanceof M))return;let e=this.getSceneRoot();if(!e)return;!this.targetNode&&this.targetNodeId&&(this.targetNode=this.findNode(this.targetNodeId));let t=this.resolveProjectionCamera(e);if(!this.targetNode||!t)return;let r=this.targetNode,i=t.camera;if(!r||!i)return;r.updateMatrixWorld(!0),this._tempWorldPos.setFromMatrixPosition(r.matrixWorld),this._tempWorldPos.y+=this.yOffset,this._tempWorldPos.project(i);let o=this.getLogicalCameraSize();if(o.width<=0||o.height<=0)return;this._tempPinnedWorldPos.set(this._tempWorldPos.x*(o.width*.5),this._tempWorldPos.y*(o.height*.5),0);let s=this.node.parent;s&&(s.updateMatrixWorld(!0),this._tempPinnedLocalPos.copy(this._tempPinnedWorldPos),s.worldToLocal(this._tempPinnedLocalPos),this.node.position.set(this._tempPinnedLocalPos.x,this._tempPinnedLocalPos.y,this.node.position.z))}getLogicalCameraSize(){let e=this.scene?.getLogicalCameraSize();if(e&&e.width>0&&e.height>0)return e;let t=this.scene?.getViewportSize(),r=t&&t.width>0?t.width:window.innerWidth,i=t&&t.height>0?t.height:window.innerHeight;return r<=0||i<=0?{width:1,height:1}:{width:r,height:i}}};var xo=class n extends O{fadeDirection=null;phase="idle";pendingDestroy=!1;delayRemaining=0;sequenceStarted=!1;constructor(e,t){super(e,t),this.config={FadeInTime:.5,FadeOutTime:.5,FadeInDelay:0,FadeOutDelay:0,DestroyOnFadeOut:!1,FadeOnStart:!1}}static getPropertySchema(){return{nodeType:"FadeBehavior",properties:[{name:"FadeInTime",type:"number",ui:{label:"FadeInTime",group:"Fade",min:0,step:.01,precision:2,unit:"s"},getValue:e=>e.getFadeInTime(),setValue:(e,t)=>{e.setFadeInTime(t)}},{name:"FadeOutTime",type:"number",ui:{label:"FadeOutTime",group:"Fade",min:0,step:.01,precision:2,unit:"s"},getValue:e=>e.getFadeOutTime(),setValue:(e,t)=>{e.setFadeOutTime(t)}},{name:"FadeInDelay",type:"number",ui:{label:"FadeInDelay",group:"Fade",min:0,step:.01,precision:2,unit:"s"},getValue:e=>e.getFadeInDelay(),setValue:(e,t)=>{e.setFadeInDelay(t)}},{name:"FadeOutDelay",type:"number",ui:{label:"FadeOutDelay",group:"Fade",min:0,step:.01,precision:2,unit:"s"},getValue:e=>e.getFadeOutDelay(),setValue:(e,t)=>{e.setFadeOutDelay(t)}},{name:"DestroyOnFadeOut",type:"boolean",ui:{label:"DestroyOnFadeOut",group:"Fade"},getValue:e=>e.getDestroyOnFadeOut(),setValue:(e,t)=>{e.setDestroyOnFadeOut(t)}},{name:"FadeOnStart",type:"boolean",ui:{label:"FadeOnStart",group:"Fade"},getValue:e=>e.getFadeOnStart(),setValue:(e,t)=>{e.setFadeOnStart(t)}}],groups:{Fade:{label:"Fade",description:"Opacity fade settings",expanded:!0}}}}onStart(){this.isNode2D()&&this.getFadeOnStart()&&(this.sequenceStarted=!0,this.node.opacity=0,this.startFade("in"))}onUpdate(e){if(this.isNode2D()){if(this.pendingDestroy){this.pendingDestroy=!1,this.destroyNode();return}this.phase==="delay"&&(this.delayRemaining=Math.max(0,this.delayRemaining-e),this.delayRemaining===0&&(this.phase="idle",this.executeFade()))}}onDetach(){super.onDetach(),this.stopFade(),this.pendingDestroy=!1,this.sequenceStarted=!1}fadeIn(){this.sequenceStarted=!1,this.startFade("in")}fadeOut(){this.sequenceStarted=!1,this.startFade("out")}startFade(e){if(!this.isNode2D())return;this.pendingDestroy=!1,this.fadeDirection=e;let t=e==="in"?this.getFadeInDelay():this.getFadeOutDelay();if(t>0){this.phase="delay",this.delayRemaining=t;return}this.executeFade()}executeFade(){if(!this.isNode2D()||!this.fadeDirection)return;let e=this.fadeDirection==="in"?this.getFadeInTime():this.getFadeOutTime(),t=()=>this.onFadeComplete();this.fadeDirection==="in"?this.node.show(e,t):this.node.hide(e,t)}onFadeComplete(){let e=this.fadeDirection;if(this.stopFade(),e==="in"&&this.sequenceStarted){this.startFade("out");return}e==="out"&&this.getDestroyOnFadeOut()&&(this.pendingDestroy=!0)}stopFade(){this.fadeDirection=null,this.phase="idle",this.delayRemaining=0}destroyNode(){if(!this.node)return;let e=this.node.parentNode;e&&e.disownChild(this.node)}isNode2D(){return this.node instanceof M}getFadeInTime(){return n.toNonNegativeNumber(this.config.FadeInTime,.5)}setFadeInTime(e){this.config.FadeInTime=n.toNonNegativeNumber(e,.5)}getFadeOutTime(){return n.toNonNegativeNumber(this.config.FadeOutTime,.5)}setFadeOutTime(e){this.config.FadeOutTime=n.toNonNegativeNumber(e,.5)}getFadeInDelay(){return n.toNonNegativeNumber(this.config.FadeInDelay,0)}setFadeInDelay(e){this.config.FadeInDelay=n.toNonNegativeNumber(e,0)}getFadeOutDelay(){return n.toNonNegativeNumber(this.config.FadeOutDelay,0)}setFadeOutDelay(e){this.config.FadeOutDelay=n.toNonNegativeNumber(e,0)}getDestroyOnFadeOut(){return!!this.config.DestroyOnFadeOut}setDestroyOnFadeOut(e){this.config.DestroyOnFadeOut=!!e}getFadeOnStart(){return!!this.config.FadeOnStart}setFadeOnStart(e){this.config.FadeOnStart=!!e}static toNonNegativeNumber(e,t){let r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?Math.max(0,r):t}};var RN=`
|
|
196
|
-
varying vec2 vUv;
|
|
197
|
-
void main() {
|
|
198
|
-
vUv = uv;
|
|
199
|
-
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
|
|
200
|
-
}
|
|
201
|
-
`,BN=`
|
|
202
|
-
uniform sampler2D map;
|
|
203
|
-
uniform bool hasMap;
|
|
204
|
-
uniform vec3 color;
|
|
205
|
-
uniform float opacity;
|
|
206
|
-
uniform float progress;
|
|
207
|
-
uniform float startAngleCos;
|
|
208
|
-
uniform float startAngleSin;
|
|
209
|
-
uniform float direction;
|
|
210
|
-
|
|
211
|
-
varying vec2 vUv;
|
|
212
|
-
|
|
213
|
-
void main() {
|
|
214
|
-
vec4 texColor = hasMap ? texture2D(map, vUv) : vec4(1.0);
|
|
215
|
-
texColor.rgb *= color;
|
|
216
|
-
|
|
217
|
-
vec2 uv = vUv - 0.5;
|
|
218
|
-
// Rotate by -startAngle: new_x = cos*x - sin*y, new_y = sin*x + cos*y (clockwise rotation)
|
|
219
|
-
// We rotate the uv point to align the start angle with "up" (positive y)
|
|
220
|
-
vec2 rotated = vec2(
|
|
221
|
-
startAngleCos * uv.x + startAngleSin * uv.y,
|
|
222
|
-
-startAngleSin * uv.x + startAngleCos * uv.y
|
|
223
|
-
);
|
|
224
|
-
|
|
225
|
-
// atan(x, y) gives angle from +y axis (top), going clockwise for positive x
|
|
226
|
-
float angle = atan(rotated.x * direction, rotated.y);
|
|
227
|
-
|
|
228
|
-
const float TWO_PI = 6.28318530718;
|
|
229
|
-
if (angle < 0.0) angle += TWO_PI;
|
|
230
|
-
|
|
231
|
-
float threshold = clamp(progress, 0.0, 1.0) * TWO_PI;
|
|
232
|
-
if (angle > threshold) {
|
|
233
|
-
discard;
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
gl_FragColor = vec4(texColor.rgb, texColor.a * opacity);
|
|
237
|
-
}
|
|
238
|
-
`,Po=class extends O{_value=1;_currentValue=1;_animationSpeed=3;_startAngle=0;_clockwise=!0;_opacity=1;_radialMaterial=null;_originalMaterial=null;_spriteMesh=null;_lastKnownTexture=null;constructor(e,t){super(e,t),this.config={value:this._value,animationSpeed:this._animationSpeed,startAngle:this._startAngle,clockwise:this._clockwise}}static getPropertySchema(){return{nodeType:"RadialProgressBehavior",properties:[{name:"value",type:"number",ui:{label:"Value",description:"Target progress from 0.0 (empty) to 1.0 (full)",group:"Progress",min:0,max:1,step:.01,precision:2},getValue:e=>e.getValue(),setValue:(e,t)=>e.setValue(Number(t))},{name:"animationSpeed",type:"number",ui:{label:"Animation Speed",description:"How fast the progress bar animates (higher = faster)",group:"Progress",min:0,max:20,step:.1,precision:1},getValue:e=>e.getAnimationSpeed(),setValue:(e,t)=>e.setAnimationSpeed(Number(t))},{name:"startAngle",type:"number",ui:{label:"Start Angle",description:"Starting angle in degrees. 0 = top (12 o'clock), 90 = right",group:"Progress",min:-360,max:360,step:1,precision:0,unit:"\xB0"},getValue:e=>Math.round(e.getStartAngle()*(180/Math.PI)),setValue:(e,t)=>e.setStartAngle(Number(t)*(Math.PI/180))},{name:"clockwise",type:"boolean",ui:{label:"Clockwise",description:"Fill direction: clockwise or counter-clockwise",group:"Progress"},getValue:e=>e.getClockwise(),setValue:(e,t)=>e.setClockwise(!!t)}],groups:{Progress:{label:"Radial Progress",description:"Parameters for radial progress masking",expanded:!0}}}}onAttach(){if(!(this.node instanceof Le)){console.warn("[RadialProgressBehavior] Must be attached to a Sprite2D node");return}let t=this.node.children.find(s=>s instanceof B);if(!t){console.warn("[RadialProgressBehavior] No mesh found on Sprite2D");return}this._spriteMesh=t,this._originalMaterial=t.material;let i=Array.isArray(t.material)?t.material[0]:t.material,o=i.map??null;this._lastKnownTexture=o,this._opacity=i.opacity??1,this._radialMaterial=this._buildMaterial(o,i),t.material=this._radialMaterial,this._currentValue=this._value,this._updateUniforms()}onUpdate(e){if(!this._radialMaterial||!this._spriteMesh)return;let t=this._animationSpeed;if(t<=0)this._currentValue=this._value;else{let r=this._value-this._currentValue,i=r*Math.min(t*e,1);this._currentValue+=i,Math.abs(r)<1e-4&&(this._currentValue=this._value)}this._syncTexture(),this._updateUniforms()}onDetach(){this._spriteMesh&&this._originalMaterial!==null&&(this._spriteMesh.material=this._originalMaterial)}getValue(){return this._value}setValue(e,t=!1){let r=Math.max(0,Math.min(1,e));this._value=r,this.config.value=r,t&&(this._currentValue=r,this._updateUniforms())}setValueImmediate(e){this.setValue(e,!0)}getAnimationSpeed(){return this._animationSpeed}setAnimationSpeed(e){this._animationSpeed=Math.max(0,e),this.config.animationSpeed=this._animationSpeed}getStartAngle(){return this._startAngle}setStartAngle(e){this._startAngle=e,this.config.startAngle=Math.round(e*(180/Math.PI)),this._updateAngleUniforms()}getClockwise(){return this._clockwise}setClockwise(e){this._clockwise=e,this.config.clockwise=e,this._radialMaterial&&(this._radialMaterial.uniforms.direction.value=e?1:-1)}_buildMaterial(e,t){let r=t.color?.r??1,i=t.color?.g??1,o=t.color?.b??1;return new hm({uniforms:{map:{value:e},hasMap:{value:e!==null},color:{value:[r,i,o]},opacity:{value:this._opacity},progress:{value:this._currentValue},startAngleCos:{value:Math.cos(this._startAngle)},startAngleSin:{value:Math.sin(this._startAngle)},direction:{value:this._clockwise?1:-1}},vertexShader:RN,fragmentShader:BN,transparent:!0,depthTest:!1})}_syncTexture(){if(!this._originalMaterial||!this._radialMaterial)return;let t=(Array.isArray(this._originalMaterial)?this._originalMaterial[0]:this._originalMaterial).map??null;t!==this._lastKnownTexture&&(this._lastKnownTexture=t,this._radialMaterial.uniforms.map.value=t,this._radialMaterial.uniforms.hasMap.value=t!==null)}_updateUniforms(){this._radialMaterial&&(this._radialMaterial.uniforms.progress.value=this._currentValue,this._radialMaterial.uniforms.opacity.value=this._opacity)}_updateAngleUniforms(){this._radialMaterial&&(this._radialMaterial.uniforms.startAngleCos.value=Math.cos(this._startAngle),this._radialMaterial.uniforms.startAngleSin.value=Math.sin(this._startAngle))}};var ko=class extends O{onNodeSignal=()=>{this.playConfiguredSound()};constructor(e,t){super(e,t),this.config={audioTrack:"",triggerEvent:"pointerdown",volume:1,loop:!1,bus:"sfx",pitchVariation:0,volumeVariation:0}}static getPropertySchema(){return{nodeType:"PlaySoundBehavior",properties:[{name:"audioTrack",type:"string",ui:{label:"Audio Track",description:"Asset URL (res://..., data:audio/..., or absolute URL)",group:"Audio",editor:"audio-resource"},getValue:e=>e.getAudioTrack(),setValue:(e,t)=>{e.setAudioTrack(t)}},{name:"triggerEvent",type:"string",ui:{label:"Trigger Event",description:"Node signal or UI event (pointerdown, pointerup, click)",group:"Audio"},getValue:e=>e.getTriggerEvent(),setValue:(e,t)=>{e.setTriggerEvent(t)}},{name:"volume",type:"number",ui:{label:"Volume",group:"Audio",min:0,max:1,step:.01,precision:2},getValue:e=>e.getVolume(),setValue:(e,t)=>{e.setVolume(t)}},{name:"loop",type:"boolean",ui:{label:"Loop",group:"Audio"},getValue:e=>e.getLoop(),setValue:(e,t)=>{e.setLoop(t)}},{name:"bus",type:"enum",ui:{label:"Bus",group:"Audio",options:[...ut]},getValue:e=>e.getBus(),setValue:(e,t)=>{e.setBus(t)}},{name:"pitchVariation",type:"number",ui:{label:"Pitch Variation",description:"Random \xB1 playback-rate spread per shot",group:"Audio",min:0,max:1,step:.01,precision:2},getValue:e=>e.getPitchVariation(),setValue:(e,t)=>{e.setPitchVariation(t)}},{name:"volumeVariation",type:"number",ui:{label:"Volume Variation",description:"Random \xB1 volume spread per shot",group:"Audio",min:0,max:1,step:.01,precision:2},getValue:e=>e.getVolumeVariation(),setValue:(e,t)=>{e.setVolumeVariation(t)}}],groups:{Audio:{label:"Audio",expanded:!0}}}}onStart(){this.bindTrigger()}onDetach(){this.unbindTrigger(),super.onDetach()}bindTrigger(){if(!this.node)return;let e=this.getTriggerEvent();this.node.connect(e,this,this.onNodeSignal)}unbindTrigger(){if(!this.node)return;let e=this.getTriggerEvent();this.node.disconnect(e,this,this.onNodeSignal)}async playConfiguredSound(){let e=this.scene,t=this.node;if(!e||!t)return;let r=this.getAudioTrack();if(!r){console.warn("[PlaySoundBehavior] audioTrack is not configured.");return}let i=e.getAssetLoader(),o=e.getAudioService();if(!i||!o){console.warn("[PlaySoundBehavior] Audio services are not available in this runtime context.");return}try{let s=await i.loadAudio(r),a=e.getAudioService();if(!a)return;let l=i.getAudioMetadata(r);a.play(s,{resourcePath:r,sizeBytes:l?.sizeBytes,volume:this.getVolume(),loop:this.getLoop(),bus:this.getBus(),pitchVariation:this.getPitchVariation(),volumeVariation:this.getVolumeVariation()})}catch(s){console.warn(`[PlaySoundBehavior] Failed to play "${r}" on node "${t.name}":`,s)}}getAudioTrack(){return this.normalizeTrack(this.config.audioTrack)}setAudioTrack(e){this.config.audioTrack=this.normalizeTrack(e)}getTriggerEvent(){let e=this.config.triggerEvent;if(typeof e!="string")return"pointerdown";let t=e.trim();return t.length>0?t:"pointerdown"}setTriggerEvent(e){let t=!!this.node;t&&this.unbindTrigger(),this.config.triggerEvent=this.toTrimmedString(e,"pointerdown"),t&&this.bindTrigger()}getVolume(){return this.toVolume(this.config.volume,1)}setVolume(e){this.config.volume=this.toVolume(e,1)}getLoop(){return this.toBoolean(this.config.loop,!1)}setLoop(e){this.config.loop=this.toBoolean(e,!1)}getBus(){return this.toBus(this.config.bus)}setBus(e){this.config.bus=this.toBus(e)}getPitchVariation(){return this.toVariation(this.config.pitchVariation)}setPitchVariation(e){this.config.pitchVariation=this.toVariation(e)}getVolumeVariation(){return this.toVariation(this.config.volumeVariation)}setVolumeVariation(e){this.config.volumeVariation=this.toVariation(e)}normalizeTrack(e){return this.toTrimmedString(e,"")}toTrimmedString(e,t){if(typeof e!="string")return t;let r=e.trim();return r.length>0?r:t}toBoolean(e,t){if(typeof e=="boolean")return e;if(typeof e=="string"){let r=e.trim().toLowerCase();if(r==="true")return!0;if(r==="false")return!1}return t}toVolume(e,t){let r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?Math.min(1,Math.max(0,r)):t}toBus(e){return typeof e=="string"&&ut.includes(e)?e:"sfx"}toVariation(e){let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?Math.min(1,Math.max(0,t)):0}};var Ao=class n extends O{boundSignal=null;onSignal=()=>{this.scene?.audio.sfx(this.getPreset(),{volume:this.getVolume(),pitch:this.getPitch()})};constructor(e,t){super(e,t),this.config={signal:"pointerdown",preset:"tap",volume:1,pitch:1}}static getPropertySchema(){return{nodeType:"SfxOnSignalBehavior",properties:[{name:"signal",type:"string",ui:{label:"Signal",description:"Node signal that plays the sound (pointerdown, hit, damaged, \u2026)",group:"Procedural SFX"},getValue:e=>e.getSignal(),setValue:(e,t)=>{e.setSignal(t)}},{name:"preset",type:"enum",ui:{label:"Preset",description:"Built-in synth patch played on the sfx bus",group:"Procedural SFX",options:[...ll]},getValue:e=>e.getPreset(),setValue:(e,t)=>{e.config.preset=Mi(t)?t:"tap"}},{name:"volume",type:"number",ui:{label:"Volume",group:"Procedural SFX",min:0,max:1,step:.01,precision:2},getValue:e=>e.getVolume(),setValue:(e,t)=>{e.config.volume=n.clamp01(t)}},{name:"pitch",type:"number",ui:{label:"Pitch",description:"Frequency multiplier: 2 = an octave up, 0.5 = an octave down",group:"Procedural SFX",min:.25,max:4,step:.05,precision:2},getValue:e=>e.getPitch(),setValue:(e,t)=>{e.config.pitch=Lr(t)}}],groups:{"Procedural SFX":{label:"Procedural SFX",description:"Synthesized one-shot played when the signal fires",expanded:!0}}}}onStart(){this.bind()}onDetach(){this.unbind(),super.onDetach()}bind(){this.node&&(this.boundSignal=this.getSignal(),this.node.connect(this.boundSignal,this,this.onSignal))}unbind(){!this.node||!this.boundSignal||(this.node.disconnect(this.boundSignal,this,this.onSignal),this.boundSignal=null)}getSignal(){let e=this.config.signal;if(typeof e!="string")return"pointerdown";let t=e.trim();return t.length>0?t:"pointerdown"}setSignal(e){let t=!!this.node;t&&this.unbind(),this.config.signal=typeof e=="string"&&e.trim().length>0?e.trim():"pointerdown",t&&this.bind()}getPreset(){return Mi(this.config.preset)?this.config.preset:"tap"}getVolume(){return n.clamp01(this.config.volume)}getPitch(){return Lr(this.config.pitch)}static clamp01(e){let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?Math.min(1,Math.max(0,t)):1}};var To=class n extends O{boundSignal=null;onSignal=()=>{let e=this.node,t=this.scene;!e||!t||t.juice.burst(e,this.buildOptions())};constructor(e,t){super(e,t),this.config={signal:"hit",count:14,color:"",speed:260,sizePx:10,lifeSec:.5,gravityY:-600}}static getPropertySchema(){return{nodeType:"BurstOnSignalBehavior",properties:[{name:"signal",type:"string",ui:{label:"Signal",description:"Node signal that fires the burst (e.g. hit, damaged, pointerdown)",group:"Burst"},getValue:e=>e.getSignal(),setValue:(e,t)=>{e.setSignal(t)}},{name:"count",type:"number",ui:{label:"Count",description:"Particles per burst",group:"Burst",min:1,max:512,step:1,precision:0},getValue:e=>e.getNumber("count",14),setValue:(e,t)=>{e.config.count=n.num(t,14)}},{name:"color",type:"color",ui:{label:"Color",description:"Particle colour; empty = white",group:"Burst"},getValue:e=>e.getColor(),setValue:(e,t)=>{e.config.color=typeof t=="string"?t.trim():""}},{name:"speed",type:"number",ui:{label:"Speed",description:"Initial particle speed",group:"Burst",min:0,step:10,precision:0,unit:"px/s"},getValue:e=>e.getNumber("speed",260),setValue:(e,t)=>{e.config.speed=n.num(t,260)}},{name:"sizePx",type:"number",ui:{label:"Size",group:"Burst",min:.5,step:1,precision:1,unit:"px"},getValue:e=>e.getNumber("sizePx",10),setValue:(e,t)=>{e.config.sizePx=n.num(t,10)}},{name:"lifeSec",type:"number",ui:{label:"Life",group:"Burst",min:.05,step:.05,precision:2,unit:"s"},getValue:e=>e.getNumber("lifeSec",.5),setValue:(e,t)=>{e.config.lifeSec=n.num(t,.5)}},{name:"gravityY",type:"number",ui:{label:"Gravity Y",description:"Vertical acceleration; negative falls, 0 = weightless",group:"Burst",step:50,precision:0,unit:"px/s\xB2"},getValue:e=>e.getNumber("gravityY",-600),setValue:(e,t)=>{e.config.gravityY=n.num(t,-600)}}],groups:{Burst:{label:"Particle Burst",description:"One-shot particles spawned when the signal fires",expanded:!0}}}}onStart(){this.bind()}onDetach(){this.unbind(),super.onDetach()}buildOptions(){let e=this.getColor();return{count:this.getNumber("count",14),speed:this.getNumber("speed",260),sizePx:this.getNumber("sizePx",10),lifeSec:this.getNumber("lifeSec",.5),gravityY:this.getNumber("gravityY",-600),...e?{color:e}:{}}}bind(){this.node&&(this.boundSignal=this.getSignal(),this.node.connect(this.boundSignal,this,this.onSignal))}unbind(){!this.node||!this.boundSignal||(this.node.disconnect(this.boundSignal,this,this.onSignal),this.boundSignal=null)}getSignal(){let e=this.config.signal;if(typeof e!="string")return"hit";let t=e.trim();return t.length>0?t:"hit"}setSignal(e){let t=!!this.node;t&&this.unbind(),this.config.signal=typeof e=="string"&&e.trim().length>0?e.trim():"hit",t&&this.bind()}getColor(){return typeof this.config.color=="string"?this.config.color.trim():""}getNumber(e,t){return n.num(this.config[e],t)}static num(e,t){if(e==null||e==="")return t;let r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?r:t}};function Gr(n){if(!Array.isArray(n)||n.length===0)return[];if(typeof n[0]=="number"){let t=[];for(let r=0;r+1<n.length;r+=2){let i=Number(n[r]),o=Number(n[r+1]);Number.isFinite(i)&&Number.isFinite(o)&&t.push({x:i,y:o})}return t}let e=[];for(let t of n){if(Array.isArray(t)){let r=Number(t[0]),i=Number(t[1]);Number.isFinite(r)&&Number.isFinite(i)&&e.push({x:r,y:i});continue}if(t&&typeof t=="object"){let r=Number(t.x),i=Number(t.y);Number.isFinite(r)&&Number.isFinite(i)&&e.push({x:r,y:i})}}return e}function VN(n){return n.map(e=>({x:Math.round(e.x*100)/100,y:Math.round(e.y*100)/100}))}var Co=class extends O{debugLine=null;debugKey="";polygonCacheInput=void 0;polygonCache=[];constructor(e,t){super(e,t),this.config={shape:"rect",width:64,height:64,radius:32,offsetX:0,offsetY:0,points:[],polygonSource:"manual",group:"default",debugDraw:!1}}static getPropertySchema(){let e=(t,r,i)=>({name:t,type:"number",ui:{label:r,group:i,step:1},getValue:o=>o.config[t],setValue:(o,s)=>{o.config[t]=Number(s)}});return{nodeType:"Hitbox2D",properties:[{name:"shape",type:"select",ui:{label:"Shape",description:"Rect and circle are axis-aligned (rotation ignored, scale honored); polygon is rotation-aware and may be concave",group:"Shape",options:["rect","circle","polygon"]},getValue:t=>t.config.shape,setValue:(t,r)=>{t.config.shape=r==="circle"?"circle":r==="polygon"?"polygon":"rect"}},e("width","Width","Shape"),e("height","Height","Shape"),e("radius","Radius","Shape"),e("offsetX","Offset X","Shape"),e("offsetY","Offset Y","Shape"),{name:"polygonSource",type:"select",ui:{label:"Polygon Source",description:"manual: the vertices below. frame: the collision polygon of the animation frame currently showing on this AnimatedSprite2D.",group:"Shape",options:["manual","frame"]},getValue:t=>t.config.polygonSource??"manual",setValue:(t,r)=>{t.config.polygonSource=r==="frame"?"frame":"manual"}},{name:"points",type:"object",ui:{label:"Polygon",description:"Vertices in node-local pixels (y up). Edit them in the viewport.",group:"Shape",editor:"collision-polygon"},getValue:t=>t.config.points??[],setValue:(t,r)=>{t.config.points=Gr(r)}},{name:"group",type:"string",ui:{label:"Group",description:"Collision group tag used to filter queries (Godot-style group)",group:"Filtering"},getValue:t=>t.config.group,setValue:(t,r)=>{t.config.group=String(r??"default")}},{name:"debugDraw",type:"boolean",ui:{label:"Debug Draw",description:"Render the shape outline in play mode",group:"Debug"},getValue:t=>t.config.debugDraw,setValue:(t,r)=>{t.config.debugDraw=!!r}}],groups:{Shape:{label:"Shape",expanded:!0},Filtering:{label:"Filtering",expanded:!0},Debug:{label:"Debug",expanded:!1}}}}getHitboxShape(){let e=this.config.shape;return e==="circle"?"circle":e==="polygon"?"polygon":"rect"}getHitboxSize(){return{width:Number(this.config.width)||0,height:Number(this.config.height)||0,radius:Number(this.config.radius)||0}}getHitboxOffset(){return{x:Number(this.config.offsetX)||0,y:Number(this.config.offsetY)||0}}getHitboxGroup(){return String(this.config.group??"default")}getHitboxPolygon(){if(this.config.polygonSource==="frame"){let t=this.node;return typeof t?.getFrameCollisionPolygon=="function"?t.getFrameCollisionPolygon():[]}let e=this.config.points;return e!==this.polygonCacheInput&&(this.polygonCacheInput=e,this.polygonCache=Gr(e)),this.polygonCache}onStart(){this.scene?.collision2d.register(this)}onUpdate(){this.syncDebugDraw()}onDetach(){this.scene?.collision2d.unregister(this),this.removeDebugLine(),super.onDetach()}syncDebugDraw(){let e=this.node;if(!e)return;if(!this.config.debugDraw){this.removeDebugLine();return}let t=this.getHitboxSize(),r=this.getHitboxOffset(),i=this.getHitboxShape(),o=i==="polygon"?this.getHitboxPolygon():null,s=i==="polygon"?`polygon|${r.x}|${r.y}|${o?.map(d=>`${d.x},${d.y}`).join(" ")}`:`${i}|${t.width}|${t.height}|${t.radius}|${r.x}|${r.y}`;if(this.debugLine&&s===this.debugKey)return;this.removeDebugLine(),this.debugKey=s;let a=[];if(i==="polygon"){if(!o||o.length<3)return;for(let d of o)a.push(r.x+d.x,r.y+d.y,0)}else if(i==="circle")for(let h=0;h<32;h++){let p=h/32*Math.PI*2;a.push(r.x+Math.cos(p)*t.radius,r.y+Math.sin(p)*t.radius,0)}else{let d=t.width/2,h=t.height/2;a.push(r.x-d,r.y-h,0,r.x+d,r.y-h,0,r.x+d,r.y+h,0,r.x-d,r.y+h,0)}let l=new le;l.setAttribute("position",new J(a,3));let c=new Ct({color:8255999,depthTest:!1,transparent:!0,opacity:.9}),u=new jo(l,c);u.renderOrder=5e3,u.userData[Fe]=!0,e.add(u),this.debugLine=u}removeDebugLine(){this.debugLine&&(this.debugLine.removeFromParent(),this.debugLine.geometry.dispose(),this.debugLine.material.dispose(),this.debugLine=null,this.debugKey="")}};var Mo=class extends O{constructor(e,t){super(e,t),this.config={bodyType:"dynamic",gravityScale:1,mass:0,linearDamping:0,angularDamping:.05,fixedRotation:!1,bullet:!1,canSleep:!0,emitContacts:!1}}static getPropertySchema(){let e=(r,i,o,s,a=.05)=>({name:r,type:"number",ui:{label:i,group:o,step:a,description:s},getValue:l=>l.config[r],setValue:(l,c)=>{l.config[r]=Number(c)}}),t=(r,i,o,s)=>({name:r,type:"boolean",ui:{label:i,group:o,description:s},getValue:a=>a.config[r],setValue:(a,l)=>{a.config[r]=!!l}});return{nodeType:"PhysicsBody2D",properties:[{name:"bodyType",type:"select",ui:{label:"Body Type",description:"static: never moves. kinematic: moved by scripts/animation, pushes others, is not pushed. dynamic: simulated.",group:"Body",options:["static","kinematic","dynamic"]},getValue:r=>r.config.bodyType,setValue:(r,i)=>{r.config.bodyType=i==="static"?"static":i==="kinematic"?"kinematic":"dynamic"}},e("gravityScale","Gravity Scale","Body","Multiplier on world gravity. 0 makes the body float; negative makes it rise."),e("mass","Mass","Body","Explicit mass. 0 derives it from the collider area times its density.",.1),e("linearDamping","Linear Damping","Damping","Per-second velocity decay."),e("angularDamping","Angular Damping","Damping","Per-second spin decay."),t("fixedRotation","Fixed Rotation","Body","Lock the rotation \u2014 the usual choice for a character or a UI prop."),t("bullet","Bullet (CCD)","Body","Sweep this body against static geometry so a fast circle cannot tunnel through a wall."),t("canSleep","Can Sleep","Body","Let the body stop simulating once it has been at rest for half a second."),t("emitContacts","Emit Contacts","Signals","Fire contact-started / contact-ended on this node. Off by default: most games never read them.")],groups:{Body:{label:"Body",expanded:!0},Damping:{label:"Damping",expanded:!1},Signals:{label:"Signals",expanded:!1}}}}getBodyType(){let e=this.config.bodyType;return e==="static"?"static":e==="kinematic"?"kinematic":"dynamic"}getBodyConfig(){return{gravityScale:yl(this.config.gravityScale,1),mass:Math.max(0,yl(this.config.mass,0)),linearDamping:Math.max(0,yl(this.config.linearDamping,0)),angularDamping:Math.max(0,yl(this.config.angularDamping,0)),fixedRotation:!!this.config.fixedRotation,bullet:!!this.config.bullet,canSleep:this.config.canSleep!==!1,emitContacts:!!this.config.emitContacts}}onStart(){this.scene?.physics2d.registerBody(this)}onDetach(){this.scene?.physics2d.unregisterBody(this),super.onDetach()}};function yl(n,e){let t=Number(n);return Number.isFinite(t)?t:e}var Do=class extends O{polygonCacheInput=void 0;polygonCache=[];constructor(e,t){super(e,t),this.config={shape:"rect",width:64,height:64,radius:32,offsetX:0,offsetY:0,points:[],polygonSource:"manual",friction:.4,restitution:.2,density:1,sensor:!1,group:"default"}}static getPropertySchema(){let e=(t,r,i,o,s=1)=>({name:t,type:"number",ui:{label:r,group:i,step:s,description:o},getValue:a=>a.config[t],setValue:(a,l)=>{a.config[t]=Number(l)}});return{nodeType:"Collider2D",properties:[{name:"shape",type:"select",ui:{label:"Shape",description:"All of them follow the node rotation and scale. A capsule is upright along local Y and sized by height + radius (Godot\u2019s convention). A polygon may be concave; it is split into convex parts for you.",group:"Shape",options:["rect","circle","polygon","capsule"]},getValue:t=>t.config.shape,setValue:(t,r)=>{let i=String(r);t.config.shape=["circle","polygon","capsule"].includes(i)?i:"rect"}},e("width","Width","Shape","Rect width in design pixels."),e("height","Height","Shape","Rect height, or a capsule\u2019s TOTAL height including both caps."),e("radius","Radius","Shape","Circle radius, or a capsule\u2019s cap radius (its half-width)."),e("offsetX","Offset X","Shape","Shape offset from the node origin."),e("offsetY","Offset Y","Shape","Shape offset from the node origin."),{name:"polygonSource",type:"select",ui:{label:"Polygon Source",description:"manual: the vertices below. frame: the collision polygon of the animation frame showing right now.",group:"Shape",options:["manual","frame"]},getValue:t=>t.config.polygonSource??"manual",setValue:(t,r)=>{t.config.polygonSource=r==="frame"?"frame":"manual"}},{name:"points",type:"object",ui:{label:"Polygon",description:"Vertices in node-local pixels (y up). Edit them in the viewport.",group:"Shape",editor:"collision-polygon"},getValue:t=>t.config.points??[],setValue:(t,r)=>{t.config.points=Gr(r)}},e("friction","Friction","Material","Coulomb friction. Combined between two colliders as the geometric mean.",.05),e("restitution","Restitution","Material","Bounciness, 0 to 1. Combined as the maximum of the two. Slow contacts never bounce.",.05),e("density","Density","Material","Mass per unit area, used when the body derives its own mass.",.1),{name:"sensor",type:"boolean",ui:{label:"Sensor",description:"Detect overlaps and report body-entered / body-exited without pushing anything (Godot Area2D).",group:"Filtering"},getValue:t=>t.config.sensor,setValue:(t,r)=>{t.config.sensor=!!r}},{name:"group",type:"string",ui:{label:"Group",description:"Tag used to filter physics queries (same convention as Hitbox2D).",group:"Filtering"},getValue:t=>t.config.group,setValue:(t,r)=>{t.config.group=String(r??"default")}}],groups:{Shape:{label:"Shape",expanded:!0},Material:{label:"Material",expanded:!0},Filtering:{label:"Filtering",expanded:!1}}}}getColliderShape(){let e=this.config.shape;return e==="circle"||e==="polygon"||e==="capsule"?e:"rect"}getColliderSize(){return{width:Number(this.config.width)||0,height:Number(this.config.height)||0,radius:Number(this.config.radius)||0}}getColliderOffset(){return{x:Number(this.config.offsetX)||0,y:Number(this.config.offsetY)||0}}getColliderPolygon(){if(this.config.polygonSource==="frame"){let t=this.node;return typeof t?.getFrameCollisionPolygon=="function"?t.getFrameCollisionPolygon():[]}let e=this.config.points;return e!==this.polygonCacheInput&&(this.polygonCacheInput=e,this.polygonCache=Gr(e)),this.polygonCache}getColliderMaterial(){return{friction:Math.max(0,Number(this.config.friction)||0),restitution:Math.min(1,Math.max(0,Number(this.config.restitution)||0)),density:Math.max(1e-4,Number(this.config.density)||1)}}isSensor(){return!!this.config.sensor}getColliderGroup(){return String(this.config.group??"default")}getColliderRevision(){let e=this.config;if(e.polygonSource==="frame"){let r=this.getColliderPolygon(),i=r[0];return`frame|${r.length}|${i?.x??0},${i?.y??0}|${e.friction}|${e.restitution}|${e.density}|${e.sensor}|${e.group}`}let t=this.getColliderPolygon();return[e.shape,e.width,e.height,e.radius,e.offsetX,e.offsetY,t.length,t.map(r=>`${r.x},${r.y}`).join(" "),e.friction,e.restitution,e.density,e.sensor,e.group].join("|")}onStart(){this.scene?.physics2d.registerCollider(this)}onDetach(){this.scene?.physics2d.unregisterCollider(this),super.onDetach()}};var No=class extends O{constructor(e,t){super(e,t),this.config={gravityX:0,gravityY:-1960}}static getPropertySchema(){let e=(t,r,i)=>({name:t,type:"number",ui:{label:r,group:"Gravity",step:10,description:i},getValue:o=>o.config[t],setValue:(o,s)=>{o.config[t]=Number(s)}});return{nodeType:"PhysicsWorld2D",properties:[e("gravityX","Gravity X","Sideways gravity in px/s^2. 0 for most games."),e("gravityY","Gravity Y","Vertical gravity in px/s^2. Y is up, so falling is NEGATIVE.")],groups:{Gravity:{label:"Gravity",expanded:!0}}}}onStart(){this.applyGravity()}onUpdate(){this.applyGravity()}applyGravity(){this.scene?.physics2d.setGravity(Number(this.config.gravityX)||0,Number(this.config.gravityY)||0)}};var Eo=class extends O{constructor(e,t){super(e,t),this.config={anchorX:0,anchorY:0,connectedNode:"",limitEnabled:!1,lowerAngle:-45,upperAngle:45,motorEnabled:!1,motorSpeed:0,maxMotorTorque:1e5,collideConnected:!1}}static getPropertySchema(){let e=(r,i,o,s)=>({name:r,type:"number",ui:{label:i,group:o,step:1,description:s},getValue:a=>a.config[r],setValue:(a,l)=>{a.config[r]=Number(l)}}),t=(r,i,o,s)=>({name:r,type:"boolean",ui:{label:i,group:o,description:s},getValue:a=>a.config[r],setValue:(a,l)=>{a.config[r]=!!l}});return{nodeType:"RevoluteJoint2D",properties:[e("anchorX","Anchor X","Hinge","Pivot point in this node\u2019s local pixels. (0, 0) hinges on the node origin."),e("anchorY","Anchor Y","Hinge","Pivot point in this node\u2019s local pixels."),{name:"connectedNode",type:"string",ui:{label:"Connected Node",description:"Name, id or path of the body to hinge to. Empty pins the hinge to the world, which is what a flipper or a swinging door wants.",group:"Hinge"},getValue:r=>r.config.connectedNode??"",setValue:(r,i)=>{r.config.connectedNode=String(i??"")}},t("limitEnabled","Limit","Limits","Restrict the swing to an angle range."),e("lowerAngle","Lower Angle","Limits","Degrees, relative to the rest pose."),e("upperAngle","Upper Angle","Limits","Degrees, relative to the rest pose."),t("motorEnabled","Motor","Motor","Drive the hinge towards a target spin."),e("motorSpeed","Motor Speed","Motor","Target spin in degrees per second. Flip its sign to swing the other way."),e("maxMotorTorque","Max Motor Torque","Motor","Torque ceiling. Too low and the motor cannot lift the arm; too high and it ignores everything it hits."),t("collideConnected","Collide Connected","Hinge","Let the two hinged bodies collide. Off by default: they overlap at the pivot, and a contact there fights the joint.")],groups:{Hinge:{label:"Hinge",expanded:!0},Limits:{label:"Limits",expanded:!0},Motor:{label:"Motor",expanded:!0}}}}getJointAnchor(){return{x:Number(this.config.anchorX)||0,y:Number(this.config.anchorY)||0}}getConnectedNode(){let e=String(this.config.connectedNode??"").trim();return e?this.findNode(e):null}getJointConfig(){let e=t=>(Number(t)||0)*Math.PI/180;return{limitEnabled:!!this.config.limitEnabled,lowerAngle:e(this.config.lowerAngle),upperAngle:e(this.config.upperAngle),motorEnabled:!!this.config.motorEnabled,motorSpeed:e(this.config.motorSpeed),maxMotorTorque:Math.max(0,Number(this.config.maxMotorTorque)||0),collideConnected:!!this.config.collideConnected}}onStart(){this.scene?.physics2d.registerJoint(this)}onDetach(){this.scene?.physics2d.unregisterJoint(this),super.onDetach()}};var Hv=["owned","shared","transferable"];function Mp(n){return Hv.includes(n)?n:"owned"}var nr=class extends O{boundNetId=0;spawnedLocally=!1;spawnInFlight=!1;lastSpawnError=null;constructor(e,t){super(e,t),this.config={prefabPath:"",ownership:"owned",appFlags:0,spawnOnStart:!0,despawnOnDetach:!0}}static getPropertySchema(){return{nodeType:"NetworkedNode",properties:[{name:"prefabPath",type:"string",ui:{label:"Prefab",description:"This node's own prefab (res:// path). Indexes the build's netKindTable to the wire kind, and is what every other client instantiates for this entity.",group:"Identity"},getValue:e=>e.config.prefabPath,setValue:(e,t)=>{e.config.prefabPath=String(t??"")}},{name:"ownership",type:"select",ui:{label:"Ownership",description:"What happens when the owner leaves: owned = despawned, shared = reassigned to the new host, transferable = reassignable to anyone.",group:"Identity",options:[...Hv]},getValue:e=>e.config.ownership,setValue:(e,t)=>{e.config.ownership=Mp(t)}},{name:"spawnOnStart",type:"boolean",ui:{label:"Spawn On Start",description:"Request an entity as soon as this node starts. Turn it off for a node a script spawns explicitly, or for a prefab that only ever represents a peer.",group:"Lifecycle"},getValue:e=>e.config.spawnOnStart!==!1,setValue:(e,t)=>{e.config.spawnOnStart=!!t}},{name:"despawnOnDetach",type:"boolean",ui:{label:"Despawn On Detach",description:"Despawn the entity when this node goes away (scene change, queueFree). Off leaves a ghost in the room until its owner disconnects.",group:"Lifecycle"},getValue:e=>e.config.despawnOnDetach!==!1,setValue:(e,t)=>{e.config.despawnOnDetach=!!t}},{name:"appFlags",type:"number",ui:{label:"App Flags",description:"Game-defined flag bits 3\u20137 (0\u201331), replicated verbatim.",group:"Identity",min:0,max:31,step:1},getValue:e=>e.config.appFlags,setValue:(e,t)=>{let r=Number(t);e.config.appFlags=Number.isFinite(r)?Math.max(0,Math.min(31,Math.round(r))):0}}],groups:{Identity:{label:"Identity",expanded:!0},Lifecycle:{label:"Lifecycle",expanded:!0}}}}get netId(){return this.boundNetId}get isBound(){return this.boundNetId!==0}get isMine(){if(!this.isBound)return!1;if(this.spawnedLocally)return!0;let e=this.network,t=e?.getEntity(this.boundNetId)?.ownerId??0;return t!==0&&t===e?.clientId}get ownerId(){let e=this.network;if(!this.isBound||!e)return 0;let t=e.getEntity(this.boundNetId)?.ownerId??0;return t!==0?t:this.spawnedLocally?e.clientId:0}get ownership(){let e=this.network?.getEntity(this.boundNetId)?.flags;return e===void 0?Mp(this.config.ownership):Kh(e)}get spawnError(){return this.lastSpawnError}async spawn(){if(this.isBound||this.spawnInFlight)return this.boundNetId;let e=this.network,t=this.node;if(!e||!t||!e.isOnline)return 0;let r=String(this.config.prefabPath??"");this.spawnInFlight=!0;try{let i=await e.spawn(r,{position:{x:t.position.x,y:t.position.y},rotation:t.rotation.z,ownership:Mp(this.config.ownership),appFlags:Number(this.config.appFlags)||0});return this.lastSpawnError=null,this.spawnedLocally=!0,this.adopt(i),i}catch(i){return this.lastSpawnError=i instanceof ge?i:new ge("invalid",r,String(i)),console.warn(`[core:NetworkedNode] Spawn of "${r}" failed (${this.lastSpawnError.kind}): `+this.lastSpawnError.message),0}finally{this.spawnInFlight=!1}}despawn(){let e=this.boundNetId;e!==0&&(this.spawnedLocally&&this.network?.despawn(e),this.binder?.unbind(e),this.boundNetId=0,this.spawnedLocally=!1)}onStart(){let e=this.binder,t=this.node;if(!e||!t)return;e.reconcile();let r=e.getNetId(t);if(r!==0){this.boundNetId=r,this.spawnedLocally=!1;return}this.config.spawnOnStart!==!1&&this.spawn()}onDetach(){this.boundNetId!==0&&this.config.despawnOnDetach!==!1?this.despawn():this.boundNetId!==0&&(this.binder?.unbind(this.boundNetId),this.boundNetId=0),super.onDetach()}adopt(e){let t=this.node;!t||e===0||(this.boundNetId=e,this.binder?.bind(e,t))}get network(){return this.scene?.network??null}get binder(){return this.scene?.netNodes??null}};var bl=Math.PI*2,ON=50,LN=20,Dp=500,FN=.2,_N=1e3,jv=64;function zN(n,e,t){let r=(e-n)%bl;return r>Math.PI?r-=bl:r<-Math.PI&&(r+=bl),n+r*t}var Io=class extends O{timeSource=()=>Date.now();boundNetId=0;listener=null;sendAccumulatorMs=0;buffer=[];lastArrivalMs=0;jitterMs=0;snapPending=!1;scratchSnap={x:0,y:0};constructor(e,t){super(e,t),this.config={sendRateHz:20,replicateRotation:!0,interpolationDelayMs:0,plane:"xy"}}static getPropertySchema(){return{nodeType:"ReplicatedTransform",properties:[{name:"sendRateHz",type:"number",ui:{label:"Send Rate (Hz)",description:"How often the owner publishes. The session still only sends what actually changed (dirty detection compares quantized integers), so an idle entity costs nothing.",group:"Send",min:1,max:60,step:1},getValue:e=>e.config.sendRateHz,setValue:(e,t)=>{let r=Number(t);e.config.sendRateHz=Number.isFinite(r)&&r>0?Math.min(60,r):20}},{name:"replicateRotation",type:"boolean",ui:{label:"Replicate Rotation",description:"Send rotation as well as position (256 steps per turn, 1.41\xB0).",group:"Send"},getValue:e=>e.config.replicateRotation!==!1,setValue:(e,t)=>{e.config.replicateRotation=!!t}},{name:"plane",type:"select",ui:{label:"Plane",description:"Which axes the wire's X/Y drive: xy for 2D nodes, xz for a top-down 3D game.",group:"Send",options:["xy","xz"]},getValue:e=>e.config.plane,setValue:(e,t)=>{e.config.plane=t==="xz"?"xz":"xy"}},{name:"interpolationDelayMs",type:"number",ui:{label:"Interpolation Delay (ms)",description:"0 = adaptive (two room ticks plus measured jitter). Raise it for a lossy link, lower it for a LAN \u2014 it is latency traded for smoothness.",group:"Receive",min:0,max:Dp,step:5},getValue:e=>e.config.interpolationDelayMs,setValue:(e,t)=>{let r=Number(t);e.config.interpolationDelayMs=Number.isFinite(r)&&r>0?Math.min(Dp,r):0}}],groups:{Send:{label:"Send (owner)",expanded:!0},Receive:{label:"Receive (remote)",expanded:!0}}}}get netId(){return this.boundNetId}get isOwner(){let e=this.node?.getComponent(nr);if(e)return e.isMine;let t=this.network;return t!==null&&this.boundNetId!==0&&t.ownsEntity(this.boundNetId)}get interpolationDelayMs(){let e=Number(this.config.interpolationDelayMs)||0;if(e>0)return e;let t=this.tickIntervalMs*2+this.jitterMs;return Math.min(Dp,Math.max(LN,t))}get bufferedSampleCount(){return this.buffer.length}teleportTo(e,t,r){!this.network||this.boundNetId===0||(this.writeNodeTransform(e,t,r??this.readNodeRotation()),this.publishFromNode(!0))}onStart(){let e=this.node;e instanceof M&&e.layoutEnabled&&(console.warn(`[core:ReplicatedTransform] Disabling anchored layout on "${e.nodeId}": a replicated transform and the per-frame anchor reflow cannot both own the position.`),e.layoutEnabled=!1),this.rebind()}onUpdate(e){this.boundNetId===0&&(this.rebind(),this.boundNetId===0)||(this.isOwner?this.tickOwner(e):this.tickRemote())}onDetach(){this.boundNetId!==0&&this.binder?.setListener(this.boundNetId,null),this.boundNetId=0,this.listener=null,this.buffer.length=0,super.onDetach()}tickOwner(e){let t=1e3/(Number(this.config.sendRateHz)||20);this.sendAccumulatorMs+=Math.max(0,e)*1e3,!(this.sendAccumulatorMs<t)&&(this.sendAccumulatorMs%=t,this.publishFromNode(!1))}publishFromNode(e){let t=this.network,r=this.node;if(!t||!r)return;let{x:i,y:o}=this.readNodePosition();if(!t.snapPosition(i,o,this.scratchSnap))return;let a=this.config.replicateRotation!==!1?t.snapRotation(this.readNodeRotation()):null;t.publish(this.boundNetId,{x:this.scratchSnap.x,y:this.scratchSnap.y,rotation:a??void 0,teleport:e}),this.writeNodeTransform(this.scratchSnap.x,this.scratchSnap.y,a??void 0)}tickRemote(){if(this.buffer.length===0)return;if(this.snapPending){this.snapPending=!1;let i=this.buffer[this.buffer.length-1];this.buffer.length=0,this.buffer.push(i),this.writeNodeTransform(i.x,i.y,i.rotation);return}let e=this.timeSource()-this.interpolationDelayMs;this.trimBuffer(e);let t=this.buffer[0];if(e<=t.t||this.buffer.length===1){this.writeNodeTransform(t.x,t.y,t.rotation);return}let r=this.buffer[this.buffer.length-1];if(e>=r.t){this.writeNodeTransform(r.x,r.y,r.rotation);return}for(let i=this.buffer.length-1;i>0;i-=1){let o=this.buffer[i],s=this.buffer[i-1];if(e<s.t)continue;let a=o.t-s.t,l=a>0?(e-s.t)/a:1;this.writeNodeTransform(s.x+(o.x-s.x)*l,s.y+(o.y-s.y)*l,zN(s.rotation,o.rotation,l));return}}trimBuffer(e){for(;this.buffer.length>2&&this.buffer[1].t<=e;)this.buffer.shift();for(;this.buffer.length>1&&e-this.buffer[0].t>_N;)this.buffer.shift();for(;this.buffer.length>jv;)this.buffer.shift()}handleChange(e){if(e.kind==="leave"){this.buffer.length=0;return}let r=this.network?.quantizer;if(!r)return;let i=this.timeSource();if(this.lastArrivalMs!==0){let s=Math.abs(i-this.lastArrivalMs-this.tickIntervalMs);this.jitterMs+=(s-this.jitterMs)*FN}this.lastArrivalMs=i;let o={t:i,x:r.dequantizeX(e.entity.qx),y:r.dequantizeY(e.entity.qy),rotation:e.entity.qrot*bl/256};(e.kind==="enter"||Xh(e.mask))&&(this.snapPending=!0,this.buffer.length=0),this.buffer.push(o),this.buffer.length>jv&&this.buffer.shift()}rebind(){let e=this.node,t=this.binder;if(!e||!t)return;let r=e.getComponent(nr)?.netId||t.getNetId(e);if(r===this.boundNetId||(this.boundNetId!==0&&t.setListener(this.boundNetId,null),this.boundNetId=r,this.buffer.length=0,this.lastArrivalMs=0,this.snapPending=!1,r===0))return;this.listener??=o=>this.handleChange(o),t.setListener(r,this.listener);let i=this.network?.getEntity(r);i&&this.handleChange({kind:"enter",netId:r,entity:i,mask:0})}get plane(){return this.config.plane==="xz"?"xz":"xy"}readNodePosition(){let e=this.node?.position;return e?this.plane==="xz"?{x:e.x,y:e.z}:{x:e.x,y:e.y}:{x:0,y:0}}readNodeRotation(){let e=this.node?.rotation;return e?this.plane==="xz"?e.y:e.z:0}writeNodeTransform(e,t,r){let i=this.node;i&&(this.plane==="xz"?(i.position.x=e,i.position.z=t):(i.position.x=e,i.position.y=t),r!==void 0&&this.config.replicateRotation!==!1&&(this.plane==="xz"?i.rotation.y=r:i.rotation.z=r))}get tickIntervalMs(){let e=this.network?.tickHz??0;return e>0?1e3/e:ON}get network(){return this.scene?.network??null}get binder(){return this.scene?.netNodes??null}};var Sl=class extends O{targetNode=null;targetWorldPosition=new S;targetLocalPosition=new S;targetWorldQuaternion=new _;targetLocalQuaternion=new _;parentWorldQuaternion=new _;parentWorldQuaternionInverse=new _;targetEuler=new Yr;constructor(e,t){super(e,t),this.config={targetNodeId:"",positionSmoothing:8,rotationSmoothing:8,followPositionX:!0,followPositionY:!0,followPositionZ:!0,followRotationX:!1,followRotationY:!0,followRotationZ:!1}}static getPropertySchema(){return{nodeType:"FollowBehavior",properties:[{name:"targetNodeId",type:"node",ui:{label:"Target Node",description:"Node to follow",group:"Target"},getValue:e=>e.getTargetNodeId(),setValue:(e,t)=>{e.setTargetNodeId(typeof t=="string"?t:"")}},{name:"positionSmoothing",type:"number",ui:{label:"Position Smoothing",description:"Higher values follow position faster",group:"Position",min:0,step:.1},getValue:e=>e.getPositionSmoothing(),setValue:(e,t)=>{let r=e,i=Number(t);!Number.isFinite(i)||i<0||(r.config.positionSmoothing=i)}},{name:"followPositionX",type:"boolean",ui:{label:"Follow Position X",group:"Position"},getValue:e=>e.isPositionAxisEnabled("x"),setValue:(e,t)=>{typeof t=="boolean"&&(e.config.followPositionX=t)}},{name:"followPositionY",type:"boolean",ui:{label:"Follow Position Y",group:"Position"},getValue:e=>e.isPositionAxisEnabled("y"),setValue:(e,t)=>{typeof t=="boolean"&&(e.config.followPositionY=t)}},{name:"followPositionZ",type:"boolean",ui:{label:"Follow Position Z",group:"Position"},getValue:e=>e.isPositionAxisEnabled("z"),setValue:(e,t)=>{typeof t=="boolean"&&(e.config.followPositionZ=t)}},{name:"rotationSmoothing",type:"number",ui:{label:"Rotation Smoothing",description:"Higher values follow rotation faster",group:"Rotation",min:0,step:.1},getValue:e=>e.getRotationSmoothing(),setValue:(e,t)=>{let r=e,i=Number(t);!Number.isFinite(i)||i<0||(r.config.rotationSmoothing=i)}},{name:"followRotationX",type:"boolean",ui:{label:"Follow Rotation X",group:"Rotation"},getValue:e=>e.isRotationAxisEnabled("x"),setValue:(e,t)=>{typeof t=="boolean"&&(e.config.followRotationX=t)}},{name:"followRotationY",type:"boolean",ui:{label:"Follow Rotation Y",group:"Rotation"},getValue:e=>e.isRotationAxisEnabled("y"),setValue:(e,t)=>{typeof t=="boolean"&&(e.config.followRotationY=t)}},{name:"followRotationZ",type:"boolean",ui:{label:"Follow Rotation Z",group:"Rotation"},getValue:e=>e.isRotationAxisEnabled("z"),setValue:(e,t)=>{typeof t=="boolean"&&(e.config.followRotationZ=t)}}],groups:{Target:{label:"Target",expanded:!0},Position:{label:"Position",expanded:!0},Rotation:{label:"Rotation",expanded:!0}}}}onStart(){this.targetNode=null,this.resolveTargetNode()}onUpdate(e){!this.node||e<=0||((!this.targetNode||!this.targetNode.parent)&&this.resolveTargetNode(),!(!this.targetNode||this.targetNode===this.node)&&(this.updatePosition(e),this.updateRotation(e)))}updatePosition(e){if(!this.node||!this.targetNode)return;let t=this.isPositionAxisEnabled("x"),r=this.isPositionAxisEnabled("y"),i=this.isPositionAxisEnabled("z");if(!t&&!r&&!i)return;this.targetNode.getWorldPosition(this.targetWorldPosition),this.node.parent?(this.targetLocalPosition.copy(this.targetWorldPosition),this.node.parent.worldToLocal(this.targetLocalPosition)):this.targetLocalPosition.copy(this.targetWorldPosition);let o=this.getDampingAlpha(this.getPositionSmoothing(),e),s=t?E.lerp(this.node.position.x,this.targetLocalPosition.x,o):this.node.position.x,a=r?E.lerp(this.node.position.y,this.targetLocalPosition.y,o):this.node.position.y,l=i?E.lerp(this.node.position.z,this.targetLocalPosition.z,o):this.node.position.z;this.node.position.set(s,a,l)}updateRotation(e){if(!this.node||!this.targetNode)return;let t=this.isRotationAxisEnabled("x"),r=this.isRotationAxisEnabled("y"),i=this.isRotationAxisEnabled("z");if(!t&&!r&&!i)return;this.targetNode.getWorldQuaternion(this.targetWorldQuaternion),this.node.parent?(this.node.parent.getWorldQuaternion(this.parentWorldQuaternion),this.parentWorldQuaternionInverse.copy(this.parentWorldQuaternion).invert(),this.targetLocalQuaternion.copy(this.parentWorldQuaternionInverse).multiply(this.targetWorldQuaternion)):this.targetLocalQuaternion.copy(this.targetWorldQuaternion),this.targetEuler.setFromQuaternion(this.targetLocalQuaternion,this.node.rotation.order);let o=this.getDampingAlpha(this.getRotationSmoothing(),e),s=t?this.dampAngle(this.node.rotation.x,this.targetEuler.x,o):this.node.rotation.x,a=r?this.dampAngle(this.node.rotation.y,this.targetEuler.y,o):this.node.rotation.y,l=i?this.dampAngle(this.node.rotation.z,this.targetEuler.z,o):this.node.rotation.z;this.node.rotation.set(s,a,l,this.node.rotation.order)}resolveTargetNode(){if(!this.node)return;let e=this.getTargetNodeId();if(!e){this.targetNode=null;return}this.targetNode=this.findNode(e)}getTargetNodeId(){let e=this.config.targetNodeId;return typeof e=="string"?e:""}setTargetNodeId(e){this.config.targetNodeId=e,this.targetNode=null}getPositionSmoothing(){let e=this.config.positionSmoothing,t=typeof e=="number"?e:Number(e);return Number.isFinite(t)&&t>=0?t:8}getRotationSmoothing(){let e=this.config.rotationSmoothing,t=typeof e=="number"?e:Number(e);return Number.isFinite(t)&&t>=0?t:8}isPositionAxisEnabled(e){let t=e==="x"?"followPositionX":e==="y"?"followPositionY":"followPositionZ",r=this.config[t];return typeof r=="boolean"?r:!0}isRotationAxisEnabled(e){let t=e==="x"?"followRotationX":e==="y"?"followRotationY":"followRotationZ",r=this.config[t];return typeof r=="boolean"?r:!1}getDampingAlpha(e,t){return e<=0?1:1-Math.exp(-e*t)}dampAngle(e,t,r){let i=Math.atan2(Math.sin(t-e),Math.cos(t-e));return e+i*r}};var vl=class extends O{armed=!1;remaining=0;boundSignal=null;onSignal=()=>{this.armed||(this.armed=!0,this.remaining=this.getDelay())};constructor(e,t){super(e,t),this.config={signal:"animation-finished",delay:0}}static getPropertySchema(){return{nodeType:"FreeOnSignalBehavior",properties:[{name:"signal",type:"string",ui:{label:"Signal",description:"Node signal that triggers the free (e.g. animation-finished)",group:"Lifecycle"},getValue:e=>e.getSignal(),setValue:(e,t)=>{e.setSignal(t)}},{name:"delay",type:"number",ui:{label:"Delay",description:"Seconds to wait after the signal before freeing",group:"Lifecycle",min:0,step:.01,precision:2,unit:"s"},getValue:e=>e.getDelay(),setValue:(e,t)=>{e.setDelay(t)}}],groups:{Lifecycle:{label:"Lifecycle",description:"Free this node when a signal fires",expanded:!0}}}}onStart(){this.bind()}onUpdate(e){!this.armed||!this.node||(this.remaining-=e,this.remaining<=0&&(this.armed=!1,this.node.queueFree()))}onDetach(){this.unbind(),this.armed=!1,super.onDetach()}bind(){this.node&&(this.boundSignal=this.getSignal(),this.node.connect(this.boundSignal,this,this.onSignal))}unbind(){!this.node||!this.boundSignal||(this.node.disconnect(this.boundSignal,this,this.onSignal),this.boundSignal=null)}getSignal(){let e=this.config.signal;if(typeof e!="string")return"animation-finished";let t=e.trim();return t.length>0?t:"animation-finished"}setSignal(e){let t=!!this.node;t&&this.unbind(),this.config.signal=typeof e=="string"&&e.trim().length>0?e.trim():"animation-finished",t&&this.bind()}getDelay(){let e=typeof this.config.delay=="number"?this.config.delay:Number(this.config.delay);return Number.isFinite(e)?Math.max(0,e):0}setDelay(e){let t=typeof e=="number"?e:Number(e);this.config.delay=Number.isFinite(t)?Math.max(0,t):0}};var wl=class extends O{point="";applyRotation=!0;offsetX=0;offsetY=0;spriteNodeId="";sprite=null;static getPropertySchema(){return{nodeType:"PointAttachmentBehavior",properties:[x("point","string",{ui:{label:"Point",description:"Named frame point to follow"},getValue:e=>e.point,setValue:(e,t)=>{e.point=String(t??"").trim()}}),x("applyRotation","boolean",{ui:{label:"Apply Rotation",description:"Copy the point's angle into this node"},getValue:e=>e.applyRotation,setValue:(e,t)=>{e.applyRotation=!!t}}),x("offsetX","number",{ui:{label:"Offset X",step:1},getValue:e=>e.offsetX,setValue:(e,t)=>{e.offsetX=Number(t)||0}}),x("offsetY","number",{ui:{label:"Offset Y",step:1},getValue:e=>e.offsetY,setValue:(e,t)=>{e.offsetY=Number(t)||0}}),x("spriteNodeId","node",{ui:{label:"Sprite",description:"AnimatedSprite2D to read points from (empty = nearest ancestor)",nodeTypes:["AnimatedSprite2D"]},getValue:e=>e.spriteNodeId,setValue:(e,t)=>{let r=e;r.spriteNodeId=String(t??"").trim(),r.sprite=null}})],groups:{}}}onStart(){this.sprite=null}onUpdate(e){let t=this.node;if(!t||!(t instanceof M)||this.point.length===0)return;let r=this.resolveSprite();if(!r)return;let i=r.getFramePoint(this.point);if(!i)return;let o=t.parent;if(o){if(o===r)t.position.set(i.x+this.offsetX,i.y+this.offsetY,t.position.z);else{let s=r.getFramePointWorld(this.point);if(!s)return;o.updateMatrixWorld(!0),t.position.set(s.x,s.y,s.z),o.worldToLocal(t.position),t.position.x+=this.offsetX,t.position.y+=this.offsetY}this.applyRotation&&(t.rotation.z=E.degToRad(i.angle))}}resolveSprite(){if(this.sprite)return this.sprite;if(this.spriteNodeId){let t=this.findNode(this.spriteNodeId);return this.sprite=t instanceof Ke?t:null,this.sprite}let e=this.node?.parent??null;for(;e;){if(e instanceof Ke)return this.sprite=e,e;e=e.parent}return null}};function UN(n){n.registerComponent({id:"core:Rotate",displayName:"Rotate",description:"Rotates a 3D node continuously",category:"Transform",componentClass:bo,keywords:["rotate","animation"]}),n.registerComponent({id:"core:SimpleMove",displayName:"Simple Move",description:"Moves a 3D node in a simple pattern (for testing)",category:"Test",componentClass:So,keywords:["move","test","animation"]}),n.registerComponent({id:"core:Sine",displayName:"Sine Oscillator",description:"Oscillates a node along a selected axis",category:"Animation",componentClass:vo,keywords:["sine","oscillation","animation"]}),n.registerComponent({id:"core:PinToNode",displayName:"Pin to Node",description:"Pins a 2D UI node to a 3D target node",category:"UI",componentClass:wo,keywords:["ui","tracking","pin"]}),n.registerComponent({id:"core:Follow",displayName:"Follow",description:"Smoothly follows a target node position and/or rotation",category:"Transform",componentClass:Sl,keywords:["follow","camera","tracking","smooth"]}),n.registerComponent({id:"core:Fade",displayName:"Fade",description:"Fades 2D node opacity in and out with optional auto-destroy",category:"Animation",componentClass:xo,keywords:["fade","opacity","animation"]}),n.registerComponent({id:"core:RadialProgress",displayName:"Radial Progress",description:"Masks a Sprite2D texture as a circular progress bar",category:"UI",componentClass:Po,keywords:["radial","progress","bar","circle","mask","ui"]}),n.registerComponent({id:"core:AnimationPlayer",displayName:"Animation Player",description:"Plays keyframe animation clips on this node and its descendants",category:"Animation",componentClass:ir,keywords:["animation","keyframe","tween","timeline","player","clip"]}),n.registerComponent({id:"core:PlaySound",displayName:"Play Sound",description:"Plays an audio track when a node signal is emitted",category:"Audio",componentClass:ko,keywords:["audio","sound","sfx","trigger","event"]}),n.registerComponent({id:"core:SfxOnSignal",displayName:"SFX on Signal",description:"Play a procedural (asset-free) sound preset when a node signal fires",category:"Audio",componentClass:Ao,keywords:["audio","sfx","sound","procedural","synth","preset","signal","juice"]}),n.registerComponent({id:"core:BurstOnSignal",displayName:"Burst on Signal",description:"Spawn a one-shot 2D particle burst at this node when a signal fires (juice)",category:"Juice",componentClass:To,keywords:["particles","burst","juice","vfx","sparks","confetti","signal","impact"]}),n.registerComponent({id:"core:FreeOnSignal",displayName:"Free on Signal",description:"Frees this node when a signal fires on it (e.g. animation-finished) \u2014 one-shot VFX lifecycle",category:"Lifecycle",componentClass:vl,keywords:["free","destroy","despawn","queuefree","one-shot","lifecycle","signal","vfx","finished"]}),n.registerComponent({id:"core:Shake",displayName:"Shake",description:"Smooth positional shake, additive over other motion (juice)",category:"Juice",componentClass:Bt,keywords:["shake","juice","camera","impact","screenshake"]}),n.registerComponent({id:"core:PunchScale",displayName:"Punch Scale",description:"Squash-and-stretch scale punch on a signal or on start (juice)",category:"Juice",componentClass:Zt,keywords:["punch","scale","squash","stretch","juice","pop"]}),n.registerComponent({id:"core:PopIn",displayName:"Pop In",description:"Scales a node up from zero with an overshoot on spawn (juice)",category:"Juice",componentClass:er,keywords:["pop","spawn","scale","juice","appear","intro"]}),n.registerComponent({id:"core:CameraBrain",displayName:"Camera Brain",description:"Blends the render camera between virtual cameras by priority (Cinemachine-lite)",category:"Camera",componentClass:Ur,keywords:["camera","brain","cinemachine","virtual","blend","priority","follow"]}),n.registerComponent({id:"core:Hitbox2D",displayName:"Hitbox 2D",description:"Queryable 2D collision shape (rect/circle) with group filtering \u2014 hit-test via scene.collision2d",category:"Physics",componentClass:Co,keywords:["hitbox","collision","collider","area","2d","overlap","raycast","hit"]}),n.registerComponent({id:"core:PhysicsBody2D",displayName:"Physics Body 2D",description:"Rigid body simulated by scene.physics2d \u2014 static, kinematic or dynamic. Shape comes from sibling or descendant Collider 2D components.",category:"Physics",componentClass:Mo,keywords:["physics","rigidbody","body","dynamic","gravity","mass","2d","simulate"]}),n.registerComponent({id:"core:Collider2D",displayName:"Collider 2D",description:"Physics shape (rect/circle/polygon, rotation-aware, may be concave). With no Physics Body above it this is static world geometry; as a sensor it reports body-entered / body-exited.",category:"Physics",componentClass:Do,keywords:["collider","physics","shape","polygon","sensor","area","2d","collision"]}),n.registerComponent({id:"core:RevoluteJoint2D",displayName:"Revolute Joint 2D",description:"Hinge: pins this body to a pivot so it can only rotate about it. With no connected node the hinge is fixed to the world \u2014 the pinball flipper / swinging door case. Optional angle limits and a motor.",category:"Physics",componentClass:Eo,keywords:["joint","hinge","revolute","pivot","flipper","door","motor","physics","2d"]}),n.registerComponent({id:"core:PhysicsWorld2D",displayName:"Physics World 2D",description:"Sets the 2D world gravity. Attach to the scene root.",category:"Physics",componentClass:No,keywords:["physics","gravity","world","2d"]}),n.registerComponent({id:"core:PointAttachment",displayName:"Point Attachment",description:"Keeps this node on a named frame point of a parent AnimatedSprite2D (hand socket, muzzle) every tick",category:"Animation",componentClass:wl,keywords:["point","socket","attach","muzzle","hand","bone","sprite","animation"]}),n.registerComponent({id:"core:NetworkedNode",displayName:"Networked Node",description:"Binds this node to a replicated entity \u2014 spawns one for the local player, or adopts the entity a peer spawned",category:"Network",componentClass:nr,keywords:["network","multiplayer","net","entity","spawn","despawn","owner","authority","online"]}),n.registerComponent({id:"core:ReplicatedTransform",displayName:"Replicated Transform",description:"Replicates this node's position and rotation: the owner publishes quantized values, peers render them on a timed interpolation buffer",category:"Network",componentClass:Io,keywords:["network","multiplayer","replicate","transform","position","sync","interpolation","lerp","online"]}),console.log("[ScriptRegistry] Registered built-in script components")}var Yv=class{get shadowRoot(){return this.__host.__shadowRoot}constructor(e){this.ariaAtomic="",this.ariaAutoComplete="",this.ariaBrailleLabel="",this.ariaBrailleRoleDescription="",this.ariaBusy="",this.ariaChecked="",this.ariaColCount="",this.ariaColIndex="",this.ariaColSpan="",this.ariaCurrent="",this.ariaDescription="",this.ariaDisabled="",this.ariaExpanded="",this.ariaHasPopup="",this.ariaHidden="",this.ariaInvalid="",this.ariaKeyShortcuts="",this.ariaLabel="",this.ariaLevel="",this.ariaLive="",this.ariaModal="",this.ariaMultiLine="",this.ariaMultiSelectable="",this.ariaOrientation="",this.ariaPlaceholder="",this.ariaPosInSet="",this.ariaPressed="",this.ariaReadOnly="",this.ariaRequired="",this.ariaRoleDescription="",this.ariaRowCount="",this.ariaRowIndex="",this.ariaRowSpan="",this.ariaSelected="",this.ariaSetSize="",this.ariaSort="",this.ariaValueMax="",this.ariaValueMin="",this.ariaValueNow="",this.ariaValueText="",this.role="",this.form=null,this.labels=[],this.states=new Set,this.validationMessage="",this.validity={},this.willValidate=!0,this.__host=e}checkValidity(){return console.warn("`ElementInternals.checkValidity()` was called on the server.This method always returns true."),!0}reportValidity(){return!0}setFormValue(){}setValidity(){}};var ot=function(n,e,t,r,i){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!i:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?i.call(n,t):i?i.value=t:e.set(n,t),t},pe=function(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)},Ei,xl,Pl,Ro,Np,Bo,kl,qr,Vo,or,Al,$v,Kv=n=>typeof n=="boolean"?n:n?.capture??!1;var Ep=class{constructor(){this.__eventListeners=new Map,this.__captureEventListeners=new Map}addEventListener(e,t,r){if(t==null)return;let i=Kv(r)?this.__captureEventListeners:this.__eventListeners,o=i.get(e);if(o===void 0)o=new Map,i.set(e,o);else if(o.has(t))return;let s=typeof r=="object"&&r?r:{};s.signal?.addEventListener("abort",()=>this.removeEventListener(e,t,r)),o.set(t,s??{})}removeEventListener(e,t,r){if(t==null)return;let i=Kv(r)?this.__captureEventListeners:this.__eventListeners,o=i.get(e);o!==void 0&&(o.delete(t),o.size||i.delete(e))}dispatchEvent(e){let t=[this],r=this.__eventTargetParent;if(e.composed)for(;r;)t.push(r),r=r.__eventTargetParent;else for(;r&&r!==this.__host;)t.push(r),r=r.__eventTargetParent;let i=!1,o=!1,s=0,a=null,l=null,c=null,u=e.stopPropagation,d=e.stopImmediatePropagation;Object.defineProperties(e,{target:{get(){return a??l},...K},srcElement:{get(){return e.target},...K},currentTarget:{get(){return c},...K},eventPhase:{get(){return s},...K},composedPath:{value:()=>t,...K},stopPropagation:{value:()=>{i=!0,u.call(e)},...K},stopImmediatePropagation:{value:()=>{o=!0,d.call(e)},...K}});let h=(y,b,v)=>{typeof y=="function"?y(e):typeof y?.handleEvent=="function"&&y.handleEvent(e),b.once&&v.delete(y)},p=()=>(c=null,s=0,!e.defaultPrevented),f=t.slice().reverse();a=!this.__host||!e.composed?this:null;let m=y=>{for(l=this;l.__host&&y.includes(l.__host);)l=l.__host};for(let y of f){!a&&(!l||l===y.__host)&&m(f.slice(f.indexOf(y))),c=y,s=y===e.target?2:1;let b=y.__captureEventListeners.get(e.type);if(b){for(let[v,w]of b)if(h(v,w,b),o)return p()}if(i)return p()}let g=e.bubbles?t:[this];l=null;for(let y of g){!a&&(!l||y===l.__host)&&m(g.slice(0,g.indexOf(y)+1)),c=y,s=y===e.target?2:3;let b=y.__eventListeners.get(e.type);if(b){for(let[v,w]of b)if(h(v,w,b),o)return p()}if(i)return p()}return p()}},Ip=Ep;var K={__proto__:null};K.enumerable=!0;Object.freeze(K);var Rp=(or=class{constructor(e,t={}){if(Ei.set(this,!1),xl.set(this,!1),Pl.set(this,!1),Ro.set(this,!1),Np.set(this,Date.now()),Bo.set(this,!1),kl.set(this,void 0),qr.set(this,void 0),Vo.set(this,void 0),this.NONE=0,this.CAPTURING_PHASE=1,this.AT_TARGET=2,this.BUBBLING_PHASE=3,arguments.length===0)throw new Error("The type argument must be specified");if(typeof t!="object"||!t)throw new Error('The "options" argument must be an object');let{bubbles:r,cancelable:i,composed:o}=t;ot(this,Ei,!!i,"f"),ot(this,xl,!!r,"f"),ot(this,Pl,!!o,"f"),ot(this,kl,`${e}`,"f"),ot(this,qr,null,"f"),ot(this,Vo,!1,"f")}initEvent(e,t,r){throw new Error("Method not implemented.")}stopImmediatePropagation(){this.stopPropagation()}preventDefault(){ot(this,Ro,!0,"f")}get target(){return pe(this,qr,"f")}get currentTarget(){return pe(this,qr,"f")}get srcElement(){return pe(this,qr,"f")}get type(){return pe(this,kl,"f")}get cancelable(){return pe(this,Ei,"f")}get defaultPrevented(){return pe(this,Ei,"f")&&pe(this,Ro,"f")}get timeStamp(){return pe(this,Np,"f")}composedPath(){return pe(this,Vo,"f")?[pe(this,qr,"f")]:[]}get returnValue(){return!pe(this,Ei,"f")||!pe(this,Ro,"f")}get bubbles(){return pe(this,xl,"f")}get composed(){return pe(this,Pl,"f")}get eventPhase(){return pe(this,Vo,"f")?or.AT_TARGET:or.NONE}get cancelBubble(){return pe(this,Bo,"f")}set cancelBubble(e){e&&ot(this,Bo,!0,"f")}stopPropagation(){ot(this,Bo,!0,"f")}get isTrusted(){return!1}},Ei=new WeakMap,xl=new WeakMap,Pl=new WeakMap,Ro=new WeakMap,Np=new WeakMap,Bo=new WeakMap,kl=new WeakMap,qr=new WeakMap,Vo=new WeakMap,or.NONE=0,or.CAPTURING_PHASE=1,or.AT_TARGET=2,or.BUBBLING_PHASE=3,or);Object.defineProperties(Rp.prototype,{initEvent:K,stopImmediatePropagation:K,preventDefault:K,target:K,currentTarget:K,srcElement:K,type:K,cancelable:K,defaultPrevented:K,timeStamp:K,composedPath:K,returnValue:K,bubbles:K,composed:K,eventPhase:K,cancelBubble:K,stopPropagation:K,isTrusted:K});var Xv=($v=class extends Rp{constructor(e,t={}){super(e,t),Al.set(this,void 0),ot(this,Al,t?.detail??null,"f")}initCustomEvent(e,t,r,i){throw new Error("Method not implemented.")}get detail(){return pe(this,Al,"f")}},Al=new WeakMap,$v);Object.defineProperties(Xv.prototype,{detail:K});var Bp=Rp,Vp=Xv;globalThis.Event??=Bp;globalThis.CustomEvent??=Vp;var Qv=new WeakMap,Oo=n=>{let e=Qv.get(n);return e===void 0&&Qv.set(n,e=new Map),e},WN=class extends Ip{constructor(){super(...arguments),this.__shadowRootMode=null,this.__shadowRoot=null,this.__internals=null}get attributes(){return Array.from(Oo(this)).map(([e,t])=>({name:e,value:t}))}get shadowRoot(){return this.__shadowRootMode==="closed"?null:this.__shadowRoot}get localName(){return this.constructor.__localName}get tagName(){return this.localName?.toUpperCase()}setAttribute(e,t){Oo(this).set(e,String(t))}removeAttribute(e){Oo(this).delete(e)}toggleAttribute(e,t){if(this.hasAttribute(e)){if(t===void 0||!t)return this.removeAttribute(e),!1}else return t===void 0||t?(this.setAttribute(e,""),!0):!1;return!0}hasAttribute(e){return Oo(this).has(e)}attachShadow(e){let t={host:this};return this.__shadowRootMode=e.mode,e&&e.mode==="open"&&(this.__shadowRoot=t),t}attachInternals(){if(this.__internals!==null)throw new Error("Failed to execute 'attachInternals' on 'HTMLElement': ElementInternals for the specified element was already attached.");let e=new Yv(this);return this.__internals=e,e}getAttribute(e){return Oo(this).get(e)??null}};var GN=class extends WN{},Lp=GN;globalThis.litServerRoot??=Object.defineProperty(new Lp,"localName",{get(){return"lit-server-root"}});function qN(){let n,e;return{promise:new Promise((r,i)=>{n=r,e=i}),resolve:n,reject:e}}var Op=class{constructor(){this.__definitions=new Map,this.__reverseDefinitions=new Map,this.__pendingWhenDefineds=new Map}define(e,t){if(this.__definitions.has(e))if(process.env.NODE_ENV==="development")console.warn(`'CustomElementRegistry' already has "${e}" defined. This may have been caused by live reload or hot module replacement in which case it can be safely ignored.
|
|
239
|
-
Make sure to test your application with a production build as repeat registrations will throw in production.`);else throw new Error(`Failed to execute 'define' on 'CustomElementRegistry': the name "${e}" has already been used with this registry`);if(this.__reverseDefinitions.has(t))throw new Error(`Failed to execute 'define' on 'CustomElementRegistry': the constructor has already been used with this registry for the tag name ${this.__reverseDefinitions.get(t)}`);t.__localName=e,this.__definitions.set(e,{ctor:t,observedAttributes:t.observedAttributes??[]}),this.__reverseDefinitions.set(t,e),this.__pendingWhenDefineds.get(e)?.resolve(t),this.__pendingWhenDefineds.delete(e)}get(e){return this.__definitions.get(e)?.ctor}getName(e){return this.__reverseDefinitions.get(e)??null}upgrade(e){throw new Error("customElements.upgrade is not currently supported in SSR. Please file a bug if you need it.")}async whenDefined(e){let t=this.__definitions.get(e);if(t)return t.ctor;let r=this.__pendingWhenDefineds.get(e);return r||(r=qN(),this.__pendingWhenDefineds.set(e,r)),r.promise}},HN=Op;var Jv=new HN;var Lo=globalThis,Cl=Lo.ShadowRoot&&(Lo.ShadyCSS===void 0||Lo.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,ew=Symbol(),Zv=new WeakMap,Tl=class{constructor(e,t,r){if(this._$cssResult$=!0,r!==ew)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(Cl&&e===void 0){let r=t!==void 0&&t.length===1;r&&(e=Zv.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),r&&Zv.set(t,e))}return e}toString(){return this.cssText}},tw=n=>new Tl(typeof n=="string"?n:n+"",void 0,ew);var rw=(n,e)=>{if(Cl)n.adoptedStyleSheets=e.map((t=>t instanceof CSSStyleSheet?t:t.styleSheet));else for(let t of e){let r=document.createElement("style"),i=Lo.litNonce;i!==void 0&&r.setAttribute("nonce",i),r.textContent=t.cssText,n.appendChild(r)}},Fp=Cl||Lo.CSSStyleSheet===void 0?n=>n:n=>n instanceof CSSStyleSheet?(e=>{let t="";for(let r of e.cssRules)t+=r.cssText;return tw(t)})(n):n;var{is:jN,defineProperty:YN,getOwnPropertyDescriptor:$N,getOwnPropertyNames:KN,getOwnPropertySymbols:XN,getPrototypeOf:QN}=Object,zo=globalThis;zo.customElements??=Jv;var iw=zo.trustedTypes,JN=iw?iw.emptyScript:"",ZN=zo.reactiveElementPolyfillSupport,Fo=(n,e)=>n,_o={toAttribute(n,e){switch(e){case Boolean:n=n?JN:null;break;case Object:case Array:n=n==null?n:JSON.stringify(n)}return n},fromAttribute(n,e){let t=n;switch(e){case Boolean:t=n!==null;break;case Number:t=n===null?null:Number(n);break;case Object:case Array:try{t=JSON.parse(n)}catch{t=null}}return t}},Ml=(n,e)=>!jN(n,e),nw={attribute:!0,type:String,converter:_o,reflect:!1,useDefault:!1,hasChanged:Ml};Symbol.metadata??=Symbol("metadata"),zo.litPropertyMetadata??=new WeakMap;var Hr=class extends(globalThis.HTMLElement??Lp){static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=nw){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){let r=Symbol(),i=this.getPropertyDescriptor(e,r,t);i!==void 0&&YN(this.prototype,e,i)}}static getPropertyDescriptor(e,t,r){let{get:i,set:o}=$N(this.prototype,e)??{get(){return this[t]},set(s){this[t]=s}};return{get:i,set(s){let a=i?.call(this);o?.call(this,s),this.requestUpdate(e,a,r)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??nw}static _$Ei(){if(this.hasOwnProperty(Fo("elementProperties")))return;let e=QN(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Fo("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Fo("properties"))){let t=this.properties,r=[...KN(t),...XN(t)];for(let i of r)this.createProperty(i,t[i])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[r,i]of t)this.elementProperties.set(r,i)}this._$Eh=new Map;for(let[t,r]of this.elementProperties){let i=this._$Eu(t,r);i!==void 0&&this._$Eh.set(i,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let r=new Set(e.flat(1/0).reverse());for(let i of r)t.unshift(Fp(i))}else e!==void 0&&t.push(Fp(e));return t}static _$Eu(e,t){let r=t.attribute;return r===!1?void 0:typeof r=="string"?r:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise((e=>this.enableUpdating=e)),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach((e=>e(this)))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let r of t.keys())this.hasOwnProperty(r)&&(e.set(r,this[r]),delete this[r]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return rw(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach((e=>e.hostConnected?.()))}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach((e=>e.hostDisconnected?.()))}attributeChangedCallback(e,t,r){this._$AK(e,r)}_$ET(e,t){let r=this.constructor.elementProperties.get(e),i=this.constructor._$Eu(e,r);if(i!==void 0&&r.reflect===!0){let o=(r.converter?.toAttribute!==void 0?r.converter:_o).toAttribute(t,r.type);this._$Em=e,o==null?this.removeAttribute(i):this.setAttribute(i,o),this._$Em=null}}_$AK(e,t){let r=this.constructor,i=r._$Eh.get(e);if(i!==void 0&&this._$Em!==i){let o=r.getPropertyOptions(i),s=typeof o.converter=="function"?{fromAttribute:o.converter}:o.converter?.fromAttribute!==void 0?o.converter:_o;this._$Em=i;let a=s.fromAttribute(t,o.type);this[i]=a??this._$Ej?.get(i)??a,this._$Em=null}}requestUpdate(e,t,r){if(e!==void 0){let i=this.constructor,o=this[e];if(r??=i.getPropertyOptions(e),!((r.hasChanged??Ml)(o,t)||r.useDefault&&r.reflect&&o===this._$Ej?.get(e)&&!this.hasAttribute(i._$Eu(e,r))))return;this.C(e,t,r)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,t,{useDefault:r,reflect:i,wrapped:o},s){r&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,s??t??this[e]),o!==!0||s!==void 0)||(this._$AL.has(e)||(this.hasUpdated||r||(t=void 0),this._$AL.set(e,t)),i===!0&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}let e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(let[i,o]of this._$Ep)this[i]=o;this._$Ep=void 0}let r=this.constructor.elementProperties;if(r.size>0)for(let[i,o]of r){let{wrapped:s}=o,a=this[i];s!==!0||this._$AL.has(i)||a===void 0||this.C(i,void 0,o,a)}}let e=!1,t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach((r=>r.hostUpdate?.())),this.update(t)):this._$EM()}catch(r){throw e=!1,this._$EM(),r}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach((t=>t.hostUpdated?.())),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach((t=>this._$ET(t,this[t]))),this._$EM()}updated(e){}firstUpdated(e){}};Hr.elementStyles=[],Hr.shadowRootOptions={mode:"open"},Hr[Fo("elementProperties")]=new Map,Hr[Fo("finalized")]=new Map,ZN?.({ReactiveElement:Hr}),(zo.reactiveElementVersions??=[]).push("2.1.1");var eE={attribute:!0,type:String,converter:_o,reflect:!1,hasChanged:Ml},tE=(n=eE,e,t)=>{let{kind:r,metadata:i}=t,o=globalThis.litPropertyMetadata.get(i);if(o===void 0&&globalThis.litPropertyMetadata.set(i,o=new Map),r==="setter"&&((n=Object.create(n)).wrapped=!0),o.set(t.name,n),r==="accessor"){let{name:s}=t;return{set(a){let l=e.get.call(this);e.set.call(this,a),this.requestUpdate(s,l,n)},init(a){return a!==void 0&&this.C(s,void 0,n,a),a}}}if(r==="setter"){let{name:s}=t;return function(a){let l=this[s];e.call(this,a),this.requestUpdate(s,l,n)}}throw Error("Unsupported decorator location: "+r)};function Dl(n){return(e,t)=>typeof t=="object"?tE(n,e,t):((r,i,o)=>{let s=i.hasOwnProperty(o);return i.constructor.createProperty(o,r),s?Object.getOwnPropertyDescriptor(i,o):void 0})(n,e,t)}function ow(n){return Dl({...n,state:!0,attribute:!1})}var rE={};lw(rE,{AO_MODES:()=>Mu,ATLAS_MANIFEST_PATH:()=>Gv,ATLAS_REGION_KEY:()=>Bw,ATLAS_SHEET_DIR:()=>qv,ATLAS_SHEET_SCHEME:()=>Rw,ATLAS_SIZE_KEY:()=>Vw,AUDIO_BUS_NAMES:()=>ut,AmbientLightNode:()=>_t,AnimatedSprite2D:()=>Ke,AnimatedSprite3D:()=>yr,AnimationPlayerBehavior:()=>ir,AssetLoader:()=>Uc,AudioApi:()=>ho,AudioPlayer:()=>gt,AudioService:()=>Wc,BATCHABLE_2D_KEY:()=>Ne,BLEND_MODES_2D:()=>jm,BLEND_MODE_2D_OPTIONS:()=>Yc,BUILTIN_SHADER_EFFECTS:()=>ps,BURST_MAX_PARTICLES:()=>yv,Bar2D:()=>wr,Batch2DSystem:()=>Ji,BurstOnSignalBehavior:()=>To,Button2D:()=>mt,CAMERA2D_DEFAULTS:()=>ks,CONTACT_MARGIN:()=>Br,CURRENT_SCENE_FORMAT_VERSION:()=>IT,Camera2D:()=>Vt,Camera3D:()=>fe,CameraBrainBehavior:()=>Ur,CanvasLayer2D:()=>sn,Checkbox2D:()=>xr,Collider2DBehavior:()=>Do,Collision2DService:()=>Hn,ColorRect2D:()=>dr,CutsceneApi:()=>po,DEFAULT_CLIP_DURATION:()=>hp,DEFAULT_FIXED_DELTA_SEC:()=>bp,DEFAULT_GEOMETRY_MATERIAL_TYPE:()=>gu,DEFAULT_RUNTIME_TIME_CONFIG:()=>Sp,DIRECTION_AXES_ENABLED_KEY:()=>jl,DirectionalLightNode:()=>Ot,EASING_NAMES:()=>Tu,ECSService:()=>yo,EMOJI_GUARDED_TEXT_PROPERTIES:()=>hh,FadeBehavior:()=>xo,FloatText2D:()=>so,GAME_DEBUG_GLOBAL_KEY:()=>Oi,GEOMETRY_KINDS:()=>Su,GEOMETRY_MATERIAL_TYPES:()=>kr,GameCommandRegistry:()=>no,GameTime:()=>Vr,GeometryMesh:()=>yt,Group2D:()=>Ae,HemisphereLightNode:()=>zt,Hitbox2DBehavior:()=>Co,INSTANCE_TRANSFORM_KEYS:()=>$T,InputService:()=>Wn,InstancedMesh3D:()=>bt,InventorySlot2D:()=>Pr,Joystick2D:()=>br,JuiceApi:()=>lo,KNOWN_SCENE_NODE_TYPES:()=>iu,LABEL_AUTO_SIZE_BLEED:()=>Ds,LABEL_GLOW_STRENGTH_LIMIT:()=>di,LABEL_H_ALIGN_VALUES:()=>du,LABEL_LINE_HEIGHT_FACTOR:()=>Mf,LABEL_V_ALIGN_VALUES:()=>Ms,Label2D:()=>ft,LocalizationService:()=>Wr,MAX_NET_KIND:()=>NF,MAX_POLYGON_VERTICES:()=>mF,MAX_TICKS_PER_FRAME:()=>Ov,MIN_CLIP_DURATION:()=>Cv,MIN_POLYGON_VERTICES:()=>pF,MeshInstance:()=>ct,NET_APP_FLAGS_SHIFT:()=>cv,NET_OWNERSHIP_MASK:()=>$h,NetKindTable:()=>Kn,NetRoomVars:()=>rl,NetworkConnectError:()=>nt,NetworkNodeBinder:()=>io,NetworkService:()=>ro,NetworkSpawnError:()=>ge,NetworkedNodeBehavior:()=>nr,Node2D:()=>M,Node3D:()=>U,NodeBase:()=>V,OVERLAY_2D_FLAG:()=>Fe,PHYSICS_DEBUG_ENABLED_KEY:()=>Hl,PHYSICS_DEBUG_GLOBAL_KEY:()=>Li,POST_PROCESS_DEFAULTS:()=>Yf,PROJECT_AO_MODES:()=>Gf,PROJECT_SCRIPT_DIRECTORIES:()=>qb,PROJECT_SCRIPT_ENTRY_PATTERN:()=>Hb,PROJECT_TEXTURE_FILTERING_MODES:()=>Im,ParticleBurst2D:()=>oo,Particles3D:()=>pt,Physics2DService:()=>Yn,PhysicsBody2DBehavior:()=>Mo,PhysicsWorld2DBehavior:()=>No,PinToNodeBehavior:()=>wo,PlaySoundBehavior:()=>ko,PointLightNode:()=>Lt,PopInBehavior:()=>er,PostProcess:()=>et,PostProcessingPipeline:()=>go,PunchScaleBehavior:()=>Zt,RUNTIME_PROPERTY_SINK_GLOBAL_KEY:()=>Gl,RUNTIME_SCENE_GLOBAL_KEY:()=>Wl,RadialProgressBehavior:()=>Po,RejectCode:()=>q,ReplicatedTransformBehavior:()=>Io,ResourceManager:()=>Ul,RevoluteJoint2DBehavior:()=>Eo,RotateBehavior:()=>bo,RuntimeRenderer:()=>Cp,SCENE_COMPONENT_DEFINITION_KEYS:()=>VT,SCENE_DISK_FORMAT_TYPES:()=>WT,SCENE_DOCUMENT_KEYS:()=>RT,SCENE_NODE_DEFINITION_KEYS:()=>BT,SCRIPT_ERROR_SINK_GLOBAL_KEY:()=>Fi,SEMANTIC_POINTER_ID:()=>ui,SFX_PRESETS:()=>ll,SHARED_UNIT_QUAD_GEOMETRY:()=>Me,SIGNAL_EMIT_SINK_GLOBAL_KEY:()=>_i,SceneLoader:()=>uh,SceneManager:()=>mh,SceneRunner:()=>Tp,SceneSaver:()=>ph,SceneService:()=>mo,SceneValidationError:()=>ve,Script:()=>O,ScriptRegistry:()=>Gc,ScrollContainer2D:()=>Je,SfxOnSignalBehavior:()=>Ao,SfxSynth:()=>uo,ShaderEffectStack:()=>Oe,ShakeBehavior:()=>Bt,SimpleMoveBehavior:()=>So,SineBehavior:()=>vo,Slider2D:()=>vr,SpineSkeleton2D:()=>ur,SpineSkeletonView:()=>tn,SpotLightNode:()=>Ft,Sprite2D:()=>Le,Sprite3D:()=>ht,TARGET_DISTANCE:()=>Lf,TEST_COMPONENT_TYPE_PREFIX:()=>Pm,TRAIL_MAX_POINTS:()=>bv,TiledSprite2D:()=>pr,Trail2D:()=>ao,TweenApi:()=>co,UIControl2D:()=>te,USER_SCRIPT_ID_PREFIX:()=>jb,VIRTUAL_CAMERA_DEFAULTS:()=>ze,VirtualCamera3D:()=>vt,WS_CLOSE_NORMAL:()=>Ka,WS_CLOSE_PROTOCOL_VIOLATION:()=>Lh,WsTransport:()=>Xn,ZERO_SLICE_BORDER:()=>cf,Z_INDEX_LIMIT:()=>Xi,aimCameraNodeAt:()=>Is,aoModeUsesSSAO:()=>Cu,applyBlendMode2DToMaterial:()=>Ki,applyClipAtTime:()=>Fr,applyEasing:()=>St,applyLocaleToTree:()=>dl,applyTextStyle:()=>Sr,applyTextureRegionToTexture:()=>lr,assign2DRenderOrder:()=>Cs,assignWithoutSchemaRefresh:()=>ri,atlasSizeOf:()=>Gi,attachComponentDefinitions:()=>us,baseRegionOf:()=>Wi,blendingForMode2D:()=>Ym,boxPolygon:()=>Ai,buildSkinGeometry:()=>hr,buildTiledSpriteGeometry:()=>li,capsulePolygon:()=>Sh,circleIntersectsPolygon:()=>qn,circlePolygon:()=>tS,clampSfxPitch:()=>Lr,cleanPolygon:()=>yh,coerceKeyframeValue:()=>Nv,coerceTextureResource:()=>D,coerceToPropertyType:()=>ds,collectAudioKeysInRange:()=>lp,collectClipPointNames:()=>ec,collectComponentDefinitions:()=>Yi,collectEventKeysInRange:()=>cp,collectRenderabilityIssues:()=>kT,collectTimedKeysInRange:()=>ap,collideCirclePolygon:()=>Wa,collideCircles:()=>Ch,collidePolygons:()=>Mh,composeEffectShaders:()=>Kc,composeTextureRegion:()=>Ui,configure2DTexture:()=>Y,convexHull:()=>La,convexPolygonsIntersect:()=>iS,copyAtlasMetadata:()=>ac,createAtlasResolver:()=>lc,createClipBindings:()=>dp,createDefaultClip:()=>tN,createEmptyAnimationSet:()=>mp,cssFont:()=>vf,cssFontFamily:()=>bf,cssFontWeight:()=>Sf,decodeSignalPayload:()=>wD,decomposeConvex:()=>_a,defineGroup:()=>sx,defineProperty:()=>x,describeFontFace:()=>ji,describeRejectCode:()=>tl,describeThrown:()=>Nt,describeUnknownNodeType:()=>ou,distanceToPolygonBoundary:()=>rS,drawStyledText:()=>ln,effectSupportsTarget:()=>hs,encodeSignalPayload:()=>dv,ensureCounterClockwise:()=>ki,findActiveCamera2D:()=>ru,findAnimationClip:()=>rc,findAnimationFramePoint:()=>Zl,findEmojiArtInSceneYaml:()=>eC,findKeyframeClip:()=>zr,fireEventKey:()=>up,fromSchemaValue:()=>YD,generateTrackId:()=>Dv,getActiveLocalization:()=>Ye,getAllShaderEffectTypes:()=>mx,getAnimationFrameTexturePath:()=>Ql,getComponentSchemaProperties:()=>Gm,getGameDebug:()=>uw,getNetKindTable:()=>Oh,getNodePropertySchema:()=>ke,getPhysicsDebugSource:()=>ql,getProjectAODefault:()=>Hf,getProjectTextureFiltering:()=>nc,getPropertiesByGroup:()=>ix,getPropertyDefinition:()=>It,getPropertyDisplayValue:()=>nx,getRuntimeLivePropertySink:()=>hw,getRuntimeSceneRoot:()=>dw,getSceneNodeDiskFormat:()=>jT,getScriptErrorSink:()=>km,getShaderEffectType:()=>fs,getSignalEmitSink:()=>Am,installAtlasFromManifest:()=>IN,installReactiveSchemaProperties:()=>G,interpolateValue:()=>Pv,isDirectionAxesEnabled:()=>Yl,isEmojiOnlyText:()=>Gb,isFontFaceRegistered:()=>Zw,isHighEndDevice:()=>$f,isInertNode:()=>zb,isInteractive:()=>Ix,isKeyframeEasing:()=>_e,isKnownSceneNodeType:()=>nu,isNetTeleport:()=>Xh,isPhysicsDebugEnabled:()=>zi,isPolygonConvex:()=>eS,isProjectScriptEntry:()=>tC,isProjectScriptPath:()=>Kb,isSameTextureRegion:()=>Iw,isScriptComponent:()=>Qw,isScriptComponentClass:()=>Xb,isSequenceAnimationFrame:()=>Jl,isSfxPreset:()=>Mi,isShaderEffectHost:()=>gx,isSliceBorderEmpty:()=>ci,isSpineModuleAvailable:()=>Lw,isTestHarnessComponentType:()=>gw,isTextProperty:()=>JT,isTextureResourceRef:()=>ef,isTrackValueType:()=>Mv,labelDecorationPadding:()=>pu,labelGlowBlurPx:()=>hu,labelGlowPasses:()=>Df,layoutLabelText:()=>mu,loadProjectFonts:()=>Hc,loadSpineAsset:()=>dc,loadSpineModule:()=>cc,makeSchemaPropertyReactive:()=>Em,mergeSchemas:()=>ce,netFlagsByte:()=>uv,netOwnershipOf:()=>Kh,normalizeAnimationResource:()=>tc,normalizeBlendMode2D:()=>$i,normalizeKeyframeAnimationSet:()=>cl,normalizeNodeTypeName:()=>an,normalizePolygonConfig:()=>Gr,normalizeProjectTextureFiltering:()=>ic,normalizeSliceBorder:()=>Ee,paintLabelCanvas:()=>fu,parseEventArgs:()=>en,parseSpineAtlasPageNames:()=>_w,playable:()=>kp,pointInPolygon:()=>kt,polygonArea:()=>gh,polygonBounds:()=>bh,polygonCentroid:()=>Gn,polygonSignedArea:()=>Fa,property:()=>Dl,quaternionToRotationZ:()=>aS,reactiveSchemaPropertyNames:()=>vw,readBooleanArg:()=>au,readNumberArg:()=>Qe,readStringArg:()=>Rx,readWorldTransform2D:()=>it,rectIntersectsConvexPolygon:()=>oC,rectIntersectsPolygon:()=>vh,registerBuiltInScripts:()=>UN,registerGameDebug:()=>cw,registerNetworkPrefab:()=>IC,registerPhysicsDebugSource:()=>pw,registerProjectScriptExports:()=>rC,registerRuntimeLivePropertySink:()=>ts,registerRuntimeSceneRoot:()=>es,registerScriptErrorSink:()=>yw,registerShaderEffect:()=>Xm,registerSignalEmitSink:()=>bw,reportScriptError:()=>Dt,reportSignalEmit:()=>$l,resetNetKindTable:()=>RC,resetProjectFontRegistry:()=>Jw,resolveAnimatedSpriteFrameLayout:()=>Jc,resolveFramePointToLocal:()=>Zc,resolveFramePolygonToLocal:()=>eu,resolveLocalizedText:()=>Zi,resolvePendingComponents:()=>jc,resolveRuntimeTimeConfig:()=>vp,resolveSceneDiskKey:()=>YT,resolveSceneNodeType:()=>As,resolveSpinePagePath:()=>Bm,resolveTrackTarget:()=>sp,sampleTrack:()=>kv,sanitizeTextureRegion:()=>oc,segmentPolygonT:()=>wh,serializePolygonConfig:()=>VN,setActiveLocalization:()=>Ss,setDefaultStoreUrl:()=>wN,setDirectionAxesEnabled:()=>fw,setNetworkPrefabTable:()=>EC,setNodePropertyValue:()=>si,setPhysicsDebugEnabled:()=>mw,setPlayableAdapter:()=>vN,setPostprocessingModuleLoader:()=>dN,setProjectAODefault:()=>Hx,setProjectTextureFiltering:()=>Ew,setSpineModuleLoader:()=>Ow,shaderEffectsCacheKey:()=>Xc,shakeNoise:()=>mr,spineAssetKey:()=>ni,stampAtlasView:()=>sc,state:()=>ow,styledTextPadding:()=>cn,suggestSceneNodeType:()=>mf,summarizeRenderabilityIssues:()=>AT,sweepCircleAgainstPolygon:()=>jn,toSchemaValue:()=>Av,transformPolygon:()=>Rr,userScriptComponentId:()=>Yb,validatePropertyValue:()=>Hm,worldToCanvasLogical:()=>yp,worldToCanvasThroughCamera:()=>hl});export{ch as a,Ul as b,Oi as c,cw as d,uw as e,Wl as f,es as g,dw as h,Gl as i,ts as j,hw as k,Li as l,pw as m,ql as n,Hl as o,mw as p,zi as q,jl as r,fw as s,Yl as t,Pm as u,gw as v,Fi as w,yw as x,km as y,_i as z,bw as A,Am as B,$l as C,Dt as D,Nt as E,Me as F,V as G,U as H,Em as I,G as J,vw as K,ri as L,ct as M,Ql as N,Jl as O,Zl as P,ec as Q,tc as R,rc as S,Im as T,ic as U,Ew as V,nc as W,Y as X,oc as Y,lr as Z,Ui as _,Iw as $,Rw as aa,Bw as ba,Vw as ca,Wi as da,Gi as ea,sc as fa,ac as ga,lc as ha,Ow as ia,Lw as ja,cc as ka,ni as la,Bm as ma,_w as na,dc as oa,Uc as pa,ut as qa,Wc as ra,Gc as sa,O as ta,Qw as ua,ji as va,Jw as wa,Zw as xa,Hc as ya,Gm as za,us as Aa,jc as Ba,Yi as Ca,ke as Da,ix as Ea,It as Fa,nx as Ga,Hm as Ha,si as Ia,jm as Ja,Yc as Ka,$i as La,Ym as Ma,Ki as Na,Xi as Oa,M as Pa,x as Qa,ds as Ra,sx as Sa,ce as Ta,hs as Ua,ps as Va,Xm as Wa,fs as Xa,mx as Ya,Kc as Za,Xc as _a,gx as $a,Oe as ab,ef as bb,D as cb,Ne as db,Ji as eb,Ss as fb,Ye as gb,Zi as hb,Le as ib,en as jb,Jc as kb,Zc as lb,eu as mb,Ke as nb,tn as ob,ur as pb,dr as qb,li as rb,cf as sb,Ee as tb,ci as ub,hr as vb,pr as wb,Ae as xb,Bt as yb,mr as zb,ks as Ab,Vt as Bb,ru as Cb,sn as Db,Ot as Eb,Lt as Fb,Ft as Gb,_t as Hb,iu as Ib,an as Jb,As as Kb,nu as Lb,mf as Mb,ou as Nb,zt as Ob,ht as Pb,yr as Qb,pt as Rb,Ix as Sb,Qe as Tb,au as Ub,Rx as Vb,br as Wb,bf as Xb,Sf as Yb,vf as Zb,ln as _b,Sr as $b,cn as ac,Fe as bc,Cs as cc,Je as dc,ui as ec,te as fc,mt as gc,vr as hc,wr as ic,xr as jc,Pr as kc,du as lc,Ms as mc,Mf as nc,Ds as oc,di as pc,hu as qc,Df as rc,pu as sc,mu as tc,fu as uc,ft as vc,gt as wc,kr as xc,gu as yc,Su as zc,yt as Ac,bt as Bc,Lf as Cc,Is as Dc,fe as Ec,Tu as Fc,_e as Gc,St as Hc,ze as Ic,vt as Jc,Mu as Kc,Gf as Lc,Hx as Mc,Hf as Nc,Yf as Oc,et as Pc,Cu as Qc,$f as Rc,ve as Sc,uh as Tc,kT as Uc,AT as Vc,zb as Wc,IT as Xc,RT as Yc,BT as Zc,VT as _c,WT as $c,jT as ad,YT as bd,$T as cd,hh as dd,Gb as ed,JT as fd,eC as gd,qb as hd,Hb as id,jb as jd,Yb as kd,Kb as ld,tC as md,Xb as nd,rC as od,ph as pd,mh as qd,Wn as rd,pF as sd,mF as td,Fa as ud,gh as vd,Gn as wd,eS as xd,ki as yd,yh as zd,La as Ad,bh as Bd,Rr as Cd,Ai as Dd,tS as Ed,Sh as Fd,kt as Gd,rS as Hd,qn as Id,vh as Jd,oC as Kd,iS as Ld,wh as Md,_a as Nd,it as Od,aS as Pd,Hn as Qd,Br as Rd,Ch as Sd,Wa as Td,Mh as Ud,jn as Vd,Yn as Wd,q as Xd,NF as Yd,Kn as Zd,Oh as _d,EC as $d,IC as ae,RC as be,Lh as ce,Ka as de,Xn as ee,$h as fe,cv as ge,Kh as he,uv as ie,Xh as je,ge as ke,nt as le,tl as me,rl as ne,ro as oe,dv as pe,wD as qe,io as re,Vr as se,no as te,Zt as ue,er as ve,yv as we,oo as xe,so as ye,bv as ze,ao as Ae,lo as Be,co as Ce,ll as De,Mi as Ee,Lr as Fe,uo as Ge,ho as He,Pv as Ie,kv as Je,ap as Ke,lp as Le,cp as Me,up as Ne,Av as Oe,YD as Pe,sp as Qe,dp as Re,Fr as Se,Cv as Te,hp as Ue,Mv as Ve,Dv as We,Nv as Xe,cl as Ye,mp as Ze,tN as _e,zr as $e,ir as af,Ur as bf,po as cf,Wr as df,mo as ef,dN as ff,go as gf,dl as hf,yo as if,yp as jf,hl as kf,bp as lf,Ov as mf,Sp as nf,vp as of,vN as pf,wN as qf,kp as rf,Tp as sf,Cp as tf,Gv as uf,qv as vf,IN as wf,bo as xf,So as yf,vo as zf,wo as Af,xo as Bf,Po as Cf,ko as Df,Ao as Ef,To as Ff,Gr as Gf,VN as Hf,Co as If,Mo as Jf,Do as Kf,No as Lf,Eo as Mf,nr as Nf,Io as Of,UN as Pf,Dl as Qf,ow as Rf,rE as Sf};
|