tide-commander 1.77.0 → 1.78.0
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/dist/assets/{BossLogsModal-DadqfwM-.js → BossLogsModal-BJUaVgOz.js} +1 -1
- package/dist/assets/{BossSpawnModal-BfBD2177.js → BossSpawnModal-CLzUp9FQ.js} +1 -1
- package/dist/assets/{ControlsModal-C7k19rVV.js → ControlsModal-BK-nIx6P.js} +1 -1
- package/dist/assets/{DockerLogsModal-zerJaMSY.js → DockerLogsModal-wW7EV327.js} +1 -1
- package/dist/assets/{EmbeddedEditor-C_sbdn9e.js → EmbeddedEditor-B7LC5gF5.js} +1 -1
- package/dist/assets/{GmailOAuthSetup-CWUAVZZM.js → GmailOAuthSetup-C_kETU4w.js} +1 -1
- package/dist/assets/{GoogleOAuthSetup-E7aWGuMy.js → GoogleOAuthSetup-Dn1hZsMs.js} +1 -1
- package/dist/assets/{IframeModal-BNwvP8Po.js → IframeModal-8t96ASFF.js} +1 -1
- package/dist/assets/{IntegrationsPanel-CWQ5Uum4.js → IntegrationsPanel-C0TjN-6q.js} +2 -2
- package/dist/assets/{LogViewerModal-BCXMLdRH.js → LogViewerModal-J_Wv4RxY.js} +1 -1
- package/dist/assets/{MonitoringModal-DK79sc5N.js → MonitoringModal-CUy6EbeR.js} +1 -1
- package/dist/assets/{PM2LogsModal-Bh3w4epV.js → PM2LogsModal-CgYX33GL.js} +1 -1
- package/dist/assets/{RestoreArchivedAreaModal-B-H5Skrp.js → RestoreArchivedAreaModal-ILOa64df.js} +1 -1
- package/dist/assets/{Scene2DCanvas-B9UN5ZKm.js → Scene2DCanvas-B9_c0Cr2.js} +1 -1
- package/dist/assets/{SceneManager-FjdQYco5.js → SceneManager-BuMbzzM8.js} +1 -1
- package/dist/assets/{SkillsPanel-B9C8MwOF.js → SkillsPanel-Bp0UiQRG.js} +1 -1
- package/dist/assets/{SpawnModal-D_LcFbP1.js → SpawnModal-DjzhiAMO.js} +1 -1
- package/dist/assets/{SubordinateAssignmentModal-BoanKhXq.js → SubordinateAssignmentModal-CWaAMKp5.js} +1 -1
- package/dist/assets/{TriggerManagerPanel-Ck-tzKLv.js → TriggerManagerPanel-DpCFDRa5.js} +1 -1
- package/dist/assets/{WorkflowEditorPanel-Bwvw_Vgj.js → WorkflowEditorPanel-D-Vcfxmm.js} +1 -1
- package/dist/assets/{index-B5v0FpYR.js → index-1yqGGDiA.js} +1 -1
- package/dist/assets/{index-Baz89OXb.js → index-7TaAASV1.js} +2 -2
- package/dist/assets/{index-DvKJEzc1.js → index-BRLyVoUe.js} +1 -1
- package/dist/assets/{index-8lOgiTZV.js → index-BeUHeagl.js} +1 -1
- package/dist/assets/{index-BJJScfkg.js → index-COln_-Fk.js} +1 -1
- package/dist/assets/index-D6--gGWa.js +2 -0
- package/dist/assets/{index-BKq2RkPI.js → index-DX-7fZ78.js} +3 -3
- package/dist/assets/{index-BAwissdJ.js → index-DyidqysN.js} +1 -1
- package/dist/assets/{index-7isjCekP.js → index-rGRqmeiB.js} +1 -1
- package/dist/assets/{main-CiaEK7il.js → main-COvyQg-T.js} +4 -4
- package/dist/assets/{web-C1fk4YYO.js → web-CpCf-DCG.js} +1 -1
- package/dist/assets/{web-BdPxI-ix.js → web-N_FykYu_.js} +1 -1
- package/dist/index.html +1 -1
- package/package.json +1 -1
- package/dist/assets/index-DMa3VOph.js +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var ns=Object.defineProperty;var as=(a,e,t)=>e in a?ns(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var u=(a,e,t)=>as(a,typeof e!="symbol"?e+"":e,t);import{E as y,S as Wt,v as A,x as v,ak as rs,ai as We,al as ot,A as wt,am as K,an as J,ah as ke,w as oe,ao as se,l as bt,o as te,U as Y,ap as j,g as T,aq as ls,aj as cs,ar as hs,as as ds,t as Pe,K as Ye,at as pe,z as le,B as Ae,s as pt,au as Me,av as O,I as me,f as Xe,Q as Ee,aw as Ft,ax as z,ay as xe,P as us,C as H,a8 as gs,R as Ge,az as Je,aA as ps,i as Nt,af as jt,aB as fs,D as et,aC as ms,V as re,aD as Fe,aE as je,X as $t,u as ge,H as ce,ag as yt,aF as we,aG as Ut,aH as Mt,aI as ws,G as Yt,aJ as bs,aK as ys,aa as nt,aL as Ms,aM as ye,aN as ve,aO as Ss,W as vs,Y as Cs,aP as St,aQ as at,aR as Ps,aS as ks,aT as As,aU as xs,ac as Bs,ad as Xt,ae as Ts,aV as Is,aW as Ds,aX as Ls,aY as Es,ab as _s}from"./vendor-three-Chj50gSY.js";import{bS as Os,bT as zs,bU as Gs,bX as Ie,bV as Rs,k as Vt,l as Zt,A as rt,m as Hs,bY as Ws,T as Fs,bZ as ft,b_ as Ce,s as k,x as $e,v as lt,b$ as Ns,c0 as js,F as Be,n as he,o as $s,S as Us,w as Ne,t as Ys,c1 as Xs,c2 as Vs,c3 as vt,c4 as Zs}from"./main-CiaEK7il.js";import"./vendor-react--Eh9ivFN.js";function Ct(a){const e=new Map,t=new Map,s=a.clone();return Kt(a,s,function(i,o){e.set(o,i),t.set(i,o)}),s.traverse(function(i){if(!i.isSkinnedMesh)return;const o=i,n=e.get(i),r=n.skeleton.bones;o.skeleton=n.skeleton.clone(),o.bindMatrix.copy(n.bindMatrix),o.skeleton.bones=r.map(function(l){return t.get(l)}),o.bind(o.skeleton,o.bindMatrix)}),s}function Kt(a,e,t){t(a,e);for(let s=0;s<a.children.length;s++)Kt(a.children[s],e.children[s],t)}class Ks{constructor(){u(this,"models",new Map);u(this,"customModels",new Map);u(this,"loaded",!1);u(this,"loadingPromise",null);u(this,"loader");u(this,"dracoLoader");u(this,"loadingCustomModels",new Map);this.loader=new Os,this.dracoLoader=new zs,this.dracoLoader.setDecoderPath("https://www.gstatic.com/draco/versioned/decoders/1.5.7/"),this.loader.setDRACOLoader(this.dracoLoader),this.loader.setMeshoptDecoder(Gs)}get isLoaded(){return this.loaded}async loadAll(){if(this.loaded){console.log("[CharacterLoader] Already loaded, skipping");return}if(this.loadingPromise)return console.log("[CharacterLoader] Already loading, waiting for existing promise"),this.loadingPromise;const e=[...new Set([...Object.values(Ie),...Rs.map(t=>t.file)])];return console.log(`[CharacterLoader] Starting to load ${e.length} models`),this.loadingPromise=Promise.all(e.map(t=>this.loadModel(t))).then(()=>{this.loaded=!0,console.log(`[CharacterLoader] All models loaded. Cache size: ${this.models.size}`)}),this.loadingPromise}loadModel(e){return new Promise(t=>{const s=`/assets/characters/${e}`;console.log(`[CharacterLoader] Loading model: ${s}`),this.loader.load(s,i=>{console.log(`[CharacterLoader] Successfully loaded: ${e}`);const o=this.prepareModel(i.scene);this.models.set(e,{scene:o,animations:i.animations}),t()},i=>{},i=>{console.error(`[CharacterLoader] Failed to load ${e}:`,i),t()})})}prepareModel(e){return e.scale.setScalar(1),e.position.set(0,0,0),e.rotation.set(0,0,0),e.visible=!1,e.traverse(t=>{if(t instanceof y&&(t.castShadow=!0,t.receiveShadow=!0,t.material)){const s=t.material;s.map&&(s.map.colorSpace=Wt),s.isMeshStandardMaterial&&(s.roughness=s.roughness??.6,s.metalness=s.metalness??0,s.envMapIntensity=.8,s.needsUpdate=!0)}}),e}clone(e){const t=Ie[e];return this.cloneByModelFile(t)}cloneByModelFile(e){const t=this.models.get(e);if(!t)return console.warn(`[CharacterLoader] Model not found: ${e}`),null;const s=Ct(t.scene);return s.visible=!0,s.position.set(0,0,0),s.rotation.set(0,0,0),s.traverse(i=>{i.visible=!0,i instanceof y&&i.material&&(Array.isArray(i.material)?i.material=i.material.map(o=>o.clone()):i.material=i.material.clone())}),{mesh:s,animations:t.animations}}getAnimations(e){const t=Ie[e],s=this.models.get(t);return(s==null?void 0:s.animations)??null}hasModel(e){const t=Ie[e];return this.models.has(t)}async loadCustomModel(e){if(this.customModels.has(e))return;const t=this.loadingCustomModels.get(e);if(t)return t;const s=new Promise(i=>{this.loader.load(Vt(Zt(`/api/custom-models/${e}`)),o=>{const n=this.prepareModel(o.scene);this.customModels.set(e,{scene:n,animations:o.animations}),console.log(`[CharacterLoader] Loaded custom model for class: ${e} (${o.animations.length} animations)`),i()},void 0,o=>{console.error(`[CharacterLoader] Failed to load custom model for ${e}:`,o),i()})});this.loadingCustomModels.set(e,s);try{await s}finally{this.loadingCustomModels.delete(e)}}hasCustomModel(e){return this.customModels.has(e)}cloneCustomModel(e){const t=this.customModels.get(e);if(!t)return null;const s=Ct(t.scene);return s.visible=!0,s.position.set(0,0,0),s.rotation.set(0,0,0),s.traverse(i=>{i.visible=!0,i instanceof y&&i.material&&(Array.isArray(i.material)?i.material=i.material.map(o=>o.clone()):i.material=i.material.clone())}),{mesh:s,animations:t.animations}}getCustomModelAnimations(e){const t=this.customModels.get(e);return(t==null?void 0:t.animations)??null}unloadCustomModel(e){const t=this.customModels.get(e);t&&(this.disposeCachedModel(t),this.customModels.delete(e),console.log(`[CharacterLoader] Unloaded custom model for class: ${e}`))}disposeCachedModel(e){e.scene.traverse(t=>{var s;t instanceof y&&((s=t.geometry)==null||s.dispose(),Array.isArray(t.material)?t.material.forEach(i=>this.disposeMaterial(i)):t.material&&this.disposeMaterial(t.material))})}disposeMaterial(e){var t,s,i,o,n,r,l,c,d,h,g;(e instanceof A||e instanceof v||e instanceof rs)&&((t=e.map)==null||t.dispose(),"normalMap"in e&&((s=e.normalMap)==null||s.dispose()),"roughnessMap"in e&&((i=e.roughnessMap)==null||i.dispose()),"metalnessMap"in e&&((o=e.metalnessMap)==null||o.dispose()),"emissiveMap"in e&&((n=e.emissiveMap)==null||n.dispose()),"aoMap"in e&&((r=e.aoMap)==null||r.dispose()),"lightMap"in e&&((l=e.lightMap)==null||l.dispose()),"bumpMap"in e&&((c=e.bumpMap)==null||c.dispose()),"displacementMap"in e&&((d=e.displacementMap)==null||d.dispose()),"alphaMap"in e&&((h=e.alphaMap)==null||h.dispose()),"envMap"in e&&((g=e.envMap)==null||g.dispose())),e.dispose()}dispose(){for(const[e,t]of this.models)this.disposeCachedModel(t),console.log(`[CharacterLoader] Disposed model template: ${e}`);this.models.clear();for(const[e,t]of this.customModels)this.disposeCachedModel(t),console.log(`[CharacterLoader] Disposed custom model: ${e}`);this.customModels.clear(),this.dracoLoader.dispose(),this.loaded=!1,this.loadingPromise=null,this.loadingCustomModels.clear(),console.log("[CharacterLoader] All model caches disposed")}getCacheStats(){return{builtInModels:this.models.size,customModels:this.customModels.size,modelNames:Array.from(this.models.keys()),customModelIds:Array.from(this.customModels.keys())}}}const qs="character-male-a.glb";class Qs{constructor(e){u(this,"customClasses",new Map);this.characterLoader=e}setCustomClasses(e){this.customClasses=e}getClassConfig(e){const t=rt[e];if(t)return t;const s=this.customClasses.get(e);if(s){const i=parseInt(s.color.replace("#",""),16);return{icon:s.icon,color:isNaN(i)?8947848:i,description:s.description}}return{icon:"❓",color:8947848,description:"Unknown class"}}getModelInfo(e){const t=Ie[e];if(t)return{file:t,isCustomModel:!1};const s=this.customClasses.get(e);if(s){if(s.customModelPath)return{file:s.customModelPath,isCustomModel:!0,customClassId:s.id,scale:s.modelScale,offset:s.modelOffset};if(s.model)return{file:s.model,isCustomModel:!1,scale:s.modelScale,offset:s.modelOffset}}return{file:qs,isCustomModel:!1}}createCharacterBody(e,t){const s=this.getModelInfo(e.class);let i=null;try{s.isCustomModel&&s.customClassId&&(i=this.characterLoader.cloneCustomModel(s.customClassId)),i||(i=this.characterLoader.cloneByModelFile(s.file))}catch(l){console.error(`[ModelLoader] Failed to clone model for class ${e.class} (agent ${e.name}):`,l),i=null}if(i){i.mesh.name="characterBody";const l=s.scale??1;i.mesh.userData.customModelScale=l,i.mesh.userData.isCustomModel=s.isCustomModel,s.offset&&(s.offset.x!==0||s.offset.y!==0||s.offset.z!==0)&&i.mesh.position.set(s.offset.x,s.offset.z,s.offset.y);const c=this.customClasses.get(e.class);c!=null&&c.animationMapping&&(i.mesh.userData.animationMapping=c.animationMapping);const d=new We(i.mesh),h=new Map;for(const g of i.animations){const f=g.name.toLowerCase();h.set(f,g),h.set(g.name,g)}return{body:i.mesh,mixer:d,animations:h}}const o=new ot(.5,1,4,16),n=new A({color:t,roughness:.4,metalness:.3}),r=new y(o,n);return r.position.y=1,r.castShadow=!0,r.receiveShadow=!0,r.name="characterBody",{body:r,mixer:null,animations:new Map}}calculateModelHeight(e,t){return t?2:1.5}upgradeToCharacterModel(e,t){const s=e.getObjectByName("characterBody");if(!(s instanceof y)||!(s.geometry instanceof ot))return null;const i=this.characterLoader.clone(t.class);if(!i)return null;e.remove(s),s.geometry.dispose(),s.material.dispose(),i.mesh.name="characterBody",e.add(i.mesh);const o=new We(i.mesh),n=new Map;for(const r of i.animations){const l=r.name.toLowerCase();n.set(l,r)}return{group:e,mixer:o,animations:n,currentAction:null}}replaceAgentModel(e,t){const{group:s}=e,i=this.getModelInfo(t.class);let o=null;if(i.isCustomModel&&i.customClassId&&(o=this.characterLoader.cloneCustomModel(i.customClassId)),o||(o=this.characterLoader.cloneByModelFile(i.file)),!o)return console.warn(`[ModelLoader] Could not load model for class ${t.class}, keeping current model`),s.userData.agentClass=t.class,null;const n=s.getObjectByName("characterBody");n&&(s.remove(n),n.traverse(h=>{var g;(h instanceof y||h instanceof wt)&&((g=h.geometry)==null||g.dispose(),Array.isArray(h.material)?h.material.forEach(f=>this.disposeMaterial(f)):h.material&&this.disposeMaterial(h.material))})),e.mixer&&(e.mixer.stopAllAction(),e.mixer.uncacheRoot(s)),o.mesh.name="characterBody";const r=i.scale??1;o.mesh.userData.customModelScale=r,o.mesh.userData.isCustomModel=i.isCustomModel,i.offset&&(i.offset.x!==0||i.offset.y!==0||i.offset.z!==0)&&o.mesh.position.set(i.offset.x,i.offset.z,i.offset.y);const l=this.customClasses.get(t.class);l!=null&&l.animationMapping&&(o.mesh.userData.animationMapping=l.animationMapping),s.add(o.mesh);const c=new We(o.mesh),d=new Map;for(const h of o.animations){const g=h.name.toLowerCase();d.set(g,h),d.set(h.name,h)}return s.userData.agentClass=t.class,console.log(`[ModelLoader] Agent ${t.name} model updated to ${i.file}`),{group:s,mixer:c,animations:d,currentAction:null}}disposeAgentMesh(e){for(e.mixer&&(e.mixer.stopAllAction(),e.mixer.uncacheRoot(e.group)),e.group.traverse(t=>{var s,i;t instanceof y?((s=t.geometry)==null||s.dispose(),Array.isArray(t.material)?t.material.forEach(o=>this.disposeMaterial(o)):t.material&&this.disposeMaterial(t.material)):t instanceof K?this.disposeMaterial(t.material):t instanceof wt&&((i=t.geometry)==null||i.dispose(),Array.isArray(t.material)?t.material.forEach(o=>this.disposeMaterial(o)):t.material&&this.disposeMaterial(t.material))});e.group.children.length>0;)e.group.remove(e.group.children[0]);e.animations.clear()}disposeMaterial(e){var t,s,i,o,n;(e instanceof A||e instanceof v||e instanceof J)&&((t=e.map)==null||t.dispose(),"normalMap"in e&&((s=e.normalMap)==null||s.dispose()),"roughnessMap"in e&&((i=e.roughnessMap)==null||i.dispose()),"metalnessMap"in e&&((o=e.metalnessMap)==null||o.dispose()),"emissiveMap"in e&&((n=e.emissiveMap)==null||n.dispose())),e.dispose()}}class Js{createAnimationSetup(e,t,s){s!=null&&s.animationMapping&&(e.userData.animationMapping=s.animationMapping);const i=new We(e),o=new Map;for(const n of t)o.set(n.name.toLowerCase(),n),o.set(n.name,n);return{mixer:i,animations:o}}getIdleTimerColor(e){const i=Math.min(e/60,60)/60,o=Math.pow(i,.7),n=120*(1-o),r=80+20*o,l=60-10*o,c=`hsl(${Math.round(n)}, ${Math.round(r)}%, ${Math.round(l)}%)`;return{text:c,border:c}}formatIdleTimeShort(e){if(e<60)return`${e}s`;const t=Math.floor(e/60);if(t<60){const n=e%60;return n>0?`${t}m ${n}s`:`${t}m`}const s=Math.floor(t/60),i=t%60;return s<24?i>0?`${s}h ${i}m`:`${s}h`:`${Math.floor(s/24)}d`}}const Pt={idle:4915102,working:4890367,waiting:16752202,waiting_permission:16763904,error:16730698,orphaned:16711935,default:8947848},ei=800,kt=420,At=5;function qt(a){return Hs(a).freePercent}class ti{constructor(e){u(this,"idleTimerCanvas",null);u(this,"idleTimerCtx",null);u(this,"manaBarCanvas",null);u(this,"manaBarCtx",null);u(this,"providerBadgeImages",new Map);u(this,"providerBadgeVersion",0);this.animConfig=e}getNameLabelBaseScale(e,t){return e?3.1:2.5}fitNameLabelText(e,t,s,i,o){e.font=`bold ${s}px Arial`;const n=i-(o?s*.42+s*.3:0);if(e.measureText(t).width<=n)return t;let r=t;for(;r.length>3&&e.measureText(`${r}...`).width>n;)r=r.slice(0,-1);return`${r}...`}fitTaskLabelText(e,t,s,i){if(e.font=`italic ${s}px "Segoe UI", Arial, sans-serif`,e.measureText(t).width<=i)return t;let o=t;for(;o.length>3&&e.measureText(`${o}...`).width>i;)o=o.slice(0,-1);return`${o}...`}getProviderBadgeImage(e){if(e!=="claude"&&e!=="codex"&&e!=="opencode")return null;const t=this.providerBadgeImages.get(e);if(t)return t;if(typeof Image>"u")return null;const s=new Image;return s.decoding="async",s.src=e==="codex"?"/assets/codex.png":e==="opencode"?"/assets/opencode.png":"/assets/claude.png",s.onload=()=>{this.providerBadgeVersion+=1},this.providerBadgeImages.set(e,s),s}getStatusColor(e){return Pt[e]??Pt.default}createSelectionRing(e,t=!1){const s=t?1.5:1,i=new ke(.8*s,.95*s,32),o=new v({color:e,side:oe,transparent:!0,opacity:0,depthTest:!1}),n=new y(i,o);return n.rotation.x=-Math.PI/2,n.position.y=.05,n.renderOrder=999,n.name="selectionRing",n}createStatusBarSprite(e,t,s,i,o=2){const n=document.createElement("canvas"),r=n.getContext("2d");n.width=4096,n.height=2560,this.drawStatusBar(r,n.width,n.height,e,t,s,i);const l=new se(n);l.minFilter=bt,l.magFilter=te,l.generateMipmaps=!0,l.anisotropy=16,l.needsUpdate=!0;const c=new J({map:l,transparent:!0,depthTest:!1,depthWrite:!1}),d=new K(c),h=i?.8:.5;d.position.y=o+h;const g=i?2.6:2.1,f=n.height/n.width;return d.scale.set(g,g*f,1),d.name="statusBar",d.renderOrder=1100,d.userData.modelHeight=o,d.userData.baseIndicatorScale=g,d.userData.aspectRatio=f,d}createNameLabelSprite(e,t,s,i,o){const n=document.createElement("canvas"),r=n.getContext("2d");n.width=4096,n.height=o?2048:1024,this.drawNameLabel(r,n.width,n.height,e,t,s,i,o);const l=new se(n);l.minFilter=bt,l.magFilter=te,l.generateMipmaps=!0,l.anisotropy=16,l.needsUpdate=!0;const c=new J({map:l,transparent:!0,depthTest:!1,depthWrite:!1}),d=new K(c),h=this.getNameLabelBaseScale(s,!!o);d.position.y=o?s?-1.2:-1:s?-.9:-.7;const g=n.height/n.width;return d.scale.set(h,h*g,1),d.name="nameLabelSprite",d.renderOrder=1200,d.userData.baseIndicatorScale=h,d.userData.aspectRatio=g,d.userData.nameLabelLayoutVersion=At,d.userData.providerBadgeVersion=this.providerBadgeVersion,d}drawNameLabel(e,t,s,i,o,n,r,l){e.clearRect(0,0,t,s);const c=`#${o.toString(16).padStart(6,"0")}`,d=l?s*.3:s/2,h=this.getProviderBadgeImage(r),g=h!==null,f=n?Math.max(kt,ei-300):kt;e.font=`bold ${f}px Arial`;const p=this.fitNameLabelText(e,i,f,t-400,g),m=e.measureText(p).width,b=g?f*.95:0,w=g?f*.32:0,M=b+w,S=m+M,P=t/2+M/2;if(e.textAlign="center",e.textBaseline="middle",e.shadowColor="rgba(0, 0, 0, 0.9)",e.shadowBlur=f*.12,e.shadowOffsetX=f*.04,e.shadowOffsetY=f*.04,e.strokeStyle="#000",e.lineWidth=f*.14,e.lineJoin="round",e.strokeText(p,P,d),e.shadowColor="transparent",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0,g){const C=t/2-S/2,x=d-b/2;if(h&&h.complete&&h.naturalWidth>0)e.drawImage(h,C,x,b,b);else{const B=C+b/2,I=d,L=r==="codex"?"#4a9eff":r==="opencode"?"#10b981":"#ff9e4a";e.beginPath(),e.arc(B,I,b/2,0,Math.PI*2),e.fillStyle=L,e.fill()}}if(e.fillStyle=c,e.fillText(p,P,d),l){const C=Math.round(f*.85),x=s*.55,B=t-600,I=C,L=this.fitTaskLabelText(e,l,I,B);e.font=`italic ${I}px "Segoe UI", Arial, sans-serif`,e.shadowColor="rgba(0, 0, 0, 0.8)",e.shadowBlur=I*.1,e.shadowOffsetX=I*.03,e.shadowOffsetY=I*.03,e.strokeStyle="#000",e.lineWidth=I*.12,e.lineJoin="round",e.strokeText(L,t/2,x),e.shadowColor="transparent",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0,e.fillStyle="rgba(190, 205, 225, 0.9)",e.fillText(L,t/2,x)}}drawStatusBar(e,t,s,i,o,n,r){e.clearRect(0,0,t,s);const l=t/2048;let c=80*l;r&&(e.font=`${400*l}px serif`,e.textAlign="center",e.textBaseline="top",e.fillText("👑",t/2,c),c+=440*l);const d=200*l,h=1350*l,g=(t-h)/2,f=c,p=200*l,m=g+p/2+30*l,b=f+d/2;let w;switch(o){case"working":w="#4a9eff";break;case"orphaned":w="#c060e0";break;case"error":w="#e05050";break;case"waiting":case"waiting_permission":w="#e0a030";break;default:w="#40c090"}e.beginPath(),e.arc(m,b,p/2,0,Math.PI*2),e.fillStyle=w,e.shadowColor=w,e.shadowBlur=20*l,e.fill(),e.shadowBlur=0,e.strokeStyle="rgba(0, 0, 0, 0.4)",e.lineWidth=4*l,e.stroke();const M=g+p+60*l,S=h-p-90*l,P=d-80*l,C=f+40*l,x=30*l;e.fillStyle="#0d0d14",e.beginPath(),e.roundRect(M,C,S,P,x),e.fill(),e.strokeStyle="rgba(80, 90, 110, 0.5)",e.lineWidth=4*l,e.stroke();const B=Math.max(0,Math.min(100,i))/100,I=8*l,L=Math.max(0,(S-I*2)*B);if(L>0){let G;B>.5?G="#00c896":B>.2?G="#e8a020":G="#e84040",e.fillStyle=G,e.beginPath(),e.roundRect(M+I,C+I,L,P-I*2,x-I),e.fill(),e.shadowColor=G,e.shadowBlur=12*l,e.fill(),e.shadowBlur=0}const E=`${Math.round(B*100)}%`;e.font=`bold ${180*l}px "Segoe UI", Arial, sans-serif`,e.textAlign="center",e.textBaseline="middle";const D=M+S/2,$=C+P/2;if(e.shadowColor="rgba(0, 0, 0, 0.8)",e.shadowBlur=8*l,e.shadowOffsetX=2*l,e.shadowOffsetY=2*l,e.strokeStyle="rgba(0, 0, 0, 0.9)",e.lineWidth=24*l,e.lineJoin="round",e.strokeText(E,D,$),e.shadowColor="transparent",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0,e.fillStyle="rgba(255, 255, 255, 0.95)",e.fillText(E,D,$),c+=d+60*l,o==="idle"&&n>0){const G=Math.floor((Date.now()-n)/1e3),W=this.animConfig.formatIdleTimeShort(G),Z=this.animConfig.getIdleTimerColor(G);e.font=`bold ${140*l}px Arial`;const F=e.measureText(`⏱ ${W}`).width+140*l,R=180*l,_=(t-F)/2,U=c;e.fillStyle="rgba(0, 0, 0, 0.85)",e.beginPath(),e.roundRect(_,U,F,R,28*l),e.fill(),e.strokeStyle=Z.border,e.lineWidth=12*l,e.stroke(),e.textAlign="center",e.textBaseline="middle",e.strokeStyle="#000",e.lineWidth=14*l,e.strokeText(`⏱ ${W}`,t/2,U+R/2),e.fillStyle=Z.text,e.fillText(`⏱ ${W}`,t/2,U+R/2)}}drawCombinedUI(e,t,s,i,o,n,r,l,c){e.clearRect(0,0,t,s);const d=`#${o.toString(16).padStart(6,"0")}`,h=t/2048;let g=80*h;c&&(e.font=`${288*h}px serif`,e.textAlign="center",e.textBaseline="top",e.fillText("👑",t/2,g),g+=320*h);const f=224*h,p=t-240*h;e.font=`bold ${f}px Arial`;let m=i;if(e.measureText(m).width>p){for(;m.length>3&&e.measureText(m+"...").width>p;)m=m.slice(0,-1);m+="..."}e.textAlign="center",e.textBaseline="middle";const w=g+f/2;e.strokeStyle="#000",e.lineWidth=24*h,e.lineJoin="round",e.strokeText(m,t/2,w),e.fillStyle=d,e.fillText(m,t/2,w),g+=f+64*h;const M=200*h,S=1350*h,P=(t-S)/2,C=g,x=176*h,B=P+x/2+24*h,I=C+M/2;let L;switch(r){case"working":L="#00a8ff";break;case"orphaned":L="#e040ff";break;case"error":L="#ff3030";break;case"waiting":case"waiting_permission":L="#ffc000";break;default:L="#00e090"}e.beginPath(),e.arc(B,I,x/2,0,Math.PI*2),e.fillStyle=L,e.fill(),e.shadowColor=L,e.shadowBlur=32*h,e.fill(),e.shadowBlur=0,e.strokeStyle="#000",e.lineWidth=12*h,e.stroke();const E=P+x+64*h,D=S-x-88*h,$=M-48*h,G=C+24*h;e.fillStyle="#000",e.beginPath(),e.roundRect(E,G,D,$,24*h),e.fill(),e.strokeStyle="#5a8a8a",e.lineWidth=8*h,e.stroke();const W=Math.max(0,Math.min(100,n))/100,Z=16*h,N=Math.max(0,(D-Z*2)*W);if(N>0){let U;W>.5?U="#00ff88":W>.2?U="#ffaa00":U="#ff3366",e.fillStyle=U,e.beginPath(),e.roundRect(E+Z,G+Z,N,$-Z*2,16*h),e.fill(),e.shadowColor=U,e.shadowBlur=32*h,e.fill(),e.shadowBlur=0}const F=`${Math.round(W*100)}%`;e.font=`bold ${128*h}px Arial`,e.textAlign="center",e.textBaseline="middle";const R=E+D/2,_=G+$/2;if(e.strokeStyle="#000",e.lineWidth=28*h,e.lineJoin="round",e.strokeText(F,R,_),e.fillStyle="#fff",e.shadowColor="#000",e.shadowBlur=8*h,e.fillText(F,R,_),e.shadowBlur=0,g+=M+48*h,r==="idle"&&l>0){const U=Math.floor((Date.now()-l)/1e3),q=this.animConfig.formatIdleTimeShort(U),V=this.animConfig.getIdleTimerColor(U);e.font=`bold ${160*h}px Arial`;const fe=e.measureText(`⏱ ${q}`).width+160*h,qe=216*h,os=(t-fe)/2,Qe=g;e.fillStyle="rgba(0, 0, 0, 0.85)",e.beginPath(),e.roundRect(os,Qe,fe,qe,32*h),e.fill(),e.strokeStyle=V.border,e.lineWidth=12*h,e.stroke(),e.textAlign="center",e.textBaseline="middle",e.strokeStyle="#000",e.lineWidth=16*h,e.strokeText(`⏱ ${q}`,t/2,Qe+qe/2),e.fillStyle=V.text,e.fillText(`⏱ ${q}`,t/2,Qe+qe/2)}}createManaBar(e,t,s=!1){const i=document.createElement("canvas"),o=i.getContext("2d");i.width=400,i.height=64,this.drawManaBar(o,i.width,i.height,e,t);const n=new se(i);n.minFilter=te,n.magFilter=te,n.needsUpdate=!0;const r=new J({map:n,transparent:!0,depthTest:!1}),l=new K(r);return l.position.y=s?3:2,l.scale.set(s?1.4:1.1,s?.22:.18,1),l.name="manaBar",l}drawManaBar(e,t,s,i,o){const n=Math.max(0,Math.min(100,i))/100;e.clearRect(0,0,t,s);const r=s/32,l=20*r,c=6*r,d=l+c+4*r,h=6*r,g=t-d-10*r,f=s-12*r,p=6*r;let m;switch(o){case"working":m="#4a9eff";break;case"orphaned":m="#ff00ff";break;case"error":m="#ff4a4a";break;case"waiting":case"waiting_permission":m="#ffcc00";break;default:m="#4aff9e"}const b=l/2+4*r,w=s/2;e.beginPath(),e.arc(b,w,l/2,0,Math.PI*2),e.fillStyle=m,e.fill(),e.shadowColor=m,e.shadowBlur=8*r,e.fill(),e.shadowBlur=0,e.strokeStyle="#000000",e.lineWidth=2*r,e.stroke(),e.fillStyle="#000000",e.beginPath(),e.roundRect(d,h,g,f,p),e.fill(),e.strokeStyle="#5a8a8a",e.lineWidth=2*r,e.stroke();const M=Math.max(0,(g-4*r)*n);if(M>0){let P,C;n>.5?(P="#00ff88",C="#00ff88"):n>.2?(P="#ffaa00",C="#ffaa00"):(P="#ff3366",C="#ff3366"),e.fillStyle=P,e.beginPath(),e.roundRect(d+2*r,h+2*r,M,f-4*r,p-2),e.fill(),e.shadowColor=C,e.shadowBlur=8*r,e.fill(),e.shadowBlur=0}const S=`${Math.round(n*100)}%`;e.font=`bold ${Math.round(24*r)}px Arial`,e.textAlign="center",e.textBaseline="middle",e.strokeStyle="#000000",e.lineWidth=4*r,e.strokeText(S,t/2,s/2),e.fillStyle="#ffffff",e.shadowColor="#ffffff",e.shadowBlur=2*r,e.fillText(S,t/2,s/2),e.shadowBlur=0}createIdleTimer(e,t,s=!1){const i=document.createElement("canvas"),o=i.getContext("2d");i.width=400,i.height=64,this.drawIdleTimer(o,i.width,i.height,e,t);const n=new se(i);n.minFilter=te,n.magFilter=te,n.needsUpdate=!0;const r=new J({map:n,transparent:!0,depthTest:!1}),l=new K(r);return l.position.set(0,s?3.5:2.4,0),l.scale.set(s?1.4:1.1,s?.22:.18,1),l.name="idleTimer",l}createBossCrown(){const e=document.createElement("canvas"),t=e.getContext("2d");e.width=128,e.height=128,t.clearRect(0,0,e.width,e.height),t.font="96px serif",t.textAlign="center",t.textBaseline="middle",t.fillText("👑",e.width/2,e.height/2);const s=new se(e);s.minFilter=te,s.magFilter=te,s.needsUpdate=!0;const i=new J({map:s,transparent:!0,depthTest:!1}),o=new K(i);return o.position.set(0,4,0),o.scale.set(.8,.8,1),o.name="bossCrown",o}drawIdleTimer(e,t,s,i,o){if(e.clearRect(0,0,t,s),i!=="idle"||o<=0)return;const n=Math.floor((Date.now()-o)/1e3),r=this.animConfig.formatIdleTimeShort(n),l=this.animConfig.getIdleTimerColor(n),c=s/80,d=24*c;e.font=`bold ${Math.round(44*c)}px Arial`;const g=e.measureText(`⏱ ${r}`).width+d*2,f=s-12*c,p=(t-g)/2,m=6*c;e.fillStyle="rgba(0, 0, 0, 0.9)",e.beginPath(),e.roundRect(p,m,g,f,10*c),e.fill(),e.strokeStyle=l.border,e.lineWidth=3*c,e.stroke(),e.textAlign="center",e.textBaseline="middle",e.strokeStyle="#000000",e.lineWidth=4*c,e.strokeText(`⏱ ${r}`,t/2,s/2),e.fillStyle=l.text,e.fillText(`⏱ ${r}`,t/2,s/2)}getIdleTimerCanvas(){return this.idleTimerCanvas||(this.idleTimerCanvas=document.createElement("canvas"),this.idleTimerCanvas.width=400,this.idleTimerCanvas.height=64,this.idleTimerCtx=this.idleTimerCanvas.getContext("2d")),{canvas:this.idleTimerCanvas,ctx:this.idleTimerCtx}}getManaBarCanvas(){return this.manaBarCanvas||(this.manaBarCanvas=document.createElement("canvas"),this.manaBarCanvas.width=400,this.manaBarCanvas.height=64,this.manaBarCtx=this.manaBarCanvas.getContext("2d")),{canvas:this.manaBarCanvas,ctx:this.manaBarCtx}}updateIdleTimer(e,t,s){const i=e.getObjectByName("idleTimer");if(!i)return;const o=i.material;if(!o.map)return;const n=o.map.image;if(!n||!(n instanceof HTMLCanvasElement))return;const r=n.getContext("2d");r&&(this.drawIdleTimer(r,n.width,n.height,t,s),o.map.needsUpdate=!0)}updateManaBar(e,t,s){const i=e.getObjectByName("manaBar");if(!i)return;const o=i.material;if(!o.map)return;const n=o.map.image;if(!n||!(n instanceof HTMLCanvasElement))return;const r=n.getContext("2d");r&&(this.drawManaBar(r,n.width,n.height,t,s),o.map.needsUpdate=!0)}updateNameLabel(e,t,s,i){var d;const o=e.getObjectByName("nameLabel");o&&((d=o.material.map)==null||d.dispose(),o.material.dispose(),e.remove(o));const n=rt[s],r=(n==null?void 0:n.color)??16777215,l=s==="boss"||e.userData.isBoss,c=this.createNameLabelSprite(t,r,l,i);e.add(c)}updateVisuals(e,t,s,i,o){var m;const n=t.isBoss===!0||t.class==="boss",r=Math.round(qt(t)),l=e.userData;if(l._cachedStatus!==t.status||l._cachedPercent!==r||l._cachedIsBoss!==n||t.status==="idle"&&l._cachedIdleBucket!==Math.floor((Date.now()-t.lastActivity)/6e4)){l._cachedStatus=t.status,l._cachedPercent=r,l._cachedIsBoss=n,l._cachedIdleBucket=t.status==="idle"?Math.floor((Date.now()-t.lastActivity)/6e4):0;const b=e.getObjectByName("statusBar");if(b){const P=b.material;if(P.map){const C=P.map.image;if(C instanceof HTMLCanvasElement){const x=C.getContext("2d");x&&(this.drawStatusBar(x,C.width,C.height,r,t.status,t.lastActivity,n),P.map.needsUpdate=!0)}}}const w=e.getObjectByName("combinedUI");if(w){const P=w.material;if(P.map){const C=P.map.image;if(C instanceof HTMLCanvasElement){const x=C.getContext("2d");x&&(this.drawCombinedUI(x,C.width,C.height,t.name,o,r,t.status,t.lastActivity,n),P.map.needsUpdate=!0)}}}const M=!!e.getObjectByName("statusBar"),S=!!e.getObjectByName("combinedUI");!M&&!S&&(this.updateManaBar(e,r,t.status),this.updateIdleTimer(e,t.status,t.lastActivity))}const d=t.taskLabel,h=e.getObjectByName("nameLabelSprite"),g=this.getNameLabelBaseScale(n,!!d),f=!!h&&(h.userData.nameLabelLayoutVersion!==At||h.userData.baseIndicatorScale!==g||h.userData.providerBadgeVersion!==this.providerBadgeVersion);if(l.agentName!==t.name||l._cachedTaskLabel!==d||f){if(h){if(!!l._cachedTaskLabel!==!!d||f){const P=h.material;(m=P.map)==null||m.dispose(),P.dispose(),e.remove(h);const C=t.isBoss===!0||t.class==="boss",x=this.createNameLabelSprite(t.name,o,C,t.provider,d);e.add(x)}else{const P=h.material;if(P.map){const C=P.map.image;if(C instanceof HTMLCanvasElement){const x=C.getContext("2d");x&&(this.drawNameLabel(x,C.width,C.height,t.name,o,n,t.provider,d),P.map.needsUpdate=!0)}}}l.agentName=t.name,l._cachedTaskLabel=d}const b=!!e.getObjectByName("statusBar"),w=!!e.getObjectByName("combinedUI");!b&&!w&&(this.updateNameLabel(e,t.name,t.class,t.provider),l.agentName=t.name,l._cachedTaskLabel=d)}const p=e.getObjectByName("selectionRing");if(p){const b=p.material;if(s){const w=rt[t.class];b.color.setHex((w==null?void 0:w.color)??o),b.opacity=t.isBoss===!0||t.class==="boss"?.34:.28}else i?(b.color.setHex(16766720),b.opacity=.2):b.opacity=0}}}class si{constructor(e){u(this,"modelLoader");u(this,"animConfig");u(this,"visualConfig");this.modelLoader=new Qs(e),this.animConfig=new Js,this.visualConfig=new ti(this.animConfig)}setCustomClasses(e){this.modelLoader.setCustomClasses(e)}createAgentMesh(e){const t=new Y;t.userData.agentId=e.id;const s=this.modelLoader.getClassConfig(e.class),i=e.isBoss===!0||e.class==="boss",{body:o,mixer:n,animations:r}=this.modelLoader.createCharacterBody(e,s.color);t.add(o);const l=this.modelLoader.calculateModelHeight(o,i),c=this.visualConfig.createSelectionRing(s.color,i);t.add(c);const d=qt(e),h=this.visualConfig.createStatusBarSprite(d,e.status,e.lastActivity,i,l);t.add(h);const g=this.visualConfig.createNameLabelSprite(e.name,s.color,i,e.provider,e.taskLabel);t.add(g),t.userData.agentName=e.name,t.userData.agentClass=e.class,t.userData.isBoss=i,t.position.set(e.position.x,e.position.y,e.position.z);const f=i?1:.75,p=i?3.5:2.5,m=new j(f,f,p,8),b=new v({visible:!1,transparent:!0,opacity:0}),w=new y(m,b);return w.position.y=p/2,w.name="clickHitbox",t.add(w),{group:t,mixer:n,animations:r,currentAction:null}}updateAgentClass(e,t){const{group:s}=e,i=s.userData.agentClass;if(i===t.class)return null;console.log(`[CharacterFactory] Agent ${t.name} class changed: ${i} -> ${t.class}`);const o=this.modelLoader.replaceAgentModel(e,t);return o&&this.visualConfig.updateNameLabel(s,t.name,t.class),o}updateVisuals(e,t,s,i=!1){const o=this.modelLoader.getClassConfig(t.class);this.visualConfig.updateVisuals(e,t,s,i,o.color)}upgradeToCharacterModel(e,t){return this.modelLoader.upgradeToCharacterModel(e,t)}disposeAgentMesh(e){this.modelLoader.disposeAgentMesh(e)}getStatusColor(e){return this.visualConfig.getStatusColor(e)}updateIdleTimer(e,t,s){this.visualConfig.updateIdleTimer(e,t,s)}updateManaBar(e,t,s){this.visualConfig.updateManaBar(e,t,s)}}const Q={STATIC:"static",IDLE:"idle",WALK:"walk",JUMP:"jump",SIT:"sit",DIE:"die",EMOTE_YES:"emote-yes",EMOTE_NO:"emote-no"},xt={height:.5,speed:1.5};class ii{constructor(){u(this,"movements",new Map);u(this,"jumpingAgents",new Map);u(this,"animatingAgents",new Set);u(this,"jumpTime",0)}isMoving(e){return this.movements.has(e)}hasActiveMovements(){return this.movements.size>0}resolveAnimationName(e,t){var o;const s=e.group.getObjectByName("characterBody"),i=(o=s==null?void 0:s.userData)==null?void 0:o.animationMapping;if(i){const n=i[t];if(n&&e.animations.has(n))return n;if(n&&e.animations.has(n.toLowerCase()))return n.toLowerCase()}switch(t){case"idle":return Q.IDLE;case"walk":return Q.WALK;case"working":return Q.JUMP;default:return Q.IDLE}}playAnimationForState(e,t,s){const i=this.resolveAnimationName(e,t);this.playAnimation(e,i,s)}startMovement(e,t,s){const i=t.group.position.clone(),o=new T(s.x,s.y,s.z),r=i.distanceTo(o)/Ws*1e3;this.movements.delete(e),this.movements.set(e,{agentId:e,startPos:i,endPos:o,startTime:performance.now(),duration:Math.max(r,200)});const l=this.resolveAnimationName(t,"walk");this.playAnimation(t,l),this.faceDirection(t,i,o)}cancelMovement(e,t){this.movements.delete(e);const s=this.resolveAnimationName(t,"idle");this.playAnimation(t,s)}playAnimation(e,t,s){if(!e.mixer)return;const i=e.group.userData.agentId;let o=e.animations.get(t);if(o||(o=e.animations.get(t.toLowerCase())),!o){console.warn(`[MovementAnimator] Animation not found: ${t}, available:`,Array.from(e.animations.keys()));const d=this.jumpingAgents.get(i);if(this.jumpingAgents.delete(i),d!==void 0){const h=e.group.getObjectByName("characterBody");h&&(h.position.y=d)}e.currentAction&&(e.currentAction.fadeOut(.2),e.currentAction=null);return}console.log(`[MovementAnimator] Playing: ${t}`);const{loop:n=!0,fadeTime:r=.2,timeScale:l=1}=s??{},c=e.mixer.clipAction(o);if(c.setLoop(n?ls:cs,1/0),c.clampWhenFinished=!n,c.timeScale=l,e.currentAction&&e.currentAction!==c?(e.currentAction.fadeOut(r),c.reset().fadeIn(r).play()):c.reset().play(),e.currentAction=c,this.animatingAgents.add(i),t===Q.JUMP&&n){if(!this.jumpingAgents.has(i)){const d=e.group.getObjectByName("characterBody"),h=(d==null?void 0:d.position.y)??0;this.jumpingAgents.set(i,h)}}else{const d=this.jumpingAgents.get(i);if(this.jumpingAgents.delete(i),d!==void 0){const h=e.group.getObjectByName("characterBody");h&&(h.position.y=d)}}}stopAnimation(e){this.animatingAgents.delete(e),this.jumpingAgents.delete(e)}faceDirection(e,t,s){const i=new T().subVectors(s,t).normalize();if(i.x!==0||i.z!==0){const o=e.group.getObjectByName("characterBody");if(o){const n=Math.atan2(i.x,i.z);o.rotation.y=n}}}update(e,t){var o;const s=performance.now(),i=[];this.jumpTime+=t;for(const n of this.animatingAgents){const r=e.get(n);(o=r==null?void 0:r.mixer)==null||o.update(t)}for(const[n,r]of this.jumpingAgents){const l=e.get(n);if(!l)continue;const c=l.group.getObjectByName("characterBody");if(c){const d=Math.abs(Math.sin(this.jumpTime*xt.speed*Math.PI*2))*xt.height;c.position.y=r+d}}for(const[n,r]of this.movements){const l=e.get(n);if(!l){i.push(n);continue}const c=s-r.startTime;let d=Math.min(c/r.duration,1);d=this.easeOutCubic(d),l.group.position.lerpVectors(r.startPos,r.endPos,d),this.smoothRotateToDirection(l,r.startPos,r.endPos,t),d>=1&&(i.push(n),l.group.position.copy(r.endPos))}for(const n of i)this.movements.delete(n);return i}smoothRotateToDirection(e,t,s,i){const o=new T().subVectors(s,t).normalize();if(o.x===0&&o.z===0)return;const n=e.group.getObjectByName("characterBody");if(!n)return;const r=Math.atan2(o.x,o.z),l=n.rotation.y,c=r-l,d=Math.atan2(Math.sin(c),Math.cos(c)),h=10;n.rotation.y+=d*Math.min(1,h*i)}easeOutCubic(e){return 1-Math.pow(1-e,3)}get activeCount(){return this.movements.size}clear(){this.movements.clear(),this.jumpingAgents.clear(),this.animatingAgents.clear(),this.jumpTime=0}}function Ve(){if(typeof window>"u")return{isMobile:!1,isConstrained:!1,maxPixelRatio:2,antialias:!0,enableShadows:!0,maxFps:0,indicatorUpdateInterval:100,notificationBadgeUpdateInterval:0,maxStatusSpriteDistance:28,maxNameSpriteDistance:22,maxBadgeDistance:18,maxBuildingLabelDistance:32,overlayEffectDistance:24,reduceTransientEffects:!1};const a=navigator,e=a.userAgent||"",t=window.matchMedia("(max-width: 768px)").matches,s=a.maxTouchPoints>0,i=/Android|iPhone|iPad|iPod|Mobile/i.test(e),o=t||s&&i,n=(a.deviceMemory??1/0)<=4,r=(a.hardwareConcurrency??1/0)<=6,l=o||n||r,c=!n&&(a.hardwareConcurrency??1/0)>=8;return l?{isMobile:o,isConstrained:!0,maxPixelRatio:c?1.75:1.5,antialias:c,enableShadows:!o,maxFps:30,indicatorUpdateInterval:250,notificationBadgeUpdateInterval:400,maxStatusSpriteDistance:20,maxNameSpriteDistance:14,maxBadgeDistance:11,maxBuildingLabelDistance:18,overlayEffectDistance:18,reduceTransientEffects:!0}:{isMobile:o,isConstrained:!1,maxPixelRatio:2,antialias:!0,enableShadows:!0,maxFps:0,indicatorUpdateInterval:100,notificationBadgeUpdateInterval:0,maxStatusSpriteDistance:28,maxNameSpriteDistance:22,maxBadgeDistance:18,maxBuildingLabelDistance:32,overlayEffectDistance:24,reduceTransientEffects:!1}}const De=class De{constructor(e){u(this,"scene");u(this,"moveOrderEffects",[]);u(this,"speechBubbles",[]);u(this,"sleepingEffects",[]);u(this,"waitingPermissionEffects",[]);u(this,"delegationEffects",[]);u(this,"subagentEffects",[]);u(this,"agentMeshes",new Map);u(this,"ringGeometry",null);u(this,"pulseGeometry",null);u(this,"chevronGeometry",null);u(this,"delegationPaperTexture",null);u(this,"sleepingBubbleTexture",null);u(this,"waitingPermissionTexture",null);u(this,"delegationSpritePool",[]);u(this,"moveOrderGroupPool",[]);u(this,"_needsUpdate",!1);u(this,"performanceProfile",Ve());u(this,"tempProjectedPosition",new T);u(this,"camera",null);u(this,"scale3d",1);this.scene=e,this.initializeCachedResources()}get needsUpdate(){return this._needsUpdate||this.moveOrderEffects.length>0||this.speechBubbles.length>0||this.sleepingEffects.length>0||this.waitingPermissionEffects.length>0||this.delegationEffects.length>0||this.subagentEffects.length>0}markDirty(){this._needsUpdate=!0}clearDirty(){this._needsUpdate=!1}initializeCachedResources(){this.ringGeometry=new ke(.3,.4,32),this.pulseGeometry=new ke(.1,.2,32);const e=new hs;e.moveTo(0,.15),e.lineTo(.12,.35),e.lineTo(.08,.35),e.lineTo(0,.2),e.lineTo(-.08,.35),e.lineTo(-.12,.35),e.closePath(),this.chevronGeometry=new ds(e),this.createDelegationPaperTexture(),this.createSleepingBubbleTexture(),this.createWaitingPermissionTexture(),this.initializePools()}initializePools(){for(let e=0;e<De.POOL_SIZE;e++)if(this.delegationPaperTexture){const t=new J({map:this.delegationPaperTexture,transparent:!0,opacity:0,depthTest:!1}),s=new K(t);s.scale.set(.3,.3,1),s.visible=!1,this.delegationSpritePool.push({sprite:s,inUse:!1})}for(let e=0;e<De.POOL_SIZE;e++){const t=this.createMoveOrderGroup();t.visible=!1,this.moveOrderGroupPool.push(t)}}createMoveOrderGroup(){const e=new Y,t=new v({color:4915102,side:oe,transparent:!0,opacity:.8}),s=new y(this.ringGeometry,t);s.rotation.x=-Math.PI/2,s.name="ring",e.add(s);const i=new v({color:4915102,side:oe,transparent:!0,opacity:.6}),o=new y(this.pulseGeometry,i);o.rotation.x=-Math.PI/2,o.name="pulse",e.add(o);for(let n=0;n<3;n++){const r=new v({color:4915102,side:oe,transparent:!0,opacity:.9}),l=new y(this.chevronGeometry,r);l.rotation.x=-Math.PI/2,l.position.y=.5+n*.25,l.name=`chevron${n}`,e.add(l)}return e}getDelegationSprite(){for(const s of this.delegationSpritePool)if(!s.inUse)return s.inUse=!0,s.sprite.visible=!0,s.sprite.material.opacity=1,s.sprite;const e=new J({map:this.delegationPaperTexture,transparent:!0,opacity:1,depthTest:!1}),t=new K(e);return t.scale.set(.3,.3,1),t}returnDelegationSprite(e){for(const t of this.delegationSpritePool)if(t.sprite===e){t.inUse=!1,t.sprite.visible=!1,this.scene.remove(e);return}this.scene.remove(e),e.material.dispose()}getMoveOrderGroup(){for(const e of this.moveOrderGroupPool)if(!e.visible)return e.visible=!0,e.traverse(t=>{if(t instanceof y){const s=t.material;s.opacity=t.name==="ring"?.8:t.name==="pulse"?.6:.9}}),e;return this.createMoveOrderGroup()}returnMoveOrderGroup(e){this.moveOrderGroupPool.includes(e)?(e.visible=!1,this.scene.remove(e)):(this.scene.remove(e),e.traverse(s=>{s instanceof y&&s.material.dispose()}))}createDelegationPaperTexture(){const e=document.createElement("canvas"),t=e.getContext("2d");e.width=64,e.height=64,t.fillStyle="#ffffff",t.strokeStyle="#ffd700",t.lineWidth=2,t.save(),t.translate(32,32),t.rotate(-.2),t.beginPath(),t.moveTo(-12,-18),t.lineTo(8,-18),t.lineTo(12,-14),t.lineTo(12,18),t.lineTo(-12,18),t.closePath(),t.fill(),t.stroke(),t.beginPath(),t.moveTo(8,-18),t.lineTo(8,-14),t.lineTo(12,-14),t.strokeStyle="#cccccc",t.stroke(),t.fillStyle="#f0f0f0",t.fill(),t.strokeStyle="#888888",t.lineWidth=1;for(let s=0;s<4;s++){const i=-8+s*6,o=s===3?10:16;t.beginPath(),t.moveTo(-8,i),t.lineTo(-8+o,i),t.stroke()}t.restore(),this.delegationPaperTexture=new se(e),this.delegationPaperTexture.minFilter=te,this.delegationPaperTexture.magFilter=te}createSleepingBubbleTexture(){const e=document.createElement("canvas"),t=e.getContext("2d");e.width=128,e.height=128,t.fillStyle="rgba(40, 42, 54, 0.95)",t.strokeStyle="#bd93f9",t.lineWidth=2;const s=64,i=50,o=40;t.beginPath(),t.arc(s,i,o,0,Math.PI*2),t.fill(),t.stroke(),t.beginPath(),t.arc(30,95,10,0,Math.PI*2),t.fill(),t.stroke(),t.beginPath(),t.arc(18,115,6,0,Math.PI*2),t.fill(),t.stroke(),t.fillStyle="#8be9fd",t.font="bold 28px Arial",t.textAlign="center",t.textBaseline="middle",t.shadowColor="#8be9fd",t.shadowBlur=4,t.fillText("ZZZ",s,i),this.sleepingBubbleTexture=new se(e),this.sleepingBubbleTexture.minFilter=te,this.sleepingBubbleTexture.magFilter=te}createWaitingPermissionTexture(){const e=document.createElement("canvas"),t=e.getContext("2d");e.width=128,e.height=128,t.fillStyle="rgba(40, 42, 54, 0.95)",t.strokeStyle="#ffcc00",t.lineWidth=2;const s=64,i=50,o=40;t.beginPath(),t.arc(s,i,o,0,Math.PI*2),t.fill(),t.stroke(),t.beginPath(),t.arc(30,95,10,0,Math.PI*2),t.fill(),t.stroke(),t.beginPath(),t.arc(18,115,6,0,Math.PI*2),t.fill(),t.stroke(),t.fillStyle="#ffcc00",t.font="bold 32px Arial",t.textAlign="center",t.textBaseline="middle",t.shadowColor="#ffcc00",t.shadowBlur=6,t.fillText("🔒",s,i),this.waitingPermissionTexture=new se(e),this.waitingPermissionTexture.minFilter=te,this.waitingPermissionTexture.magFilter=te}setAgentMeshes(e){this.agentMeshes.clear();for(const[t,s]of e)this.agentMeshes.set(t,s.group)}updateSleepingEffect(e,t){const s=this.sleepingEffects.find(i=>i.agentId===e);t&&!s?this.createSleepingEffect(e):!t&&s&&this.removeSleepingEffect(e)}updateWaitingPermissionEffect(e,t){const s=this.waitingPermissionEffects.find(i=>i.agentId===e);t&&!s?this.createWaitingPermissionEffect(e):!t&&s&&this.removeWaitingPermissionEffect(e)}createSleepingEffect(e){const t=this.agentMeshes.get(e);if(!t||!this.sleepingBubbleTexture)return;const s=[],i=new J({map:this.sleepingBubbleTexture,transparent:!0,opacity:.95,depthTest:!1}),o=new K(i);o.scale.set(.12,.12,1),o.userData.isBubble=!0,o.position.copy(t.position),o.position.y=2,o.position.x+=.15,this.scene.add(o),s.push(o),this.sleepingEffects.push({sprites:s,agentId:e,startTime:performance.now()}),this.markDirty()}removeSleepingEffect(e){const t=this.sleepingEffects.findIndex(s=>s.agentId===e);if(t!==-1){const s=this.sleepingEffects[t];for(const i of s.sprites)this.scene.remove(i),i.material.dispose();this.sleepingEffects.splice(t,1),this.markDirty()}}createWaitingPermissionEffect(e){const t=this.agentMeshes.get(e);if(!t||!this.waitingPermissionTexture)return;const s=[],i=new J({map:this.waitingPermissionTexture,transparent:!0,opacity:.95,depthTest:!1}),o=new K(i);o.scale.set(.12,.12,1),o.userData.isBubble=!0,o.position.copy(t.position),o.position.y=2,o.position.x+=.15,this.scene.add(o),s.push(o),this.waitingPermissionEffects.push({sprites:s,agentId:e,startTime:performance.now()}),this.markDirty()}removeWaitingPermissionEffect(e){const t=this.waitingPermissionEffects.findIndex(s=>s.agentId===e);if(t!==-1){const s=this.waitingPermissionEffects[t];for(const i of s.sprites)this.scene.remove(i),i.material.dispose();this.waitingPermissionEffects.splice(t,1),this.markDirty()}}createDelegationEffect(e,t){if(this.performanceProfile.reduceTransientEffects)return;const s=this.agentMeshes.get(e),i=this.agentMeshes.get(t);if(!s||!i||!this.delegationPaperTexture){console.log("[EffectsManager] Cannot create delegation effect - missing agent meshes or texture");return}const o=this.getDelegationSprite(),n=new T(s.position.x,s.position.y+1.5,s.position.z),r=new T(i.position.x,i.position.y+1.2,i.position.z);o.position.copy(n),this.scene.add(o),this.delegationEffects.push({sprite:o,startPosition:n.clone(),endPosition:r.clone(),startTime:performance.now(),duration:800}),this.markDirty()}createSpeechBubble(e,t,s){if(this.performanceProfile.reduceTransientEffects)return;const i=this.agentMeshes.get(e);if(!i)return;this.removeSpeechBubble(e);const o=Fs[t]||"🔧",n=this.formatToolParams(t,s),r=document.createElement("canvas"),l=r.getContext("2d");r.width=400,r.height=100;const c=n?`${o} ${t}: ${n}`:`${o} ${t}`;l.font="bold 32px Arial";const g=Math.min(l.measureText(c).width,r.width-40)+16*2,f=48,p=(r.width-g)/2,m=(r.height-f)/2,b=f/2;l.fillStyle="rgba(15, 15, 25, 0.85)",l.strokeStyle="#4a9eff",l.lineWidth=2,l.beginPath(),l.moveTo(p+b,m),l.lineTo(p+g-b,m),l.arc(p+g-b,m+b,b,-Math.PI/2,Math.PI/2),l.lineTo(p+b,m+f),l.arc(p+b,m+b,b,Math.PI/2,-Math.PI/2),l.closePath(),l.fill(),l.stroke(),l.fillStyle="#ffffff",l.font="bold 30px Arial",l.textAlign="center",l.textBaseline="middle";let w=c;const M=r.width-40;for(;l.measureText(w).width>M&&w.length>3;)w=w.slice(0,-4)+"...";l.fillText(w,r.width/2,r.height/2);const S=new se(r);S.minFilter=te,S.magFilter=te,S.needsUpdate=!0;const P=new J({map:S,transparent:!0,opacity:0,depthTest:!1}),C=new K(P);C.scale.set(2.4,.6,1),C.renderOrder=1e3;const x=!!i.userData._cachedTaskLabel,B=i.position.y-(x?2:1.3);C.position.copy(i.position),C.position.y=B,this.scene.add(C),this.speechBubbles.push({sprite:C,agentId:e,startTime:performance.now(),duration:4e3,baseY:B})}formatToolParams(e,t){if(!t)return"";switch(e){case"WebSearch":return t.query||"";case"WebFetch":return t.url||"";case"Read":case"Write":case"Edit":const s=t.file_path||t.path||"";return s.length>40?".../"+s.split("/").slice(-2).join("/"):s;case"Bash":const i=(t.command||"").slice(0,60);return i+(i.length>=60?"...":"");case"Grep":return`"${t.pattern||""}"`;case"Glob":return t.pattern||"";case"Task":return(t.description||"").slice(0,50);default:for(const[o,n]of Object.entries(t))if(typeof n=="string"&&n.length>0&&n.length<100)return n.slice(0,50);return""}}removeSpeechBubble(e){var s;const t=this.speechBubbles.findIndex(i=>i.agentId===e);if(t!==-1){const i=this.speechBubbles[t];this.scene.remove(i.sprite),(s=i.sprite.material.map)==null||s.dispose(),i.sprite.material.dispose(),this.speechBubbles.splice(t,1)}}createMoveOrderEffect(e){const t=this.getMoveOrderGroup();t.position.copy(e),t.position.y=.05;for(let o=0;o<3;o++){const n=t.getObjectByName(`chevron${o}`);n&&(n.position.y=.5+o*.25)}const s=t.getObjectByName("ring");s&&s.scale.setScalar(1);const i=t.getObjectByName("pulse");i&&i.scale.setScalar(1),this.scene.add(t),this.moveOrderEffects.push({group:t,startTime:performance.now(),duration:800}),this.markDirty()}setScale3D(e){this.scale3d=e}update(){const e=performance.now();this.updateMoveOrderEffects(e),this.updateSpeechBubbles(e),this.updateSleepingEffects(),this.updateWaitingPermissionEffects(),this.updateDelegationEffects(e),this.updateSubagentEffects(e)}updateWithCamera(e){this.camera=e}calculateZoomScale(e){if(!this.camera)return this.scale3d;const t=this.camera.position.distanceTo(e);return Math.max(.5,Math.min(2.5,t/15))*this.scale3d}shouldRenderOverlay(e,t=this.performanceProfile.overlayEffectDistance){return this.camera?this.camera.position.distanceTo(e)>t?!1:(this.tempProjectedPosition.copy(e).project(this.camera),this.tempProjectedPosition.z>=-1&&this.tempProjectedPosition.z<=1&&this.tempProjectedPosition.x>=-1.2&&this.tempProjectedPosition.x<=1.2&&this.tempProjectedPosition.y>=-1.2&&this.tempProjectedPosition.y<=1.2):!0}updateSleepingEffects(){const e=performance.now();for(const t of this.sleepingEffects){const s=this.agentMeshes.get(t.agentId);if(!s)continue;const i=e-t.startTime,o=this.calculateZoomScale(s.position),n=this.shouldRenderOverlay(s.position);for(const r of t.sprites){if(r.visible=n,!n)continue;r.position.x=s.position.x+.25*o,r.position.z=s.position.z;const l=.002,c=.04*o;r.position.y=2+Math.sin(i*l)*c;const d=.35*o,h=Math.sin(i*.003)*.015*o;r.scale.set(d+h,d+h,1);const g=Math.min(i/500,1);r.material.opacity=.95*g}}}updateWaitingPermissionEffects(){const e=performance.now();for(const t of this.waitingPermissionEffects){const s=this.agentMeshes.get(t.agentId);if(!s)continue;const i=e-t.startTime,o=this.calculateZoomScale(s.position),n=this.shouldRenderOverlay(s.position);for(const r of t.sprites){if(r.visible=n,!n)continue;r.position.x=s.position.x+.25*o,r.position.z=s.position.z;const l=.004,c=.06*o;r.position.y=2+Math.sin(i*l)*c;const d=.38*o,h=Math.sin(i*.006)*.03*o;r.scale.set(d+h,d+h,1);const g=Math.min(i/300,1),f=.85+Math.sin(i*.005)*.1;r.material.opacity=f*g}}}updateDelegationEffects(e){const t=[];for(let s=0;s<this.delegationEffects.length;s++){const i=this.delegationEffects[s],o=Math.min((e-i.startTime)/i.duration,1),n=1-(1-o)*(1-o),r=i.endPosition.x-i.startPosition.x,l=i.endPosition.y-i.startPosition.y,c=i.endPosition.z-i.startPosition.z,d=4*o*(1-o)*.8;i.sprite.position.x=i.startPosition.x+r*n,i.sprite.position.y=i.startPosition.y+l*n+d,i.sprite.position.z=i.startPosition.z+c*n,i.sprite.material.rotation=o*Math.PI*1.5,i.sprite.material.opacity=o>.8?(1-o)*5:1,o>=1&&t.push(s)}for(let s=t.length-1;s>=0;s--){const i=t[s],o=this.delegationEffects[i];this.returnDelegationSprite(o.sprite),this.delegationEffects.splice(i,1)}}updateMoveOrderEffects(e){const t=[];for(let s=0;s<this.moveOrderEffects.length;s++){const i=this.moveOrderEffects[s],o=e-i.startTime,n=Math.min(o/i.duration,1),r=1-n,l=i.group.getObjectByName("ring");l&&(l.scale.setScalar(1+n*1.5),l.material.opacity=r*.8);const c=i.group.getObjectByName("pulse");if(c){const d=(Math.sin(n*Math.PI*4)+1)/2;c.scale.setScalar(.8+d*.4),c.material.opacity=r*.6}for(let d=0;d<3;d++){const h=i.group.getObjectByName(`chevron${d}`);if(h){const g=d*.15,f=Math.max(0,Math.min((n-g)/(1-g),1));h.position.y=.5+d*.25-f*(.4+d*.15),h.material.opacity=(1-f)*.9}}n>=1&&t.push(s)}for(let s=t.length-1;s>=0;s--){const i=t[s];this.returnMoveOrderGroup(this.moveOrderEffects[i].group),this.moveOrderEffects.splice(i,1)}}updateSpeechBubbles(e){var s;const t=[];for(let i=0;i<this.speechBubbles.length;i++){const o=this.speechBubbles[i],n=e-o.startTime,r=Math.min(n/o.duration,1),l=this.agentMeshes.get(o.agentId);if(l){o.sprite.position.x=l.position.x,o.sprite.position.z=l.position.z;const f=this.calculateZoomScale(l.position);o.sprite.scale.set(2.4*f,.6*f,1)}const c=Math.min(n/200,1),d=r>.7?1-(r-.7)/.3:1;o.sprite.material.opacity=c*d;const h=l?l.position.y:0,g=l?!!l.userData._cachedTaskLabel:!1;o.sprite.position.y=h-(g?2:1.3),r>=1&&t.push(i)}for(let i=t.length-1;i>=0;i--){const o=t[i],n=this.speechBubbles[o];this.scene.remove(n.sprite),(s=n.sprite.material.map)==null||s.dispose(),n.sprite.material.dispose(),this.speechBubbles.splice(o,1)}}disposeEffect(e){this.scene.remove(e.group),e.group.traverse(t=>{t instanceof y&&t.material.dispose()})}addSubagentEffect(e,t,s,i){if(this.performanceProfile.reduceTransientEffects)return;const o=this.agentMeshes.get(t);if(!o){console.warn(`[EffectsManager] Cannot add subagent effect: parent agent ${t} not found`);return}if(this.subagentEffects.find(w=>w.subagentId===e))return;const n=document.createElement("canvas");n.width=256,n.height=64;const r=n.getContext("2d");r.fillStyle="rgba(30, 30, 60, 0.85)";const l=12;r.beginPath(),r.moveTo(l,0),r.lineTo(n.width-l,0),r.quadraticCurveTo(n.width,0,n.width,l),r.lineTo(n.width,n.height-l),r.quadraticCurveTo(n.width,n.height,n.width-l,n.height),r.lineTo(l,n.height),r.quadraticCurveTo(0,n.height,0,n.height-l),r.lineTo(0,l),r.quadraticCurveTo(0,0,l,0),r.closePath(),r.fill(),r.strokeStyle="rgba(100, 180, 255, 0.8)",r.lineWidth=2,r.stroke(),r.fillStyle="#64b4ff",r.font="bold 28px monospace",r.fillText("⑂",8,40),r.fillStyle="#ffffff",r.font="22px sans-serif";const c=s.length>14?s.slice(0,12)+"..":s;r.fillText(c,40,38);const d=new se(n);d.needsUpdate=!0;const h=new J({map:d,transparent:!0,opacity:.85,depthTest:!1}),g=new K(h);g.scale.set(1.5,.4,1);const f=this.subagentEffects.filter(w=>w.parentAgentId===t&&!w.completed).length,p=f*Math.PI/4-Math.PI/4,m=1.5,b=o.position;g.position.set(b.x+Math.sin(p)*m,b.y+2.5+f*.5,b.z+Math.cos(p)*m),this.scene.add(g),this.subagentEffects.push({sprite:g,subagentId:e,parentAgentId:t,name:s,subagentType:i,startTime:performance.now(),completed:!1,completedAt:0}),this.markDirty(),console.log(`[EffectsManager] Added subagent effect: ${s} (${e}) near ${t}`)}completeSubagentEffect(e){const t=this.subagentEffects.find(s=>s.subagentId===e);t?(t.completed=!0,t.completedAt=performance.now(),this.markDirty(),console.log(`[EffectsManager] Marked subagent effect completed: ${t.name} (${e})`)):console.warn(`[EffectsManager] completeSubagentEffect: no effect found for subagentId=${e}`)}removeSubagentEffect(e){var s;const t=this.subagentEffects.findIndex(i=>i.subagentId===e);if(t!==-1){const i=this.subagentEffects[t];this.scene.remove(i.sprite),(s=i.sprite.material.map)==null||s.dispose(),i.sprite.material.dispose(),this.subagentEffects.splice(t,1),this.markDirty()}}updateSubagentEffects(e){var s;const t=[];for(let i=0;i<this.subagentEffects.length;i++){const o=this.subagentEffects[i],n=this.agentMeshes.get(o.parentAgentId);if(!n){t.push(i);continue}const r=this.subagentEffects.slice(0,i).filter(g=>g.parentAgentId===o.parentAgentId&&!g.completed).length,l=r*Math.PI/4-Math.PI/4,c=1.5,d=n.position;o.sprite.position.set(d.x+Math.sin(l)*c,d.y+2.5+r*.5,d.z+Math.cos(l)*c);const h=(e-o.startTime)/1e3;if(o.sprite.position.y+=Math.sin(h*1.5)*.05,o.completed&&o.completedAt>0){const g=(e-o.completedAt)/1e3;if(g>2){const f=Math.max(0,.85-(g-2)*.3);o.sprite.material.opacity=f,f<=0&&t.push(i)}}o.completed||(o.sprite.material.opacity=.75+Math.sin(h*2)*.1)}for(let i=t.length-1;i>=0;i--){const o=t[i],n=this.subagentEffects[o];this.scene.remove(n.sprite),(s=n.sprite.material.map)==null||s.dispose(),n.sprite.material.dispose(),this.subagentEffects.splice(o,1)}}removeAgentEffects(e){this.removeSleepingEffect(e),this.removeWaitingPermissionEffect(e),this.removeSpeechBubble(e);const t=this.subagentEffects.filter(s=>s.parentAgentId===e).map(s=>s.subagentId);for(const s of t)this.removeSubagentEffect(s);this.agentMeshes.delete(e)}clear(){var e,t;for(const s of this.moveOrderEffects)this.returnMoveOrderGroup(s.group);this.moveOrderEffects=[];for(const s of this.sleepingEffects)for(const i of s.sprites)this.scene.remove(i),i.material.dispose();this.sleepingEffects=[];for(const s of this.waitingPermissionEffects)for(const i of s.sprites)this.scene.remove(i),i.material.dispose();this.waitingPermissionEffects=[];for(const s of this.delegationEffects)this.returnDelegationSprite(s.sprite);this.delegationEffects=[];for(const s of this.speechBubbles)this.scene.remove(s.sprite),(e=s.sprite.material.map)==null||e.dispose(),s.sprite.material.dispose();this.speechBubbles=[];for(const s of this.subagentEffects)this.scene.remove(s.sprite),(t=s.sprite.material.map)==null||t.dispose(),s.sprite.material.dispose();this.subagentEffects=[]}dispose(){var e,t,s,i,o,n;this.clear(),(e=this.ringGeometry)==null||e.dispose(),(t=this.pulseGeometry)==null||t.dispose(),(s=this.chevronGeometry)==null||s.dispose(),this.ringGeometry=null,this.pulseGeometry=null,this.chevronGeometry=null,(i=this.delegationPaperTexture)==null||i.dispose(),(o=this.sleepingBubbleTexture)==null||o.dispose(),(n=this.waitingPermissionTexture)==null||n.dispose(),this.delegationPaperTexture=null,this.sleepingBubbleTexture=null,this.waitingPermissionTexture=null;for(const r of this.delegationSpritePool)r.sprite.material.dispose();this.delegationSpritePool=[];for(const r of this.moveOrderGroupPool)r.traverse(l=>{l instanceof y&&l.material.dispose()});this.moveOrderGroupPool=[],this.agentMeshes.clear()}};u(De,"POOL_SIZE",10);let ct=De;class oi{constructor(){u(this,"animations",new Map)}register(e,t,s="idle"){this.animations.set(e,{state:s,time:Math.random()*Math.PI*2,basePosition:t.position.clone(),baseRotation:t.rotation.clone(),baseScale:t.scale.clone()})}unregister(e){this.animations.delete(e)}has(e){return this.animations.has(e)}setState(e,t){const s=this.animations.get(e);s&&s.state!==t&&(s.state=t,s.time=0)}updateBasePosition(e,t){const s=this.animations.get(e);s&&s.basePosition.copy(t)}update(e,t){for(const[s,i]of this.animations){const o=t.get(s);if(o)switch(i.time+=e,i.state){case"idle":this.applyIdleAnimation(o,i);break;case"working":this.applyWorkingAnimation(o,i);break;case"waiting":this.applyWaitingAnimation(o,i);break;case"error":this.applyErrorAnimation(o,i);break;case"static":this.resetToBase(o,i);break}}}applyIdleAnimation(e,t){const s=t.time,n=Math.sin(s*1.5)*.02,c=Math.sin(s*.8)*.01;e.position.set(t.basePosition.x+c,t.basePosition.y+n,t.basePosition.z)}applyWorkingAnimation(e,t){const s=t.time,n=Math.abs(Math.sin(s*6))*.25,r=.15,l=3,c=Math.sin(s*l)*r,g=Math.sin(s*3)*.22,p=Math.sin(s*l*.7)*.1,w=Math.sin(s*4)*.12;e.position.set(t.basePosition.x+c,t.basePosition.y+n,t.basePosition.z+p),e.rotation.set(t.baseRotation.x+g,t.baseRotation.y+w,t.baseRotation.z)}applyWaitingAnimation(e,t){const s=t.time,i=.02,o=1.2,n=Math.sin(s*o)*i,l=Math.sin(s*o)*.03,h=Math.sin(s*2)*.01;e.position.set(t.basePosition.x+n,t.basePosition.y+h,t.basePosition.z),e.rotation.set(t.baseRotation.x,t.baseRotation.y,t.baseRotation.z+l)}applyErrorAnimation(e,t){const s=t.time,i=.015,o=15,n=Math.sin(s*o)*i,r=Math.cos(s*o*1.3)*i*.5;e.position.set(t.basePosition.x+n,t.basePosition.y,t.basePosition.z+r)}resetToBase(e,t){e.position.copy(t.basePosition),e.rotation.copy(t.baseRotation),e.scale.copy(t.baseScale)}clear(){this.animations.clear()}}function Bt(a){const e=document.createElement("canvas"),t=e.getContext("2d"),s=a==="pokemon-stadium"?1024:512;switch(e.width=s,e.height=s,a){case"galactic":ai(t,e.width,e.height);break;case"metal":ri(t,e.width,e.height);break;case"hex":li(t,e.width,e.height);break;case"circuit":ci(t,e.width,e.height);break;case"pokemon-stadium":hi(t,e.width,e.height);break;default:ni(t,e.width,e.height)}return new se(e)}function ni(a,e,t){a.fillStyle="#4a4a4a",a.fillRect(0,0,e,t);for(let s=0;s<5e3;s++){const i=Math.random()*e,o=Math.random()*t,n=60+Math.random()*40;a.fillStyle=`rgba(${n}, ${n}, ${n}, 0.3)`,a.fillRect(i,o,2,2)}a.strokeStyle="rgba(30, 30, 30, 0.4)",a.lineWidth=1;for(let s=0;s<8;s++){a.beginPath();let i=Math.random()*e,o=Math.random()*t;a.moveTo(i,o);for(let n=0;n<5;n++)i+=(Math.random()-.5)*100,o+=(Math.random()-.5)*100,a.lineTo(i,o);a.stroke()}}function ai(a,e,t){const s=a.createRadialGradient(e/2,t/2,0,e/2,t/2,e/1.5);s.addColorStop(0,"#1a0a30"),s.addColorStop(.5,"#0d0520"),s.addColorStop(1,"#050210"),a.fillStyle=s,a.fillRect(0,0,e,t);for(let i=0;i<3;i++){const o=Math.random()*e,n=Math.random()*t,r=100+Math.random()*150,l=["#ff00ff","#00ffff","#ff6600","#6600ff","#00ff66"],c=l[Math.floor(Math.random()*l.length)],d=a.createRadialGradient(o,n,0,o,n,r);d.addColorStop(0,c.replace("ff","66")+"40"),d.addColorStop(.5,c+"20"),d.addColorStop(1,"transparent"),a.fillStyle=d,a.fillRect(0,0,e,t)}for(let i=0;i<300;i++){const o=Math.random()*e,n=Math.random()*t,r=Math.random()*2,l=150+Math.random()*105;if(Math.random()>.8){const c=a.createRadialGradient(o,n,0,o,n,r*4);c.addColorStop(0,`rgba(${l}, ${l}, 255, 0.8)`),c.addColorStop(1,"transparent"),a.fillStyle=c,a.fillRect(o-r*4,n-r*4,r*8,r*8)}a.fillStyle=`rgba(${l}, ${l}, 255, 1)`,a.beginPath(),a.arc(o,n,r,0,Math.PI*2),a.fill()}a.strokeStyle="rgba(100, 50, 150, 0.15)",a.lineWidth=20,a.beginPath();for(let i=0;i<Math.PI*4;i+=.1){const o=20+i*30,n=e/2+Math.cos(i)*o,r=t/2+Math.sin(i)*o;i===0?a.moveTo(n,r):a.lineTo(n,r)}a.stroke()}function ri(a,e,t){a.fillStyle="#3a3a44",a.fillRect(0,0,e,t);for(let i=0;i<200;i++){const o=Math.random()*t,n=50+Math.random()*30;a.strokeStyle=`rgba(${n+20}, ${n+20}, ${n+30}, 0.3)`,a.lineWidth=1,a.beginPath(),a.moveTo(0,o),a.lineTo(e,o+(Math.random()-.5)*4),a.stroke()}a.strokeStyle="rgba(20, 20, 25, 0.8)",a.lineWidth=3;const s=e/4;for(let i=0;i<=e;i+=s)a.beginPath(),a.moveTo(i,0),a.lineTo(i,t),a.stroke();for(let i=0;i<=t;i+=s)a.beginPath(),a.moveTo(0,i),a.lineTo(e,i),a.stroke();a.fillStyle="#555566";for(let i=0;i<=e;i+=s)for(let o=0;o<=t;o+=s)a.beginPath(),a.arc(i,o,8,0,Math.PI*2),a.fill(),a.fillStyle="#666677",a.beginPath(),a.arc(i-2,o-2,4,0,Math.PI*2),a.fill(),a.fillStyle="#555566"}function li(a,e,t){a.fillStyle="#1a2530",a.fillRect(0,0,e,t);const s=30,i=s*Math.sqrt(3);for(let o=-1;o<t/i+1;o++)for(let n=-1;n<e/(s*1.5)+1;n++){const r=n*s*1.5,l=o*i+(n%2===0?0:i/2),c=30+Math.random()*20;a.fillStyle=`rgb(${c}, ${c+20}, ${c+40})`,a.beginPath();for(let d=0;d<6;d++){const h=Math.PI/3*d+Math.PI/6,g=r+Math.cos(h)*(s-2),f=l+Math.sin(h)*(s-2);d===0?a.moveTo(g,f):a.lineTo(g,f)}if(a.closePath(),a.fill(),a.strokeStyle="rgba(80, 150, 200, 0.5)",a.lineWidth=2,a.stroke(),Math.random()>.85){const d=a.createRadialGradient(r,l,0,r,l,s);d.addColorStop(0,"rgba(100, 200, 255, 0.3)"),d.addColorStop(1,"transparent"),a.fillStyle=d,a.fill()}}}function ci(a,e,t){a.fillStyle="#0a1a0f",a.fillRect(0,0,e,t),a.strokeStyle="#00ff66",a.lineWidth=2,a.shadowColor="#00ff66",a.shadowBlur=4;for(let s=20;s<t;s+=40){a.beginPath();let i=0;for(a.moveTo(i,s);i<e;){const o=20+Math.random()*60;if(i+=o,a.lineTo(i,s),Math.random()>.7&&i<e-40){const n=s+(Math.random()>.5?20:-20);a.lineTo(i,n),a.lineTo(i+20,n),i+=20}}a.stroke()}for(let s=20;s<e;s+=40)if(Math.random()>.5){a.beginPath(),a.moveTo(s,0);let i=0;for(;i<t;){const o=20+Math.random()*60;if(i+=o,a.lineTo(s,i),Math.random()>.7&&i<t-40){const n=s+(Math.random()>.5?20:-20);a.lineTo(n,i),a.lineTo(n,i+20),i+=20,a.lineTo(s,i)}}a.stroke()}a.shadowBlur=0,a.fillStyle="#111";for(let s=0;s<6;s++){const i=50+Math.random()*(e-100),o=50+Math.random()*(t-100),n=30+Math.random()*40,r=20+Math.random()*30;a.fillRect(i-n/2,o-r/2,n,r),a.fillStyle="#888";for(let l=0;l<n;l+=8)a.fillRect(i-n/2+l,o-r/2-4,4,4),a.fillRect(i-n/2+l,o+r/2,4,4);a.fillStyle="#111"}a.fillStyle="#997700";for(let s=0;s<50;s++){const i=Math.random()*e,o=Math.random()*t;a.beginPath(),a.arc(i,o,4,0,Math.PI*2),a.fill()}}function hi(a,e,t){const s=e/2,i=t/2;a.fillStyle="#2E4F2C",a.fillRect(0,0,e,t);for(let m=0;m<6e3;m++){const b=Math.random()*e,w=Math.random()*t,M=Math.random()>.5;a.fillStyle=M?"rgba(30, 50, 28, 0.3)":"rgba(55, 90, 52, 0.12)",a.fillRect(b,w,2,4)}const o=e*.05,n=30;a.strokeStyle="#ffffff",a.lineWidth=6,a.beginPath(),a.roundRect(o,o,e-o*2,t-o*2,n),a.stroke(),a.lineWidth=4,a.beginPath(),a.moveTo(o,i),a.lineTo(e-o,i),a.stroke();const r=Math.min(e,t)*.2;a.beginPath(),a.arc(s,i,r,0,Math.PI*2),a.stroke();const l=r*.6;a.fillStyle="#cc3333",a.beginPath(),a.arc(s,i,l,Math.PI,0),a.closePath(),a.fill(),a.fillStyle="#f0f0f0",a.beginPath(),a.arc(s,i,l,0,Math.PI),a.closePath(),a.fill(),a.fillStyle="#1a1a1a",a.fillRect(s-l,i-5,l*2,10),a.strokeStyle="#1a1a1a",a.lineWidth=4,a.beginPath(),a.arc(s,i,l,0,Math.PI*2),a.stroke();const c=l*.28;a.fillStyle="#f0f0f0",a.beginPath(),a.arc(s,i,c,0,Math.PI*2),a.fill(),a.strokeStyle="#1a1a1a",a.lineWidth=4,a.stroke(),a.fillStyle="#ffffff",a.beginPath(),a.arc(s,i,c*.5,0,Math.PI*2),a.fill();const d=e*.08,h=t*.05,g=r+t*.08;a.strokeStyle="#ffffff",a.lineWidth=3,a.strokeRect(s-d/2,i-g-h,d,h),a.strokeRect(s-d/2,i+g,d,h);const f=e*.05,p=o+15;a.lineWidth=3,a.beginPath(),a.moveTo(p,p+f),a.lineTo(p,p),a.lineTo(p+f,p),a.stroke(),a.beginPath(),a.moveTo(e-p-f,p),a.lineTo(e-p,p),a.lineTo(e-p,p+f),a.stroke(),a.beginPath(),a.moveTo(p,t-p-f),a.lineTo(p,t-p),a.lineTo(p+f,t-p),a.stroke(),a.beginPath(),a.moveTo(e-p-f,t-p),a.lineTo(e-p,t-p),a.lineTo(e-p,t-p-f),a.stroke()}function di(a){const e=new Y;e.name="galacticFloor";const t=[];ui(e);const s=gi(e);return pi(e,t),mi(e),fi(e),a.add(e),console.log("[Battlefield] Galactic group added to scene:",e),{group:e,stars:s,nebulas:t,time:0}}function ui(a){const e=document.createElement("canvas"),t=e.getContext("2d");e.width=2048,e.height=2048;const s=t.createRadialGradient(1024,1024,0,1024,1024,1024);s.addColorStop(0,"#2a1050"),s.addColorStop(.2,"#1a0a40"),s.addColorStop(.5,"#0d0525"),s.addColorStop(.8,"#060215"),s.addColorStop(1,"#020108"),t.fillStyle=s,t.fillRect(0,0,2048,2048),t.save(),t.translate(1024,1024);for(let d=0;d<3;d++){const h=d/3*Math.PI*2;t.save(),t.rotate(h);for(let g=0;g<1500;g++){const f=g/1500*800,p=f*.012,m=f*.15,b=Math.cos(p)*f+(Math.random()-.5)*m,w=Math.sin(p)*f+(Math.random()-.5)*m,M=1-f/800*.6,S=(1-f/800)*4+Math.random()*3,P=Math.floor(220*M+35),C=Math.floor(200*M+55),x=Math.floor(255);if(t.fillStyle=`rgba(${P}, ${C}, ${x}, ${M})`,t.beginPath(),t.arc(b,w,S,0,Math.PI*2),t.fill(),M>.7&&Math.random()>.5){const B=t.createRadialGradient(b,w,0,b,w,S*3);B.addColorStop(0,`rgba(${P}, ${C}, ${x}, 0.6)`),B.addColorStop(1,"transparent"),t.fillStyle=B,t.beginPath(),t.arc(b,w,S*3,0,Math.PI*2),t.fill()}}t.restore()}const i=t.createRadialGradient(0,0,0,0,0,200);i.addColorStop(0,"rgba(255, 255, 255, 1)"),i.addColorStop(.1,"rgba(255, 240, 220, 0.95)"),i.addColorStop(.3,"rgba(255, 200, 150, 0.7)"),i.addColorStop(.6,"rgba(200, 150, 255, 0.4)"),i.addColorStop(1,"transparent"),t.fillStyle=i,t.beginPath(),t.arc(0,0,200,0,Math.PI*2),t.fill(),t.restore();for(let d=0;d<1e3;d++){const h=Math.random()*2048,g=Math.random()*2048,f=.5+Math.random()*2.5,p=150+Math.random()*105,m=Math.random();let b,w,M;if(m<.6?(b=p,w=p,M=255):m<.8?(b=255,w=p,M=p*.7):(b=255,w=p*.6,M=p),t.fillStyle=`rgba(${b}, ${w}, ${M}, 1)`,t.beginPath(),t.arc(h,g,f,0,Math.PI*2),t.fill(),Math.random()>.85){const S=t.createRadialGradient(h,g,0,h,g,f*6);S.addColorStop(0,`rgba(${b}, ${w}, ${M}, 0.7)`),S.addColorStop(.5,`rgba(${b}, ${w}, ${M}, 0.2)`),S.addColorStop(1,"transparent"),t.fillStyle=S,t.beginPath(),t.arc(h,g,f*6,0,Math.PI*2),t.fill()}}const o=["#ff00ff","#00ffff","#ff6600","#6600ff"];for(let d=0;d<8;d++){const h=300+Math.random()*1448,g=300+Math.random()*1448,f=100+Math.random()*200,p=o[d%o.length],m=t.createRadialGradient(h,g,0,h,g,f);m.addColorStop(0,p+"40"),m.addColorStop(.5,p+"15"),m.addColorStop(1,"transparent"),t.fillStyle=m,t.beginPath(),t.arc(h,g,f,0,Math.PI*2),t.fill()}const n=new se(e);n.colorSpace=Wt;const r=new pe(30,30),l=new v({map:n,side:oe}),c=new y(r,l);c.rotation.x=-Math.PI/2,c.position.y=.01,c.name="galaxyPlane",c.receiveShadow=!0,a.add(c),console.log("[Battlefield] Galaxy plane created:",c.position)}function gi(a){const e=new le,t=500,s=new Float32Array(t*3),i=new Float32Array(t*3);for(let r=0;r<t;r++){const l=Math.random()*Math.PI*2,c=Math.random()*14;s[r*3]=Math.cos(l)*c,s[r*3+1]=.05+Math.random()*.3,s[r*3+2]=Math.sin(l)*c;const d=Math.random();d<.4?(i[r*3]=.9,i[r*3+1]=.9,i[r*3+2]=1):d<.6?(i[r*3]=1,i[r*3+1]=.8,i[r*3+2]=.4):d<.8?(i[r*3]=1,i[r*3+1]=.4,i[r*3+2]=.8):(i[r*3]=.4,i[r*3+1]=1,i[r*3+2]=1)}e.setAttribute("position",new Ae(s,3)),e.setAttribute("color",new Ae(i,3));const o=new pt({size:.15,transparent:!0,opacity:.9,vertexColors:!0,blending:Me,depthWrite:!1}),n=new Ye(e,o);return n.name="galacticStars",n.renderOrder=5,a.add(n),n}function pi(a,e){const t=[16711935,65535,16737792,6684927,65382];for(let s=0;s<4;s++){const i=document.createElement("canvas"),o=i.getContext("2d");i.width=256,i.height=256;const n=o.createRadialGradient(128,128,0,128,128,128);n.addColorStop(0,"rgba(255, 255, 255, 0.6)"),n.addColorStop(.3,"rgba(255, 255, 255, 0.3)"),n.addColorStop(.6,"rgba(255, 255, 255, 0.1)"),n.addColorStop(1,"transparent"),o.fillStyle=n,o.fillRect(0,0,256,256);const r=new se(i),l=6+Math.random()*6,c=new pe(l,l),d=new v({map:r,color:t[s%t.length],transparent:!0,opacity:.25,blending:Me,depthWrite:!1,side:oe}),h=new y(c,d);h.rotation.x=-Math.PI/2,h.position.set((Math.random()-.5)*20,.03+s*.01,(Math.random()-.5)*20),h.name=`nebula_${s}`,h.renderOrder=2+s,e.push(h),a.add(h)}}function fi(a){const e=new le,t=150,s=new Float32Array(t*3);for(let n=0;n<t;n++){const r=Math.random()*Math.PI*2,l=Math.random()*14;s[n*3]=Math.cos(r)*l,s[n*3+1]=.1+Math.random()*2,s[n*3+2]=Math.sin(r)*l}e.setAttribute("position",new Ae(s,3));const i=new pt({size:.15,color:8947967,transparent:!0,opacity:.5,blending:Me,depthWrite:!1}),o=new Ye(e,i);o.name="cosmicDust",a.add(o)}function mi(a){const e=new ke(14.5,15.5,64),t=new v({color:4491519,transparent:!0,opacity:.6,side:oe,blending:Me}),s=new y(e,t);s.rotation.x=-Math.PI/2,s.position.y=.02,s.name="portalRim",a.add(s);const i=new ke(13.5,14.5,64),o=new v({color:8930559,transparent:!0,opacity:.3,side:oe,blending:Me}),n=new y(i,o);n.rotation.x=-Math.PI/2,n.position.y=.01,n.name="portalInnerRim",a.add(n)}function Tt(a,e,t){e&&(e.group.traverse(s=>{var i,o;s instanceof y?((i=s.geometry)==null||i.dispose(),s.material instanceof Pe?t(s.material):Array.isArray(s.material)&&s.material.forEach(n=>t(n))):s instanceof Ye&&((o=s.geometry)==null||o.dispose(),s.material instanceof Pe&&s.material.dispose())}),a.remove(e.group))}function wi(a,e){a.time+=e;const t=a.group.getObjectByName("galaxyPlane");t&&(t.rotation.z=a.time*.02),a.nebulas.forEach((n,r)=>{n.rotation.z+=e*.03*(r%2===0?1:-1),n.position.x+=Math.sin(a.time*.2+r*2)*e*.1,n.position.z+=Math.cos(a.time*.15+r*2)*e*.1,Math.abs(n.position.x)>12&&(n.position.x*=.9),Math.abs(n.position.z)>12&&(n.position.z*=.9);const l=n.material;l.opacity=.15+Math.sin(a.time*.5+r)*.1});const s=a.group.getObjectByName("portalRim");if(s){const n=s.material;n.opacity=.5+Math.sin(a.time*2)*.3}const i=a.group.getObjectByName("portalInnerRim");if(i){const n=i.material;n.opacity=.3+Math.sin(a.time*3+1)*.2}const o=a.group.getObjectByName("cosmicDust");if(o){const n=o.geometry.attributes.position.array;for(let r=0;r<n.length;r+=3)if(n[r+1]+=e*.15,n[r+1]>3){n[r+1]=.1;const l=Math.random()*Math.PI*2,c=Math.random()*14;n[r]=Math.cos(l)*c,n[r+2]=Math.sin(l)*c}o.geometry.attributes.position.needsUpdate=!0}if(a.stars){const n=a.stars.material;n.opacity=.7+Math.sin(a.time*4)*.2,a.stars.rotation.y=a.time*.01}}const It=new T,Dt=new T;function Lt(){return{phase:"dawn",sunPosition:new T(50,10,-60),moonPosition:new T(-40,15,-50),ambientColor:10075101,ambientIntensity:.6,hemiSkyColor:6724044,hemiGroundColor:4478310,hemiIntensity:.75,mainLightColor:12312063,mainLightIntensity:1.1,fogColor:4487082,fogDensity:.008,skyColor:3368618,starsOpacity:.2,moonOpacity:.3,sunOpacity:.9,lampIntensity:.5,windowEmissive:.3}}function Et(){return{phase:"dusk",sunPosition:new T(-50,8,-60),moonPosition:new T(40,12,-50),ambientColor:7833787,ambientIntensity:.55,hemiSkyColor:4482747,hemiGroundColor:3359829,hemiIntensity:.65,mainLightColor:10075118,mainLightIntensity:.9,fogColor:2245802,fogDensity:.01,skyColor:2245802,starsOpacity:.3,moonOpacity:.4,sunOpacity:.8,lampIntensity:1.5,windowEmissive:.5}}function tt(){return{phase:"night",sunPosition:new T(30,-20,-50),moonPosition:new T(-30,35,-50),ambientColor:5596842,ambientIntensity:.5,hemiSkyColor:3359863,hemiGroundColor:2236996,hemiIntensity:.6,mainLightColor:13426175,mainLightIntensity:.9,fogColor:662058,fogDensity:.012,skyColor:662058,starsOpacity:.9,moonOpacity:1,sunOpacity:0,lampIntensity:2.5,windowEmissive:.8}}function st(){return{phase:"day",sunPosition:new T(30,50,-30),moonPosition:new T(-30,-20,-50),ambientColor:16777215,ambientIntensity:.85,hemiSkyColor:5939433,hemiGroundColor:5596791,hemiIntensity:1,mainLightColor:16777198,mainLightIntensity:1.5,fogColor:6990048,fogDensity:.005,skyColor:4886745,starsOpacity:0,moonOpacity:0,sunOpacity:1,lampIntensity:0,windowEmissive:.1}}function Re(a,e,t,s){const i=(n,r)=>n+(r-n)*t,o=(n,r)=>{const l=n>>16&255,c=n>>8&255,d=n&255,h=r>>16&255,g=r>>8&255,f=r&255,p=Math.round(i(l,h)),m=Math.round(i(c,g)),b=Math.round(i(d,f));return p<<16|m<<8|b};return It.lerpVectors(a.sunPosition,e.sunPosition,t),Dt.lerpVectors(a.moonPosition,e.moonPosition,t),{phase:s,sunPosition:It,moonPosition:Dt,ambientColor:o(a.ambientColor,e.ambientColor),ambientIntensity:i(a.ambientIntensity,e.ambientIntensity),hemiSkyColor:o(a.hemiSkyColor,e.hemiSkyColor),hemiGroundColor:o(a.hemiGroundColor,e.hemiGroundColor),hemiIntensity:i(a.hemiIntensity,e.hemiIntensity),mainLightColor:o(a.mainLightColor,e.mainLightColor),mainLightIntensity:i(a.mainLightIntensity,e.mainLightIntensity),fogColor:o(a.fogColor,e.fogColor),fogDensity:i(a.fogDensity,e.fogDensity),skyColor:o(a.skyColor,e.skyColor),starsOpacity:i(a.starsOpacity,e.starsOpacity),moonOpacity:i(a.moonOpacity,e.moonOpacity),sunOpacity:i(a.sunOpacity,e.sunOpacity),lampIntensity:i(a.lampIntensity,e.lampIntensity),windowEmissive:i(a.windowEmissive,e.windowEmissive)}}function bi(a){if(a>=5&&a<6){const e=a-5;return Re(tt(),Lt(),e,"dawn")}else if(a>=6&&a<7){const e=a-6;return Re(Lt(),st(),e,"dawn")}else{if(a>=7&&a<18)return st();if(a>=18&&a<19.5){const e=(a-18)/1.5;return Re(st(),Et(),e,"dusk")}else if(a>=19.5&&a<21){const e=(a-19.5)/1.5;return Re(Et(),tt(),e,"dusk")}else return tt()}}function yi(){const a=document.createElement("canvas"),e=a.getContext("2d");a.width=512,a.height=512;const t=256,s=256,i=e.createRadialGradient(t,s,50,t,s,256);i.addColorStop(0,"rgba(255, 255, 200, 1)"),i.addColorStop(.2,"rgba(255, 240, 150, 0.8)"),i.addColorStop(.4,"rgba(255, 220, 100, 0.4)"),i.addColorStop(.7,"rgba(255, 200, 80, 0.1)"),i.addColorStop(1,"rgba(255, 180, 50, 0)"),e.fillStyle=i,e.fillRect(0,0,512,512);const o=e.createRadialGradient(t,s,0,t,s,80);o.addColorStop(0,"rgba(255, 255, 255, 1)"),o.addColorStop(.5,"rgba(255, 255, 220, 1)"),o.addColorStop(1,"rgba(255, 240, 150, 0.8)"),e.fillStyle=o,e.beginPath(),e.arc(t,s,80,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(t,s,60,0,Math.PI*2),e.fillStyle="#ffffee",e.fill();const n=new se(a),r=new J({map:n,transparent:!0,depthWrite:!1,blending:Me}),l=new K(r);return l.position.set(30,50,-30),l.scale.set(50,50,1),l.name="sun",l.visible=!1,l}function Mi(){const a=document.createElement("canvas"),e=a.getContext("2d");a.width=512,a.height=512;const t=256,s=256,i=e.createRadialGradient(t,s,60,t,s,256);i.addColorStop(0,"rgba(200, 220, 255, 1)"),i.addColorStop(.2,"rgba(180, 200, 240, 0.8)"),i.addColorStop(.4,"rgba(150, 180, 220, 0.5)"),i.addColorStop(.7,"rgba(120, 150, 200, 0.2)"),i.addColorStop(1,"rgba(100, 130, 180, 0)"),e.fillStyle=i,e.fillRect(0,0,512,512);const o=e.createRadialGradient(t,s,0,t,s,100);o.addColorStop(0,"rgba(255, 255, 255, 1)"),o.addColorStop(.5,"rgba(230, 240, 255, 0.9)"),o.addColorStop(1,"rgba(200, 220, 255, 0.3)"),e.fillStyle=o,e.beginPath(),e.arc(t,s,100,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(t,s,70,0,Math.PI*2),e.fillStyle="#e8eeff",e.fill(),e.fillStyle="rgba(180, 190, 210, 0.6)",e.beginPath(),e.arc(t-25,s-20,18,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(t+25,s+15,12,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(t-5,s+30,10,0,Math.PI*2),e.fill();const n=new se(a),r=new J({map:n,transparent:!0,depthWrite:!1,blending:Me}),l=new K(r);return l.position.set(-30,35,-50),l.scale.set(40,40,1),l.name="moon",l}function Si(a=1){const e=new Y,t=new A({color:16777215,transparent:!0,opacity:.85,roughness:1,metalness:0,depthWrite:!1}),s=new O(1,16,12);return[{x:0,y:0,z:0,scale:1.2},{x:-1,y:.1,z:.2,scale:1},{x:1,y:.15,z:-.1,scale:1.1},{x:-.5,y:.3,z:.4,scale:.8},{x:.6,y:.35,z:.3,scale:.9},{x:-1.5,y:-.1,z:0,scale:.7},{x:1.5,y:-.05,z:.1,scale:.75},{x:0,y:.4,z:0,scale:.7}].forEach(o=>{const n=new y(s,t);n.position.set(o.x*a,o.y*a,o.z*a),n.scale.setScalar(o.scale*a),e.add(n)}),e.userData.material=t,e}function vi(){const a=new Y;a.name="clouds";const e=[];return[{x:-25,y:35,z:-20,scale:3.5,speed:.8},{x:15,y:40,z:-35,scale:4,speed:1},{x:-40,y:38,z:10,scale:3,speed:.9},{x:30,y:42,z:15,scale:3.8,speed:1.1},{x:0,y:36,z:-45,scale:3.2,speed:.85},{x:-15,y:44,z:30,scale:2.8,speed:1.05},{x:45,y:37,z:-10,scale:3.6,speed:.95},{x:-35,y:41,z:-30,scale:2.5,speed:1.15}].forEach((s,i)=>{const o=Si(s.scale);o.position.set(s.x,s.y,s.z),o.userData.baseX=s.x,o.userData.speed=s.speed,o.userData.index=i,a.add(o),e.push(o)}),{group:a,clouds:e,time:0}}function Ci(a,e){a.time+=e,a.clouds.forEach(t=>{const s=t.userData.baseX,i=t.userData.speed,o=t.userData.index,n=60,r=.015*i,l=o*.7,c=Math.sin(a.time*r+l)*n*.5;t.position.x=s+c;const d=.3*i,h=.5;t.position.y+=Math.sin(a.time*d+l)*h*e})}function Pi(a,e){a.clouds.forEach(t=>{const s=t.userData.material;s&&(s.opacity=e*.85)})}function ki(){const a=new le,e=300,t=new Float32Array(e*3);for(let o=0;o<e;o++){const n=Math.random()*Math.PI*2,r=Math.random()*Math.PI*.5,l=80+Math.random()*40;t[o*3]=l*Math.sin(r)*Math.cos(n),t[o*3+1]=l*Math.cos(r)+20,t[o*3+2]=l*Math.sin(r)*Math.sin(n)}a.setAttribute("position",new Ae(t,3));const s=new pt({color:16777215,size:.5,transparent:!0,opacity:.8}),i=new Ye(a,s);return i.name="stars",i}function Ai(a){const t=a/2+5;return[{x:-t,z:-t+2,scale:1.2},{x:-t+2,z:-t,scale:1.4},{x:t,z:-t+2,scale:1.3},{x:t-2,z:-t,scale:1},{x:-t,z:t-2,scale:1.1},{x:-t+2,z:t,scale:1.5},{x:t,z:t-2,scale:1.25},{x:t-2,z:t,scale:1.35}]}function xi(a){const e=a/2,t=e+3,s=e*.5;return[{x:-t,z:-s},{x:-t,z:0},{x:-t,z:s},{x:t,z:-s},{x:t,z:0},{x:t,z:s},{x:-s,z:-t},{x:0,z:-t},{x:s,z:-t},{x:-s,z:t},{x:0,z:t},{x:s,z:t},{x:-t-5,z:s+2},{x:-t-8,z:s+5}]}function Bi(a){const e=a/2+2;return[{x:-e,z:-e},{x:e,z:-e},{x:-e,z:e},{x:e,z:e}]}function _t(a,e=ft){const t=Ti(a,e),s=Ii(a,e),{house:i,windowMaterials:o}=Di(a,e),{lamps:n,lampLights:r}=Li(a,e);return{trees:t,bushes:s,house:i,lamps:n,lampLights:r,windowMaterials:o}}function Ti(a,e){const t=new Y;t.name="trees_instanced";const s=Ai(e),i=s.length,o=new A({color:4863784,roughness:.9}),n=new A({color:2972199,roughness:.8}),r=new j(.3,.5,3,8),l=new O(2,8,6),c=new O(1.5,8,6),d=new me(r,o,i),h=new me(l,n,i),g=new me(c,n,i);d.castShadow=!0,d.receiveShadow=!0,h.castShadow=!0,g.castShadow=!0,d.name="trees_trunks",h.name="trees_foliage1",g.name="trees_foliage2";const f=new Xe,p=new T,m=new Ee,b=new T;return s.forEach((w,M)=>{const S=w.scale,P=Math.random()*Math.PI*2;p.set(w.x,1.5*S,w.z),m.setFromEuler(new Ft(0,P,0)),b.set(S,S,S),f.compose(p,m,b),d.setMatrixAt(M,f),p.set(w.x,4*S,w.z),b.set(S,S*.8,S),f.compose(p,m,b),h.setMatrixAt(M,f),p.set(w.x,5.5*S,w.z),b.set(S,S,S),f.compose(p,m,b),g.setMatrixAt(M,f)}),d.instanceMatrix.needsUpdate=!0,h.instanceMatrix.needsUpdate=!0,g.instanceMatrix.needsUpdate=!0,t.add(d),t.add(h),t.add(g),a.add(t),t}function Ii(a,e){const t=xi(e),s=[],i=g=>{const f=Math.sin(g)*1e4;return f-Math.floor(f)};t.forEach((g,f)=>{const p=2+Math.floor(i(f*100)*2);for(let m=0;m<p;m++){const b=f*100+m,w=.6+i(b)*.4,M=(i(b+1)-.5)*.8,S=(i(b+2)-.5)*.8,P=.7+i(b+3)*.2;s.push({x:g.x+M,y:w*.7,z:g.z+S,scaleX:w,scaleY:w*P,scaleZ:w})}});const o=new A({color:4024887,roughness:.85}),n=new O(1,8,6),r=new me(n,o,s.length);r.castShadow=!0,r.receiveShadow=!0,r.name="bushes_instanced";const l=new Xe,c=new T,d=new Ee,h=new T;return s.forEach((g,f)=>{c.set(g.x,g.y,g.z),d.identity(),h.set(g.scaleX,g.scaleY,g.scaleZ),l.compose(c,d,h),r.setMatrixAt(f,l)}),r.instanceMatrix.needsUpdate=!0,a.add(r),r}function Di(a,e){const t=new Y,s=[],i=new z(6,4,5),o=new A({color:13935988,roughness:.8}),n=new y(i,o);n.position.y=2,n.castShadow=!0,n.receiveShadow=!0,t.add(n);const r=new xe(5,3,4),l=new A({color:9127187,roughness:.7}),c=new y(r,l);c.position.y=5.5,c.rotation.y=Math.PI/4,c.castShadow=!0,t.add(c);const d=new z(1.2,2,.1),h=new A({color:6045747,roughness:.6}),g=new y(d,h);g.position.set(0,1,2.55),t.add(g);const f=new z(.8,.8,.1),p=new A({color:16777130,emissive:16755268,emissiveIntensity:.5,roughness:.3});s.push(p);const m=new y(f,p);m.position.set(-1.5,2.5,2.55),t.add(m);const b=new y(f,p);b.position.set(1.5,2.5,2.55),t.add(b);const w=new z(.8,2,.8),M=new A({color:9127187,roughness:.8}),S=new y(w,M);S.position.set(1.5,6,-1),S.castShadow=!0,t.add(S);const P=e/2;return t.position.set(-P-5,0,P-5),t.rotation.y=Math.PI/6,t.name="house",a.add(t),{house:t,windowMaterials:s}}function Li(a,e){const t=new Y;t.name="lamps_instanced";const s=[],i=Bi(e),o=i.length,n=new A({color:3355443,roughness:.5,metalness:.5}),r=new A({color:2236962,roughness:.4,metalness:.6}),l=new A({color:16772778,emissive:16755268,emissiveIntensity:2,roughness:.2}),c=new j(.1,.15,5,8),d=new j(.05,.05,1,8),h=new j(.4,.3,.6,8),g=new O(.25,8,8),f=new me(c,n,o),p=new me(d,n,o),m=new me(h,r,o),b=new me(g,l,o);f.castShadow=!0,f.name="lamps_poles",p.name="lamps_arms",m.name="lamps_housings",b.name="lamps_bulbs";const w=new Xe,M=new T,S=new Ee,P=new T(1,1,1);return i.forEach((C,x)=>{M.set(C.x,2.5,C.z),S.identity(),w.compose(M,S,P),f.setMatrixAt(x,w),M.set(C.x+.4,4.8,C.z),S.setFromEuler(new Ft(0,0,Math.PI/2)),w.compose(M,S,P),p.setMatrixAt(x,w),M.set(C.x+.8,4.8,C.z),S.identity(),w.compose(M,S,P),m.setMatrixAt(x,w),M.set(C.x+.8,4.5,C.z),w.compose(M,S,P),b.setMatrixAt(x,w);const B=new us(16755285,1.5,15);B.position.set(C.x,5,C.z),s.push(B),a.add(B)}),f.instanceMatrix.needsUpdate=!0,p.instanceMatrix.needsUpdate=!0,m.instanceMatrix.needsUpdate=!0,b.instanceMatrix.needsUpdate=!0,t.add(f),t.add(p),t.add(m),t.add(b),a.add(t),{lamps:t,lampLights:s}}function Ot(a,e=ft){const t=e*1.5,s=new pe(t,t),i=new A({color:2972199,roughness:.9,metalness:0}),o=new y(s,i);return o.rotation.x=-Math.PI/2,o.position.y=-.05,o.receiveShadow=!0,o.name="grass",a.add(o),o}class Ei{constructor(e){u(this,"scene");u(this,"ground",null);u(this,"gridHelper",null);u(this,"sun",null);u(this,"moon",null);u(this,"stars",null);u(this,"ambientLight",null);u(this,"hemiLight",null);u(this,"mainLight",null);u(this,"fillLight",null);u(this,"lampLights",[]);u(this,"windowMaterials",[]);u(this,"trees",null);u(this,"bushes",null);u(this,"house",null);u(this,"lamps",null);u(this,"grass",null);u(this,"baseFogDensity",.01);u(this,"brightness",1);u(this,"skyColorOverride",null);u(this,"currentFloorStyle","concrete");u(this,"galacticState",null);u(this,"cloudState",null);u(this,"cloudsVisible",!0);u(this,"debugHourOverride",null);u(this,"tempColor",new H);u(this,"currentSize",ft);u(this,"terrainVisibility",{trees:!0,bushes:!0,house:!0,lamps:!0,grass:!0});u(this,"gridVisible",!0);u(this,"simpleMode",!1);this.scene=e}setGridVisible(e){this.gridVisible=e,this.gridHelper&&(this.gridHelper.visible=e)}create(){this.createGround(),this.grass=Ot(this.scene,this.currentSize),this.createGrid(),this.sun=yi(),this.scene.add(this.sun),this.moon=Mi(),this.scene.add(this.moon),this.stars=ki(),this.scene.add(this.stars),this.cloudState=vi(),this.scene.add(this.cloudState.group);const e=_t(this.scene,this.currentSize);this.trees=e.trees,this.bushes=e.bushes,this.house=e.house,this.lamps=e.lamps,this.lampLights=e.lampLights,this.windowMaterials=e.windowMaterials,this.createLighting(),this.createFog(),this.updateTimeOfDay()}updateTimeOfDay(){const e=bi(this.getCurrentHour());this.applyTimeConfig(e)}getCurrentHour(){if(this.debugHourOverride!==null)return this.debugHourOverride;const e=new Date;return e.getHours()+e.getMinutes()/60}setDebugTime(e){this.debugHourOverride=e,this.updateTimeOfDay(),console.log(`[Battlefield] Time set to: ${e!==null?`${e}:00`:"real time"}`)}setTimeMode(e){const s={auto:null,day:12,night:23,dawn:6,dusk:19.5}[e]??null;this.debugHourOverride=s,this.updateTimeOfDay(),console.log(`[Battlefield] Time mode set to: ${e} (${s!==null?`${s}:00`:"real time"})`)}setTerrainConfig(e){if(e.battlefieldSize!==void 0&&e.battlefieldSize!==this.currentSize&&this.resizeBattlefield(e.battlefieldSize),this.terrainVisibility={trees:e.showTrees,bushes:e.showBushes,house:e.showHouse,lamps:e.showLamps,grass:e.showGrass},this.trees&&(this.trees.visible=e.showTrees),this.bushes&&(this.bushes.visible=e.showBushes),this.house&&(this.house.visible=e.showHouse),this.lamps&&(this.lamps.visible=e.showLamps),this.lampLights.forEach(t=>{t.visible=e.showLamps}),this.grass&&(this.grass.visible=e.showGrass),e.showClouds!==void 0&&(this.cloudsVisible=e.showClouds,this.cloudState&&(this.cloudState.group.visible=e.showClouds)),this.baseFogDensity=e.fogDensity*.008,e.brightness!==void 0&&(this.brightness=e.brightness),e.skyColor!==void 0&&(this.skyColorOverride=e.skyColor),e.simpleMode!==void 0){const t=this.simpleMode;this.simpleMode=e.simpleMode,t&&!this.simpleMode&&this.setFloorStyle(this.currentFloorStyle,!0)}this.updateTimeOfDay()}resizeBattlefield(e){this.currentSize=e,console.log(`[Battlefield] Resizing to ${e}x${e}`),this.ground&&(this.ground.geometry.dispose(),this.disposeMaterial(this.ground.material),this.scene.remove(this.ground),this.ground=null),this.createGround(),this.setFloorStyle(this.currentFloorStyle,!0),this.gridHelper&&(this.gridHelper.geometry.dispose(),this.gridHelper.material instanceof Pe&&this.gridHelper.material.dispose(),this.scene.remove(this.gridHelper),this.gridHelper=null),this.createGrid(),this.grass&&(this.grass.geometry.dispose(),this.disposeMaterial(this.grass.material),this.scene.remove(this.grass)),this.grass=Ot(this.scene,this.currentSize),this.grass.visible=this.terrainVisibility.grass,this.disposeTerrainElements();const t=_t(this.scene,this.currentSize);if(this.trees=t.trees,this.bushes=t.bushes,this.house=t.house,this.lamps=t.lamps,this.lampLights=t.lampLights,this.windowMaterials=t.windowMaterials,this.trees&&(this.trees.visible=this.terrainVisibility.trees),this.bushes&&(this.bushes.visible=this.terrainVisibility.bushes),this.house&&(this.house.visible=this.terrainVisibility.house),this.lamps&&(this.lamps.visible=this.terrainVisibility.lamps),this.lampLights.forEach(s=>{s.visible=this.terrainVisibility.lamps}),this.mainLight){const s=this.currentSize*.6;this.mainLight.shadow.camera.left=-s,this.mainLight.shadow.camera.right=s,this.mainLight.shadow.camera.top=s,this.mainLight.shadow.camera.bottom=-s,this.mainLight.shadow.camera.updateProjectionMatrix()}}disposeTerrainElements(){this.trees&&(this.disposeGroup(this.trees),this.scene.remove(this.trees),this.trees=null),this.bushes&&(this.bushes.geometry.dispose(),this.bushes.material.dispose(),this.scene.remove(this.bushes),this.bushes=null),this.house&&(this.disposeGroup(this.house),this.scene.remove(this.house),this.house=null),this.lamps&&(this.disposeGroup(this.lamps),this.scene.remove(this.lamps),this.lamps=null);for(const e of this.lampLights)this.scene.remove(e),e.dispose();this.lampLights=[],this.windowMaterials=[]}setFloorStyle(e,t=!1){if(this.currentFloorStyle===e&&!t)return;const s=this.currentFloorStyle;if(this.currentFloorStyle=e,typeof window<"u"&&window.__TIDE_MEMORY_DEBUG__&&console.log(`[Battlefield] Memory: Switching floor from ${s} to ${e}`),s==="galactic"&&(Tt(this.scene,this.galacticState,this.disposeMaterial.bind(this)),this.galacticState=null,this.ground&&(this.ground.visible=!0)),this.ground){const i=this.ground.material;if(e==="galactic")console.log("[Battlefield] Creating galactic floor..."),this.ground.visible=!1,this.galacticState=di(this.scene),console.log("[Battlefield] Galactic elements created");else{this.ground.visible=!0,i.transparent=!1,i.opacity=1,i.side=gs,i.depthWrite=!0,this.ground.renderOrder=0;const o=i.map;if(e==="none")i.map=null,i.color.setHex(2972199),i.roughness=.9,i.metalness=0,i.emissive.setHex(0),i.emissiveIntensity=0,i.needsUpdate=!0;else{const n=Bt(e);n.wrapS=Ge,n.wrapT=Ge;const r=e==="pokemon-stadium"?1:Math.round(this.currentSize/5);n.repeat.set(r,r),i.map=n,i.needsUpdate=!0}switch(o&&(o.dispose(),typeof window<"u"&&window.__TIDE_MEMORY_DEBUG__&&console.log("[Battlefield] Memory: Disposed old floor texture")),e){case"none":break;case"metal":i.color.setHex(8947865),i.roughness=.4,i.metalness=.8,i.emissive.setHex(0),i.emissiveIntensity=0;break;case"hex":i.color.setHex(4482696),i.roughness=.6,i.metalness=.4,i.emissive.setHex(1122867),i.emissiveIntensity=.2;break;case"circuit":i.color.setHex(2245683),i.roughness=.7,i.metalness=.3,i.emissive.setHex(13090),i.emissiveIntensity=.4;break;case"pokemon-stadium":i.color.setHex(11184810),i.roughness=1,i.metalness=0,i.emissive.setHex(0),i.emissiveIntensity=0;break;default:i.color.setHex(5592405),i.roughness=.8,i.metalness=.1,i.emissive.setHex(0),i.emissiveIntensity=0}}}console.log(`[Battlefield] Floor style set to: ${e}`)}updateGalacticAnimation(e){this.currentFloorStyle!=="galactic"||!this.galacticState||wi(this.galacticState,e)}updateCloudAnimation(e){!this.cloudState||!this.cloudsVisible||Ci(this.cloudState,e)}disposeMaterial(e){var t;(e instanceof v||e instanceof A||e instanceof J)&&((t=e.map)==null||t.dispose()),e.dispose()}applyTimeConfig(e){if(this.simpleMode){this.scene.background instanceof H?this.scene.background.setHex(657935):this.scene.background=new H(657935),this.scene.fog instanceof Je&&(this.scene.fog.density=0),this.sun&&(this.sun.visible=!1),this.moon&&(this.moon.visible=!1),this.stars&&(this.stars.visible=!1),this.cloudState&&(this.cloudState.group.visible=!1),this.trees&&(this.trees.visible=!1),this.bushes&&(this.bushes.visible=!1),this.house&&(this.house.visible=!1),this.lamps&&(this.lamps.visible=!1),this.lampLights.forEach(s=>{s.visible=!1}),this.grass&&(this.grass.visible=!1),this.ground&&this.currentFloorStyle!=="galactic"&&(this.ground.visible=!0,this.ground.material.color.setHex(855314)),this.ambientLight&&(this.ambientLight.color.setHex(16777215),this.ambientLight.intensity=.85*this.brightness),this.hemiLight&&(this.hemiLight.intensity=1*this.brightness),this.mainLight&&(this.mainLight.intensity=1.5*this.brightness);return}const t=this.skyColorOverride?parseInt(this.skyColorOverride.replace("#",""),16):e.skyColor;if(this.scene.background instanceof H?this.scene.background.setHex(t):this.scene.background=this.tempColor.setHex(t).clone(),this.scene.fog instanceof Je){const s=this.skyColorOverride?parseInt(this.skyColorOverride.replace("#",""),16):e.fogColor;this.scene.fog.color.setHex(s);const i=this.baseFogDensity>0?this.baseFogDensity/.008:0;this.scene.fog.density=e.fogDensity*i}if(this.sun&&(this.sun.position.copy(e.sunPosition),this.sun.material.opacity=e.sunOpacity,this.sun.visible=e.sunOpacity>.01),this.moon&&(this.moon.position.copy(e.moonPosition),this.moon.material.opacity=e.moonOpacity,this.moon.visible=e.moonOpacity>.01),this.stars&&(this.stars.material.opacity=e.starsOpacity,this.stars.visible=e.starsOpacity>.01),this.ambientLight&&(this.ambientLight.color.setHex(e.ambientColor),this.ambientLight.intensity=e.ambientIntensity*this.brightness),this.hemiLight&&(this.hemiLight.color.setHex(e.hemiSkyColor),this.hemiLight.groundColor.setHex(e.hemiGroundColor),this.hemiLight.intensity=e.hemiIntensity*this.brightness),this.mainLight&&(this.mainLight.color.setHex(e.mainLightColor),this.mainLight.intensity=e.mainLightIntensity*this.brightness,e.sunOpacity>e.moonOpacity?this.mainLight.position.copy(e.sunPosition):this.mainLight.position.copy(e.moonPosition)),this.lampLights.forEach(s=>{s.intensity=e.lampIntensity}),this.windowMaterials.forEach(s=>{s.emissiveIntensity=e.windowEmissive}),this.cloudState&&this.cloudsVisible){let s;switch(e.phase){case"day":s=1;break;case"dawn":case"dusk":s=.7;break;case"night":s=.2;break;default:s=1}Pi(this.cloudState,s)}}getGround(){return this.ground}createGround(){const e=new pe(this.currentSize,this.currentSize),t=Bt(this.currentFloorStyle);t.wrapS=Ge,t.wrapT=Ge;const s=this.currentFloorStyle==="galactic"?1:Math.round(this.currentSize/5);t.repeat.set(s,s);const i=new A({map:t,color:5592405,roughness:.8,metalness:.1});this.ground=new y(e,i),this.ground.rotation.x=-Math.PI/2,this.ground.receiveShadow=!0,this.ground.name="ground",this.scene.add(this.ground)}createGrid(){const e=Math.round(this.currentSize/2);this.gridHelper=new ps(this.currentSize,e,2763322,1710634),this.gridHelper.position.y=.01,this.gridHelper.visible=this.gridVisible,this.scene.add(this.gridHelper)}createLogo(){const t=new Nt().load("/assets/textures/logo-blanco.png"),s=10,i=4,o=new pe(s,i),n=new v({map:t,transparent:!0,opacity:.8,side:oe,depthWrite:!1}),r=new y(o,n);r.rotation.x=-Math.PI/2,r.position.set(0,.02,0),r.name="tideLogo",this.scene.add(r)}createFog(){this.scene.fog=new Je(662058,.01),this.scene.background=new H(662058)}createLighting(){this.ambientLight=new jt(16777215,.6),this.scene.add(this.ambientLight),this.hemiLight=new fs(16777198,5596791,.7),this.hemiLight.position.set(0,20,0),this.scene.add(this.hemiLight),this.mainLight=new et(16777215,1.2),this.mainLight.position.set(30,50,-30),this.mainLight.castShadow=!0,this.mainLight.shadow.mapSize.width=2048,this.mainLight.shadow.mapSize.height=2048,this.mainLight.shadow.camera.near=.5,this.mainLight.shadow.camera.far=200;const e=this.currentSize*.6;this.mainLight.shadow.camera.left=-e,this.mainLight.shadow.camera.right=e,this.mainLight.shadow.camera.top=e,this.mainLight.shadow.camera.bottom=-e,this.scene.add(this.mainLight),this.fillLight=new et(16777215,.6),this.fillLight.position.set(-10,15,10),this.scene.add(this.fillLight);const t=new et(11193599,.5);t.position.set(0,20,30),this.scene.add(t)}dispose(){var t,s;Tt(this.scene,this.galacticState,this.disposeMaterial.bind(this)),this.galacticState=null;const e=this.scene.getObjectByName("tideLogo");e&&((t=e.geometry)==null||t.dispose(),this.disposeMaterial(e.material),this.scene.remove(e)),this.ground&&(this.ground.geometry.dispose(),this.disposeMaterial(this.ground.material),this.scene.remove(this.ground)),this.gridHelper&&(this.gridHelper.geometry.dispose(),this.gridHelper.material instanceof Pe&&this.gridHelper.material.dispose(),this.scene.remove(this.gridHelper)),this.grass&&(this.grass.geometry.dispose(),this.disposeMaterial(this.grass.material),this.scene.remove(this.grass)),this.sun&&(this.disposeMaterial(this.sun.material),this.scene.remove(this.sun)),this.moon&&(this.disposeMaterial(this.moon.material),this.scene.remove(this.moon)),this.stars&&(this.stars.geometry.dispose(),this.stars.material.dispose(),this.scene.remove(this.stars)),this.trees&&(this.disposeGroup(this.trees),this.scene.remove(this.trees),this.trees=null),this.bushes&&(this.bushes.geometry.dispose(),this.bushes.material.dispose(),this.scene.remove(this.bushes),this.bushes=null),this.house&&(this.disposeGroup(this.house),this.scene.remove(this.house),this.house=null),this.lamps&&(this.disposeGroup(this.lamps),this.scene.remove(this.lamps),this.lamps=null);for(const i of this.lampLights)this.scene.remove(i),i.dispose();this.lampLights=[],this.windowMaterials=[],this.ambientLight&&this.scene.remove(this.ambientLight),this.hemiLight&&this.scene.remove(this.hemiLight),this.mainLight&&((s=this.mainLight.shadow.map)==null||s.dispose(),this.scene.remove(this.mainLight)),this.fillLight&&this.scene.remove(this.fillLight)}disposeGroup(e){e.traverse(t=>{var s;t instanceof y&&((s=t.geometry)==null||s.dispose(),t.material instanceof Pe?this.disposeMaterial(t.material):Array.isArray(t.material)&&t.material.forEach(i=>this.disposeMaterial(i)))})}}class Te{constructor(e=200){u(this,"lastClickTime",0);u(this,"lastClickId",null);u(this,"clickTimer",null);u(this,"threshold");this.threshold=e}handleClick(e){const t=performance.now(),s=t-this.lastClickTime;return this.lastClickTime>0&&this.lastClickId===e&&s<this.threshold?(this.clearTimer(),this.reset(),"double"):(this.lastClickId=e,this.lastClickTime=t,this.clearTimer(),this.clickTimer=setTimeout(()=>{this.clickTimer=null,this.lastClickId=null,this.lastClickTime=0},this.threshold),"single")}reset(){this.clearTimer(),this.lastClickId=null,this.lastClickTime=0}clearTimer(){this.clickTimer&&(clearTimeout(this.clickTimer),this.clickTimer=null)}dispose(){this.clearTimer()}}const Ue=class Ue{constructor(e,t,s){u(this,"canvas");u(this,"controls");u(this,"callbacks");u(this,"activePointers",new Map);u(this,"touchStartTime",0);u(this,"touchStartPos",{x:0,y:0});u(this,"isTouchDragging",!1);u(this,"isTouchPanning",!1);u(this,"touchPanStart",{x:0,y:0});u(this,"longPressTimer",null);u(this,"longPressTriggered",!1);u(this,"isPinching",!1);u(this,"lastPinchDistance",0);u(this,"twoFingerPanStart",{x:0,y:0});u(this,"lastTwoFingerAngle",0);u(this,"isThreeFingerDrag",!1);u(this,"threeFingerStart",{x:0,y:0});this.canvas=e,this.controls=t,this.callbacks=s}onTouchStart(e){for(let t=0;t<e.changedTouches.length;t++){const s=e.changedTouches[t];this.activePointers.set(s.identifier,{x:s.clientX,y:s.clientY})}this.clearLongPressTimer(),this.longPressTriggered=!1,e.touches.length===1?this.handleSingleTouchStart(e.touches[0]):e.touches.length===2?this.handleTwoTouchStart(e):e.touches.length>=3&&this.handleThreeTouchStart(e)}onTouchMove(e){for(let t=0;t<e.changedTouches.length;t++){const s=e.changedTouches[t];this.activePointers.set(s.identifier,{x:s.clientX,y:s.clientY})}e.touches.length>=3&&this.isThreeFingerDrag?this.handleThreeTouchMove(e):e.touches.length===2&&this.isPinching?this.handleTwoTouchMove(e):e.touches.length===1&&!this.isPinching&&this.handleSingleTouchMove(e.touches[0])}onTouchEnd(e){this.clearLongPressTimer();for(let t=0;t<e.changedTouches.length;t++){const s=e.changedTouches[t];this.activePointers.delete(s.identifier)}return e.touches.length===0?this.handleAllTouchesEnd(e):(e.touches.length===2?this.transitionToTwoTouches(e):e.touches.length===1&&this.transitionToOneTouch(e.touches[0]),!1)}onPointerCancel(e){this.activePointers.delete(e),this.reset()}reset(){this.isTouchPanning=!1,this.isPinching=!1,this.isThreeFingerDrag=!1,this.lastPinchDistance=0,this.isTouchDragging=!1,this.longPressTriggered=!1,this.clearLongPressTimer()}get isDragging(){return this.isTouchDragging}get wasLongPress(){return this.longPressTriggered}dispose(){this.clearLongPressTimer(),this.activePointers.clear()}reattach(e,t){this.canvas=e,this.controls=t}handleSingleTouchStart(e){this.touchStartTime=performance.now(),this.touchStartPos={x:e.clientX,y:e.clientY},this.isTouchDragging=!1,this.isTouchPanning=!1;const t=e.clientX,s=e.clientY;this.longPressTimer=setTimeout(()=>{this.longPressTriggered=!0,this.longPressTimer=null,this.callbacks.onLongPress(t,s),navigator.vibrate&&navigator.vibrate(50)},Ue.LONG_PRESS_DURATION)}handleTwoTouchStart(e){e.preventDefault(),this.isPinching=!0,this.isTouchPanning=!1,this.isThreeFingerDrag=!1,this.lastPinchDistance=this.getTouchDistance(e.touches[0],e.touches[1]);const t=this.getTouchCenter(e.touches[0],e.touches[1]);this.twoFingerPanStart={x:t.x,y:t.y},this.lastTwoFingerAngle=this.getTwoFingerAngle(e.touches[0],e.touches[1])}handleThreeTouchStart(e){e.preventDefault(),this.isPinching=!1,this.isThreeFingerDrag=!0,this.controls.enableRotate=!0;const t=this.getMultiTouchCenter(e.touches);this.threeFingerStart={x:t.x,y:t.y}}handleSingleTouchMove(e){const t=e.clientX-this.touchStartPos.x,s=e.clientY-this.touchStartPos.y;if(!this.isTouchPanning&&(Math.abs(t)>Ce||Math.abs(s)>Ce)&&(this.clearLongPressTimer(),this.isTouchPanning=!0,this.isTouchDragging=!0,this.touchPanStart={x:e.clientX,y:e.clientY}),this.isTouchPanning){const i=e.clientX-this.touchPanStart.x,o=e.clientY-this.touchPanStart.y;this.callbacks.onPan(i,o),this.touchPanStart={x:e.clientX,y:e.clientY}}}handleTwoTouchMove(e){this.clearLongPressTimer(),e.preventDefault();const t=this.getTouchDistance(e.touches[0],e.touches[1]),s=this.getTouchCenter(e.touches[0],e.touches[1]),i=this.getTwoFingerAngle(e.touches[0],e.touches[1]);if(this.lastPinchDistance>0){const l=this.lastPinchDistance/t;this.callbacks.onPinchZoom(l,s)}this.lastPinchDistance=t;const o=s.x-this.twoFingerPanStart.x,n=s.y-this.twoFingerPanStart.y;(Math.abs(o)>1||Math.abs(n)>1)&&(this.callbacks.onOrbit(o,n),this.twoFingerPanStart={x:s.x,y:s.y});let r=i-this.lastTwoFingerAngle;r>Math.PI&&(r-=2*Math.PI),r<-Math.PI&&(r+=2*Math.PI),Math.abs(r)>.01&&(this.callbacks.onRotation(r),this.lastTwoFingerAngle=i)}handleThreeTouchMove(e){this.clearLongPressTimer(),e.preventDefault();const t=this.getMultiTouchCenter(e.touches),s=t.x-this.threeFingerStart.x,i=t.y-this.threeFingerStart.y;(Math.abs(s)>1||Math.abs(i)>1)&&(this.callbacks.onOrbit(s,i),this.threeFingerStart={x:t.x,y:t.y})}handleAllTouchesEnd(e){const t=performance.now()-this.touchStartTime,s=!this.isTouchDragging&&!this.longPressTriggered&&t<400,i=this.isTouchPanning;if(s&&e.changedTouches.length>0){const o=e.changedTouches[0];this.callbacks.onTap(o.clientX,o.clientY)}return i&&this.callbacks.onPanEnd(),this.reset(),s}transitionToTwoTouches(e){this.isThreeFingerDrag=!1,this.isPinching=!0,this.lastPinchDistance=this.getTouchDistance(e.touches[0],e.touches[1]);const t=this.getTouchCenter(e.touches[0],e.touches[1]);this.twoFingerPanStart={x:t.x,y:t.y}}transitionToOneTouch(e){this.isPinching=!1,this.isThreeFingerDrag=!1,this.lastPinchDistance=0,this.touchPanStart={x:e.clientX,y:e.clientY},this.touchStartPos={x:e.clientX,y:e.clientY}}clearLongPressTimer(){this.longPressTimer&&(clearTimeout(this.longPressTimer),this.longPressTimer=null)}getTouchDistance(e,t){const s=t.clientX-e.clientX,i=t.clientY-e.clientY;return Math.sqrt(s*s+i*i)}getTouchCenter(e,t){return{x:(e.clientX+t.clientX)/2,y:(e.clientY+t.clientY)/2}}getTwoFingerAngle(e,t){const s=t.clientX-e.clientX,i=t.clientY-e.clientY;return Math.atan2(i,s)}getMultiTouchCenter(e){let t=0,s=0;for(let i=0;i<e.length;i++)t+=e[i].clientX,s+=e[i].clientY;return{x:t/e.length,y:s/e.length}}};u(Ue,"LONG_PRESS_DURATION",500);let ht=Ue;function _i(a){const e=Math.abs(a.deltaX),t=Math.abs(a.deltaY);return a.ctrlKey||e>1?!0:t>80&&e<1?!1:t>0&&t<=80}class Oi{constructor(e,t,s){u(this,"cameraController");u(this,"callbacks");u(this,"canvas");u(this,"isGestureActive",!1);u(this,"gestureScale",1);u(this,"onGestureStart",e=>{const t=e;t.preventDefault(),k.getTrackpadConfig().enabled&&(this.isGestureActive=!0,this.gestureScale=t.scale)});u(this,"onGestureChange",e=>{const t=e;t.preventDefault();const s=k.getTrackpadConfig();if(!(!s.enabled||!this.isGestureActive)&&s.pinchToZoom&&t.scale!==this.gestureScale){const i=t.scale-this.gestureScale;this.callbacks.onZoom(i*s.sensitivity.zoom,t.clientX,t.clientY),this.gestureScale=t.scale}});u(this,"onGestureEnd",e=>{e.preventDefault(),this.isGestureActive=!1,this.gestureScale=1});this.cameraController=e,this.canvas=t,this.callbacks=s,this.setupGestureEvents()}setupGestureEvents(){"GestureEvent"in window&&(this.canvas.addEventListener("gesturestart",this.onGestureStart),this.canvas.addEventListener("gesturechange",this.onGestureChange),this.canvas.addEventListener("gestureend",this.onGestureEnd))}handleWheel(e){const t=k.getTrackpadConfig();if(!t.enabled||!_i(e))return!1;if(e.ctrlKey&&t.pinchToZoom){e.preventDefault();const s=-e.deltaY*.01*t.sensitivity.zoom;return this.callbacks.onZoom(s,e.clientX,e.clientY),!0}if(e.shiftKey&&t.shiftTwoFingerOrbit){e.preventDefault();const s=-e.deltaX*t.sensitivity.orbit,i=-e.deltaY*t.sensitivity.orbit;return this.callbacks.onOrbit(s,i),!0}if(t.twoFingerPan){e.preventDefault();const s=-e.deltaX*t.sensitivity.pan,i=-e.deltaY*t.sensitivity.pan;return this.callbacks.onPan(s,i),!0}return!1}setCameraController(e){this.cameraController=e}setCanvas(e){"GestureEvent"in window&&(this.canvas.removeEventListener("gesturestart",this.onGestureStart),this.canvas.removeEventListener("gesturechange",this.onGestureChange),this.canvas.removeEventListener("gestureend",this.onGestureEnd)),this.canvas=e,this.setupGestureEvents()}dispose(){"GestureEvent"in window&&(this.canvas.removeEventListener("gesturestart",this.onGestureStart),this.canvas.removeEventListener("gesturechange",this.onGestureChange),this.canvas.removeEventListener("gestureend",this.onGestureEnd))}}class zi{constructor(e,t){u(this,"camera");u(this,"canvas");u(this,"raycaster",new ms);u(this,"mouse",new re);u(this,"ground",null);u(this,"agentMeshes",new Map);u(this,"agentHitboxes",[]);u(this,"resizeHandlesGetter",()=>[]);u(this,"folderIconMeshesGetter",()=>[]);this.camera=e,this.canvas=t}setReferences(e,t){this.ground=e,this.agentMeshes=t,this.agentHitboxes=[];for(const s of t.values()){const i=s.group.getObjectByName("clickHitbox");this.agentHitboxes.push(i??s.group)}}setResizeHandlesGetter(e){this.resizeHandlesGetter=e}setFolderIconMeshesGetter(e){this.folderIconMeshesGetter=e}setCanvas(e){this.canvas=e}raycastGroundFromEvent(e){if(this.updateMouseFromEvent(e),this.raycaster.setFromCamera(this.mouse,this.camera),this.ground){const i=this.raycaster.intersectObject(this.ground);if(i.length>0){const o=i[0].point;return{x:o.x,z:o.z}}}const t=new Fe(new T(0,1,0),0),s=new T;return this.raycaster.ray.intersectPlane(t,s)?{x:s.x,z:s.z}:null}raycastGroundFromPoint(e,t){if(this.updateMouseFromPoint(e,t),this.raycaster.setFromCamera(this.mouse,this.camera),this.ground){const o=this.raycaster.intersectObject(this.ground);if(o.length>0){const n=o[0].point;return{x:n.x,z:n.z}}}const s=new Fe(new T(0,1,0),0),i=new T;return this.raycaster.ray.intersectPlane(s,i)?{x:i.x,z:i.z}:null}checkResizeHandleClick(e){const t=this.resizeHandlesGetter();if(t.length===0)return null;this.updateMouseFromEvent(e),this.raycaster.setFromCamera(this.mouse,this.camera);const s=this.raycaster.intersectObjects(t);return s.length>0?s[0].object:null}checkFolderIconClick(e){const t=this.folderIconMeshesGetter();if(t.length===0)return null;this.updateMouseFromEvent(e),this.raycaster.setFromCamera(this.mouse,this.camera);const s=this.raycaster.intersectObjects(t);return s.length>0?s[0].object:null}findAgentAtPosition(e){if(this.updateMouseFromEvent(e),this.raycaster.setFromCamera(this.mouse,this.camera),this.agentHitboxes.length===0)return null;const t=this.raycaster.intersectObjects(this.agentHitboxes,!1);if(t.length>0){let s=t[0].object;for(;s&&!s.userData.agentId;)s=s.parent;if(s&&s.userData.agentId){const i=s.userData.agentId;return this.isAgentPickable(i)?i:null}}return null}findAgentAtPoint(e,t){if(this.updateMouseFromPoint(e,t),this.raycaster.setFromCamera(this.mouse,this.camera),this.agentHitboxes.length===0)return null;const s=this.raycaster.intersectObjects(this.agentHitboxes,!1);if(s.length>0){let i=s[0].object;for(;i&&!i.userData.agentId;)i=i.parent;if(i&&i.userData.agentId){const o=i.userData.agentId;return this.isAgentPickable(o)?o:null}}return null}isAgentPickable(e){if(!$e())return!0;const t=k.getAreaForAgent(e);return lt((t==null?void 0:t.id)??null)}raycastToPlane(e,t){if(this.mouse.set(e,t),this.raycaster.setFromCamera(this.mouse,this.camera),this.ground){const o=this.raycaster.intersectObject(this.ground);if(o.length>0)return o[0].point}const s=new Fe(new T(0,1,0),0),i=new T;return this.raycaster.ray.intersectPlane(s,i)?i:null}projectToScreen(e){const t=this.canvas.getBoundingClientRect(),s=e.clone().project(this.camera);return{x:(s.x+1)/2*t.width+t.left,y:(-s.y+1)/2*t.height+t.top}}getNormalizedMouseFromEvent(e){return this.updateMouseFromEvent(e),this.mouse.clone()}getNormalizedMouseFromPoint(e,t){return this.updateMouseFromPoint(e,t),this.mouse.clone()}getAgentMeshes(){return this.agentMeshes}updateMouseFromEvent(e){const t=this.canvas.getBoundingClientRect();this.mouse.x=(e.clientX-t.left)/t.width*2-1,this.mouse.y=-((e.clientY-t.top)/t.height)*2+1}updateMouseFromPoint(e,t){const s=this.canvas.getBoundingClientRect();this.mouse.x=(e-s.left)/s.width*2-1,this.mouse.y=-((t-s.top)/s.height)*2+1}}const be=class be{constructor(e,t,s){u(this,"camera");u(this,"controls");u(this,"canvas");u(this,"raycastProvider",null);u(this,"goalCameraPos",null);u(this,"goalOrbitTarget",null);u(this,"panInertiaVelocity",new T);u(this,"lastPanEventTime",0);u(this,"panInertiaActive",!1);this.camera=e,this.controls=t,this.canvas=s}setRaycastProvider(e){this.raycastProvider=e}setControls(e){this.controls=e}setCanvas(e){this.canvas=e}handleWheelZoom(e,t=1){var S,P;this.stopPanInertia(),e.preventDefault();const s=Math.sign(e.deltaY)*Math.min(Math.abs(e.deltaY),100)/100,i=s<0,o=.08*Math.abs(s)*t,n=((S=this.goalOrbitTarget)==null?void 0:S.clone())??this.controls.target.clone(),l=(((P=this.goalCameraPos)==null?void 0:P.clone())??this.camera.position.clone()).clone().sub(n),c=l.length(),d=this.controls.minDistance,h=this.controls.maxDistance,g=i?Math.max(d,c*(1-o)):Math.min(h,c*(1+o));if(g===c)return;let f=null;if(this.raycastProvider){const C=this.raycastProvider.getNormalizedMouseFromEvent(e);f=this.raycastProvider.raycastToPlane(C.x,C.y)}if(!f){const C=l.normalize();this.goalCameraPos=n.clone().add(C.multiplyScalar(g)),this.goalOrbitTarget=n.clone();return}const p=g/c,m=f.clone().sub(n),b=1-p,w=n.clone().add(m.multiplyScalar(b));w.y=Math.max(0,w.y);const M=l.normalize();this.goalCameraPos=w.clone().add(M.multiplyScalar(g)),this.goalOrbitTarget=w}handlePinchZoom(e,t){this.stopPanInertia(),this.goalCameraPos=null,this.goalOrbitTarget=null;const s=this.camera.position.clone().sub(this.controls.target),i=s.length(),o=this.controls.minDistance,n=this.controls.maxDistance,r=Math.max(o,Math.min(n,i*e));if(r===i)return;const l=this.canvas.getBoundingClientRect(),c=(t.x-l.left)/l.width*2-1,d=-((t.y-l.top)/l.height)*2+1;let h=null;if(this.raycastProvider&&(h=this.raycastProvider.raycastToPlane(c,d)),!h){const w=s.normalize();this.camera.position.copy(this.controls.target).add(w.multiplyScalar(r));return}const g=r/i,f=h.clone().sub(this.controls.target),p=1-g,m=this.controls.target.clone().add(f.multiplyScalar(p));m.y=Math.max(0,m.y),this.controls.target.copy(m);const b=s.normalize();this.camera.position.copy(m).add(b.multiplyScalar(r))}handlePan(e,t){this.panInertiaActive=!1,this.goalCameraPos=null,this.goalOrbitTarget=null;const s=new T;this.camera.getWorldDirection(s);const i=new T(-s.z,0,s.x).normalize(),o=new T(s.x,0,s.z).normalize(),r=this.camera.position.distanceTo(this.controls.target)*.005,l=new T;l.add(i.multiplyScalar(-e*r)),l.add(o.multiplyScalar(t*r)),this.controls.target.add(l),this.camera.position.add(l);const c=performance.now(),d=this.lastPanEventTime>0?Math.max(.001,(c-this.lastPanEventTime)/1e3):1/60;this.lastPanEventTime=c,this.panInertiaVelocity.copy(l).divideScalar(d)}handleOrbit(e,t){this.stopPanInertia(),this.goalCameraPos=null,this.goalOrbitTarget=null;const s=.005,i=-e*s,o=-t*s,n=this.camera.position.clone().sub(this.controls.target),r=new je;r.setFromVector3(n),r.theta+=i,r.phi+=o,r.phi=Math.max(.1,Math.min(Math.PI-.1,r.phi)),n.setFromSpherical(r),this.camera.position.copy(this.controls.target).add(n),this.camera.lookAt(this.controls.target)}handleTwistRotation(e){this.stopPanInertia(),this.goalCameraPos=null,this.goalOrbitTarget=null;const t=this.camera.position.clone().sub(this.controls.target),s=new je;s.setFromVector3(t),s.theta+=e,s.phi=Math.max(.1,Math.min(Math.PI-.1,s.phi)),t.setFromSpherical(s),this.camera.position.copy(this.controls.target).add(t),this.camera.lookAt(this.controls.target)}updateSmoothZoom(e){if(this.updatePanInertia(e),!this.goalCameraPos||!this.goalOrbitTarget)return;const t=k.getMouseControls().sensitivity.smoothing;if(t<=0){this.camera.position.copy(this.goalCameraPos),this.controls.target.copy(this.goalOrbitTarget),this.goalCameraPos=null,this.goalOrbitTarget=null;return}const s=$t.lerp(20,3,t),i=1-Math.exp(-s*e);this.camera.position.lerp(this.goalCameraPos,i),this.controls.target.lerp(this.goalOrbitTarget,i),this.camera.position.distanceTo(this.goalCameraPos)<.005&&this.controls.target.distanceTo(this.goalOrbitTarget)<.005&&(this.camera.position.copy(this.goalCameraPos),this.controls.target.copy(this.goalOrbitTarget),this.goalCameraPos=null,this.goalOrbitTarget=null)}get isZoomAnimating(){return this.goalCameraPos!==null}endPanWithInertia(){if(this.lastPanEventTime=0,this.panInertiaVelocity.length()<be.PAN_INERTIA_MIN_SPEED){this.stopPanInertia();return}this.panInertiaActive=!0}stopPanInertia(){this.panInertiaActive=!1,this.panInertiaVelocity.set(0,0,0),this.lastPanEventTime=0}updatePanInertia(e){if(!this.panInertiaActive)return;const t=this.panInertiaVelocity.clone().multiplyScalar(e);this.controls.target.add(t),this.camera.position.add(t);const s=Math.pow(be.PAN_INERTIA_DECAY,e*60);this.panInertiaVelocity.multiplyScalar(s),this.panInertiaVelocity.length()<be.PAN_INERTIA_MIN_SPEED&&this.stopPanInertia()}};u(be,"PAN_INERTIA_DECAY",.9),u(be,"PAN_INERTIA_MIN_SPEED",.6);let dt=be;class Gi{constructor(e,t){u(this,"cameraController");u(this,"callbacks");u(this,"activeDragAction",null);u(this,"activeBinding",null);u(this,"dragStartPos",{x:0,y:0});u(this,"lastDragPos",{x:0,y:0});this.cameraController=e,this.callbacks=t}setCameraController(e){this.cameraController=e}findBinding(e,t){const s=k.getMouseControls(),i=js[t];if(!i)return null;const o=s.bindings.filter(n=>n.enabled&&n.button===i).sort((n,r)=>{const l=Object.values(n.modifiers).filter(Boolean).length;return Object.values(r.modifiers).filter(Boolean).length-l});for(const n of o)if(Ns(e,n.modifiers))return n;return null}isCameraAction(e){return e==="camera-pan"||e==="camera-orbit"||e==="camera-rotate"||e==="camera-tilt"}handlePointerDown(e){const t=this.findBinding(e,e.button);return t?(this.dragStartPos={x:e.clientX,y:e.clientY},this.lastDragPos={x:e.clientX,y:e.clientY},this.isCameraAction(t.action)?(this.activeDragAction=t.action,this.activeBinding=t,!0):!1):!1}handlePointerMove(e){if(!this.activeDragAction||!this.activeBinding)return!1;const t=e.clientX-this.lastDragPos.x,s=e.clientY-this.lastDragPos.y,i=k.getMouseControls().sensitivity;switch(this.activeDragAction){case"camera-pan":{const o=(i.invertPanX?-t:t)*i.panSpeed,n=(i.invertPanY?-s:s)*i.panSpeed;this.cameraController.handlePan(o,n);break}case"camera-orbit":{const o=(i.invertOrbitX?-t:t)*i.orbitSpeed,n=(i.invertOrbitY?-s:s)*i.orbitSpeed;this.cameraController.handleOrbit(o,n);break}case"camera-rotate":this.cameraController.handleOrbit(t*i.orbitSpeed,0);break;case"camera-tilt":this.cameraController.handleOrbit(0,s*i.orbitSpeed);break;case"selection-box":this.callbacks.onSelectionBoxMove(e.clientX,e.clientY);break}return this.lastDragPos={x:e.clientX,y:e.clientY},!0}handlePointerUp(e){const t=this.activeDragAction!==null;return this.activeDragAction==="selection-box"&&this.callbacks.onSelectionBoxEnd(e.clientX,e.clientY),this.activeDragAction=null,this.activeBinding=null,t}handleWheel(e){const t=k.getMouseControls();if(!t.bindings.find(o=>o.enabled&&o.action==="camera-zoom"))return!1;const i=t.sensitivity;return this.cameraController.handleWheelZoom(e,i.zoomSpeed),!0}get isDragging(){return this.activeDragAction!==null}get currentAction(){return this.activeDragAction}cancelDrag(){this.activeDragAction=null,this.activeBinding=null}}const de=class de{constructor(e,t,s,i,o){u(this,"canvas");u(this,"camera");u(this,"controls");u(this,"selectionBox");u(this,"callbacks");u(this,"raycaster");u(this,"cameraController");u(this,"mouseControlHandler");u(this,"trackpadHandler");u(this,"touchHandler");u(this,"agentClickDetector");u(this,"agentTapDetector");u(this,"buildingClickDetector");u(this,"workflowClickDetector");u(this,"areaClickDetector");u(this,"isDragging",!1);u(this,"dragStart",{x:0,y:0});u(this,"dragCurrent",{x:0,y:0});u(this,"pointerDownOnCanvas",!1);u(this,"isRightDragging",!1);u(this,"rightDragStart",{x:0,y:0});u(this,"isDrawing",!1);u(this,"drawingModeChecker",()=>!1);u(this,"isResizing",!1);u(this,"resizeModeChecker",()=>!1);u(this,"areaAtPositionGetter",()=>null);u(this,"buildingAtPositionGetter",()=>null);u(this,"buildingPositionsGetter",()=>new Map);u(this,"workflowAtPositionGetter",()=>null);u(this,"workflowPositionsGetter",()=>new Map);u(this,"isDraggingBuilding",!1);u(this,"draggingBuildingId",null);u(this,"buildingDragStartPos",null);u(this,"isDraggingWorkflow",!1);u(this,"draggingWorkflowId",null);u(this,"workflowDragStartPos",null);u(this,"hoveredAgentId",null);u(this,"hoverTimer",null);u(this,"lastMousePos",{x:0,y:0});u(this,"lastHoverCheckTime",0);u(this,"hoveredBuildingId",null);u(this,"buildingHoverTimer",null);u(this,"hoveredWorkflowId",null);u(this,"workflowHoverTimer",null);u(this,"onPointerDown",e=>{var s,i,o,n,r,l;if(!document.hasFocus()||document.visibilityState==="hidden")return;(i=(s=this.callbacks).onActivity)==null||i.call(s);const t=e.pointerType==="touch";if(e.button===0){this.controls.mouseButtons.LEFT=null;const c=this.raycaster.checkResizeHandleClick(e);if(c){const h=this.raycaster.raycastGroundFromEvent(e);h&&(this.isResizing=!0,t&&this.touchHandler.reset(),(n=(o=this.callbacks).onResizeStart)==null||n.call(o,c,h));return}if(this.drawingModeChecker()){const h=this.raycaster.raycastGroundFromEvent(e);h&&(this.isDrawing=!0,(l=(r=this.callbacks).onDrawStart)==null||l.call(r,h));return}const d=this.raycaster.raycastGroundFromEvent(e);if(d){const h=this.buildingAtPositionGetter(d);if(h&&!t){this.draggingBuildingId=h.id,this.buildingDragStartPos=d,this.isDraggingBuilding=!1;return}const g=this.workflowAtPositionGetter(d);if(g&&!t){this.draggingWorkflowId=g.id,this.workflowDragStartPos=d,this.isDraggingWorkflow=!1;return}}this.isDragging=!1,this.dragStart={x:e.clientX,y:e.clientY},this.dragCurrent={x:e.clientX,y:e.clientY},this.pointerDownOnCanvas=!0}if(e.button===2){if(this.mouseControlHandler.handlePointerDown(e)){this.controls.mouseButtons.RIGHT=null;return}this.controls.mouseButtons.RIGHT=null,this.isRightDragging=!1,this.rightDragStart={x:e.clientX,y:e.clientY}}if(e.button===1&&this.mouseControlHandler.handlePointerDown(e)){this.controls.mouseButtons.MIDDLE=null;return}});u(this,"onPointerMove",e=>{var t,s,i,o,n,r,l,c,d,h,g,f;if(!document.hasFocus()||document.hidden){this.isDragging&&(this.isDragging=!1,this.selectionBox.classList.remove("active"),this.pointerDownOnCanvas=!1);return}if(e.buttons&1){if(this.isResizing){const b=this.raycaster.raycastGroundFromEvent(e);b&&((s=(t=this.callbacks).onResizeMove)==null||s.call(t,b));return}if(this.isDrawing){const b=this.raycaster.raycastGroundFromEvent(e);b&&((o=(i=this.callbacks).onDrawMove)==null||o.call(i,b));return}if(this.draggingBuildingId&&this.buildingDragStartPos){const b=this.raycaster.raycastGroundFromEvent(e);if(b){const w=b.x-this.buildingDragStartPos.x,M=b.z-this.buildingDragStartPos.z,S=Math.sqrt(w*w+M*M);!this.isDraggingBuilding&&S>.2&&(this.isDraggingBuilding=!0,(r=(n=this.callbacks).onBuildingDragStart)==null||r.call(n,this.draggingBuildingId,this.buildingDragStartPos)),this.isDraggingBuilding&&((c=(l=this.callbacks).onBuildingDragMove)==null||c.call(l,this.draggingBuildingId,b))}return}if(this.draggingWorkflowId&&this.workflowDragStartPos){const b=this.raycaster.raycastGroundFromEvent(e);if(b){const w=b.x-this.workflowDragStartPos.x,M=b.z-this.workflowDragStartPos.z,S=Math.sqrt(w*w+M*M);!this.isDraggingWorkflow&&S>.2&&(this.isDraggingWorkflow=!0,(h=(d=this.callbacks).onWorkflowDragStart)==null||h.call(d,this.draggingWorkflowId,this.workflowDragStartPos)),this.isDraggingWorkflow&&((f=(g=this.callbacks).onWorkflowDragMove)==null||f.call(g,this.draggingWorkflowId,b))}return}if(e.pointerType==="touch"||!this.pointerDownOnCanvas||k.getState().terminalResizing)return;const p=e.clientX-this.dragStart.x,m=e.clientY-this.dragStart.y;!this.isDragging&&(Math.abs(p)>Ce||Math.abs(m)>Ce)&&(this.isDragging=!0,this.selectionBox.classList.add("active")),this.isDragging&&(this.dragCurrent={x:e.clientX,y:e.clientY},this.updateSelectionBox())}if(e.buttons&2){if(this.mouseControlHandler.handlePointerMove(e))return;const p=e.clientX-this.rightDragStart.x,m=e.clientY-this.rightDragStart.y;!this.isRightDragging&&(Math.abs(p)>Ce||Math.abs(m)>Ce)&&(this.isRightDragging=!0)}if(!(e.buttons&4&&this.mouseControlHandler.handlePointerMove(e))&&e.buttons===0&&e.pointerType!=="touch"){const p=performance.now();p-this.lastHoverCheckTime>de.HOVER_CHECK_INTERVAL&&(this.handleHoverDetection(e),this.lastHoverCheckTime=p)}});u(this,"onPointerUp",e=>{var t,s,i,o,n,r,l,c;if(e.button===0){if(this.controls.mouseButtons.LEFT=null,e.pointerType==="touch"&&!this.isDrawing&&!this.isResizing){this.pointerDownOnCanvas=!1;return}if(this.isResizing){(s=(t=this.callbacks).onResizeEnd)==null||s.call(t),this.isResizing=!1;return}if(this.isDrawing){const d=this.raycaster.raycastGroundFromEvent(e);d&&((o=(i=this.callbacks).onDrawEnd)==null||o.call(i,d)),this.isDrawing=!1;return}if(this.draggingBuildingId){const d=this.draggingBuildingId,h=this.raycaster.raycastGroundFromEvent(e),g={x:e.clientX,y:e.clientY};this.isDraggingBuilding&&h?(r=(n=this.callbacks).onBuildingDragEnd)==null||r.call(n,d,h):this.handleBuildingClick(d,g),this.draggingBuildingId=null,this.buildingDragStartPos=null,this.isDraggingBuilding=!1;return}if(this.draggingWorkflowId){const d=this.draggingWorkflowId,h=this.raycaster.raycastGroundFromEvent(e),g={x:e.clientX,y:e.clientY};this.isDraggingWorkflow&&h?(c=(l=this.callbacks).onWorkflowDragEnd)==null||c.call(l,d,h):this.handleWorkflowClick(d,g),this.draggingWorkflowId=null,this.workflowDragStartPos=null,this.isDraggingWorkflow=!1;return}if(this.isDragging){this.isDragging=!1,this.selectionBox.classList.remove("active");const d=Math.sqrt(Math.pow(this.dragCurrent.x-this.dragStart.x,2)+Math.pow(this.dragCurrent.y-this.dragStart.y,2));console.log("[3D InputHandler] pointerUp isDragging",{dragDist:d,shiftKey:e.shiftKey,ctrlKey:e.ctrlKey}),d<15?this.handleSingleClick(e):this.selectAgentsInBox(this.dragStart,this.dragCurrent,e.shiftKey)}else e.ctrlKey?console.log("[3D InputHandler] pointerUp BLOCKED by ctrlKey",{shiftKey:e.shiftKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey}):(console.log("[3D InputHandler] pointerUp singleClick",{shiftKey:e.shiftKey,ctrlKey:e.ctrlKey}),this.handleSingleClick(e));this.pointerDownOnCanvas=!1}e.button===2&&(this.mouseControlHandler.handlePointerUp(e),this.controls.mouseButtons.RIGHT=null,this.isRightDragging=!1),e.button===1&&(this.mouseControlHandler.handlePointerUp(e),this.controls.mouseButtons.MIDDLE=null)});u(this,"onPointerCancel",e=>{this.touchHandler.onPointerCancel(e.pointerId)});u(this,"onPointerLeave",e=>{this.clearHoverState(),this.clearBuildingHoverState(),this.clearWorkflowHoverState()});u(this,"onWindowBlur",()=>{this.cancelAllDragStates()});u(this,"onVisibilityChange",()=>{document.hidden&&this.cancelAllDragStates()});u(this,"onKeyDown",e=>{var g,f;const t=e.target,s=k.getState(),i=t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable,o=t.closest(".guake-terminal"),n=o==null?void 0:o.classList.contains("collapsed"),r=k.getShortcuts(),l=r.find(p=>p.id==="toggle-spotlight"),c=r.find(p=>p.id==="next-agent"),d=r.find(p=>p.id==="prev-agent"),h=r.find(p=>p.id==="open-terminal");if(!he(e,l)){if(i){const p=k.getShortcuts();if((he(e,p.find(b=>b.id==="next-agent"))||he(e,p.find(b=>b.id==="prev-agent"))||he(e,p.find(b=>b.id==="next-working-agent"))||he(e,p.find(b=>b.id==="prev-working-agent")))&&n)t.blur();else if(he(e,h)&&n)t.blur();else return}if((he(e,c)||he(e,d))&&!s.terminalOpen){const p=this.getOrderedAgents(s.agents);if(p.length<=1)return;const m=s.selectedAgentIds.size===1?Array.from(s.selectedAgentIds)[0]:null,b=m?p.findIndex(M=>M.id===m):-1;let w;he(e,c)?w=b===-1?0:(b+1)%p.length:w=b===-1?p.length-1:(b-1+p.length)%p.length,e.preventDefault(),k.selectAgent(p[w].id),(f=(g=this.callbacks).onActivity)==null||f.call(g);return}if(he(e,h)){if(o&&!n||t.tagName==="BUTTON"||t.tagName==="A")return;if(s.terminalOpen)if(o&&n)k.setTerminalOpen(!1);else return;const p=document.querySelector(".guake-terminal");if(p&&p.classList.contains("collapsed")&&s.terminalOpen&&k.setTerminalOpen(!1),s.selectedBuildingIds.size>0||s.selectedAreaId!==null)return;if(s.selectedAgentIds.size===0){const m=s.lastSelectedAgentId;m&&s.agents.has(m)&&(e.preventDefault(),k.selectAgent(m),k.setTerminalOpen(!0));return}e.preventDefault(),k.setTerminalOpen(!0)}}});u(this,"onContextMenu",e=>{var i,o;if(e.preventDefault(),e.altKey)return;if(this.controls.mouseButtons.RIGHT=null,this.isRightDragging){this.isRightDragging=!1;return}const t=k.getState(),s=this.raycaster.raycastGroundFromEvent(e);if(s){if(t.selectedAgentIds.size>0){this.callbacks.onAreaRightClick&&this.callbacks.onAreaRightClick(s);const n=Array.from(t.selectedAgentIds),r=new T(s.x,0,s.z);this.callbacks.onMoveCommand(r,n);return}if(this.callbacks.onContextMenu){const n=this.raycaster.findAgentAtPosition(e),r=(i=this.areaAtPositionGetter)==null?void 0:i.call(this,s),l=(o=this.buildingAtPositionGetter)==null?void 0:o.call(this,s);let c;n?c={type:"agent",id:n}:l?c={type:"building",id:l.id}:r?c={type:"area",id:r.id}:c={type:"ground"},this.callbacks.onContextMenu({x:e.clientX,y:e.clientY},s,c)}}});u(this,"onWheel",e=>{var t,s;(s=(t=this.callbacks).onActivity)==null||s.call(t),!this.trackpadHandler.handleWheel(e)&&this.mouseControlHandler.handleWheel(e)});u(this,"onTouchStart",e=>{if(this.cameraController.stopPanInertia(),this.drawingModeChecker()){e.preventDefault();return}this.touchHandler.onTouchStart(e)});u(this,"onTouchMove",e=>{if(this.isDrawing||this.isResizing){e.preventDefault();return}this.touchHandler.onTouchMove(e)});u(this,"onTouchEnd",e=>{this.isDrawing||this.isResizing||this.touchHandler.onTouchEnd(e)});u(this,"handleTouchTap",(e,t)=>{var o,n,r,l,c,d;const s=this.raycaster.findAgentAtPoint(e,t);if(s){this.agentTapDetector.handleClick(s)==="double"?this.callbacks.onAgentDoubleClick(s):this.callbacks.onAgentClick(s,!1);return}const i=this.raycaster.raycastGroundFromPoint(e,t);if(i){const h=this.buildingAtPositionGetter(i);if(h){const p={x:e,y:t};this.handleBuildingClick(h.id,p);return}const g=this.workflowAtPositionGetter(i);if(g){const p={x:e,y:t};this.handleWorkflowClick(g.id,p);return}const f=this.areaAtPositionGetter(i);if(f){this.areaClickDetector.handleClick(f.id)==="double"?(n=(o=this.callbacks).onAreaDoubleClick)==null||n.call(o,f.id):(l=(r=this.callbacks).onAreaClick)==null||l.call(r,f.id);return}}this.agentClickDetector.reset(),this.callbacks.onGroundClick(),(d=(c=this.callbacks).onGroundClickOutsideArea)==null||d.call(c)});u(this,"handleLongPress",(e,t)=>{var c,d,h;const s=k.getState(),i=this.raycaster.raycastGroundFromPoint(e,t);if(!i)return;const o=this.raycaster.findAgentAtPoint(e,t);if(o){this.callbacks.onContextMenu&&this.callbacks.onContextMenu({x:e,y:t},i,{type:"agent",id:o});return}const n=(c=this.buildingAtPositionGetter)==null?void 0:c.call(this,i);if(n){this.callbacks.onContextMenu&&this.callbacks.onContextMenu({x:e,y:t},i,{type:"building",id:n.id});return}const r=(d=this.workflowAtPositionGetter)==null?void 0:d.call(this,i);if(r){this.callbacks.onContextMenu&&this.callbacks.onContextMenu({x:e,y:t},i,{type:"building",id:r.id});return}const l=(h=this.areaAtPositionGetter)==null?void 0:h.call(this,i);if(l){this.callbacks.onContextMenu&&this.callbacks.onContextMenu({x:e,y:t},i,{type:"area",id:l.id});return}if(s.selectedAgentIds.size>0){const g=Array.from(s.selectedAgentIds),f=new T(i.x,0,i.z);this.callbacks.onMoveCommand(f,g);return}this.callbacks.onContextMenu&&this.callbacks.onContextMenu({x:e,y:t},i,{type:"ground"})});this.canvas=e,this.camera=t,this.controls=s,this.selectionBox=i,this.callbacks=o,this.raycaster=new zi(t,e),this.cameraController=new dt(t,s,e),this.cameraController.setRaycastProvider(this.raycaster),this.mouseControlHandler=new Gi(this.cameraController,{onSelectionBoxStart:(n,r)=>{this.dragStart={x:n,y:r},this.dragCurrent={x:n,y:r},this.isDragging=!0,this.selectionBox.classList.add("active")},onSelectionBoxMove:(n,r)=>{this.dragCurrent={x:n,y:r},this.updateSelectionBox()},onSelectionBoxEnd:(n,r)=>{this.isDragging=!1,this.selectionBox.classList.remove("active"),this.selectAgentsInBox(this.dragStart,{x:n,y:r},!1)}}),this.trackpadHandler=new Oi(this.cameraController,e,{onPan:(n,r)=>{this.cameraController.handlePan(n,r)},onZoom:(n,r,l)=>{const c=1-n;this.cameraController.handlePinchZoom(c,{x:r,y:l})},onOrbit:(n,r)=>{this.cameraController.handleOrbit(n,r)}}),this.agentClickDetector=new Te(300),this.agentTapDetector=new Te(450),this.buildingClickDetector=new Te(300),this.workflowClickDetector=new Te(300),this.areaClickDetector=new Te(300),this.touchHandler=new ht(e,s,{onTap:this.handleTouchTap,onLongPress:this.handleLongPress,onPan:(n,r)=>this.cameraController.handlePan(n,r),onPanEnd:()=>this.cameraController.endPanWithInertia(),onPinchZoom:(n,r)=>this.cameraController.handlePinchZoom(n,r),onOrbit:(n,r)=>this.cameraController.handleOrbit(n,r),onRotation:n=>this.cameraController.handleTwistRotation(n)}),this.setupEventListeners()}setReferences(e,t){this.raycaster.setReferences(e,t)}setDrawingModeChecker(e){this.drawingModeChecker=e}setResizeHandlers(e,t){this.raycaster.setResizeHandlesGetter(e),this.resizeModeChecker=t}setFolderIconMeshesGetter(e){this.raycaster.setFolderIconMeshesGetter(e)}setAreaAtPositionGetter(e){this.areaAtPositionGetter=e}setBuildingAtPositionGetter(e){this.buildingAtPositionGetter=e}setBuildingPositionsGetter(e){this.buildingPositionsGetter=e}setWorkflowAtPositionGetter(e){this.workflowAtPositionGetter=e}setWorkflowPositionsGetter(e){this.workflowPositionsGetter=e}raycastGround(e){return this.raycaster.raycastGroundFromEvent(e)}dispose(){this.canvas.removeEventListener("pointerdown",this.onPointerDown,!0),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerCancel),this.canvas.removeEventListener("pointerleave",this.onPointerLeave),this.canvas.removeEventListener("contextmenu",this.onContextMenu),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("touchstart",this.onTouchStart),this.canvas.removeEventListener("touchmove",this.onTouchMove),this.canvas.removeEventListener("touchend",this.onTouchEnd),this.agentClickDetector.dispose(),this.agentTapDetector.dispose(),this.buildingClickDetector.dispose(),this.workflowClickDetector.dispose(),this.areaClickDetector.dispose(),this.touchHandler.dispose(),this.trackpadHandler.dispose(),this.clearHoverTimer(),this.clearBuildingHoverTimer(),this.clearWorkflowHoverTimer(),window.removeEventListener("blur",this.onWindowBlur),document.removeEventListener("visibilitychange",this.onVisibilityChange),document.removeEventListener("keydown",this.onKeyDown,!0)}reattach(e,t,s){this.dispose(),this.canvas=e,this.selectionBox=t,this.controls=s,this.raycaster.setCanvas(e),this.cameraController.setCanvas(e),this.cameraController.setControls(s),this.mouseControlHandler.setCameraController(this.cameraController),this.trackpadHandler.setCameraController(this.cameraController),this.trackpadHandler.setCanvas(e),this.touchHandler.reattach(e,s),this.setupEventListeners()}updateSmoothZoom(e){this.cameraController.updateSmoothZoom(e)}get isZoomAnimating(){return this.cameraController.isZoomAnimating}calculateFormationPositions(e,t){const s=[];if(t===1)return[{x:e.x,y:0,z:e.z}];if(t<=6){const i=Be*Math.max(1,t/3);for(let o=0;o<t;o++){const n=o/t*Math.PI*2-Math.PI/2;s.push({x:e.x+Math.cos(n)*i,y:0,z:e.z+Math.sin(n)*i})}}else{const i=Math.ceil(Math.sqrt(t)),o=Math.ceil(t/i),n=(i-1)*Be/2,r=(o-1)*Be/2;for(let l=0;l<t;l++){const c=l%i,d=Math.floor(l/i);s.push({x:e.x+c*Be-n,y:0,z:e.z+d*Be-r})}}return s}setupEventListeners(){this.canvas.addEventListener("pointerdown",this.onPointerDown,!0),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerCancel),this.canvas.addEventListener("pointerleave",this.onPointerLeave),this.canvas.addEventListener("contextmenu",this.onContextMenu),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("touchstart",this.onTouchStart,{passive:!1}),this.canvas.addEventListener("touchmove",this.onTouchMove,{passive:!1}),this.canvas.addEventListener("touchend",this.onTouchEnd,{passive:!1}),window.addEventListener("blur",this.onWindowBlur),document.addEventListener("visibilitychange",this.onVisibilityChange),document.addEventListener("keydown",this.onKeyDown,!0)}cancelAllDragStates(){this.clearHoverState(),this.clearBuildingHoverState(),this.clearWorkflowHoverState(),this.isDragging&&(this.isDragging=!1,this.selectionBox.classList.remove("active")),this.pointerDownOnCanvas=!1}clearHoverState(){var e,t;this.clearHoverTimer(),this.hoveredAgentId!==null&&(this.hoveredAgentId=null,(t=(e=this.callbacks).onAgentHover)==null||t.call(e,null,null))}handleSingleClick(e){var o,n,r,l,c,d,h,g;console.log("[3D InputHandler] handleSingleClick",{shiftKey:e.shiftKey,pointerType:e.pointerType,button:e.button});const t=this.raycaster.checkFolderIconClick(e);if(t){const f=t.userData.areaId,p=t.userData.folderPath;if(f){(n=(o=this.callbacks).onFolderIconClick)==null||n.call(o,f,p);return}}const s=this.raycaster.findAgentAtPosition(e);if(console.log("[3D InputHandler] handleSingleClick agentId:",s,"shiftKey:",e.shiftKey),s){this.agentClickDetector.handleClick(s)==="double"?this.callbacks.onAgentDoubleClick(s):(console.log("[3D InputHandler] calling onAgentClick",{agentId:s,shiftKey:e.shiftKey}),this.callbacks.onAgentClick(s,e.shiftKey));return}this.agentClickDetector.reset();const i=this.raycaster.raycastGroundFromEvent(e);if(i){const f=this.areaAtPositionGetter(i);if(f){this.areaClickDetector.handleClick(f.id)==="double"?(l=(r=this.callbacks).onAreaDoubleClick)==null||l.call(r,f.id):(d=(c=this.callbacks).onAreaClick)==null||d.call(c,f.id);return}}this.areaClickDetector.reset(),e.shiftKey||(this.callbacks.onGroundClick(),(g=(h=this.callbacks).onGroundClickOutsideArea)==null||g.call(h))}handleBuildingClick(e,t){var i,o,n,r;if(this.buildingClickDetector.handleClick(e)==="double")(o=(i=this.callbacks).onBuildingDoubleClick)==null||o.call(i,e);else{const l=t||{x:window.innerWidth/2,y:window.innerHeight/2};(r=(n=this.callbacks).onBuildingClick)==null||r.call(n,e,l)}}handleWorkflowClick(e,t){var i,o,n,r;if(this.workflowClickDetector.handleClick(e)==="double")(o=(i=this.callbacks).onWorkflowDoubleClick)==null||o.call(i,e);else{const l=t||{x:window.innerWidth/2,y:window.innerHeight/2};(r=(n=this.callbacks).onWorkflowClick)==null||r.call(n,e,l)}}updateSelectionBox(){const e=Math.min(this.dragStart.x,this.dragCurrent.x),t=Math.min(this.dragStart.y,this.dragCurrent.y),s=Math.abs(this.dragCurrent.x-this.dragStart.x),i=Math.abs(this.dragCurrent.y-this.dragStart.y);this.selectionBox.style.left=`${e}px`,this.selectionBox.style.top=`${t}px`,this.selectionBox.style.width=`${s}px`,this.selectionBox.style.height=`${i}px`}selectAgentsInBox(e,t,s=!1){this.canvas.getBoundingClientRect();const i=Math.min(e.x,t.x),o=Math.max(e.x,t.x),n=Math.min(e.y,t.y),r=Math.max(e.y,t.y),l=[],c=[];for(const[h,g]of this.raycaster.getAgentMeshes()){const f=this.raycaster.projectToScreen(g.group.position);f.x>=i&&f.x<=o&&f.y>=n&&f.y<=r&&l.push(h)}const d=this.buildingPositionsGetter();for(const[h,g]of d){const f=this.raycaster.projectToScreen(g);f.x>=i&&f.x<=o&&f.y>=n&&f.y<=r&&c.push(h)}this.callbacks.onSelectionBox(l,c,s)}handleHoverDetection(e){var l,c,d,h,g,f;this.lastMousePos={x:e.clientX,y:e.clientY};const t=this.raycaster.findAgentAtPosition(e);t!==this.hoveredAgentId&&(this.clearHoverTimer(),this.hoveredAgentId!==null&&((c=(l=this.callbacks).onAgentHover)==null||c.call(l,null,null)),this.hoveredAgentId=t,t&&(this.hoverTimer=setTimeout(()=>{this.triggerHoverCallback()},de.HOVER_DELAY)));const s=this.raycaster.raycastGroundFromEvent(e),i=s?this.buildingAtPositionGetter(s):null,o=(i==null?void 0:i.id)??null,n=s?this.workflowAtPositionGetter(s):null,r=(n==null?void 0:n.id)??null;r!==this.hoveredWorkflowId&&(this.clearWorkflowHoverTimer(),this.hoveredWorkflowId!==null&&((h=(d=this.callbacks).onWorkflowHover)==null||h.call(d,null,null)),this.hoveredWorkflowId=r,r&&(this.workflowHoverTimer=setTimeout(()=>{this.triggerWorkflowHoverCallback()},de.WORKFLOW_HOVER_DELAY))),o!==this.hoveredBuildingId&&(this.clearBuildingHoverTimer(),this.hoveredBuildingId!==null&&((f=(g=this.callbacks).onBuildingHover)==null||f.call(g,null,null)),this.hoveredBuildingId=o,o&&(this.buildingHoverTimer=setTimeout(()=>{this.triggerBuildingHoverCallback()},de.BUILDING_HOVER_DELAY)))}triggerHoverCallback(){if(this.hoveredAgentId&&this.callbacks.onAgentHover){const e=this.raycaster.getAgentMeshes().get(this.hoveredAgentId);if(e){const t=this.raycaster.projectToScreen(e.group.position);this.callbacks.onAgentHover(this.hoveredAgentId,t)}}}clearHoverTimer(){this.hoverTimer&&(clearTimeout(this.hoverTimer),this.hoverTimer=null)}triggerBuildingHoverCallback(){if(this.hoveredBuildingId&&this.callbacks.onBuildingHover){const t=this.buildingPositionsGetter().get(this.hoveredBuildingId);if(t){const s=this.raycaster.projectToScreen(t);this.callbacks.onBuildingHover(this.hoveredBuildingId,s)}}}clearBuildingHoverTimer(){this.buildingHoverTimer&&(clearTimeout(this.buildingHoverTimer),this.buildingHoverTimer=null)}clearBuildingHoverState(){var e,t;this.clearBuildingHoverTimer(),this.hoveredBuildingId!==null&&(this.hoveredBuildingId=null,(t=(e=this.callbacks).onBuildingHover)==null||t.call(e,null,null))}triggerWorkflowHoverCallback(){if(this.hoveredWorkflowId&&this.callbacks.onWorkflowHover){const t=this.workflowPositionsGetter().get(this.hoveredWorkflowId);if(t){const s=this.raycaster.projectToScreen(t);this.callbacks.onWorkflowHover(this.hoveredWorkflowId,s)}}}clearWorkflowHoverTimer(){this.workflowHoverTimer&&(clearTimeout(this.workflowHoverTimer),this.workflowHoverTimer=null)}clearWorkflowHoverState(){var e,t;this.clearWorkflowHoverTimer(),this.hoveredWorkflowId!==null&&(this.hoveredWorkflowId=null,(t=(e=this.callbacks).onWorkflowHover)==null||t.call(e,null,null))}getOrderedAgents(e){const t=Array.from(e.values()),s=new Set(t.map(f=>f.id)),o=$s(Us.AGENT_ORDER,[]).filter(f=>s.has(f)),r=t.filter(f=>!o.includes(f.id)).sort((f,p)=>(f.createdAt||0)-(p.createdAt||0)).map(f=>f.id),l=[...o,...r],c=new Map(t.map(f=>[f.id,f])),d=l.map(f=>c.get(f)).filter(f=>f!==void 0),h=new Map;for(const f of d){const p=k.getAreaForAgent(f.id),m=(p==null?void 0:p.id)||null;h.has(m)||h.set(m,{area:p?{name:p.name}:null,agents:[]}),h.get(m).agents.push(f)}const g=Array.from(h.values());return g.sort((f,p)=>{var m,b;return!f.area&&p.area?1:f.area&&!p.area?-1:!f.area&&!p.area?0:(((m=f.area)==null?void 0:m.name)||"").localeCompare(((b=p.area)==null?void 0:b.name)||"")}),g.flatMap(f=>f.agents)}};u(de,"HOVER_DELAY",400),u(de,"HOVER_CHECK_INTERVAL",50),u(de,"BUILDING_HOVER_DELAY",5e3),u(de,"WORKFLOW_HOVER_DELAY",5e3);let ut=de;class Ri{constructor(e){u(this,"scene");u(this,"areaMeshes",new Map);u(this,"previewMesh",null);u(this,"isDrawing",!1);u(this,"drawStartPos",null);u(this,"currentTool",null);u(this,"resizeHandles",[]);u(this,"selectedAreaId",null);u(this,"isResizing",!1);u(this,"resizeHandleType",null);u(this,"resizeStartPos",null);u(this,"resizeOriginalArea",null);u(this,"areaDragAgentStartPositions",new Map);u(this,"areaDragBuildingStartPositions",new Map);u(this,"onAreaCreated",null);u(this,"onFolderIconClick",null);u(this,"folderIconMeshes",[]);u(this,"brightness",1);u(this,"logoTextures",new Map);u(this,"loadingLogoTextures",new Set);this.scene=e}setOnAreaCreated(e){this.onAreaCreated=e}setOnFolderIconClick(e){this.onFolderIconClick=e}getFolderIconMeshes(){return this.folderIconMeshes}handleFolderIconClick(e){const t=e.userData.areaId,s=e.userData.folderPath;t&&this.onFolderIconClick&&this.onFolderIconClick(t,s)}setBrightness(e){this.brightness=e;for(const[t,s]of this.areaMeshes){const i=t===this.selectedAreaId;s.traverse(o=>{if(o instanceof y&&o.name!=="resizeHandle"&&o.name!=="areaLogo"){const n=o.material,r=i?.3:.15;n.opacity=r*this.brightness}})}}setTool(e){this.currentTool=e,(!e||e==="select")&&this.cancelDrawing()}getTool(){return this.currentTool}isInDrawingMode(){return this.currentTool==="rectangle"||this.currentTool==="circle"}startDrawing(e){this.isInDrawingMode()&&(this.isDrawing=!0,this.drawStartPos=e,this.createPreview(e))}updateDrawing(e){!this.isDrawing||!this.drawStartPos||!this.previewMesh||this.updatePreview(e)}finishDrawing(e){var s;if(!this.isDrawing||!this.drawStartPos)return this.cancelDrawing(),null;const t=this.createAreaFromDraw(this.drawStartPos,e);return this.cancelDrawing(),t&&(k.addArea(t),this.renderArea(t),(s=this.onAreaCreated)==null||s.call(this,t)),t}cancelDrawing(){this.isDrawing=!1,this.drawStartPos=null,this.previewMesh&&(this.scene.remove(this.previewMesh),this.disposeGroup(this.previewMesh),this.previewMesh=null)}isCurrentlyDrawing(){return this.isDrawing}renderAllAreas(){const e=k.getState();for(const t of e.areas.values()){if(t.archived){this.areaMeshes.has(t.id)&&this.removeAreaMesh(t.id);continue}this.areaMeshes.has(t.id)||this.renderArea(t)}}renderArea(e){var n;this.removeAreaMesh(e.id);const t=new Y;t.userData.areaId=e.id,t.userData.zIndex=e.zIndex??0;const s=new H(e.color),i=(e.zIndex??0)*.001;if(e.type==="rectangle"&&e.width&&e.height){const r=new pe(e.width,e.height),l=new v({color:s,transparent:!0,opacity:.15*this.brightness,side:oe}),c=new y(r,l);c.rotation.x=-Math.PI/2,c.position.y=.02+i,t.add(c);const d=[new T(-e.width/2,0,-e.height/2),new T(e.width/2,0,-e.height/2),new T(e.width/2,0,e.height/2),new T(-e.width/2,0,e.height/2),new T(-e.width/2,0,-e.height/2)],h=new le().setFromPoints(d),g=new ge({color:s,linewidth:2}),f=new ce(h,g);f.position.y=.03+i,t.add(f)}else if(e.type==="circle"&&e.radius){const r=new yt(e.radius,32),l=new v({color:s,transparent:!0,opacity:.15*this.brightness,side:oe}),c=new y(r,l);c.rotation.x=-Math.PI/2,c.position.y=.02+i,t.add(c);const d=[];for(let p=0;p<=32;p++){const m=p/32*Math.PI*2;d.push(new T(Math.cos(m)*e.radius,0,Math.sin(m)*e.radius))}const h=new le().setFromPoints(d),g=new ge({color:s,linewidth:2}),f=new ce(h,g);f.position.y=.03+i,t.add(f)}const o=this.createTextLabel(e.name,e.color);if(o.position.y=.05+i,o.name="areaLabel",t.add(o),e.directories&&e.directories.length>0){let c=0,d=0,h=3;if(e.type==="rectangle"&&e.width&&e.height)c=-e.width/2+.4,d=-e.height/2+.4,h=Math.max(1,Math.floor((e.width-.6)/.81));else if(e.type==="circle"&&e.radius){const g=e.radius*.707;c=-g+.3,d=-g+.3,h=Math.max(1,Math.floor((e.radius*1.414-.5)/.81))}e.directories.forEach((g,f)=>{var C;const p=Math.floor(f/h),m=f%h,b=((C=e.directoryGitCounts)==null?void 0:C[f])??0,w=this.createFolderIconSprite(e.color,b);w.name="folderIcon",w.userData.areaId=e.id,w.userData.folderPath=g,w.userData.isFolderIcon=!0,w.position.set(c+m*.81,.3+i,d+p*.81),t.add(w);const M=new O(.3,8,8),S=new v({visible:!1}),P=new y(M,S);P.position.copy(w.position),P.position.x+=e.center.x,P.position.z+=e.center.z,P.name="folderIconHit",P.userData.areaId=e.id,P.userData.folderPath=g,P.userData.isFolderIcon=!0,this.scene.add(P),this.folderIconMeshes.push(P)})}(n=e.logo)!=null&&n.filename&&this.addLogoToGroup(t,e,i),t.position.set(e.center.x,0,e.center.z),this.scene.add(t),this.areaMeshes.set(e.id,t)}createTextLabel(e,t){const s=document.createElement("canvas"),i=s.getContext("2d"),o=32,n=20,r=64;s.width=1024,s.height=r,i.font=`bold ${o}px Arial`;const l=i.measureText(e).width,c=256;s.width=Math.max(c,l+n*2),i.clearRect(0,0,s.width,s.height),i.font=`bold ${o}px Arial`,i.textAlign="center",i.textBaseline="middle",i.strokeStyle="#000000",i.lineWidth=4,i.strokeText(e,s.width/2,s.height/2),i.fillStyle=t,i.fillText(e,s.width/2,s.height/2);const d=new se(s);d.needsUpdate=!0;const h=new J({map:d,transparent:!0,depthTest:!1}),g=new K(h),f=.5,p=2*(s.width/256);return g.scale.set(p,f,1),g}createFolderIconSprite(e,t=0){const s=document.createElement("canvas"),i=128;s.width=i,s.height=i;const o=s.getContext("2d");o.fillStyle="rgba(0, 0, 0, 0.6)",o.beginPath(),o.arc(i/2,i/2,i*.45,0,Math.PI*2),o.fill(),o.strokeStyle=e,o.lineWidth=3,o.beginPath(),o.arc(i/2,i/2,i*.45,0,Math.PI*2),o.stroke();const n=i*.5,r=i*.35,l=(i-n)/2,c=(i-r)/2+2,d=n*.35,h=r*.22;if(o.fillStyle=e,o.beginPath(),o.moveTo(l+4,c+h),o.lineTo(l+d,c+h),o.lineTo(l+d+h,c),o.lineTo(l+4,c),o.moveTo(l,c+h),o.lineTo(l,c+r),o.lineTo(l+n,c+r),o.lineTo(l+n,c+h),o.closePath(),o.fill(),o.strokeStyle="rgba(255, 255, 255, 0.3)",o.lineWidth=1.5,o.beginPath(),o.moveTo(l+4,c+h+3),o.lineTo(l+n-4,c+h+3),o.stroke(),t>0){const m=i*.16,b=i*.78,w=i*.78;o.fillStyle="#e8943a",o.beginPath(),o.arc(b,w,m,0,Math.PI*2),o.fill(),o.strokeStyle="rgba(0, 0, 0, 0.7)",o.lineWidth=2,o.beginPath(),o.arc(b,w,m,0,Math.PI*2),o.stroke();const M=t>99?"99+":String(t),S=m*1.3;o.font=`bold ${S}px "Segoe UI", Arial, sans-serif`,o.fillStyle="#ffffff",o.textAlign="center",o.textBaseline="middle",o.fillText(M,b,w)}const g=new se(s);g.needsUpdate=!0;const f=new J({map:g,transparent:!0,depthTest:!1}),p=new K(f);return p.scale.set(.6,.6,1),p}addLogoToGroup(e,t,s){const i=t.logo,o=Vt(Zt(`/api/areas/logos/${i.filename}`)),n=this.logoTextures.get(i.filename);if(n){this.createLogoMesh(e,t,n,s);return}if(this.loadingLogoTextures.has(i.filename))return;this.loadingLogoTextures.add(i.filename);const r=t.id;new Nt().load(o,c=>{var g;this.logoTextures.set(i.filename,c),this.loadingLogoTextures.delete(i.filename);const d=this.areaMeshes.get(r),h=k.getState().areas.get(r);if(d&&((g=h==null?void 0:h.logo)!=null&&g.filename)){const f=(h.zIndex??0)*.001;this.createLogoMesh(d,h,c,f)}},void 0,()=>{this.loadingLogoTextures.delete(i.filename)})}createLogoMesh(e,t,s,i){const o=t.logo,n=new pe(o.width,o.height),r=new v({map:s,transparent:!0,opacity:o.opacity??.8,side:oe,depthWrite:!0,alphaTest:.01}),l=new y(n,r);l.rotation.x=-Math.PI/2,l.name="areaLogo",l.renderOrder=-1;const c=this.calculateLogoOffset(t,o.position,o.width,o.height);l.position.set(c.x,.04+i,c.z),e.add(l)}calculateLogoOffset(e,t,s,i){if(t==="center")return{x:0,z:0};let o=0,n=0;e.type==="rectangle"&&e.width&&e.height?(o=e.width,n=e.height):e.type==="circle"&&e.radius&&(o=e.radius*1.414,n=e.radius*1.414);const r=s/2+.2,l=i/2+.2;switch(t){case"top-left":return{x:-o/2+r,z:-n/2+l};case"top-right":return{x:o/2-r,z:-n/2+l};case"bottom-left":return{x:-o/2+r,z:n/2-l};case"bottom-right":return{x:o/2-r,z:n/2-l};default:return{x:0,z:0}}}updateAreaMesh(e){this.renderArea(e)}removeAreaMesh(e){const t=this.areaMeshes.get(e);t&&(this.scene.remove(t),this.disposeGroup(t),this.areaMeshes.delete(e)),this.folderIconMeshes=this.folderIconMeshes.filter(s=>s.userData.areaId===e?(this.scene.remove(s),s.geometry.dispose(),s.material.dispose(),!1):!0)}highlightArea(e){this.selectedAreaId=e,this.removeResizeHandles();for(const[t,s]of this.areaMeshes){const i=t===e;s.traverse(o=>{if(o instanceof y&&o.name!=="resizeHandle"&&o.name!=="areaLogo"){const n=o.material,r=i?.3:.15;n.opacity=r*this.brightness}if(o instanceof ce){const n=o.material;n.opacity=i?1:.8}})}if(e){const t=k.getState().areas.get(e);t&&this.createResizeHandles(t)}}createResizeHandles(e){const t=new O(.15,16,16),s=new v({color:16777215,transparent:!0,opacity:.9}),i=new v({color:16763904,transparent:!0,opacity:.9}),o=(e.zIndex??0)*.001,n=new y(t.clone(),i.clone());if(n.position.set(e.center.x,.25+o,e.center.z),n.name="resizeHandle",n.userData.handleType="move",n.userData.areaId=e.id,this.scene.add(n),this.resizeHandles.push(n),e.type==="rectangle"&&e.width&&e.height){const r=[{type:"nw",x:-e.width/2,z:-e.height/2},{type:"ne",x:e.width/2,z:-e.height/2},{type:"sw",x:-e.width/2,z:e.height/2},{type:"se",x:e.width/2,z:e.height/2}];for(const h of r){const g=new y(t.clone(),s.clone());g.position.set(e.center.x+h.x,.2+o,e.center.z+h.z),g.name="resizeHandle",g.userData.handleType=h.type,g.userData.areaId=e.id,this.scene.add(g),this.resizeHandles.push(g)}const l=new v({color:11197951,transparent:!0,opacity:.9}),c=new O(.12,16,16),d=[{type:"n",x:0,z:-e.height/2},{type:"s",x:0,z:e.height/2},{type:"e",x:e.width/2,z:0},{type:"w",x:-e.width/2,z:0}];for(const h of d){const g=new y(c.clone(),l.clone());g.position.set(e.center.x+h.x,.2+o,e.center.z+h.z),g.name="resizeHandle",g.userData.handleType=h.type,g.userData.areaId=e.id,this.scene.add(g),this.resizeHandles.push(g)}l.dispose(),c.dispose()}else if(e.type==="circle"&&e.radius){const r=new y(t.clone(),s.clone());r.position.set(e.center.x+e.radius,.2+o,e.center.z),r.name="resizeHandle",r.userData.handleType="radius",r.userData.areaId=e.id,this.scene.add(r),this.resizeHandles.push(r)}t.dispose(),s.dispose(),i.dispose()}removeResizeHandles(){for(const e of this.resizeHandles)this.scene.remove(e),e.geometry.dispose(),e.material.dispose();this.resizeHandles=[]}getResizeHandles(){return this.resizeHandles}isCurrentlyResizing(){return this.isResizing}startResize(e,t){const s=e.userData.areaId,i=e.userData.handleType,o=k.getState().areas.get(s);if(o&&(this.isResizing=!0,this.resizeHandleType=i,this.resizeStartPos=t,this.resizeOriginalArea={...o},this.areaDragAgentStartPositions.clear(),this.areaDragBuildingStartPositions.clear(),i==="move")){const n=k.getState();for(const r of n.agents.values())this.isPointInsideArea(r.position.x,r.position.z,o)&&this.areaDragAgentStartPositions.set(r.id,{...r.position});for(const r of n.buildings.values())this.isPointInsideArea(r.position.x,r.position.z,o)&&this.areaDragBuildingStartPositions.set(r.id,{...r.position})}}updateResize(e){if(!this.isResizing||!this.resizeOriginalArea||!this.resizeHandleType||!this.resizeStartPos)return;const t=this.resizeOriginalArea;let s={};if(this.resizeHandleType==="move"){const i=e.x-this.resizeStartPos.x,o=e.z-this.resizeStartPos.z;s={center:{x:t.center.x+i,z:t.center.z+o}};for(const[n,r]of this.areaDragAgentStartPositions)k.moveAgentLocal(n,{x:r.x+i,y:r.y,z:r.z+o});for(const[n,r]of this.areaDragBuildingStartPositions)k.updateBuildingLocal(n,{position:{x:r.x+i,z:r.z+o}})}else if(t.type==="rectangle"&&t.width&&t.height){const i=e.x-this.resizeStartPos.x,o=e.z-this.resizeStartPos.z,n=t.width,r=t.height,l=t.center.x,c=t.center.z,d=p=>{const m=Math.max(.5,n+p);return{width:m,cx:l+(m-n)/2}},h=p=>{const m=Math.max(.5,n-p);return{width:m,cx:l+(n-m)/2}},g=p=>{const m=Math.max(.5,r+p);return{height:m,cz:c+(m-r)/2}},f=p=>{const m=Math.max(.5,r-p);return{height:m,cz:c+(r-m)/2}};switch(this.resizeHandleType){case"se":{const p=d(i),m=g(o);s={width:p.width,height:m.height,center:{x:p.cx,z:m.cz}};break}case"sw":{const p=h(i),m=g(o);s={width:p.width,height:m.height,center:{x:p.cx,z:m.cz}};break}case"ne":{const p=d(i),m=f(o);s={width:p.width,height:m.height,center:{x:p.cx,z:m.cz}};break}case"nw":{const p=h(i),m=f(o);s={width:p.width,height:m.height,center:{x:p.cx,z:m.cz}};break}case"e":{const p=d(i);s={width:p.width,center:{x:p.cx,z:c}};break}case"w":{const p=h(i);s={width:p.width,center:{x:p.cx,z:c}};break}case"s":{const p=g(o);s={height:p.height,center:{x:l,z:p.cz}};break}case"n":{const p=f(o);s={height:p.height,center:{x:l,z:p.cz}};break}}}else if(t.type==="circle"&&this.resizeHandleType==="radius"){const i=e.x-t.center.x,o=e.z-t.center.z;s={radius:Math.max(.5,Math.sqrt(i*i+o*o))}}Object.keys(s).length>0&&k.updateArea(t.id,s)}finishResize(){if(this.resizeHandleType==="move"&&this.resizeOriginalArea&&this.resizeStartPos){const t=k.getState().areas.get(this.resizeOriginalArea.id);if(t){const s=t.center.x-this.resizeOriginalArea.center.x,i=t.center.z-this.resizeOriginalArea.center.z;if(s!==0||i!==0){for(const[o,n]of this.areaDragAgentStartPositions)k.moveAgent(o,{x:n.x+s,y:n.y,z:n.z+i});for(const[o,n]of this.areaDragBuildingStartPositions)k.moveBuilding(o,{x:n.x+s,z:n.z+i})}}}if(this.isResizing=!1,this.resizeHandleType=null,this.resizeStartPos=null,this.resizeOriginalArea=null,this.areaDragAgentStartPositions.clear(),this.areaDragBuildingStartPositions.clear(),this.selectedAreaId){this.removeResizeHandles();const e=k.getState().areas.get(this.selectedAreaId);e&&this.createResizeHandles(e)}}isPointInsideArea(e,t,s){if(s.type==="rectangle"&&s.width&&s.height){const i=s.width/2,o=s.height/2;return e>=s.center.x-i&&e<=s.center.x+i&&t>=s.center.z-o&&t<=s.center.z+o}if(s.type==="circle"&&s.radius){const i=e-s.center.x,o=t-s.center.z;return i*i+o*o<=s.radius*s.radius}return!1}getAreaAtPosition(e){const t=k.getState(),s=Array.from(t.areas.values()).filter(i=>!i.archived&&Ne(i.id)).sort((i,o)=>(o.zIndex??0)-(i.zIndex??0));for(const i of s)if(i.type==="rectangle"&&i.width&&i.height){const o=i.width/2,n=i.height/2;if(e.x>=i.center.x-o&&e.x<=i.center.x+o&&e.z>=i.center.z-n&&e.z<=i.center.z+n)return i}else if(i.type==="circle"&&i.radius){const o=e.x-i.center.x,n=e.z-i.center.z;if(Math.sqrt(o*o+n*n)<=i.radius)return i}return null}syncFromStore(){const e=k.getState();for(const t of this.areaMeshes.keys()){const s=e.areas.get(t);(!s||s.archived||!Ne(t))&&this.removeAreaMesh(t)}for(const t of e.areas.values())!t.archived&&Ne(t.id)&&this.renderArea(t)}createPreview(e){this.previewMesh=new Y,this.scene.add(this.previewMesh)}updatePreview(e){if(!this.previewMesh||!this.drawStartPos)return;for(;this.previewMesh.children.length>0;){const s=this.previewMesh.children[0];this.previewMesh.remove(s),(s instanceof y||s instanceof ce)&&(s.geometry.dispose(),s.material.dispose())}const t=new H("#4a9eff");if(this.currentTool==="rectangle"){const s=Math.abs(e.x-this.drawStartPos.x),i=Math.abs(e.z-this.drawStartPos.z),o=(e.x+this.drawStartPos.x)/2,n=(e.z+this.drawStartPos.z)/2;if(s>.1&&i>.1){const r=new pe(s,i),l=new v({color:t,transparent:!0,opacity:.2,side:oe}),c=new y(r,l);c.rotation.x=-Math.PI/2,c.position.set(o,.02,n),this.previewMesh.add(c);const d=[new T(this.drawStartPos.x,.03,this.drawStartPos.z),new T(e.x,.03,this.drawStartPos.z),new T(e.x,.03,e.z),new T(this.drawStartPos.x,.03,e.z),new T(this.drawStartPos.x,.03,this.drawStartPos.z)],h=new le().setFromPoints(d),g=new ge({color:t}),f=new ce(h,g);this.previewMesh.add(f)}}else if(this.currentTool==="circle"){const s=e.x-this.drawStartPos.x,i=e.z-this.drawStartPos.z,o=Math.sqrt(s*s+i*i);if(o>.1){const n=new yt(o,32),r=new v({color:t,transparent:!0,opacity:.2,side:oe}),l=new y(n,r);l.rotation.x=-Math.PI/2,l.position.set(this.drawStartPos.x,.02,this.drawStartPos.z),this.previewMesh.add(l);const c=[];for(let f=0;f<=32;f++){const p=f/32*Math.PI*2;c.push(new T(this.drawStartPos.x+Math.cos(p)*o,.03,this.drawStartPos.z+Math.sin(p)*o))}const d=new le().setFromPoints(c),h=new ge({color:t}),g=new ce(d,h);this.previewMesh.add(g)}}}createAreaFromDraw(e,t){const s=`area_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,i=k.getState().areas.size,o=k.getNextZIndex();if(this.currentTool==="rectangle"){const n=Math.abs(t.x-e.x),r=Math.abs(t.z-e.z);return n<.5||r<.5?null:{id:s,name:`Area ${i+1}`,type:"rectangle",center:{x:(e.x+t.x)/2,z:(e.z+t.z)/2},width:n,height:r,color:"#4a9eff",zIndex:o,assignedAgentIds:[],directories:[]}}else if(this.currentTool==="circle"){const n=t.x-e.x,r=t.z-e.z,l=Math.sqrt(n*n+r*r);return l<.5?null:{id:s,name:`Area ${i+1}`,type:"circle",center:{x:e.x,z:e.z},radius:l,color:"#4a9eff",zIndex:o,assignedAgentIds:[],directories:[]}}return null}disposeGroup(e){e.traverse(t=>{if(t instanceof y&&(t.geometry.dispose(),Array.isArray(t.material)?t.material.forEach(s=>s.dispose()):t.material.dispose()),t instanceof ce&&(t.geometry.dispose(),t.material.dispose()),t instanceof K){const s=t.material;s.map&&s.map.dispose(),s.dispose()}})}dispose(){this.cancelDrawing(),this.removeResizeHandles();for(const e of this.areaMeshes.keys())this.removeAreaMesh(e);for(const e of this.folderIconMeshes)this.scene.remove(e),e.geometry.dispose(),e.material.dispose();this.folderIconMeshes=[]}}const ee={running:4915102,stopped:8947848,error:16730698,unknown:16755200,starting:4890367,stopping:16755200},_e={desktop:{primary:7438486,secondary:4871528,accent:6534125,glow:4915102},"filing-cabinet":{primary:6869905,secondary:4766584,accent:10151604,glow:4915102},satellite:{primary:8411861,secondary:7030465,accent:12031220,glow:4890367},crystal:{primary:15557798,secondary:13975436,accent:16156595,glow:10451690},factory:{primary:15567158,secondary:14510880,accent:16166229,glow:16755200}};function ue(a){return a.name}function ne(a){const e=document.createElement("canvas"),t=e.getContext("2d"),s=56,i=28,o=72,n=144;e.width=1024,e.height=n,t.font=`bold ${s}px Arial`;const r=t.measureText(a).width,l=256,c=r+i*2+16;e.width=Math.max(l,c),t.clearRect(0,0,e.width,e.height),t.font=`bold ${s}px Arial`;const d=r+i*2,h=(e.width-d)/2,g=(e.height-o)/2;t.fillStyle="rgba(0, 0, 0, 0.8)",t.beginPath(),t.roundRect(h,g,d,o,10),t.fill(),t.textAlign="center",t.textBaseline="middle",t.fillStyle="#ffffff",t.fillText(a,e.width/2,e.height/2);const f=new se(e);f.minFilter=te,f.magFilter=te,f.needsUpdate=!0;const p=new J({map:f,transparent:!0,depthTest:!1}),m=new K(p),b=.5,w=e.width/e.height;return m.scale.set(b*w,b,1),m.userData.aspectRatio=w,m}function Qt(a){const e=document.createElement("canvas"),t=e.getContext("2d");e.width=64,e.height=64,t.fillStyle="#c89a5a",t.beginPath(),t.arc(32,32,28,0,Math.PI*2),t.fill(),t.strokeStyle="rgba(0, 0, 0, 0.5)",t.lineWidth=3,t.beginPath(),t.arc(32,32,28,0,Math.PI*2),t.stroke(),t.fillStyle="#ffffff",t.font="bold 28px Arial",t.textAlign="center",t.textBaseline="middle",t.fillText(a>99?"99+":String(a),32,32);const s=new se(e);s.minFilter=te,s.magFilter=te;const i=new J({map:s,transparent:!0,depthTest:!1}),o=new K(i);return o.scale.set(.35,.35,1),o.name="gitIndicator",o}function Hi(a,e){const t=a.material;t.map&&t.map.dispose(),t.dispose();const s=Qt(e);a.material=s.material}function Jt(a,e){const t=a.label,s=ne(e);s.position.copy(t.position),s.name="buildingLabel",a.group.remove(t),t.material instanceof J&&(t.material.map&&t.material.map.dispose(),t.material.dispose()),a.group.add(s),a.label=s}function Wi(a){const e=new Y;e.userData.buildingId=a.id,e.userData.isBuilding=!0;const t=a.color?new H(a.color):new H(2763322),s=new z(1.2,2.5,.8),i=new A({color:t,metalness:.7,roughness:.3}),o=new y(s,i);o.position.y=1.25,o.castShadow=!0,o.receiveShadow=!0,o.name="buildingBody",e.add(o);for(let S=0;S<5;S++){const P=new z(1.1,.02,.75),C=new A({color:1710634,metalness:.5,roughness:.5}),x=new y(P,C);x.position.set(0,.5+S*.45,.03),e.add(x)}for(let S=0;S<5;S++){const P=new z(.08,.08,.05),C=new v({color:4915102,transparent:!0,opacity:.9}),x=new y(P,C);x.position.set(-.45,.5+S*.45,.43),x.name=`led_${S}`,e.add(x);const B=new y(P.clone(),C.clone());B.position.set(-.3,.5+S*.45,.43),B.name=`activityLed_${S}`,e.add(B)}const n=new z(1,.1,.6),r=new A({color:1710634,metalness:.3,roughness:.7}),l=new y(n,r);l.position.set(0,2.55,0),e.add(l);const c=new O(.15,16,16),d=new v({color:ee[a.status],transparent:!0,opacity:.95}),h=new y(c,d);h.position.set(0,2.75,0),h.name="statusLight",e.add(h);const g=new O(.25,16,16),f=new v({color:ee[a.status],transparent:!0,opacity:.3}),p=new y(g,f);p.position.set(0,2.75,0),p.name="statusGlow",e.add(p);const m=new z(1.5,.1,1.1),b=new A({color:3816010,metalness:.5,roughness:.5}),w=new y(m,b);w.position.y=.05,w.receiveShadow=!0,e.add(w);const M=ne(ue(a));return M.position.set(0,3.2,0),M.name="buildingLabel",e.add(M),e.position.set(a.position.x,0,a.position.z),{group:e,statusLight:h,label:M}}function Fi(a,e){for(let t=0;t<5;t++){const s=a.group.getObjectByName(`led_${t}`);if(s&&s.material instanceof v){const o=Math.sin(e*.8+t*1.2);s.material.opacity=o>.3?.6:.15}const i=a.group.getObjectByName(`activityLed_${t}`);i&&i.material instanceof v&&(i.material.opacity=Math.random()>.97?.5:.1)}}function Ni(a,e){for(let t=0;t<5;t++){const s=a.group.getObjectByName(`activityLed_${t}`);s&&s.material instanceof v&&Math.random()>.95&&(s.material.opacity=s.material.opacity>.5?.2:.9)}}function ji(a){const e=new Y;e.userData.buildingId=a.id,e.userData.isBuilding=!0;const t=a.color?new H(a.color):new H(2767434),s=new j(.5,.7,3,8),i=new A({color:t,metalness:.6,roughness:.4}),o=new y(s,i);o.position.y=1.5,o.castShadow=!0,o.receiveShadow=!0,o.name="buildingBody",e.add(o);for(let D=0;D<4;D++){const $=new j(.52-D*.03,.62-D*.03,.1,8),G=new v({color:4890367,transparent:!0,opacity:.7}),W=new y($,G);W.position.y=.7+D*.6,W.name=`windowBand_${D}`,e.add(W)}const n=new j(.6,.5,.2,8),r=new A({color:3816010,metalness:.7,roughness:.3}),l=new y(n,r);l.position.y=3.1,e.add(l);const c=new j(.15,.2,.3,6),d=new A({color:4868698,metalness:.8,roughness:.2}),h=new y(c,d);h.position.y=3.35,e.add(h);const g=new Y;g.position.y=3.6,g.name="antenna";const f=new z(.05,.6,.05),p=new A({color:6974074,metalness:.9,roughness:.1}),m=new y(f,p);m.position.y=.3,g.add(m);const b=new xe(.15,.1,8);for(let D=0;D<2;D++){const $=new y(b,p);$.rotation.x=Math.PI/2,$.position.set(D===0?.2:-.2,.4,0),$.rotation.z=D===0?Math.PI/2:-Math.PI/2,g.add($)}e.add(g);const w=new O(.12,16,16),M=new v({color:ee[a.status],transparent:!0,opacity:.95}),S=new y(w,M);S.position.set(0,4.3,0),S.name="statusLight",e.add(S);const P=new O(.2,16,16),C=new v({color:ee[a.status],transparent:!0,opacity:.3}),x=new y(P,C);x.position.set(0,4.3,0),x.name="statusGlow",e.add(x);const B=new j(.9,1,.15,8),I=new A({color:3816010,metalness:.5,roughness:.5}),L=new y(B,I);L.position.y=.075,L.receiveShadow=!0,e.add(L);const E=ne(ue(a));return E.position.set(0,4.7,0),E.name="buildingLabel",e.add(E),e.position.set(a.position.x,0,a.position.z),{group:e,statusLight:S,label:E}}function $i(a,e,t){const s=a.group.getObjectByName("antenna");s&&(s.rotation.y+=t*.3);for(let i=0;i<4;i++){const o=a.group.getObjectByName(`windowBand_${i}`);o&&o.material instanceof v&&(o.material.opacity=.3+Math.sin(e*.5+i*.4)*.15)}}function Ui(a,e,t){const s=a.group.getObjectByName("antenna");s&&(s.rotation.y+=t*2);for(let i=0;i<4;i++){const o=a.group.getObjectByName(`windowBand_${i}`);if(o&&o.material instanceof v){const n=Math.sin(e*4+i*.5)*.3+.7;o.material.opacity=n}}}function Yi(a){const e=new Y;e.userData.buildingId=a.id,e.userData.isBuilding=!0;const t=a.color?new H(a.color):new H(2763338),s=new O(1.2,32,16,0,Math.PI*2,0,Math.PI/2),i=new A({color:t,metalness:.4,roughness:.6,transparent:!0,opacity:.9}),o=new y(s,i);o.position.y=.15,o.castShadow=!0,o.receiveShadow=!0,o.name="buildingBody",e.add(o);const n=new O(.8,24,12,0,Math.PI*2,0,Math.PI/2),r=new v({color:4890367,transparent:!0,opacity:.3}),l=new y(n,r);l.position.y=.15,l.name="innerDome",e.add(l);const c=new we(1,.05,8,32),d=new v({color:4915102,transparent:!0,opacity:.8}),h=new y(c,d);h.position.y=.6,h.rotation.x=Math.PI/2,h.name="energyRing",e.add(h);const g=new y(c.clone(),d.clone());g.position.y=.8,g.rotation.x=Math.PI/3,g.name="energyRing2",e.add(g);for(let B=0;B<4;B++){const I=new j(.03,.03,1.2,8),L=new v({color:4890367,transparent:!0,opacity:.6}),E=new y(I,L),D=B/4*Math.PI*2;E.position.set(Math.cos(D)*.5,.75,Math.sin(D)*.5),E.name=`beam_${B}`,e.add(E)}const f=new O(.15,16,16),p=new v({color:ee[a.status],transparent:!0,opacity:.95}),m=new y(f,p);m.position.set(0,1.4,0),m.name="statusLight",e.add(m);const b=new O(.25,16,16),w=new v({color:ee[a.status],transparent:!0,opacity:.3}),M=new y(b,w);M.position.set(0,1.4,0),M.name="statusGlow",e.add(M);const S=new j(1.4,1.5,.15,32),P=new A({color:3816010,metalness:.6,roughness:.4}),C=new y(S,P);C.position.y=.075,C.receiveShadow=!0,e.add(C);const x=ne(ue(a));return x.position.set(0,1.9,0),x.name="buildingLabel",e.add(x),e.position.set(a.position.x,0,a.position.z),{group:e,statusLight:m,label:x}}function Xi(a,e,t){const s=a.group.getObjectByName("energyRing"),i=a.group.getObjectByName("energyRing2");s&&(s.rotation.z+=t*.2),i&&(i.rotation.z-=t*.15);const o=a.group.getObjectByName("innerDome");o&&o.material instanceof v&&(o.material.opacity=.15+Math.sin(e*.6)*.1);for(let n=0;n<4;n++){const r=a.group.getObjectByName(`beam_${n}`);r&&r.material instanceof v&&(r.material.opacity=.2+Math.sin(e*.5+n*.3)*.1)}}function Vi(a,e,t){const s=a.group.getObjectByName("energyRing"),i=a.group.getObjectByName("energyRing2");s&&(s.rotation.z+=t*1.5),i&&(i.rotation.z-=t*1.2);const o=a.group.getObjectByName("innerDome");o&&o.material instanceof v&&(o.material.opacity=.2+Math.sin(e*2)*.15);for(let n=0;n<4;n++){const r=a.group.getObjectByName(`beam_${n}`);if(r&&r.material instanceof v){const l=Math.sin(e*5+n*1.5)*.3+.6;r.material.opacity=l}}}function Zi(a){const e=new Y;e.userData.buildingId=a.id,e.userData.isBuilding=!0;const t=a.color?new H(a.color):new H(3815978),s=new xe(1.3,2.5,4),i=new A({color:t,metalness:.3,roughness:.7}),o=new y(s,i);o.position.y=1.25,o.rotation.y=Math.PI/4,o.castShadow=!0,o.receiveShadow=!0,o.name="buildingBody",e.add(o);const n=new xe(.6,1.2,4),r=new v({color:16755200,transparent:!0,opacity:.6}),l=new y(n,r);l.position.y=.8,l.rotation.y=Math.PI/4,l.name="pyramidCore",e.add(l);const c=[{x:.9,z:0},{x:-.9,z:0},{x:0,z:.9},{x:0,z:-.9}];for(let E=0;E<4;E++){const D=new j(.02,.02,2.7,8),$=new v({color:4915102,transparent:!0,opacity:.7}),G=new y(D,$),W=c[E];G.position.set(W.x*.5,1.25,W.z*.5);const Z=Math.atan2(1.25,.65);E<2?G.rotation.z=E===0?-Z:Z:G.rotation.x=E===2?Z:-Z,G.name=`edgeLine_${E}`,e.add(G)}const d=new O(.15,16,16),h=new v({color:16755200,transparent:!0,opacity:.9}),g=new y(d,h);g.position.y=2.7,g.name="pyramidEye",e.add(g);const f=new O(.25,16,16),p=new v({color:16755200,transparent:!0,opacity:.3}),m=new y(f,p);m.position.y=2.7,m.name="pyramidEyeGlow",e.add(m);const b=new O(.12,16,16),w=new v({color:ee[a.status],transparent:!0,opacity:.95}),M=new y(b,w);M.position.set(1.2,.3,0),M.name="statusLight",e.add(M);const S=new O(.2,16,16),P=new v({color:ee[a.status],transparent:!0,opacity:.3}),C=new y(S,P);C.position.set(1.2,.3,0),C.name="statusGlow",e.add(C);const x=new z(2.8,.15,2.8),B=new A({color:4868666,metalness:.2,roughness:.8}),I=new y(x,B);I.position.y=.075,I.receiveShadow=!0,e.add(I);const L=ne(ue(a));return L.position.set(0,3.2,0),L.name="buildingLabel",e.add(L),e.position.set(a.position.x,0,a.position.z),{group:e,statusLight:M,label:L}}function Ki(a,e){const t=a.group.getObjectByName("pyramidEye"),s=a.group.getObjectByName("pyramidEyeGlow");t&&(t.position.y=2.7+Math.sin(e*.5)*.03,t.material instanceof v&&(t.material.opacity=.4+Math.sin(e*.7)*.2)),s&&(s.position.y=2.7+Math.sin(e*.5)*.03,s.material instanceof v&&(s.material.opacity=.15+Math.sin(e*.7)*.1));const i=a.group.getObjectByName("pyramidCore");i&&i.material instanceof v&&(i.material.opacity=.2+Math.sin(e*.5)*.1)}function qi(a,e){const t=a.group.getObjectByName("pyramidCore");t&&t.material instanceof v&&(t.material.opacity=.4+Math.sin(e*2)*.2);const s=a.group.getObjectByName("pyramidEye"),i=a.group.getObjectByName("pyramidEyeGlow");s&&s.material instanceof v&&(s.material.opacity=.7+Math.sin(e*3)*.3),i&&i.material instanceof v&&(i.material.opacity=.2+Math.sin(e*3)*.15),s&&(s.position.y=2.7+Math.sin(e*1.5)*.1),i&&(i.position.y=2.7+Math.sin(e*1.5)*.1)}function Qi(a){const e=new Y;e.userData.buildingId=a.id,e.userData.isBuilding=!0;const t=_e.desktop,s=a.color?new H(a.color):new H(t.primary),i=new z(1.4,1,.15),o=new A({color:s,metalness:.4,roughness:.6}),n=new y(i,o);n.position.set(0,1.4,0),n.castShadow=!0,n.name="buildingBody",e.add(n);const r=new z(1.2,.8,.02),l=new v({color:661032,transparent:!0,opacity:.95}),c=new y(r,l);c.position.set(0,1.4,.09),c.name="screen",e.add(c);for(let R=0;R<6;R++){const _=new z(.8-R%3*.2,.05,.01),U=new v({color:t.glow,transparent:!0,opacity:.9}),q=new y(_,U);q.position.set(-.1+R%2*.1,1.65-R*.1,.1),q.name=`codeLine_${R}`,e.add(q)}const d=new z(.15,.6,.15),h=new A({color:t.secondary,metalness:.5,roughness:.5}),g=new y(d,h);g.position.set(0,.6,0),e.add(g);const f=new z(.6,.08,.4),p=new y(f,h);p.position.set(0,.25,0),e.add(p);const m=new z(1,.08,.35),b=new A({color:t.secondary,metalness:.3,roughness:.7}),w=new y(m,b);w.position.set(0,.2,.6),w.rotation.x=-.1,e.add(w);for(let R=0;R<3;R++)for(let _=0;_<10;_++){const U=new z(.07,.03,.07),q=new A({color:t.accent,metalness:.2,roughness:.8}),V=new y(U,q);V.position.set(-.38+_*.085,.25,.45+R*.1),e.add(V)}const M=new z(.4,.9,.8),S=new A({color:s,metalness:.4,roughness:.6}),P=new y(M,S);P.position.set(-1.1,.55,0),P.castShadow=!0,e.add(P);const C=new z(.05,.05,.02),x=new v({color:4915102,transparent:!0,opacity:.9}),B=new y(C,x);B.position.set(-.88,.7,.3),B.name="cpuLed",e.add(B);const I=new O(.1,16,16),L=new v({color:ee[a.status],transparent:!0,opacity:.95}),E=new y(I,L);E.position.set(.6,1.85,.1),E.name="statusLight",e.add(E);const D=new O(.18,16,16),$=new v({color:ee[a.status],transparent:!0,opacity:.3}),G=new y(D,$);G.position.set(.6,1.85,.1),G.name="statusGlow",e.add(G);const W=new z(2.6,.1,1.4),Z=new A({color:3816010,metalness:.5,roughness:.5}),N=new y(W,Z);N.position.y=.05,N.receiveShadow=!0,e.add(N);const F=ne(ue(a));return F.position.set(0,2.3,0),F.name="buildingLabel",e.add(F),e.position.set(a.position.x,0,a.position.z),{group:e,statusLight:E,label:F}}function Ji(a,e){const t=a.group.getObjectByName("buildingBody");t&&(t.rotation.y=Math.sin(e*.3)*.01);for(let s=0;s<6;s++){const i=a.group.getObjectByName(`codeLine_${s}`);i&&i.material instanceof v&&(i.material.opacity=.3+Math.sin(e*.4+s*.2)*.1)}}function eo(a,e){for(let s=0;s<6;s++){const i=a.group.getObjectByName(`codeLine_${s}`);if(i&&i.material instanceof v){const o=Math.random()>.98?.4:.8;i.material.opacity=o}}const t=a.group.getObjectByName("cpuLed");if(t&&t.material instanceof v){const s=Math.sin(e*6)>0?.9:.3;t.material.opacity=s}}function to(a){const e=new Y;e.userData.buildingId=a.id,e.userData.isBuilding=!0;const t=_e["filing-cabinet"],s=a.color?new H(a.color):new H(t.primary),i=new z(1,2.4,.8),o=new A({color:s,metalness:.5,roughness:.5}),n=new y(i,o);n.position.y=1.2,n.castShadow=!0,n.name="buildingBody",e.add(n);for(let w=0;w<4;w++){const M=new z(.9,.5,.05),S=new A({color:t.secondary,metalness:.4,roughness:.6}),P=new y(M,S);P.position.set(0,.35+w*.55,.4),P.name=`drawer_${w}`,e.add(P);const C=new z(.3,.06,.05),x=new A({color:t.accent,metalness:.7,roughness:.3}),B=new y(C,x);B.position.set(0,.35+w*.55,.47),B.name=`handle_${w}`,e.add(B);const I=new z(.4,.15,.02),L=new v({color:16777198}),E=new y(I,L);E.position.set(0,.45+w*.55,.44),e.add(E)}for(let w=0;w<4;w++){const M=new z(.06,.06,.02),S=new v({color:w%2===0?t.glow:t.accent,transparent:!0,opacity:.9}),P=new y(M,S);P.position.set(-.38,.35+w*.55,.42),P.name=`indicator_${w}`,e.add(P)}const r=new O(.12,16,16),l=new v({color:ee[a.status],transparent:!0,opacity:.95}),c=new y(r,l);c.position.set(0,2.55,0),c.name="statusLight",e.add(c);const d=new O(.2,16,16),h=new v({color:ee[a.status],transparent:!0,opacity:.3}),g=new y(d,h);g.position.set(0,2.55,0),g.name="statusGlow",e.add(g);const f=new z(1.3,.1,1.1),p=new A({color:3816010,metalness:.5,roughness:.5}),m=new y(f,p);m.position.y=.05,m.receiveShadow=!0,e.add(m);const b=ne(ue(a));return b.position.set(0,3,0),b.name="buildingLabel",e.add(b),e.position.set(a.position.x,0,a.position.z),{group:e,statusLight:c,label:b}}function so(a,e){a.group.rotation.y=Math.sin(e*.5)*.005;for(let t=0;t<4;t++){const s=a.group.getObjectByName(`indicator_${t}`);s&&s.material instanceof v&&(s.material.opacity=.3+Math.sin(e*.6+t*.4)*.15)}}function io(a,e){for(let t=0;t<4;t++){const s=a.group.getObjectByName(`indicator_${t}`);if(s&&s.material instanceof v){const i=Math.sin(e*3+t*.8)*.3+.7;s.material.opacity=i}}for(let t=0;t<4;t++){const s=a.group.getObjectByName(`handle_${t}`);s&&(s.position.z=.47+Math.sin(e*8+t)*.005)}}function oo(a){const e=new Y;e.userData.buildingId=a.id,e.userData.isBuilding=!0;const t=_e.satellite,s=a.color?new H(a.color):new H(t.primary),i=new j(.1,.15,2,8),o=new A({color:t.secondary,metalness:.6,roughness:.4}),n=new y(i,o);n.position.y=1,n.castShadow=!0,e.add(n);const r=new z(.3,.2,.3),l=new y(r,o);l.position.y=2.1,e.add(l);const c=new Y;c.position.y=2.3,c.name="dishGroup";const d=new O(1,32,16,0,Math.PI*2,0,Math.PI/3),h=new A({color:s,metalness:.5,roughness:.5,side:oe}),g=new y(d,h);g.rotation.x=Math.PI/2+.3,g.name="buildingBody",c.add(g);const f=new O(.95,32,16,0,Math.PI*2,0,Math.PI/3),p=new A({color:t.accent,metalness:.3,roughness:.7,side:Ut}),m=new y(f,p);m.rotation.x=Math.PI/2+.3,c.add(m);const b=new j(.03,.03,.8,8),w=new A({color:t.secondary,metalness:.6,roughness:.4}),M=new y(b,w);M.position.set(0,.1,.5),M.rotation.x=-.6,c.add(M);const S=new xe(.1,.2,8),P=new A({color:t.accent,metalness:.4,roughness:.6}),C=new y(S,P);C.position.set(0,.5,.85),C.rotation.x=Math.PI/2-.6,c.add(C);const x=new O(.08,16,16),B=new v({color:t.glow,transparent:!0,opacity:.9}),I=new y(x,B);I.position.set(0,.55,.92),I.name="signal",c.add(I),e.add(c);for(let _=0;_<3;_++){const U=new ke(.2+_*.15,.22+_*.15,16),q=new v({color:t.glow,transparent:!0,opacity:.6-_*.15,side:oe}),V=new y(U,q);V.position.set(0,2.85+_*.1,.92+_*.1),V.rotation.x=-.6,V.name=`wave_${_}`,e.add(V)}const L=new O(.1,16,16),E=new v({color:ee[a.status],transparent:!0,opacity:.95}),D=new y(L,E);D.position.set(0,.3,.5),D.name="statusLight",e.add(D);const $=new O(.18,16,16),G=new v({color:ee[a.status],transparent:!0,opacity:.3}),W=new y($,G);W.position.set(0,.3,.5),W.name="statusGlow",e.add(W);const Z=new j(.6,.7,.15,16),N=new A({color:t.secondary,metalness:.5,roughness:.5}),F=new y(Z,N);F.position.y=.075,F.receiveShadow=!0,e.add(F);const R=ne(ue(a));return R.position.set(0,3.8,0),R.name="buildingLabel",e.add(R),e.position.set(a.position.x,0,a.position.z),{group:e,statusLight:D,label:R}}function no(a,e,t){const s=a.group.getObjectByName("dishGroup");s&&(s.rotation.y+=t*.1);for(let i=0;i<3;i++){const o=a.group.getObjectByName(`wave_${i}`);o&&o.material instanceof v&&(o.material.opacity=.15+Math.sin(e*.5+i*.3)*.1)}}function ao(a,e,t){const s=a.group.getObjectByName("dishGroup");s&&(s.rotation.y+=t*.5);const i=a.group.getObjectByName("signal");i&&i.material instanceof v&&(i.material.opacity=.6+Math.sin(e*8)*.4);for(let o=0;o<3;o++){const n=a.group.getObjectByName(`wave_${o}`);if(n&&n.material instanceof v){const r=1+Math.sin(e*4+o)*.1;n.scale.set(r,r,1),n.material.opacity=(.5-o*.15)*(.5+Math.sin(e*4+o)*.5)}}}function ro(a){const e=new Y;e.userData.buildingId=a.id,e.userData.isBuilding=!0;const t=_e.crystal,s=a.color?new H(a.color):new H(t.primary),i=new Mt(.8),o=new A({color:s,metalness:.3,roughness:.2,transparent:!0,opacity:.85}),n=new y(i,o);n.position.y=1.8,n.castShadow=!0,n.name="buildingBody",e.add(n);const r=new Mt(.5),l=new v({color:t.glow,transparent:!0,opacity:.6}),c=new y(r,l);c.position.y=1.8,c.name="crystalInner",e.add(c);for(let G=0;G<6;G++){const W=new O(.06,8,8),Z=new v({color:G%2===0?t.accent:t.glow,transparent:!0,opacity:.9}),N=new y(W,Z),F=G/6*Math.PI*2;N.position.set(Math.cos(F)*1.2,1.8+Math.sin(F*2)*.3,Math.sin(F)*1.2),N.name=`particle_${G}`,e.add(N)}const d=new ws(1.3,1),h=new v({color:t.accent,wireframe:!0,transparent:!0,opacity:.4}),g=new y(d,h);g.position.y=1.8,g.name="energyField",e.add(g);const f=new j(.3,.5,.8,6),p=new A({color:t.secondary,metalness:.5,roughness:.5}),m=new y(f,p);m.position.y=.4,e.add(m);const b=new j(.05,.05,.9,8),w=new v({color:t.glow,transparent:!0,opacity:.7}),M=new y(b,w);M.position.y=1.25,M.name="energyBeam",e.add(M);const S=new O(.1,16,16),P=new v({color:ee[a.status],transparent:!0,opacity:.95}),C=new y(S,P);C.position.set(.7,.5,0),C.name="statusLight",e.add(C);const x=new O(.18,16,16),B=new v({color:ee[a.status],transparent:!0,opacity:.3}),I=new y(x,B);I.position.set(.7,.5,0),I.name="statusGlow",e.add(I);const L=new j(.8,.9,.1,6),E=new A({color:t.secondary,metalness:.6,roughness:.4}),D=new y(L,E);D.position.y=.05,D.receiveShadow=!0,e.add(D);const $=ne(ue(a));return $.position.set(0,3,0),$.name="buildingLabel",e.add($),e.position.set(a.position.x,0,a.position.z),{group:e,statusLight:C,label:$}}function lo(a,e,t){const s=a.group.getObjectByName("buildingBody");s&&(s.rotation.y+=t*.2,s.position.y=1.8+Math.sin(e*.8)*.05);const i=a.group.getObjectByName("crystalInner");i&&(i.rotation.y-=t*.3,i.position.y=1.8+Math.sin(e*.8)*.05,i.material instanceof v&&(i.material.opacity=.25+Math.sin(e*.6)*.15));const o=a.group.getObjectByName("energyField");o&&(o.rotation.y+=t*.1,o.position.y=1.8+Math.sin(e*.8)*.05,o.material instanceof v&&(o.material.opacity=.15+Math.sin(e*.5)*.1));for(let r=0;r<6;r++){const l=a.group.getObjectByName(`particle_${r}`);if(l){const c=r/6*Math.PI*2+e*.3;l.position.x=Math.cos(c)*1.2,l.position.z=Math.sin(c)*1.2,l.position.y=1.8+Math.sin(e*.8)*.05+Math.sin(c*2)*.2}}const n=a.group.getObjectByName("energyBeam");n&&n.material instanceof v&&(n.material.opacity=.2+Math.sin(e*.7)*.15)}function co(a,e,t){const s=a.group.getObjectByName("buildingBody"),i=a.group.getObjectByName("crystalInner"),o=a.group.getObjectByName("energyField");s&&(s.rotation.y+=t*.8,s.position.y=1.8+Math.sin(e*1.5)*.1),i&&(i.rotation.y-=t*1.2,i.position.y=1.8+Math.sin(e*1.5)*.1,i.material instanceof v&&(i.material.opacity=.4+Math.sin(e*3)*.2)),o&&(o.rotation.y+=t*.3,o.rotation.x+=t*.2,o.position.y=1.8+Math.sin(e*1.5)*.1);for(let r=0;r<6;r++){const l=a.group.getObjectByName(`particle_${r}`);if(l){const c=r/6*Math.PI*2+e*1.5,d=1.2+Math.sin(e*2+r)*.1;l.position.x=Math.cos(c)*d,l.position.z=Math.sin(c)*d,l.position.y=1.8+Math.sin(e*1.5)*.1+Math.sin(c*2)*.3}}const n=a.group.getObjectByName("energyBeam");n&&n.material instanceof v&&(n.material.opacity=.4+Math.sin(e*4)*.3)}function ho(a){const e=new Y;e.userData.buildingId=a.id,e.userData.isBuilding=!0;const t=_e.factory,s=a.color?new H(a.color):new H(t.primary),i=new z(1.8,1.2,1.2),o=new A({color:s,metalness:.4,roughness:.6}),n=new y(i,o);n.position.set(0,.6,0),n.castShadow=!0,n.name="buildingBody",e.add(n);const r=new z(2,.15,1.4),l=new A({color:t.secondary,metalness:.5,roughness:.5}),c=new y(r,l);c.position.set(0,1.25,0),c.rotation.z=.05,e.add(c);const d=new j(.15,.18,1.2,8),h=new A({color:t.secondary,metalness:.5,roughness:.5}),g=new y(d,h);g.position.set(.5,1.8,.3),e.add(g);const f=new we(.17,.03,8,16),p=new y(f,h);p.position.set(.5,2.4,.3),p.rotation.x=Math.PI/2,e.add(p);for(let _=0;_<4;_++){const U=new O(.08+_*.03,8,8),q=new v({color:11184810,transparent:!0,opacity:.7-_*.12}),V=new y(U,q);V.position.set(.5,2.5+_*.25,.3),V.name=`smoke_${_}`,e.add(V)}for(let _=0;_<3;_++){const U=new z(.25,.35,.05),q=new v({color:t.glow,transparent:!0,opacity:.9}),V=new y(U,q);V.position.set(-.6+_*.5,.7,.63),V.name=`window_${_}`,e.add(V)}const m=new z(.4,.6,.05),b=new A({color:t.secondary,metalness:.4,roughness:.6}),w=new y(m,b);w.position.set(.6,.35,.63),e.add(w);const M=new z(.3,.1,1.6),S=new A({color:t.secondary,metalness:.6,roughness:.4}),P=new y(M,S);P.position.set(-1,.25,0),e.add(P);for(let _=0;_<3;_++){const U=new z(.15,.15,.15),q=new v({color:_%2===0?t.accent:t.glow}),V=new y(U,q);V.position.set(-1,.38,-.5+_*.4),V.name=`conveyorItem_${_}`,e.add(V)}const C=new we(.2,.05,6,8),x=new A({color:t.accent,metalness:.6,roughness:.4}),B=new y(C,x);B.position.set(-.8,.9,.63),B.name="gear1",e.add(B);const I=new y(C.clone(),x.clone());I.position.set(-.5,1.05,.63),I.name="gear2",e.add(I);const L=new O(.12,16,16),E=new v({color:ee[a.status],transparent:!0,opacity:.95}),D=new y(L,E);D.position.set(.85,1,.65),D.name="statusLight",e.add(D);const $=new O(.2,16,16),G=new v({color:ee[a.status],transparent:!0,opacity:.3}),W=new y($,G);W.position.set(.85,1,.65),W.name="statusGlow",e.add(W);const Z=new z(2.4,.1,1.8),N=new A({color:4868682,metalness:.4,roughness:.6}),F=new y(Z,N);F.position.y=.05,F.receiveShadow=!0,e.add(F);const R=ne(ue(a));return R.position.set(0,2.9,0),R.name="buildingLabel",e.add(R),e.position.set(a.position.x,0,a.position.z),{group:e,statusLight:D,label:R}}function uo(a,e,t){const s=a.group.getObjectByName("gear1"),i=a.group.getObjectByName("gear2");s&&(s.rotation.z+=t*.3),i&&(i.rotation.z-=t*.4);for(let o=0;o<3;o++){const n=a.group.getObjectByName(`window_${o}`);n&&n.material instanceof v&&(n.material.opacity=.3+Math.sin(e*.4+o*.5)*.15)}for(let o=0;o<3;o++){const n=a.group.getObjectByName(`conveyorItem_${o}`);n&&(n.position.z=(n.position.z+t*.05+.5)%1.2-.5)}for(let o=0;o<4;o++){const n=a.group.getObjectByName(`smoke_${o}`);if(n){const r=2.5+o*.25,l=(e*.15+o*.3)%1.5;n.position.y=r+l,n.position.x=.5+Math.sin(e*.3+o)*.05,n.material instanceof v&&(n.material.opacity=Math.max(0,(.25-o*.05)*(1-l/1.5)))}}}function go(a,e,t){for(let o=0;o<4;o++){const n=a.group.getObjectByName(`smoke_${o}`);if(n){const r=2.5+o*.25,l=(e*.5+o*.3)%1.5;n.position.y=r+l,n.position.x=.5+Math.sin(e+o)*.1,n.material instanceof v&&(n.material.opacity=Math.max(0,(.6-o*.12)*(1-l/1.5))),l>1.4&&(n.position.y=r)}}const s=a.group.getObjectByName("gear1"),i=a.group.getObjectByName("gear2");s&&(s.rotation.z+=t*2),i&&(i.rotation.z-=t*2.5);for(let o=0;o<3;o++){const n=a.group.getObjectByName(`conveyorItem_${o}`);n&&(n.position.z=(n.position.z+t*.3+.5)%1.2-.5)}for(let o=0;o<3;o++){const n=a.group.getObjectByName(`window_${o}`);if(n&&n.material instanceof v){const r=Math.random()>.99?.5:.8;n.material.opacity=r}}}function po(a){const e=new Y;e.userData.buildingId=a.id,e.userData.isBuilding=!0;const t=a.color?new H(a.color):new H(2763322),s=16766720,i=new j(1.8,2,.3,6),o=new A({color:t,metalness:.7,roughness:.3}),n=new y(i,o);n.position.y=.15,n.receiveShadow=!0,e.add(n);const r=new j(1.2,1.4,.2,6),l=new A({color:3816010,metalness:.8,roughness:.2}),c=new y(r,l);c.position.y=.4,e.add(c);const d=new j(.4,.6,2,6),h=new A({color:t,metalness:.6,roughness:.4}),g=new y(d,h);g.position.y=1.5,g.castShadow=!0,g.receiveShadow=!0,g.name="buildingBody",e.add(g);const f=new j(.5,.4,.3,6),p=new A({color:s,metalness:.9,roughness:.1,emissive:new H(s),emissiveIntensity:.3}),m=new y(f,p);m.position.y=2.65,m.name="crownBase",e.add(m);for(let N=0;N<5;N++){const F=N/5*Math.PI*2,R=new xe(.08,.4,4),_=new y(R,p);_.position.set(Math.cos(F)*.35,2.95,Math.sin(F)*.35),_.name=`crownSpike_${N}`,e.add(_)}const b=new we(.8,.03,8,32),w=new v({color:s,transparent:!0,opacity:.6}),M=new y(b,w);M.position.y=1.2,M.rotation.x=Math.PI/2,M.name="holoRing1",e.add(M);const S=new we(1.1,.02,8,32),P=new v({color:4915102,transparent:!0,opacity:.5}),C=new y(S,P);C.position.y=1.5,C.rotation.x=Math.PI/2,C.name="holoRing2",e.add(C);const x=new we(1.4,.02,8,32),B=new v({color:4890367,transparent:!0,opacity:.4}),I=new y(x,B);I.position.y=1.8,I.rotation.x=Math.PI/2,I.name="holoRing3",e.add(I);for(let N=0;N<6;N++){const F=N/6*Math.PI*2,R=new Y,_=new z(.3,.25,.2),U=new A({color:3816010,metalness:.6,roughness:.4}),q=new y(_,U);q.position.y=.45,R.add(q);const V=new pe(.25,.15),Se=new v({color:4890367,transparent:!0,opacity:.8}),fe=new y(V,Se);fe.position.y=.52,fe.position.z=.11,fe.rotation.x=-.3,fe.name=`consoleScreen_${N}`,R.add(fe),R.position.set(Math.cos(F)*1.5,0,Math.sin(F)*1.5),R.rotation.y=-F+Math.PI,e.add(R)}const L=new O(.15,16,16),E=new v({color:ee[a.status],transparent:!0,opacity:.95}),D=new y(L,E);D.position.set(0,3.3,0),D.name="statusLight",e.add(D);const $=new O(.25,16,16),G=new v({color:ee[a.status],transparent:!0,opacity:.3}),W=new y($,G);W.position.set(0,3.3,0),W.name="statusGlow",e.add(W);for(let N=0;N<6;N++){const F=N/6*Math.PI*2+Math.PI/6,R=new j(.06,.08,1,6),_=new A({color:s,metalness:.8,roughness:.2,emissive:new H(s),emissiveIntensity:.2}),U=new y(R,_);U.position.set(Math.cos(F)*1.85,.8,Math.sin(F)*1.85),U.name=`energyPillar_${N}`,e.add(U);const q=new O(.08,8,8),V=new v({color:s,transparent:!0,opacity:.8}),Se=new y(q,V);Se.position.set(Math.cos(F)*1.85,1.35,Math.sin(F)*1.85),Se.name=`pillarLight_${N}`,e.add(Se)}const Z=ne(ue(a));return Z.position.set(0,3.8,0),Z.name="buildingLabel",e.add(Z),e.position.set(a.position.x,0,a.position.z),{group:e,statusLight:D,label:Z}}function fo(a,e,t){const s=a.group.getObjectByName("holoRing1"),i=a.group.getObjectByName("holoRing2"),o=a.group.getObjectByName("holoRing3");s&&(s.rotation.z+=t*.3,s.material instanceof v&&(s.material.opacity=.3+Math.sin(e*.5)*.1)),i&&(i.rotation.z-=t*.2,i.material instanceof v&&(i.material.opacity=.25+Math.sin(e*.7+1)*.1)),o&&(o.rotation.z+=t*.1,o.material instanceof v&&(o.material.opacity=.2+Math.sin(e*.4+2)*.1));for(let n=0;n<6;n++){const r=a.group.getObjectByName(`pillarLight_${n}`);r&&r.material instanceof v&&(r.material.opacity=.4+Math.sin(e*.5+n*.5)*.2)}for(let n=0;n<6;n++){const r=a.group.getObjectByName(`consoleScreen_${n}`);r&&r.material instanceof v&&(r.material.opacity=.4+Math.sin(e*.3+n*.3)*.1)}}function mo(a,e,t){const s=a.group.getObjectByName("holoRing1"),i=a.group.getObjectByName("holoRing2"),o=a.group.getObjectByName("holoRing3");s&&(s.rotation.z+=t*1.5,s.rotation.x=Math.PI/2+Math.sin(e*2)*.1,s.material instanceof v&&(s.material.opacity=.5+Math.sin(e*3)*.2)),i&&(i.rotation.z-=t*1,i.rotation.x=Math.PI/2+Math.sin(e*1.5+1)*.15,i.material instanceof v&&(i.material.opacity=.4+Math.sin(e*2.5+1)*.15)),o&&(o.rotation.z+=t*.5,o.rotation.x=Math.PI/2+Math.sin(e*1+2)*.1,o.material instanceof v&&(o.material.opacity=.35+Math.sin(e*2+2)*.15));for(let r=0;r<6;r++){const l=a.group.getObjectByName(`pillarLight_${r}`);if(l&&l.material instanceof v){const c=(e*2+r*.3)%(Math.PI*2);l.material.opacity=.6+Math.sin(c)*.3}}for(let r=0;r<6;r++){const l=a.group.getObjectByName(`consoleScreen_${r}`);if(l&&l.material instanceof v){l.material.opacity=.7+Math.sin(e*4+r*.5)*.2;const c=(e*.1+r*.1)%1;l.material.color.setHSL(c*.2+.5,.8,.5)}}const n=a.group.getObjectByName("crownBase");n&&n.material instanceof A&&(n.material.emissiveIntensity=.4+Math.sin(e*2)*.2)}function wo(a){switch(a.style||"server-rack"){case"tower":return ji(a);case"dome":return Yi(a);case"pyramid":return Zi(a);case"desktop":return Qi(a);case"filing-cabinet":return to(a);case"satellite":return oo(a);case"crystal":return ro(a);case"factory":return ho(a);case"command-center":return po(a);case"server-rack":default:return Wi(a)}}function bo(a,e,t,s){switch(e.style||"server-rack"){case"server-rack":Fi(a,t);break;case"desktop":Ji(a,t);break;case"filing-cabinet":so(a,t);break;case"satellite":no(a,t,s);break;case"crystal":lo(a,t,s);break;case"factory":uo(a,t,s);break;case"tower":$i(a,t,s);break;case"dome":Xi(a,t,s);break;case"pyramid":Ki(a,t);break;case"command-center":fo(a,t,s);break}}function yo(a,e,t,s){const i=e.style||"server-rack",o=a.group.getObjectByName("statusGlow"),n=Math.sin(t*3)*.2+.8;switch(o&&o.material instanceof v&&(o.material.opacity=.3*n),i){case"server-rack":Ni(a);break;case"tower":Ui(a,t,s);break;case"dome":Vi(a,t,s);break;case"pyramid":qi(a,t);break;case"desktop":eo(a,t);break;case"filing-cabinet":io(a,t);break;case"satellite":ao(a,t,s);break;case"crystal":co(a,t,s);break;case"factory":go(a,t,s);break;case"command-center":mo(a,t,s);break}}function Mo(a,e){const t=a.group.getObjectByName("statusGlow"),s=Math.sin(e*8)*.5+.5;t&&t.material instanceof v&&(t.material.opacity=.5*s)}function So(a,e){const t=a.group.getObjectByName("statusGlow"),s=Math.sin(e*2)*.5+.5;t&&t.material instanceof v&&(t.material.opacity=.4*s)}class vo{constructor(e){u(this,"scene");u(this,"buildingMeshes",new Map);u(this,"selectedBuildingIds",new Set);u(this,"animationTime",0);u(this,"brightness",1);u(this,"bossSubordinateLines",null);u(this,"bossSubordinateMaterial",null);u(this,"cachedBossConnections",[]);u(this,"maxLineSegments",50);u(this,"onBuildingClick",null);u(this,"onBuildingDoubleClick",null);this.scene=e}setOnBuildingClick(e){this.onBuildingClick=e}setOnBuildingDoubleClick(e){this.onBuildingDoubleClick=e}setBrightness(e){this.brightness=e;for(const t of this.buildingMeshes.values()){const s=t.group.getObjectByName("statusGlow");s&&s.material instanceof v&&(s.material.opacity=.3*e),t.group.traverse(i=>{if(i instanceof y&&i.material instanceof A){const o=i.material;o.emissiveIntensity!==void 0&&(o.userData.baseEmissiveIntensity===void 0&&(o.userData.baseEmissiveIntensity=o.emissiveIntensity||1),o.emissiveIntensity=o.userData.baseEmissiveIntensity*e)}})}}addBuilding(e){this.removeBuilding(e.id);const t=wo(e);t.group.userData.style=e.style,t.group.userData.color=e.color||"";const s=e.scale||1;t.group.scale.setScalar(s),this.scene.add(t.group),this.buildingMeshes.set(e.id,t)}removeBuilding(e){const t=this.buildingMeshes.get(e);t&&(this.scene.remove(t.group),this.disposeGroup(t.group),this.buildingMeshes.delete(e))}setBuildingPosition(e,t){const s=this.buildingMeshes.get(e);s&&(s.group.position.set(t.x,0,t.z),this.updateBossLinePositions())}updateBuilding(e){var f;const t=this.buildingMeshes.get(e.id);if(!t){this.addBuilding(e);return}const s=t.group.userData.style,i=t.group.userData.color;if(s!==e.style||i!==(e.color||"")){this.removeBuilding(e.id),this.addBuilding(e);return}t.group.position.set(e.position.x,0,e.position.z);const o=e.scale||1;t.group.scale.setScalar(o);const n=ee[e.status],r=t.group.getObjectByName("statusLight");r&&r.material instanceof v&&r.material.color.setHex(n);const l=t.group.getObjectByName("statusGlow");l&&l.material instanceof v&&l.material.color.setHex(n),((f=t.label.material.map)==null?void 0:f.image)&&Jt(t,e.name);const h=e.gitChangesCount||0,g=t.group.getObjectByName("gitIndicator");if(h>0){if(g)g.userData.gitCount!==h&&(Hi(g,h),g.userData.gitCount=h);else{const p=Qt(h),m=t.label.position;p.position.set(m.x+.6,m.y+.15,m.z),t.group.add(p),t.gitIndicator=p}t.gitIndicator&&(t.gitIndicator.userData.gitCount=h)}else if(g){t.group.remove(g);const p=g.material;p.map&&p.map.dispose(),p.dispose(),t.gitIndicator=void 0}}highlightBuilding(e){for(const t of this.selectedBuildingIds){const s=this.buildingMeshes.get(t);if(s){const i=s.group.getObjectByName("buildingBody");i&&i.material instanceof A&&i.material.emissive.setHex(0)}}if(this.selectedBuildingIds.clear(),e){this.selectedBuildingIds.add(e);const t=this.buildingMeshes.get(e);if(t){const s=t.group.getObjectByName("buildingBody");s&&s.material instanceof A&&s.material.emissive.setHex(2236996)}}this.updateBossConnectionLines()}highlightBuildings(e){for(const t of this.selectedBuildingIds){const s=this.buildingMeshes.get(t);if(s){const i=s.group.getObjectByName("buildingBody");i&&i.material instanceof A&&i.material.emissive.setHex(0)}}this.selectedBuildingIds.clear();for(const t of e){this.selectedBuildingIds.add(t);const s=this.buildingMeshes.get(t);if(s){const i=s.group.getObjectByName("buildingBody");i&&i.material instanceof A&&i.material.emissive.setHex(2236996)}}this.updateBossConnectionLines()}getBuildingMeshData(){return this.buildingMeshes}getHitboxForStyle(e){switch(e){case"desktop":return{halfWidth:2,halfDepth:2};case"filing-cabinet":return{halfWidth:1.8,halfDepth:1.2};case"factory":return{halfWidth:1.5,halfDepth:1.2};case"satellite":return{halfWidth:1.2,halfDepth:1.2};case"crystal":return{halfWidth:1.5,halfDepth:1.5};case"tower":return{halfWidth:1.2,halfDepth:1};case"dome":return{halfWidth:1.5,halfDepth:1.5};case"pyramid":return{halfWidth:1.5,halfDepth:1.5};case"command-center":return{halfWidth:2.2,halfDepth:2.2};case"server-rack":default:return{halfWidth:1.2,halfDepth:1}}}getBuildingAtPosition(e){const t=k.getState();for(const s of t.buildings.values()){if(!this.isBuildingVisibleInWorkspace(s,t.areas))continue;const i=this.getHitboxForStyle(s.style),o=s.scale||1,n={halfWidth:i.halfWidth*o,halfDepth:i.halfDepth*o},r=Math.abs(e.x-s.position.x),l=Math.abs(e.z-s.position.z);if(r<=n.halfWidth&&l<=n.halfDepth)return s}return null}getBuildingMeshes(){return Array.from(this.buildingMeshes.values()).map(e=>e.group)}isBuildingVisibleInWorkspace(e,t){if(!$e())return!0;for(const s of t.values())if(!s.archived&&this.isPointInsideArea(e.position.x,e.position.z,s))return Ne(s.id);return!0}isPointInsideArea(e,t,s){if(s.type==="rectangle"&&s.width&&s.height){const i=s.width/2,o=s.height/2;return e>=s.center.x-i&&e<=s.center.x+i&&t>=s.center.z-o&&t<=s.center.z+o}if(s.type==="circle"&&s.radius){const i=e-s.center.x,o=t-s.center.z;return i*i+o*o<=s.radius*s.radius}return!1}syncFromStore(){const e=k.getState();for(const t of this.buildingMeshes.keys()){const s=e.buildings.get(t);(!s||!this.isBuildingVisibleInWorkspace(s,e.areas))&&this.removeBuilding(t)}for(const t of e.buildings.values())this.isBuildingVisibleInWorkspace(t,e.areas)&&(this.buildingMeshes.has(t.id)?this.updateBuilding(t):this.addBuilding(t))}update(e){this.animationTime+=e;const t=k.getState();for(const[s,i]of this.buildingMeshes){const o=t.buildings.get(s);o&&(bo(i,o,this.animationTime,e),o.status==="running"?yo(i,o,this.animationTime,e):o.status==="starting"||o.status==="stopping"?Mo(i,this.animationTime):o.status==="error"&&So(i,this.animationTime))}}updateBossConnectionLines(){var i;const e=k.getState(),t=[],s=new Set;for(const o of this.selectedBuildingIds){const n=e.buildings.get(o);if(n&&n.type==="boss"&&n.subordinateBuildingIds){t.push(n);for(const r of n.subordinateBuildingIds)s.add(r)}if(n){for(const[,r]of e.buildings)if(r.type==="boss"&&((i=r.subordinateBuildingIds)!=null&&i.includes(n.id))&&!t.find(l=>l.id===r.id)){t.push(r);for(const l of r.subordinateBuildingIds||[])s.add(l)}}}this.cachedBossConnections=[];for(const o of t)if(!(!this.buildingMeshes.get(o.id)||!o.subordinateBuildingIds))for(const r of o.subordinateBuildingIds)this.buildingMeshes.get(r)&&this.cachedBossConnections.push({bossId:o.id,subId:r});if(this.cachedBossConnections.length>0){if(!this.bossSubordinateLines){const r=new Float32Array(this.maxLineSegments*6),l=new le;l.setAttribute("position",new Ae(r,3)),l.setDrawRange(0,0),this.bossSubordinateMaterial=new ge({color:16766720,transparent:!0,opacity:.4}),this.bossSubordinateLines=new Yt(l,this.bossSubordinateMaterial),this.bossSubordinateLines.frustumCulled=!1,this.scene.add(this.bossSubordinateLines)}const o=this.bossSubordinateLines.geometry.attributes.position,n=o.array;for(let r=0;r<this.cachedBossConnections.length&&r<this.maxLineSegments;r++){const{bossId:l,subId:c}=this.cachedBossConnections[r],d=this.buildingMeshes.get(l),h=this.buildingMeshes.get(c);if(d&&h){const g=r*6;n[g]=d.group.position.x,n[g+1]=.1,n[g+2]=d.group.position.z,n[g+3]=h.group.position.x,n[g+4]=.1,n[g+5]=h.group.position.z}}o.needsUpdate=!0,this.bossSubordinateLines.geometry.setDrawRange(0,this.cachedBossConnections.length*2),this.bossSubordinateLines.visible=!0}else this.bossSubordinateLines&&(this.bossSubordinateLines.visible=!1);for(const[o,n]of this.buildingMeshes){if(!e.buildings.get(o))continue;const l=s.has(o),c=n.group.getObjectByName("buildingBody");c&&c.material instanceof A&&(l&&!this.selectedBuildingIds.has(o)?c.material.emissive.setHex(3351040):this.selectedBuildingIds.has(o)||c.material.emissive.setHex(0))}}updateBossLinePositions(){if(!this.bossSubordinateLines||this.cachedBossConnections.length===0)return;const e=this.bossSubordinateLines.geometry.attributes.position,t=e.array;for(let s=0;s<this.cachedBossConnections.length&&s<this.maxLineSegments;s++){const{bossId:i,subId:o}=this.cachedBossConnections[s],n=this.buildingMeshes.get(i),r=this.buildingMeshes.get(o);if(!n||!r)continue;const l=s*6;t[l]=n.group.position.x,t[l+1]=.1,t[l+2]=n.group.position.z,t[l+3]=r.group.position.x,t[l+4]=.1,t[l+5]=r.group.position.z}e.needsUpdate=!0}disposeGroup(e){e.traverse(t=>{if(t instanceof y&&(t.geometry.dispose(),Array.isArray(t.material)?t.material.forEach(s=>s.dispose()):t.material.dispose()),t instanceof K){const s=t.material;s.map&&s.map.dispose(),s.dispose()}})}dispose(){var e;for(const t of this.buildingMeshes.keys())this.removeBuilding(t);this.bossSubordinateLines&&(this.scene.remove(this.bossSubordinateLines),this.bossSubordinateLines.geometry.dispose(),(e=this.bossSubordinateMaterial)==null||e.dispose(),this.bossSubordinateLines=null,this.bossSubordinateMaterial=null),this.cachedBossConnections=[]}}const es={idle:8947848,running:4915102,completed:4890367,error:16730698},ts={flowchart:{primary:5924824,secondary:5001663,accent:10451690,glow:4890367},"circuit-board":{primary:3715756,secondary:2914939,accent:5231045,glow:4915102},constellation:{primary:8411861,secondary:7030465,accent:14073082,glow:12031220},helix:{primary:15557798,secondary:13975436,accent:16156595,glow:10451690},clockwork:{primary:14065198,secondary:12024095,accent:15518027,glow:16755200}};function Oe(a,e,t){const s=es[e],i=new O(.12,16,16),o=new v({color:s,transparent:!0,opacity:.95}),n=new y(i,o);n.position.set(0,t,0),n.name="statusLight",a.add(n);const r=new O(.2,16,16),l=new v({color:s,transparent:!0,opacity:.3}),c=new y(r,l);return c.position.set(0,t,0),c.name="statusGlow",a.add(c),n}function Ze(a){if(a.color)return new H(a.color);const e=ts[a.style||"flowchart"];return new H(e.primary)}function ze(a){const e=ts[a.style||"flowchart"];return new H(e.accent)}function Co(a,e){var m,b;const t=new Y;t.userData.workflowId=a.id,t.userData.isWorkflow=!0;const s=Ze(a),i=ze(a),o=Math.min(a.states.length,8),n=new j(1.3,1.4,.1,32),r=new A({color:2763322,metalness:.6,roughness:.4}),l=new y(n,r);l.position.y=.05,l.receiveShadow=!0,t.add(l);const c=.8;for(let w=0;w<o;w++){const M=w/o*Math.PI*2,S=Math.cos(M)*c,P=Math.sin(M)*c,C=new z(.22,.15,.22),x=new A({color:s,metalness:.3,roughness:.7,emissive:i,emissiveIntensity:.15}),B=new y(C,x);if(B.position.set(S,.55,P),B.castShadow=!0,B.name=`node_${w}`,w===0&&(B.name="buildingBody"),t.add(B),w<o-1){const I=(w+1)/o*Math.PI*2,L=Math.cos(I)*c,E=Math.sin(I)*c,D=[new T(S,.55,P),new T(L,.55,E)],$=new le().setFromPoints(D),G=new ge({color:i.getHex(),transparent:!0,opacity:.6}),W=new ce($,G);W.name=`conn_${w}`,t.add(W)}}const d=new O(.18,16,16),h=new v({color:i.getHex(),transparent:!0,opacity:.5}),g=new y(d,h);g.position.y=.55,g.name="hub",t.add(g);const f=Oe(t,e,1.1),p=ne(a.name);return p.position.set(0,1.5,0),p.name="workflowLabel",t.add(p),t.position.set(((m=a.position)==null?void 0:m.x)||0,0,((b=a.position)==null?void 0:b.z)||0),{group:t,statusLight:f,label:p}}function Po(a,e){const t=a.group.getObjectByName("hub");t&&t.material instanceof v&&(t.material.opacity=.3+Math.sin(e*.8)*.15)}function ko(a,e,t){for(let i=0;i<t;i++){const o=a.group.getObjectByName(i===0?"buildingBody":`node_${i}`);if(o&&o.material instanceof A){const n=(e*2+i*.5)%(Math.PI*2);o.material.emissiveIntensity=.15+Math.sin(n)*.25}}const s=a.group.getObjectByName("hub");s&&(s.rotation.y+=.02)}function Ao(a,e){var m,b;const t=new Y;t.userData.workflowId=a.id,t.userData.isWorkflow=!0;const s=Ze(a),i=ze(a),o=new z(2.2,.12,1.6),n=new A({color:s,metalness:.2,roughness:.8}),r=new y(o,n);r.position.y=.06,r.castShadow=!0,r.receiveShadow=!0,r.name="buildingBody",t.add(r);const l=new ge({color:i.getHex(),transparent:!0,opacity:.7}),c=Math.min(a.states.length,6);for(let w=0;w<c;w++){const S=-.9+w/c*1.8,P=[new T(S,.13,-.6),new T(S,.13,0),new T(S+.3,.13,.3),new T(S+.3,.13,.6)],C=new le().setFromPoints(P),x=new ce(C,l.clone());x.name=`trace_${w}`,t.add(x);const B=new z(.15,.08,.1),I=new A({color:2763322,metalness:.5,roughness:.3,emissive:i,emissiveIntensity:.1}),L=new y(B,I);L.position.set(S+.3,.16,.6),L.name=`chip_${w}`,t.add(L)}const d=new O(.06,8,8),h=new v({color:i.getHex(),transparent:!0,opacity:.8}),g=new y(d,h);g.position.set(-.9,.18,-.6),g.name="dataFlow",t.add(g);const f=Oe(t,e,.7),p=ne(a.name);return p.position.set(0,1.1,0),p.name="workflowLabel",t.add(p),t.position.set(((m=a.position)==null?void 0:m.x)||0,0,((b=a.position)==null?void 0:b.z)||0),{group:t,statusLight:f,label:p}}function xo(a,e,t){for(let s=0;s<t;s++){const i=a.group.getObjectByName(`chip_${s}`);i&&i.material instanceof A&&(i.material.emissiveIntensity=.05+Math.sin(e*.5+s*.4)*.05)}}function Bo(a,e,t){const s=a.group.getObjectByName("dataFlow");if(s){const i=e*.8%1;s.position.x=-.9+i*1.8,s.position.z=-.6+i*1.2}for(let i=0;i<t;i++){const o=a.group.getObjectByName(`chip_${i}`);o&&o.material instanceof A&&(o.material.emissiveIntensity=.1+Math.sin(e*3+i*.8)*.2)}}function To(a,e){var g,f;const t=new Y;t.userData.workflowId=a.id,t.userData.isWorkflow=!0;const s=ze(a),i=new j(1.2,1.3,.05,32),o=new A({color:1710638,metalness:.7,roughness:.3}),n=new y(i,o);n.position.y=.025,n.receiveShadow=!0,n.name="buildingBody",t.add(n);const r=Math.min(a.states.length,8),l=[];for(let p=0;p<r;p++){const m=p/r*Math.PI*2+p*.3,b=.4+p%3*.25,w=.4+p%2*.4,M=new T(Math.cos(m)*b,w,Math.sin(m)*b);l.push(M);const S=new O(.08,12,12),P=new v({color:s.getHex(),transparent:!0,opacity:.9}),C=new y(S,P);C.position.copy(M),C.name=`star_${p}`,t.add(C)}const c=new ge({color:s.getHex(),transparent:!0,opacity:.25});for(let p=0;p<l.length-1;p++){const m=[l[p],l[p+1]],b=new le().setFromPoints(m),w=new ce(b,c.clone());w.name=`link_${p}`,t.add(w)}const d=Oe(t,e,1.2),h=ne(a.name);return h.position.set(0,1.6,0),h.name="workflowLabel",t.add(h),t.position.set(((g=a.position)==null?void 0:g.x)||0,0,((f=a.position)==null?void 0:f.z)||0),{group:t,statusLight:d,label:h}}function Io(a,e,t){for(let s=0;s<t;s++){const i=a.group.getObjectByName(`star_${s}`);i&&i.material instanceof v&&(i.material.opacity=.5+Math.sin(e*.4+s*1.1)*.3)}}function Do(a,e,t){for(let s=0;s<t;s++){const i=a.group.getObjectByName(`star_${s}`);i&&i.material instanceof v&&(i.material.opacity=.6+Math.sin(e*2.5+s*.7)*.35,i.position.y+=Math.sin(e*1.5+s)*.001)}}function Lo(a,e){var m,b;const t=new Y;t.userData.workflowId=a.id,t.userData.isWorkflow=!0;const s=Ze(a),i=ze(a),o=new j(.8,.9,.1,24),n=new A({color:2763322,metalness:.6,roughness:.4}),r=new y(o,n);r.position.y=.05,r.receiveShadow=!0,t.add(r);const l=new Y;l.name="helixGroup";const c=24,d=1.6,h=.4;for(let w=0;w<2;w++){const M=w*Math.PI,S=[];for(let L=0;L<=c;L++){const E=L/c,D=E*Math.PI*4+M;S.push(new T(Math.cos(D)*h,.2+E*d,Math.sin(D)*h))}const P=S,C=new bs(P),x=new ys(C,c,.04,8,!1),B=new A({color:w===0?s:i,metalness:.3,roughness:.6,emissive:w===0?s:i,emissiveIntensity:.1}),I=new y(x,B);I.castShadow=!0,I.name=w===0?"buildingBody":`strand_${w}`,l.add(I)}const g=Math.min(a.states.length,8);for(let w=0;w<g;w++){const M=(w+.5)/g,S=M*Math.PI*4,P=S+Math.PI,C=.2+M*d,x=new T(Math.cos(S)*h,C,Math.sin(S)*h),B=new T(Math.cos(P)*h,C,Math.sin(P)*h),I=new j(.02,.02,x.distanceTo(B),6),L=new v({color:16777215,transparent:!0,opacity:.3}),E=new y(I,L);E.position.copy(x.clone().add(B).multiplyScalar(.5)),E.lookAt(B),E.rotateX(Math.PI/2),E.name=`rung_${w}`,l.add(E)}t.add(l);const f=Oe(t,e,d+.5),p=ne(a.name);return p.position.set(0,d+.9,0),p.name="workflowLabel",t.add(p),t.position.set(((m=a.position)==null?void 0:m.x)||0,0,((b=a.position)==null?void 0:b.z)||0),{group:t,statusLight:f,label:p}}function Eo(a,e,t){const s=a.group.getObjectByName("helixGroup");s&&(s.rotation.y+=t*.15)}function _o(a,e,t,s){const i=a.group.getObjectByName("helixGroup");i&&(i.rotation.y+=t*.6);for(let o=0;o<s;o++){const n=a.group.getObjectByName(`rung_${o}`);n&&n.material instanceof v&&(n.material.opacity=.2+Math.sin(e*3+o*.8)*.3)}}function Oo(a,e){var C,x;const t=new Y;t.userData.workflowId=a.id,t.userData.isWorkflow=!0;const s=Ze(a),i=ze(a),o=new j(1.3,1.4,.12,32),n=new A({color:3815978,metalness:.7,roughness:.3}),r=new y(o,n);r.position.y=.06,r.receiveShadow=!0,t.add(r);const l=new we(.7,.08,8,24),c=new A({color:s,metalness:.8,roughness:.2}),d=new y(l,c);d.position.y=.5,d.rotation.x=Math.PI/2,d.castShadow=!0,d.name="buildingBody",t.add(d);const h=new Y;h.name="mainGearTeeth";const g=16;for(let B=0;B<g;B++){const I=B/g*Math.PI*2,L=new z(.06,.06,.18),E=new A({color:s,metalness:.8,roughness:.2}),D=new y(L,E);D.position.set(Math.cos(I)*.78,.5,Math.sin(I)*.78),D.lookAt(new T(0,.5,0)),h.add(D)}t.add(h);const f=new we(.35,.06,8,16),p=new A({color:i,metalness:.7,roughness:.3,emissive:i,emissiveIntensity:.1}),m=new y(f,p);m.position.set(.85,.5,.4),m.rotation.x=Math.PI/2,m.name="secGear",t.add(m);const b=new j(.08,.08,.6,12),w=new A({color:8947848,metalness:.9,roughness:.1}),M=new y(b,w);M.position.y=.4,t.add(M);const S=Oe(t,e,1),P=ne(a.name);return P.position.set(0,1.4,0),P.name="workflowLabel",t.add(P),t.position.set(((C=a.position)==null?void 0:C.x)||0,0,((x=a.position)==null?void 0:x.z)||0),{group:t,statusLight:S,label:P}}function zo(a,e,t){const s=a.group.getObjectByName("mainGearTeeth");s&&(s.rotation.y+=t*.1);const i=a.group.getObjectByName("secGear");i&&(i.rotation.z-=t*.15)}function Go(a,e,t){const s=a.group.getObjectByName("mainGearTeeth");s&&(s.rotation.y+=t*.5);const i=a.group.getObjectByName("secGear");i&&(i.rotation.z-=t*.75)}function Ro(a,e){switch(a.style||"flowchart"){case"circuit-board":return Ao(a,e);case"constellation":return To(a,e);case"helix":return Lo(a,e);case"clockwork":return Oo(a,e);case"flowchart":default:return Co(a,e)}}function Ho(a,e,t,s){const i=e.style||"flowchart",o=Math.min(e.states.length,8);switch(i){case"flowchart":Po(a,t);break;case"circuit-board":xo(a,t,o);break;case"constellation":Io(a,t,o);break;case"helix":Eo(a,t,s);break;case"clockwork":zo(a,t,s);break}}function Wo(a,e,t,s){const i=e.style||"flowchart",o=Math.min(e.states.length,8),n=a.group.getObjectByName("statusGlow"),r=Math.sin(t*3)*.2+.8;switch(n&&n.material instanceof v&&(n.material.opacity=.3*r),i){case"flowchart":ko(a,t,o);break;case"circuit-board":Bo(a,t,o);break;case"constellation":Do(a,t,o);break;case"helix":_o(a,t,s,o);break;case"clockwork":Go(a,t,s);break}}function Fo(a,e){const t=a.group.getObjectByName("statusGlow"),s=Math.sin(e*2)*.5+.5;t&&t.material instanceof v&&(t.material.opacity=.4*s)}class No{constructor(e){u(this,"scene");u(this,"workflowMeshes",new Map);u(this,"animationTime",0);u(this,"brightness",1);u(this,"statusProvider",null);u(this,"onWorkflowClick",null);u(this,"onWorkflowDoubleClick",null);this.scene=e}setOnWorkflowClick(e){this.onWorkflowClick=e}setOnWorkflowDoubleClick(e){this.onWorkflowDoubleClick=e}setStatusProvider(e){this.statusProvider=e}setBrightness(e){this.brightness=e;for(const t of this.workflowMeshes.values()){const s=t.group.getObjectByName("statusGlow");s&&s.material instanceof v&&(s.material.opacity=.3*e),t.group.traverse(i=>{if(i instanceof y&&i.material instanceof A){const o=i.material;o.userData.baseEmissiveIntensity===void 0&&(o.userData.baseEmissiveIntensity=o.emissiveIntensity||1),o.emissiveIntensity=o.userData.baseEmissiveIntensity*e}})}}addWorkflow(e){var o;this.removeWorkflow(e.id);const t=((o=this.statusProvider)==null?void 0:o.call(this,e.id))||"idle",s=Ro(e,t);s.group.userData.style=e.style||"flowchart",s.group.userData.color=e.color||"";const i=e.scale||1;s.group.scale.setScalar(i),this.scene.add(s.group),this.workflowMeshes.set(e.id,s)}removeWorkflow(e){const t=this.workflowMeshes.get(e);t&&(this.scene.remove(t.group),this.disposeGroup(t.group),this.workflowMeshes.delete(e))}updateWorkflow(e){var g,f,p,m;const t=this.workflowMeshes.get(e.id);if(!t){this.addWorkflow(e);return}const s=t.group.userData.style,i=t.group.userData.color;if(s!==(e.style||"flowchart")||i!==(e.color||"")){this.removeWorkflow(e.id),this.addWorkflow(e);return}t.group.position.set(((g=e.position)==null?void 0:g.x)||0,0,((f=e.position)==null?void 0:f.z)||0);const o=e.scale||1;t.group.scale.setScalar(o);const n=((p=this.statusProvider)==null?void 0:p.call(this,e.id))||"idle",r=es[n],l=t.group.getObjectByName("statusLight");l&&l.material instanceof v&&l.material.color.setHex(r);const c=t.group.getObjectByName("statusGlow");c&&c.material instanceof v&&c.material.color.setHex(r),((m=t.label.material.map)==null?void 0:m.image)&&Jt(t,e.name)}setWorkflowPosition(e,t){const s=this.workflowMeshes.get(e);s&&s.group.position.set(t.x,0,t.z)}getWorkflowAtPosition(e,t){for(const[s,i]of this.workflowMeshes){const o=t.get(s);if(!o)continue;const n=o.scale||1,r=1.5*n,l=1.5*n,c=Math.abs(e.x-i.group.position.x),d=Math.abs(e.z-i.group.position.z);if(c<=r&&d<=l)return o}return null}getWorkflowMeshes(){return Array.from(this.workflowMeshes.values()).map(e=>e.group)}getWorkflowMeshData(){return this.workflowMeshes}highlightWorkflow(e){for(const t of this.workflowMeshes.values()){const s=t.group.getObjectByName("buildingBody");s&&s.material instanceof A&&s.material.emissive.setHex(0)}if(e){const t=this.workflowMeshes.get(e);if(t){const s=t.group.getObjectByName("buildingBody");s&&s.material instanceof A&&s.material.emissive.setHex(2236996)}}}syncFromDefinitions(e){for(const t of this.workflowMeshes.keys())e.has(t)||this.removeWorkflow(t);for(const t of e.values())this.workflowMeshes.has(t.id)?this.updateWorkflow(t):this.addWorkflow(t)}update(e,t){var s;this.animationTime+=e;for(const[i,o]of this.workflowMeshes){const n=t.get(i);if(!n)continue;const r=((s=this.statusProvider)==null?void 0:s.call(this,i))||"idle";Ho(o,n,this.animationTime,e),r==="running"?Wo(o,n,this.animationTime,e):r==="error"&&Fo(o,this.animationTime)}}disposeGroup(e){e.traverse(t=>{if(t instanceof y&&(t.geometry.dispose(),Array.isArray(t.material)?t.material.forEach(s=>s.dispose()):t.material.dispose()),t instanceof K){const s=t.material;s.map&&s.map.dispose(),s.dispose()}t instanceof ce&&(t.geometry.dispose(),t.material instanceof Pe&&t.material.dispose())})}dispose(){for(const e of this.workflowMeshes.keys())this.removeWorkflow(e)}}const Le=class Le{constructor(e,t,s,i,o,n){u(this,"scene");u(this,"characterLoader");u(this,"characterFactory");u(this,"movementAnimator");u(this,"proceduralAnimator");u(this,"effectsManager");u(this,"agentMeshes",new Map);u(this,"pendingAgents",[]);u(this,"modelsReady",!1);u(this,"characterScale",.5);u(this,"brightness",1);u(this,"idleAnimation",Q.SIT);u(this,"workingAnimation",Q.WALK);u(this,"previousAgentStatuses",new Map);u(this,"modelStyle",{saturation:1,roughness:-1,metalness:-1,emissiveBoost:0,envMapIntensity:-1,wireframe:!1,colorMode:"normal"});u(this,"onAgentMeshesChanged",null);u(this,"onProceduralCacheInvalidated",null);u(this,"onToast",null);this.scene=e,this.characterLoader=t,this.characterFactory=s,this.movementAnimator=i,this.proceduralAnimator=o,this.effectsManager=n}setOnAgentMeshesChanged(e){this.onAgentMeshesChanged=e}setOnProceduralCacheInvalidated(e){this.onProceduralCacheInvalidated=e}setOnToast(e){this.onToast=e}getAgentMeshes(){return this.agentMeshes}isModelsReady(){return this.modelsReady}setCharacterScale(e){this.characterScale=e;for(const t of this.agentMeshes.values()){const s=t.group.getObjectByName("characterBody");if(s){const i=s.userData.customModelScale??1,o=t.group.userData.isBoss===!0,n=o?1.5:1;s.scale.setScalar(i*e*n);const r=t.group.getObjectByName("statusBar");if(r){const c=new nt().setFromObject(s).max.y,d=o?.2:.3,h=o?3:2.2;r.position.y=Math.min(Math.max(c,1)+d,h)}}}}setBrightness(e){this.brightness=e;for(const t of this.agentMeshes.values())this.applyStyleToMesh(t.group)}setModelStyle(e){Object.assign(this.modelStyle,e);for(const t of this.agentMeshes.values())this.applyStyleToMesh(t.group)}getModelStyle(){return{...this.modelStyle}}injectColorShader(e){const t=this.modelStyle.saturation,s=Le.COLOR_MODE_INDEX[this.modelStyle.colorMode]??0;if(e.userData.hasColorShader)e.userData.shader&&(e.userData.shader.uniforms.uSaturation.value=t,e.userData.shader.uniforms.uColorMode.value=s);else{e.userData.hasColorShader=!0;const i=this;e.onBeforeCompile=o=>{o.uniforms.uSaturation={value:i.modelStyle.saturation},o.uniforms.uColorMode={value:Le.COLOR_MODE_INDEX[i.modelStyle.colorMode]??0},o.fragmentShader=o.fragmentShader.replace("#include <common>",`#include <common>
|
|
1
|
+
var ns=Object.defineProperty;var as=(a,e,t)=>e in a?ns(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var u=(a,e,t)=>as(a,typeof e!="symbol"?e+"":e,t);import{E as y,S as Wt,v as A,x as v,ak as rs,ai as We,al as ot,A as wt,am as K,an as J,ah as ke,w as oe,ao as se,l as bt,o as te,U as Y,ap as j,g as T,aq as ls,aj as cs,ar as hs,as as ds,t as Pe,K as Ye,at as pe,z as le,B as Ae,s as pt,au as Me,av as O,I as me,f as Xe,Q as Ee,aw as Ft,ax as z,ay as xe,P as us,C as H,a8 as gs,R as Ge,az as Je,aA as ps,i as Nt,af as jt,aB as fs,D as et,aC as ms,V as re,aD as Fe,aE as je,X as $t,u as ge,H as ce,ag as yt,aF as we,aG as Ut,aH as Mt,aI as ws,G as Yt,aJ as bs,aK as ys,aa as nt,aL as Ms,aM as ye,aN as ve,aO as Ss,W as vs,Y as Cs,aP as St,aQ as at,aR as Ps,aS as ks,aT as As,aU as xs,ac as Bs,ad as Xt,ae as Ts,aV as Is,aW as Ds,aX as Ls,aY as Es,ab as _s}from"./vendor-three-Chj50gSY.js";import{bS as Os,bT as zs,bU as Gs,bX as Ie,bV as Rs,k as Vt,l as Zt,A as rt,m as Hs,bY as Ws,T as Fs,bZ as ft,b_ as Ce,s as k,x as $e,v as lt,b$ as Ns,c0 as js,F as Be,n as he,o as $s,S as Us,w as Ne,t as Ys,c1 as Xs,c2 as Vs,c3 as vt,c4 as Zs}from"./main-COvyQg-T.js";import"./vendor-react--Eh9ivFN.js";function Ct(a){const e=new Map,t=new Map,s=a.clone();return Kt(a,s,function(i,o){e.set(o,i),t.set(i,o)}),s.traverse(function(i){if(!i.isSkinnedMesh)return;const o=i,n=e.get(i),r=n.skeleton.bones;o.skeleton=n.skeleton.clone(),o.bindMatrix.copy(n.bindMatrix),o.skeleton.bones=r.map(function(l){return t.get(l)}),o.bind(o.skeleton,o.bindMatrix)}),s}function Kt(a,e,t){t(a,e);for(let s=0;s<a.children.length;s++)Kt(a.children[s],e.children[s],t)}class Ks{constructor(){u(this,"models",new Map);u(this,"customModels",new Map);u(this,"loaded",!1);u(this,"loadingPromise",null);u(this,"loader");u(this,"dracoLoader");u(this,"loadingCustomModels",new Map);this.loader=new Os,this.dracoLoader=new zs,this.dracoLoader.setDecoderPath("https://www.gstatic.com/draco/versioned/decoders/1.5.7/"),this.loader.setDRACOLoader(this.dracoLoader),this.loader.setMeshoptDecoder(Gs)}get isLoaded(){return this.loaded}async loadAll(){if(this.loaded){console.log("[CharacterLoader] Already loaded, skipping");return}if(this.loadingPromise)return console.log("[CharacterLoader] Already loading, waiting for existing promise"),this.loadingPromise;const e=[...new Set([...Object.values(Ie),...Rs.map(t=>t.file)])];return console.log(`[CharacterLoader] Starting to load ${e.length} models`),this.loadingPromise=Promise.all(e.map(t=>this.loadModel(t))).then(()=>{this.loaded=!0,console.log(`[CharacterLoader] All models loaded. Cache size: ${this.models.size}`)}),this.loadingPromise}loadModel(e){return new Promise(t=>{const s=`/assets/characters/${e}`;console.log(`[CharacterLoader] Loading model: ${s}`),this.loader.load(s,i=>{console.log(`[CharacterLoader] Successfully loaded: ${e}`);const o=this.prepareModel(i.scene);this.models.set(e,{scene:o,animations:i.animations}),t()},i=>{},i=>{console.error(`[CharacterLoader] Failed to load ${e}:`,i),t()})})}prepareModel(e){return e.scale.setScalar(1),e.position.set(0,0,0),e.rotation.set(0,0,0),e.visible=!1,e.traverse(t=>{if(t instanceof y&&(t.castShadow=!0,t.receiveShadow=!0,t.material)){const s=t.material;s.map&&(s.map.colorSpace=Wt),s.isMeshStandardMaterial&&(s.roughness=s.roughness??.6,s.metalness=s.metalness??0,s.envMapIntensity=.8,s.needsUpdate=!0)}}),e}clone(e){const t=Ie[e];return this.cloneByModelFile(t)}cloneByModelFile(e){const t=this.models.get(e);if(!t)return console.warn(`[CharacterLoader] Model not found: ${e}`),null;const s=Ct(t.scene);return s.visible=!0,s.position.set(0,0,0),s.rotation.set(0,0,0),s.traverse(i=>{i.visible=!0,i instanceof y&&i.material&&(Array.isArray(i.material)?i.material=i.material.map(o=>o.clone()):i.material=i.material.clone())}),{mesh:s,animations:t.animations}}getAnimations(e){const t=Ie[e],s=this.models.get(t);return(s==null?void 0:s.animations)??null}hasModel(e){const t=Ie[e];return this.models.has(t)}async loadCustomModel(e){if(this.customModels.has(e))return;const t=this.loadingCustomModels.get(e);if(t)return t;const s=new Promise(i=>{this.loader.load(Vt(Zt(`/api/custom-models/${e}`)),o=>{const n=this.prepareModel(o.scene);this.customModels.set(e,{scene:n,animations:o.animations}),console.log(`[CharacterLoader] Loaded custom model for class: ${e} (${o.animations.length} animations)`),i()},void 0,o=>{console.error(`[CharacterLoader] Failed to load custom model for ${e}:`,o),i()})});this.loadingCustomModels.set(e,s);try{await s}finally{this.loadingCustomModels.delete(e)}}hasCustomModel(e){return this.customModels.has(e)}cloneCustomModel(e){const t=this.customModels.get(e);if(!t)return null;const s=Ct(t.scene);return s.visible=!0,s.position.set(0,0,0),s.rotation.set(0,0,0),s.traverse(i=>{i.visible=!0,i instanceof y&&i.material&&(Array.isArray(i.material)?i.material=i.material.map(o=>o.clone()):i.material=i.material.clone())}),{mesh:s,animations:t.animations}}getCustomModelAnimations(e){const t=this.customModels.get(e);return(t==null?void 0:t.animations)??null}unloadCustomModel(e){const t=this.customModels.get(e);t&&(this.disposeCachedModel(t),this.customModels.delete(e),console.log(`[CharacterLoader] Unloaded custom model for class: ${e}`))}disposeCachedModel(e){e.scene.traverse(t=>{var s;t instanceof y&&((s=t.geometry)==null||s.dispose(),Array.isArray(t.material)?t.material.forEach(i=>this.disposeMaterial(i)):t.material&&this.disposeMaterial(t.material))})}disposeMaterial(e){var t,s,i,o,n,r,l,c,d,h,g;(e instanceof A||e instanceof v||e instanceof rs)&&((t=e.map)==null||t.dispose(),"normalMap"in e&&((s=e.normalMap)==null||s.dispose()),"roughnessMap"in e&&((i=e.roughnessMap)==null||i.dispose()),"metalnessMap"in e&&((o=e.metalnessMap)==null||o.dispose()),"emissiveMap"in e&&((n=e.emissiveMap)==null||n.dispose()),"aoMap"in e&&((r=e.aoMap)==null||r.dispose()),"lightMap"in e&&((l=e.lightMap)==null||l.dispose()),"bumpMap"in e&&((c=e.bumpMap)==null||c.dispose()),"displacementMap"in e&&((d=e.displacementMap)==null||d.dispose()),"alphaMap"in e&&((h=e.alphaMap)==null||h.dispose()),"envMap"in e&&((g=e.envMap)==null||g.dispose())),e.dispose()}dispose(){for(const[e,t]of this.models)this.disposeCachedModel(t),console.log(`[CharacterLoader] Disposed model template: ${e}`);this.models.clear();for(const[e,t]of this.customModels)this.disposeCachedModel(t),console.log(`[CharacterLoader] Disposed custom model: ${e}`);this.customModels.clear(),this.dracoLoader.dispose(),this.loaded=!1,this.loadingPromise=null,this.loadingCustomModels.clear(),console.log("[CharacterLoader] All model caches disposed")}getCacheStats(){return{builtInModels:this.models.size,customModels:this.customModels.size,modelNames:Array.from(this.models.keys()),customModelIds:Array.from(this.customModels.keys())}}}const qs="character-male-a.glb";class Qs{constructor(e){u(this,"customClasses",new Map);this.characterLoader=e}setCustomClasses(e){this.customClasses=e}getClassConfig(e){const t=rt[e];if(t)return t;const s=this.customClasses.get(e);if(s){const i=parseInt(s.color.replace("#",""),16);return{icon:s.icon,color:isNaN(i)?8947848:i,description:s.description}}return{icon:"❓",color:8947848,description:"Unknown class"}}getModelInfo(e){const t=Ie[e];if(t)return{file:t,isCustomModel:!1};const s=this.customClasses.get(e);if(s){if(s.customModelPath)return{file:s.customModelPath,isCustomModel:!0,customClassId:s.id,scale:s.modelScale,offset:s.modelOffset};if(s.model)return{file:s.model,isCustomModel:!1,scale:s.modelScale,offset:s.modelOffset}}return{file:qs,isCustomModel:!1}}createCharacterBody(e,t){const s=this.getModelInfo(e.class);let i=null;try{s.isCustomModel&&s.customClassId&&(i=this.characterLoader.cloneCustomModel(s.customClassId)),i||(i=this.characterLoader.cloneByModelFile(s.file))}catch(l){console.error(`[ModelLoader] Failed to clone model for class ${e.class} (agent ${e.name}):`,l),i=null}if(i){i.mesh.name="characterBody";const l=s.scale??1;i.mesh.userData.customModelScale=l,i.mesh.userData.isCustomModel=s.isCustomModel,s.offset&&(s.offset.x!==0||s.offset.y!==0||s.offset.z!==0)&&i.mesh.position.set(s.offset.x,s.offset.z,s.offset.y);const c=this.customClasses.get(e.class);c!=null&&c.animationMapping&&(i.mesh.userData.animationMapping=c.animationMapping);const d=new We(i.mesh),h=new Map;for(const g of i.animations){const f=g.name.toLowerCase();h.set(f,g),h.set(g.name,g)}return{body:i.mesh,mixer:d,animations:h}}const o=new ot(.5,1,4,16),n=new A({color:t,roughness:.4,metalness:.3}),r=new y(o,n);return r.position.y=1,r.castShadow=!0,r.receiveShadow=!0,r.name="characterBody",{body:r,mixer:null,animations:new Map}}calculateModelHeight(e,t){return t?2:1.5}upgradeToCharacterModel(e,t){const s=e.getObjectByName("characterBody");if(!(s instanceof y)||!(s.geometry instanceof ot))return null;const i=this.characterLoader.clone(t.class);if(!i)return null;e.remove(s),s.geometry.dispose(),s.material.dispose(),i.mesh.name="characterBody",e.add(i.mesh);const o=new We(i.mesh),n=new Map;for(const r of i.animations){const l=r.name.toLowerCase();n.set(l,r)}return{group:e,mixer:o,animations:n,currentAction:null}}replaceAgentModel(e,t){const{group:s}=e,i=this.getModelInfo(t.class);let o=null;if(i.isCustomModel&&i.customClassId&&(o=this.characterLoader.cloneCustomModel(i.customClassId)),o||(o=this.characterLoader.cloneByModelFile(i.file)),!o)return console.warn(`[ModelLoader] Could not load model for class ${t.class}, keeping current model`),s.userData.agentClass=t.class,null;const n=s.getObjectByName("characterBody");n&&(s.remove(n),n.traverse(h=>{var g;(h instanceof y||h instanceof wt)&&((g=h.geometry)==null||g.dispose(),Array.isArray(h.material)?h.material.forEach(f=>this.disposeMaterial(f)):h.material&&this.disposeMaterial(h.material))})),e.mixer&&(e.mixer.stopAllAction(),e.mixer.uncacheRoot(s)),o.mesh.name="characterBody";const r=i.scale??1;o.mesh.userData.customModelScale=r,o.mesh.userData.isCustomModel=i.isCustomModel,i.offset&&(i.offset.x!==0||i.offset.y!==0||i.offset.z!==0)&&o.mesh.position.set(i.offset.x,i.offset.z,i.offset.y);const l=this.customClasses.get(t.class);l!=null&&l.animationMapping&&(o.mesh.userData.animationMapping=l.animationMapping),s.add(o.mesh);const c=new We(o.mesh),d=new Map;for(const h of o.animations){const g=h.name.toLowerCase();d.set(g,h),d.set(h.name,h)}return s.userData.agentClass=t.class,console.log(`[ModelLoader] Agent ${t.name} model updated to ${i.file}`),{group:s,mixer:c,animations:d,currentAction:null}}disposeAgentMesh(e){for(e.mixer&&(e.mixer.stopAllAction(),e.mixer.uncacheRoot(e.group)),e.group.traverse(t=>{var s,i;t instanceof y?((s=t.geometry)==null||s.dispose(),Array.isArray(t.material)?t.material.forEach(o=>this.disposeMaterial(o)):t.material&&this.disposeMaterial(t.material)):t instanceof K?this.disposeMaterial(t.material):t instanceof wt&&((i=t.geometry)==null||i.dispose(),Array.isArray(t.material)?t.material.forEach(o=>this.disposeMaterial(o)):t.material&&this.disposeMaterial(t.material))});e.group.children.length>0;)e.group.remove(e.group.children[0]);e.animations.clear()}disposeMaterial(e){var t,s,i,o,n;(e instanceof A||e instanceof v||e instanceof J)&&((t=e.map)==null||t.dispose(),"normalMap"in e&&((s=e.normalMap)==null||s.dispose()),"roughnessMap"in e&&((i=e.roughnessMap)==null||i.dispose()),"metalnessMap"in e&&((o=e.metalnessMap)==null||o.dispose()),"emissiveMap"in e&&((n=e.emissiveMap)==null||n.dispose())),e.dispose()}}class Js{createAnimationSetup(e,t,s){s!=null&&s.animationMapping&&(e.userData.animationMapping=s.animationMapping);const i=new We(e),o=new Map;for(const n of t)o.set(n.name.toLowerCase(),n),o.set(n.name,n);return{mixer:i,animations:o}}getIdleTimerColor(e){const i=Math.min(e/60,60)/60,o=Math.pow(i,.7),n=120*(1-o),r=80+20*o,l=60-10*o,c=`hsl(${Math.round(n)}, ${Math.round(r)}%, ${Math.round(l)}%)`;return{text:c,border:c}}formatIdleTimeShort(e){if(e<60)return`${e}s`;const t=Math.floor(e/60);if(t<60){const n=e%60;return n>0?`${t}m ${n}s`:`${t}m`}const s=Math.floor(t/60),i=t%60;return s<24?i>0?`${s}h ${i}m`:`${s}h`:`${Math.floor(s/24)}d`}}const Pt={idle:4915102,working:4890367,waiting:16752202,waiting_permission:16763904,error:16730698,orphaned:16711935,default:8947848},ei=800,kt=420,At=5;function qt(a){return Hs(a).freePercent}class ti{constructor(e){u(this,"idleTimerCanvas",null);u(this,"idleTimerCtx",null);u(this,"manaBarCanvas",null);u(this,"manaBarCtx",null);u(this,"providerBadgeImages",new Map);u(this,"providerBadgeVersion",0);this.animConfig=e}getNameLabelBaseScale(e,t){return e?3.1:2.5}fitNameLabelText(e,t,s,i,o){e.font=`bold ${s}px Arial`;const n=i-(o?s*.42+s*.3:0);if(e.measureText(t).width<=n)return t;let r=t;for(;r.length>3&&e.measureText(`${r}...`).width>n;)r=r.slice(0,-1);return`${r}...`}fitTaskLabelText(e,t,s,i){if(e.font=`italic ${s}px "Segoe UI", Arial, sans-serif`,e.measureText(t).width<=i)return t;let o=t;for(;o.length>3&&e.measureText(`${o}...`).width>i;)o=o.slice(0,-1);return`${o}...`}getProviderBadgeImage(e){if(e!=="claude"&&e!=="codex"&&e!=="opencode")return null;const t=this.providerBadgeImages.get(e);if(t)return t;if(typeof Image>"u")return null;const s=new Image;return s.decoding="async",s.src=e==="codex"?"/assets/codex.png":e==="opencode"?"/assets/opencode.png":"/assets/claude.png",s.onload=()=>{this.providerBadgeVersion+=1},this.providerBadgeImages.set(e,s),s}getStatusColor(e){return Pt[e]??Pt.default}createSelectionRing(e,t=!1){const s=t?1.5:1,i=new ke(.8*s,.95*s,32),o=new v({color:e,side:oe,transparent:!0,opacity:0,depthTest:!1}),n=new y(i,o);return n.rotation.x=-Math.PI/2,n.position.y=.05,n.renderOrder=999,n.name="selectionRing",n}createStatusBarSprite(e,t,s,i,o=2){const n=document.createElement("canvas"),r=n.getContext("2d");n.width=4096,n.height=2560,this.drawStatusBar(r,n.width,n.height,e,t,s,i);const l=new se(n);l.minFilter=bt,l.magFilter=te,l.generateMipmaps=!0,l.anisotropy=16,l.needsUpdate=!0;const c=new J({map:l,transparent:!0,depthTest:!1,depthWrite:!1}),d=new K(c),h=i?.8:.5;d.position.y=o+h;const g=i?2.6:2.1,f=n.height/n.width;return d.scale.set(g,g*f,1),d.name="statusBar",d.renderOrder=1100,d.userData.modelHeight=o,d.userData.baseIndicatorScale=g,d.userData.aspectRatio=f,d}createNameLabelSprite(e,t,s,i,o){const n=document.createElement("canvas"),r=n.getContext("2d");n.width=4096,n.height=o?2048:1024,this.drawNameLabel(r,n.width,n.height,e,t,s,i,o);const l=new se(n);l.minFilter=bt,l.magFilter=te,l.generateMipmaps=!0,l.anisotropy=16,l.needsUpdate=!0;const c=new J({map:l,transparent:!0,depthTest:!1,depthWrite:!1}),d=new K(c),h=this.getNameLabelBaseScale(s,!!o);d.position.y=o?s?-1.2:-1:s?-.9:-.7;const g=n.height/n.width;return d.scale.set(h,h*g,1),d.name="nameLabelSprite",d.renderOrder=1200,d.userData.baseIndicatorScale=h,d.userData.aspectRatio=g,d.userData.nameLabelLayoutVersion=At,d.userData.providerBadgeVersion=this.providerBadgeVersion,d}drawNameLabel(e,t,s,i,o,n,r,l){e.clearRect(0,0,t,s);const c=`#${o.toString(16).padStart(6,"0")}`,d=l?s*.3:s/2,h=this.getProviderBadgeImage(r),g=h!==null,f=n?Math.max(kt,ei-300):kt;e.font=`bold ${f}px Arial`;const p=this.fitNameLabelText(e,i,f,t-400,g),m=e.measureText(p).width,b=g?f*.95:0,w=g?f*.32:0,M=b+w,S=m+M,P=t/2+M/2;if(e.textAlign="center",e.textBaseline="middle",e.shadowColor="rgba(0, 0, 0, 0.9)",e.shadowBlur=f*.12,e.shadowOffsetX=f*.04,e.shadowOffsetY=f*.04,e.strokeStyle="#000",e.lineWidth=f*.14,e.lineJoin="round",e.strokeText(p,P,d),e.shadowColor="transparent",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0,g){const C=t/2-S/2,x=d-b/2;if(h&&h.complete&&h.naturalWidth>0)e.drawImage(h,C,x,b,b);else{const B=C+b/2,I=d,L=r==="codex"?"#4a9eff":r==="opencode"?"#10b981":"#ff9e4a";e.beginPath(),e.arc(B,I,b/2,0,Math.PI*2),e.fillStyle=L,e.fill()}}if(e.fillStyle=c,e.fillText(p,P,d),l){const C=Math.round(f*.85),x=s*.55,B=t-600,I=C,L=this.fitTaskLabelText(e,l,I,B);e.font=`italic ${I}px "Segoe UI", Arial, sans-serif`,e.shadowColor="rgba(0, 0, 0, 0.8)",e.shadowBlur=I*.1,e.shadowOffsetX=I*.03,e.shadowOffsetY=I*.03,e.strokeStyle="#000",e.lineWidth=I*.12,e.lineJoin="round",e.strokeText(L,t/2,x),e.shadowColor="transparent",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0,e.fillStyle="rgba(190, 205, 225, 0.9)",e.fillText(L,t/2,x)}}drawStatusBar(e,t,s,i,o,n,r){e.clearRect(0,0,t,s);const l=t/2048;let c=80*l;r&&(e.font=`${400*l}px serif`,e.textAlign="center",e.textBaseline="top",e.fillText("👑",t/2,c),c+=440*l);const d=200*l,h=1350*l,g=(t-h)/2,f=c,p=200*l,m=g+p/2+30*l,b=f+d/2;let w;switch(o){case"working":w="#4a9eff";break;case"orphaned":w="#c060e0";break;case"error":w="#e05050";break;case"waiting":case"waiting_permission":w="#e0a030";break;default:w="#40c090"}e.beginPath(),e.arc(m,b,p/2,0,Math.PI*2),e.fillStyle=w,e.shadowColor=w,e.shadowBlur=20*l,e.fill(),e.shadowBlur=0,e.strokeStyle="rgba(0, 0, 0, 0.4)",e.lineWidth=4*l,e.stroke();const M=g+p+60*l,S=h-p-90*l,P=d-80*l,C=f+40*l,x=30*l;e.fillStyle="#0d0d14",e.beginPath(),e.roundRect(M,C,S,P,x),e.fill(),e.strokeStyle="rgba(80, 90, 110, 0.5)",e.lineWidth=4*l,e.stroke();const B=Math.max(0,Math.min(100,i))/100,I=8*l,L=Math.max(0,(S-I*2)*B);if(L>0){let G;B>.5?G="#00c896":B>.2?G="#e8a020":G="#e84040",e.fillStyle=G,e.beginPath(),e.roundRect(M+I,C+I,L,P-I*2,x-I),e.fill(),e.shadowColor=G,e.shadowBlur=12*l,e.fill(),e.shadowBlur=0}const E=`${Math.round(B*100)}%`;e.font=`bold ${180*l}px "Segoe UI", Arial, sans-serif`,e.textAlign="center",e.textBaseline="middle";const D=M+S/2,$=C+P/2;if(e.shadowColor="rgba(0, 0, 0, 0.8)",e.shadowBlur=8*l,e.shadowOffsetX=2*l,e.shadowOffsetY=2*l,e.strokeStyle="rgba(0, 0, 0, 0.9)",e.lineWidth=24*l,e.lineJoin="round",e.strokeText(E,D,$),e.shadowColor="transparent",e.shadowBlur=0,e.shadowOffsetX=0,e.shadowOffsetY=0,e.fillStyle="rgba(255, 255, 255, 0.95)",e.fillText(E,D,$),c+=d+60*l,o==="idle"&&n>0){const G=Math.floor((Date.now()-n)/1e3),W=this.animConfig.formatIdleTimeShort(G),Z=this.animConfig.getIdleTimerColor(G);e.font=`bold ${140*l}px Arial`;const F=e.measureText(`⏱ ${W}`).width+140*l,R=180*l,_=(t-F)/2,U=c;e.fillStyle="rgba(0, 0, 0, 0.85)",e.beginPath(),e.roundRect(_,U,F,R,28*l),e.fill(),e.strokeStyle=Z.border,e.lineWidth=12*l,e.stroke(),e.textAlign="center",e.textBaseline="middle",e.strokeStyle="#000",e.lineWidth=14*l,e.strokeText(`⏱ ${W}`,t/2,U+R/2),e.fillStyle=Z.text,e.fillText(`⏱ ${W}`,t/2,U+R/2)}}drawCombinedUI(e,t,s,i,o,n,r,l,c){e.clearRect(0,0,t,s);const d=`#${o.toString(16).padStart(6,"0")}`,h=t/2048;let g=80*h;c&&(e.font=`${288*h}px serif`,e.textAlign="center",e.textBaseline="top",e.fillText("👑",t/2,g),g+=320*h);const f=224*h,p=t-240*h;e.font=`bold ${f}px Arial`;let m=i;if(e.measureText(m).width>p){for(;m.length>3&&e.measureText(m+"...").width>p;)m=m.slice(0,-1);m+="..."}e.textAlign="center",e.textBaseline="middle";const w=g+f/2;e.strokeStyle="#000",e.lineWidth=24*h,e.lineJoin="round",e.strokeText(m,t/2,w),e.fillStyle=d,e.fillText(m,t/2,w),g+=f+64*h;const M=200*h,S=1350*h,P=(t-S)/2,C=g,x=176*h,B=P+x/2+24*h,I=C+M/2;let L;switch(r){case"working":L="#00a8ff";break;case"orphaned":L="#e040ff";break;case"error":L="#ff3030";break;case"waiting":case"waiting_permission":L="#ffc000";break;default:L="#00e090"}e.beginPath(),e.arc(B,I,x/2,0,Math.PI*2),e.fillStyle=L,e.fill(),e.shadowColor=L,e.shadowBlur=32*h,e.fill(),e.shadowBlur=0,e.strokeStyle="#000",e.lineWidth=12*h,e.stroke();const E=P+x+64*h,D=S-x-88*h,$=M-48*h,G=C+24*h;e.fillStyle="#000",e.beginPath(),e.roundRect(E,G,D,$,24*h),e.fill(),e.strokeStyle="#5a8a8a",e.lineWidth=8*h,e.stroke();const W=Math.max(0,Math.min(100,n))/100,Z=16*h,N=Math.max(0,(D-Z*2)*W);if(N>0){let U;W>.5?U="#00ff88":W>.2?U="#ffaa00":U="#ff3366",e.fillStyle=U,e.beginPath(),e.roundRect(E+Z,G+Z,N,$-Z*2,16*h),e.fill(),e.shadowColor=U,e.shadowBlur=32*h,e.fill(),e.shadowBlur=0}const F=`${Math.round(W*100)}%`;e.font=`bold ${128*h}px Arial`,e.textAlign="center",e.textBaseline="middle";const R=E+D/2,_=G+$/2;if(e.strokeStyle="#000",e.lineWidth=28*h,e.lineJoin="round",e.strokeText(F,R,_),e.fillStyle="#fff",e.shadowColor="#000",e.shadowBlur=8*h,e.fillText(F,R,_),e.shadowBlur=0,g+=M+48*h,r==="idle"&&l>0){const U=Math.floor((Date.now()-l)/1e3),q=this.animConfig.formatIdleTimeShort(U),V=this.animConfig.getIdleTimerColor(U);e.font=`bold ${160*h}px Arial`;const fe=e.measureText(`⏱ ${q}`).width+160*h,qe=216*h,os=(t-fe)/2,Qe=g;e.fillStyle="rgba(0, 0, 0, 0.85)",e.beginPath(),e.roundRect(os,Qe,fe,qe,32*h),e.fill(),e.strokeStyle=V.border,e.lineWidth=12*h,e.stroke(),e.textAlign="center",e.textBaseline="middle",e.strokeStyle="#000",e.lineWidth=16*h,e.strokeText(`⏱ ${q}`,t/2,Qe+qe/2),e.fillStyle=V.text,e.fillText(`⏱ ${q}`,t/2,Qe+qe/2)}}createManaBar(e,t,s=!1){const i=document.createElement("canvas"),o=i.getContext("2d");i.width=400,i.height=64,this.drawManaBar(o,i.width,i.height,e,t);const n=new se(i);n.minFilter=te,n.magFilter=te,n.needsUpdate=!0;const r=new J({map:n,transparent:!0,depthTest:!1}),l=new K(r);return l.position.y=s?3:2,l.scale.set(s?1.4:1.1,s?.22:.18,1),l.name="manaBar",l}drawManaBar(e,t,s,i,o){const n=Math.max(0,Math.min(100,i))/100;e.clearRect(0,0,t,s);const r=s/32,l=20*r,c=6*r,d=l+c+4*r,h=6*r,g=t-d-10*r,f=s-12*r,p=6*r;let m;switch(o){case"working":m="#4a9eff";break;case"orphaned":m="#ff00ff";break;case"error":m="#ff4a4a";break;case"waiting":case"waiting_permission":m="#ffcc00";break;default:m="#4aff9e"}const b=l/2+4*r,w=s/2;e.beginPath(),e.arc(b,w,l/2,0,Math.PI*2),e.fillStyle=m,e.fill(),e.shadowColor=m,e.shadowBlur=8*r,e.fill(),e.shadowBlur=0,e.strokeStyle="#000000",e.lineWidth=2*r,e.stroke(),e.fillStyle="#000000",e.beginPath(),e.roundRect(d,h,g,f,p),e.fill(),e.strokeStyle="#5a8a8a",e.lineWidth=2*r,e.stroke();const M=Math.max(0,(g-4*r)*n);if(M>0){let P,C;n>.5?(P="#00ff88",C="#00ff88"):n>.2?(P="#ffaa00",C="#ffaa00"):(P="#ff3366",C="#ff3366"),e.fillStyle=P,e.beginPath(),e.roundRect(d+2*r,h+2*r,M,f-4*r,p-2),e.fill(),e.shadowColor=C,e.shadowBlur=8*r,e.fill(),e.shadowBlur=0}const S=`${Math.round(n*100)}%`;e.font=`bold ${Math.round(24*r)}px Arial`,e.textAlign="center",e.textBaseline="middle",e.strokeStyle="#000000",e.lineWidth=4*r,e.strokeText(S,t/2,s/2),e.fillStyle="#ffffff",e.shadowColor="#ffffff",e.shadowBlur=2*r,e.fillText(S,t/2,s/2),e.shadowBlur=0}createIdleTimer(e,t,s=!1){const i=document.createElement("canvas"),o=i.getContext("2d");i.width=400,i.height=64,this.drawIdleTimer(o,i.width,i.height,e,t);const n=new se(i);n.minFilter=te,n.magFilter=te,n.needsUpdate=!0;const r=new J({map:n,transparent:!0,depthTest:!1}),l=new K(r);return l.position.set(0,s?3.5:2.4,0),l.scale.set(s?1.4:1.1,s?.22:.18,1),l.name="idleTimer",l}createBossCrown(){const e=document.createElement("canvas"),t=e.getContext("2d");e.width=128,e.height=128,t.clearRect(0,0,e.width,e.height),t.font="96px serif",t.textAlign="center",t.textBaseline="middle",t.fillText("👑",e.width/2,e.height/2);const s=new se(e);s.minFilter=te,s.magFilter=te,s.needsUpdate=!0;const i=new J({map:s,transparent:!0,depthTest:!1}),o=new K(i);return o.position.set(0,4,0),o.scale.set(.8,.8,1),o.name="bossCrown",o}drawIdleTimer(e,t,s,i,o){if(e.clearRect(0,0,t,s),i!=="idle"||o<=0)return;const n=Math.floor((Date.now()-o)/1e3),r=this.animConfig.formatIdleTimeShort(n),l=this.animConfig.getIdleTimerColor(n),c=s/80,d=24*c;e.font=`bold ${Math.round(44*c)}px Arial`;const g=e.measureText(`⏱ ${r}`).width+d*2,f=s-12*c,p=(t-g)/2,m=6*c;e.fillStyle="rgba(0, 0, 0, 0.9)",e.beginPath(),e.roundRect(p,m,g,f,10*c),e.fill(),e.strokeStyle=l.border,e.lineWidth=3*c,e.stroke(),e.textAlign="center",e.textBaseline="middle",e.strokeStyle="#000000",e.lineWidth=4*c,e.strokeText(`⏱ ${r}`,t/2,s/2),e.fillStyle=l.text,e.fillText(`⏱ ${r}`,t/2,s/2)}getIdleTimerCanvas(){return this.idleTimerCanvas||(this.idleTimerCanvas=document.createElement("canvas"),this.idleTimerCanvas.width=400,this.idleTimerCanvas.height=64,this.idleTimerCtx=this.idleTimerCanvas.getContext("2d")),{canvas:this.idleTimerCanvas,ctx:this.idleTimerCtx}}getManaBarCanvas(){return this.manaBarCanvas||(this.manaBarCanvas=document.createElement("canvas"),this.manaBarCanvas.width=400,this.manaBarCanvas.height=64,this.manaBarCtx=this.manaBarCanvas.getContext("2d")),{canvas:this.manaBarCanvas,ctx:this.manaBarCtx}}updateIdleTimer(e,t,s){const i=e.getObjectByName("idleTimer");if(!i)return;const o=i.material;if(!o.map)return;const n=o.map.image;if(!n||!(n instanceof HTMLCanvasElement))return;const r=n.getContext("2d");r&&(this.drawIdleTimer(r,n.width,n.height,t,s),o.map.needsUpdate=!0)}updateManaBar(e,t,s){const i=e.getObjectByName("manaBar");if(!i)return;const o=i.material;if(!o.map)return;const n=o.map.image;if(!n||!(n instanceof HTMLCanvasElement))return;const r=n.getContext("2d");r&&(this.drawManaBar(r,n.width,n.height,t,s),o.map.needsUpdate=!0)}updateNameLabel(e,t,s,i){var d;const o=e.getObjectByName("nameLabel");o&&((d=o.material.map)==null||d.dispose(),o.material.dispose(),e.remove(o));const n=rt[s],r=(n==null?void 0:n.color)??16777215,l=s==="boss"||e.userData.isBoss,c=this.createNameLabelSprite(t,r,l,i);e.add(c)}updateVisuals(e,t,s,i,o){var m;const n=t.isBoss===!0||t.class==="boss",r=Math.round(qt(t)),l=e.userData;if(l._cachedStatus!==t.status||l._cachedPercent!==r||l._cachedIsBoss!==n||t.status==="idle"&&l._cachedIdleBucket!==Math.floor((Date.now()-t.lastActivity)/6e4)){l._cachedStatus=t.status,l._cachedPercent=r,l._cachedIsBoss=n,l._cachedIdleBucket=t.status==="idle"?Math.floor((Date.now()-t.lastActivity)/6e4):0;const b=e.getObjectByName("statusBar");if(b){const P=b.material;if(P.map){const C=P.map.image;if(C instanceof HTMLCanvasElement){const x=C.getContext("2d");x&&(this.drawStatusBar(x,C.width,C.height,r,t.status,t.lastActivity,n),P.map.needsUpdate=!0)}}}const w=e.getObjectByName("combinedUI");if(w){const P=w.material;if(P.map){const C=P.map.image;if(C instanceof HTMLCanvasElement){const x=C.getContext("2d");x&&(this.drawCombinedUI(x,C.width,C.height,t.name,o,r,t.status,t.lastActivity,n),P.map.needsUpdate=!0)}}}const M=!!e.getObjectByName("statusBar"),S=!!e.getObjectByName("combinedUI");!M&&!S&&(this.updateManaBar(e,r,t.status),this.updateIdleTimer(e,t.status,t.lastActivity))}const d=t.taskLabel,h=e.getObjectByName("nameLabelSprite"),g=this.getNameLabelBaseScale(n,!!d),f=!!h&&(h.userData.nameLabelLayoutVersion!==At||h.userData.baseIndicatorScale!==g||h.userData.providerBadgeVersion!==this.providerBadgeVersion);if(l.agentName!==t.name||l._cachedTaskLabel!==d||f){if(h){if(!!l._cachedTaskLabel!==!!d||f){const P=h.material;(m=P.map)==null||m.dispose(),P.dispose(),e.remove(h);const C=t.isBoss===!0||t.class==="boss",x=this.createNameLabelSprite(t.name,o,C,t.provider,d);e.add(x)}else{const P=h.material;if(P.map){const C=P.map.image;if(C instanceof HTMLCanvasElement){const x=C.getContext("2d");x&&(this.drawNameLabel(x,C.width,C.height,t.name,o,n,t.provider,d),P.map.needsUpdate=!0)}}}l.agentName=t.name,l._cachedTaskLabel=d}const b=!!e.getObjectByName("statusBar"),w=!!e.getObjectByName("combinedUI");!b&&!w&&(this.updateNameLabel(e,t.name,t.class,t.provider),l.agentName=t.name,l._cachedTaskLabel=d)}const p=e.getObjectByName("selectionRing");if(p){const b=p.material;if(s){const w=rt[t.class];b.color.setHex((w==null?void 0:w.color)??o),b.opacity=t.isBoss===!0||t.class==="boss"?.34:.28}else i?(b.color.setHex(16766720),b.opacity=.2):b.opacity=0}}}class si{constructor(e){u(this,"modelLoader");u(this,"animConfig");u(this,"visualConfig");this.modelLoader=new Qs(e),this.animConfig=new Js,this.visualConfig=new ti(this.animConfig)}setCustomClasses(e){this.modelLoader.setCustomClasses(e)}createAgentMesh(e){const t=new Y;t.userData.agentId=e.id;const s=this.modelLoader.getClassConfig(e.class),i=e.isBoss===!0||e.class==="boss",{body:o,mixer:n,animations:r}=this.modelLoader.createCharacterBody(e,s.color);t.add(o);const l=this.modelLoader.calculateModelHeight(o,i),c=this.visualConfig.createSelectionRing(s.color,i);t.add(c);const d=qt(e),h=this.visualConfig.createStatusBarSprite(d,e.status,e.lastActivity,i,l);t.add(h);const g=this.visualConfig.createNameLabelSprite(e.name,s.color,i,e.provider,e.taskLabel);t.add(g),t.userData.agentName=e.name,t.userData.agentClass=e.class,t.userData.isBoss=i,t.position.set(e.position.x,e.position.y,e.position.z);const f=i?1:.75,p=i?3.5:2.5,m=new j(f,f,p,8),b=new v({visible:!1,transparent:!0,opacity:0}),w=new y(m,b);return w.position.y=p/2,w.name="clickHitbox",t.add(w),{group:t,mixer:n,animations:r,currentAction:null}}updateAgentClass(e,t){const{group:s}=e,i=s.userData.agentClass;if(i===t.class)return null;console.log(`[CharacterFactory] Agent ${t.name} class changed: ${i} -> ${t.class}`);const o=this.modelLoader.replaceAgentModel(e,t);return o&&this.visualConfig.updateNameLabel(s,t.name,t.class),o}updateVisuals(e,t,s,i=!1){const o=this.modelLoader.getClassConfig(t.class);this.visualConfig.updateVisuals(e,t,s,i,o.color)}upgradeToCharacterModel(e,t){return this.modelLoader.upgradeToCharacterModel(e,t)}disposeAgentMesh(e){this.modelLoader.disposeAgentMesh(e)}getStatusColor(e){return this.visualConfig.getStatusColor(e)}updateIdleTimer(e,t,s){this.visualConfig.updateIdleTimer(e,t,s)}updateManaBar(e,t,s){this.visualConfig.updateManaBar(e,t,s)}}const Q={STATIC:"static",IDLE:"idle",WALK:"walk",JUMP:"jump",SIT:"sit",DIE:"die",EMOTE_YES:"emote-yes",EMOTE_NO:"emote-no"},xt={height:.5,speed:1.5};class ii{constructor(){u(this,"movements",new Map);u(this,"jumpingAgents",new Map);u(this,"animatingAgents",new Set);u(this,"jumpTime",0)}isMoving(e){return this.movements.has(e)}hasActiveMovements(){return this.movements.size>0}resolveAnimationName(e,t){var o;const s=e.group.getObjectByName("characterBody"),i=(o=s==null?void 0:s.userData)==null?void 0:o.animationMapping;if(i){const n=i[t];if(n&&e.animations.has(n))return n;if(n&&e.animations.has(n.toLowerCase()))return n.toLowerCase()}switch(t){case"idle":return Q.IDLE;case"walk":return Q.WALK;case"working":return Q.JUMP;default:return Q.IDLE}}playAnimationForState(e,t,s){const i=this.resolveAnimationName(e,t);this.playAnimation(e,i,s)}startMovement(e,t,s){const i=t.group.position.clone(),o=new T(s.x,s.y,s.z),r=i.distanceTo(o)/Ws*1e3;this.movements.delete(e),this.movements.set(e,{agentId:e,startPos:i,endPos:o,startTime:performance.now(),duration:Math.max(r,200)});const l=this.resolveAnimationName(t,"walk");this.playAnimation(t,l),this.faceDirection(t,i,o)}cancelMovement(e,t){this.movements.delete(e);const s=this.resolveAnimationName(t,"idle");this.playAnimation(t,s)}playAnimation(e,t,s){if(!e.mixer)return;const i=e.group.userData.agentId;let o=e.animations.get(t);if(o||(o=e.animations.get(t.toLowerCase())),!o){console.warn(`[MovementAnimator] Animation not found: ${t}, available:`,Array.from(e.animations.keys()));const d=this.jumpingAgents.get(i);if(this.jumpingAgents.delete(i),d!==void 0){const h=e.group.getObjectByName("characterBody");h&&(h.position.y=d)}e.currentAction&&(e.currentAction.fadeOut(.2),e.currentAction=null);return}console.log(`[MovementAnimator] Playing: ${t}`);const{loop:n=!0,fadeTime:r=.2,timeScale:l=1}=s??{},c=e.mixer.clipAction(o);if(c.setLoop(n?ls:cs,1/0),c.clampWhenFinished=!n,c.timeScale=l,e.currentAction&&e.currentAction!==c?(e.currentAction.fadeOut(r),c.reset().fadeIn(r).play()):c.reset().play(),e.currentAction=c,this.animatingAgents.add(i),t===Q.JUMP&&n){if(!this.jumpingAgents.has(i)){const d=e.group.getObjectByName("characterBody"),h=(d==null?void 0:d.position.y)??0;this.jumpingAgents.set(i,h)}}else{const d=this.jumpingAgents.get(i);if(this.jumpingAgents.delete(i),d!==void 0){const h=e.group.getObjectByName("characterBody");h&&(h.position.y=d)}}}stopAnimation(e){this.animatingAgents.delete(e),this.jumpingAgents.delete(e)}faceDirection(e,t,s){const i=new T().subVectors(s,t).normalize();if(i.x!==0||i.z!==0){const o=e.group.getObjectByName("characterBody");if(o){const n=Math.atan2(i.x,i.z);o.rotation.y=n}}}update(e,t){var o;const s=performance.now(),i=[];this.jumpTime+=t;for(const n of this.animatingAgents){const r=e.get(n);(o=r==null?void 0:r.mixer)==null||o.update(t)}for(const[n,r]of this.jumpingAgents){const l=e.get(n);if(!l)continue;const c=l.group.getObjectByName("characterBody");if(c){const d=Math.abs(Math.sin(this.jumpTime*xt.speed*Math.PI*2))*xt.height;c.position.y=r+d}}for(const[n,r]of this.movements){const l=e.get(n);if(!l){i.push(n);continue}const c=s-r.startTime;let d=Math.min(c/r.duration,1);d=this.easeOutCubic(d),l.group.position.lerpVectors(r.startPos,r.endPos,d),this.smoothRotateToDirection(l,r.startPos,r.endPos,t),d>=1&&(i.push(n),l.group.position.copy(r.endPos))}for(const n of i)this.movements.delete(n);return i}smoothRotateToDirection(e,t,s,i){const o=new T().subVectors(s,t).normalize();if(o.x===0&&o.z===0)return;const n=e.group.getObjectByName("characterBody");if(!n)return;const r=Math.atan2(o.x,o.z),l=n.rotation.y,c=r-l,d=Math.atan2(Math.sin(c),Math.cos(c)),h=10;n.rotation.y+=d*Math.min(1,h*i)}easeOutCubic(e){return 1-Math.pow(1-e,3)}get activeCount(){return this.movements.size}clear(){this.movements.clear(),this.jumpingAgents.clear(),this.animatingAgents.clear(),this.jumpTime=0}}function Ve(){if(typeof window>"u")return{isMobile:!1,isConstrained:!1,maxPixelRatio:2,antialias:!0,enableShadows:!0,maxFps:0,indicatorUpdateInterval:100,notificationBadgeUpdateInterval:0,maxStatusSpriteDistance:28,maxNameSpriteDistance:22,maxBadgeDistance:18,maxBuildingLabelDistance:32,overlayEffectDistance:24,reduceTransientEffects:!1};const a=navigator,e=a.userAgent||"",t=window.matchMedia("(max-width: 768px)").matches,s=a.maxTouchPoints>0,i=/Android|iPhone|iPad|iPod|Mobile/i.test(e),o=t||s&&i,n=(a.deviceMemory??1/0)<=4,r=(a.hardwareConcurrency??1/0)<=6,l=o||n||r,c=!n&&(a.hardwareConcurrency??1/0)>=8;return l?{isMobile:o,isConstrained:!0,maxPixelRatio:c?1.75:1.5,antialias:c,enableShadows:!o,maxFps:30,indicatorUpdateInterval:250,notificationBadgeUpdateInterval:400,maxStatusSpriteDistance:20,maxNameSpriteDistance:14,maxBadgeDistance:11,maxBuildingLabelDistance:18,overlayEffectDistance:18,reduceTransientEffects:!0}:{isMobile:o,isConstrained:!1,maxPixelRatio:2,antialias:!0,enableShadows:!0,maxFps:0,indicatorUpdateInterval:100,notificationBadgeUpdateInterval:0,maxStatusSpriteDistance:28,maxNameSpriteDistance:22,maxBadgeDistance:18,maxBuildingLabelDistance:32,overlayEffectDistance:24,reduceTransientEffects:!1}}const De=class De{constructor(e){u(this,"scene");u(this,"moveOrderEffects",[]);u(this,"speechBubbles",[]);u(this,"sleepingEffects",[]);u(this,"waitingPermissionEffects",[]);u(this,"delegationEffects",[]);u(this,"subagentEffects",[]);u(this,"agentMeshes",new Map);u(this,"ringGeometry",null);u(this,"pulseGeometry",null);u(this,"chevronGeometry",null);u(this,"delegationPaperTexture",null);u(this,"sleepingBubbleTexture",null);u(this,"waitingPermissionTexture",null);u(this,"delegationSpritePool",[]);u(this,"moveOrderGroupPool",[]);u(this,"_needsUpdate",!1);u(this,"performanceProfile",Ve());u(this,"tempProjectedPosition",new T);u(this,"camera",null);u(this,"scale3d",1);this.scene=e,this.initializeCachedResources()}get needsUpdate(){return this._needsUpdate||this.moveOrderEffects.length>0||this.speechBubbles.length>0||this.sleepingEffects.length>0||this.waitingPermissionEffects.length>0||this.delegationEffects.length>0||this.subagentEffects.length>0}markDirty(){this._needsUpdate=!0}clearDirty(){this._needsUpdate=!1}initializeCachedResources(){this.ringGeometry=new ke(.3,.4,32),this.pulseGeometry=new ke(.1,.2,32);const e=new hs;e.moveTo(0,.15),e.lineTo(.12,.35),e.lineTo(.08,.35),e.lineTo(0,.2),e.lineTo(-.08,.35),e.lineTo(-.12,.35),e.closePath(),this.chevronGeometry=new ds(e),this.createDelegationPaperTexture(),this.createSleepingBubbleTexture(),this.createWaitingPermissionTexture(),this.initializePools()}initializePools(){for(let e=0;e<De.POOL_SIZE;e++)if(this.delegationPaperTexture){const t=new J({map:this.delegationPaperTexture,transparent:!0,opacity:0,depthTest:!1}),s=new K(t);s.scale.set(.3,.3,1),s.visible=!1,this.delegationSpritePool.push({sprite:s,inUse:!1})}for(let e=0;e<De.POOL_SIZE;e++){const t=this.createMoveOrderGroup();t.visible=!1,this.moveOrderGroupPool.push(t)}}createMoveOrderGroup(){const e=new Y,t=new v({color:4915102,side:oe,transparent:!0,opacity:.8}),s=new y(this.ringGeometry,t);s.rotation.x=-Math.PI/2,s.name="ring",e.add(s);const i=new v({color:4915102,side:oe,transparent:!0,opacity:.6}),o=new y(this.pulseGeometry,i);o.rotation.x=-Math.PI/2,o.name="pulse",e.add(o);for(let n=0;n<3;n++){const r=new v({color:4915102,side:oe,transparent:!0,opacity:.9}),l=new y(this.chevronGeometry,r);l.rotation.x=-Math.PI/2,l.position.y=.5+n*.25,l.name=`chevron${n}`,e.add(l)}return e}getDelegationSprite(){for(const s of this.delegationSpritePool)if(!s.inUse)return s.inUse=!0,s.sprite.visible=!0,s.sprite.material.opacity=1,s.sprite;const e=new J({map:this.delegationPaperTexture,transparent:!0,opacity:1,depthTest:!1}),t=new K(e);return t.scale.set(.3,.3,1),t}returnDelegationSprite(e){for(const t of this.delegationSpritePool)if(t.sprite===e){t.inUse=!1,t.sprite.visible=!1,this.scene.remove(e);return}this.scene.remove(e),e.material.dispose()}getMoveOrderGroup(){for(const e of this.moveOrderGroupPool)if(!e.visible)return e.visible=!0,e.traverse(t=>{if(t instanceof y){const s=t.material;s.opacity=t.name==="ring"?.8:t.name==="pulse"?.6:.9}}),e;return this.createMoveOrderGroup()}returnMoveOrderGroup(e){this.moveOrderGroupPool.includes(e)?(e.visible=!1,this.scene.remove(e)):(this.scene.remove(e),e.traverse(s=>{s instanceof y&&s.material.dispose()}))}createDelegationPaperTexture(){const e=document.createElement("canvas"),t=e.getContext("2d");e.width=64,e.height=64,t.fillStyle="#ffffff",t.strokeStyle="#ffd700",t.lineWidth=2,t.save(),t.translate(32,32),t.rotate(-.2),t.beginPath(),t.moveTo(-12,-18),t.lineTo(8,-18),t.lineTo(12,-14),t.lineTo(12,18),t.lineTo(-12,18),t.closePath(),t.fill(),t.stroke(),t.beginPath(),t.moveTo(8,-18),t.lineTo(8,-14),t.lineTo(12,-14),t.strokeStyle="#cccccc",t.stroke(),t.fillStyle="#f0f0f0",t.fill(),t.strokeStyle="#888888",t.lineWidth=1;for(let s=0;s<4;s++){const i=-8+s*6,o=s===3?10:16;t.beginPath(),t.moveTo(-8,i),t.lineTo(-8+o,i),t.stroke()}t.restore(),this.delegationPaperTexture=new se(e),this.delegationPaperTexture.minFilter=te,this.delegationPaperTexture.magFilter=te}createSleepingBubbleTexture(){const e=document.createElement("canvas"),t=e.getContext("2d");e.width=128,e.height=128,t.fillStyle="rgba(40, 42, 54, 0.95)",t.strokeStyle="#bd93f9",t.lineWidth=2;const s=64,i=50,o=40;t.beginPath(),t.arc(s,i,o,0,Math.PI*2),t.fill(),t.stroke(),t.beginPath(),t.arc(30,95,10,0,Math.PI*2),t.fill(),t.stroke(),t.beginPath(),t.arc(18,115,6,0,Math.PI*2),t.fill(),t.stroke(),t.fillStyle="#8be9fd",t.font="bold 28px Arial",t.textAlign="center",t.textBaseline="middle",t.shadowColor="#8be9fd",t.shadowBlur=4,t.fillText("ZZZ",s,i),this.sleepingBubbleTexture=new se(e),this.sleepingBubbleTexture.minFilter=te,this.sleepingBubbleTexture.magFilter=te}createWaitingPermissionTexture(){const e=document.createElement("canvas"),t=e.getContext("2d");e.width=128,e.height=128,t.fillStyle="rgba(40, 42, 54, 0.95)",t.strokeStyle="#ffcc00",t.lineWidth=2;const s=64,i=50,o=40;t.beginPath(),t.arc(s,i,o,0,Math.PI*2),t.fill(),t.stroke(),t.beginPath(),t.arc(30,95,10,0,Math.PI*2),t.fill(),t.stroke(),t.beginPath(),t.arc(18,115,6,0,Math.PI*2),t.fill(),t.stroke(),t.fillStyle="#ffcc00",t.font="bold 32px Arial",t.textAlign="center",t.textBaseline="middle",t.shadowColor="#ffcc00",t.shadowBlur=6,t.fillText("🔒",s,i),this.waitingPermissionTexture=new se(e),this.waitingPermissionTexture.minFilter=te,this.waitingPermissionTexture.magFilter=te}setAgentMeshes(e){this.agentMeshes.clear();for(const[t,s]of e)this.agentMeshes.set(t,s.group)}updateSleepingEffect(e,t){const s=this.sleepingEffects.find(i=>i.agentId===e);t&&!s?this.createSleepingEffect(e):!t&&s&&this.removeSleepingEffect(e)}updateWaitingPermissionEffect(e,t){const s=this.waitingPermissionEffects.find(i=>i.agentId===e);t&&!s?this.createWaitingPermissionEffect(e):!t&&s&&this.removeWaitingPermissionEffect(e)}createSleepingEffect(e){const t=this.agentMeshes.get(e);if(!t||!this.sleepingBubbleTexture)return;const s=[],i=new J({map:this.sleepingBubbleTexture,transparent:!0,opacity:.95,depthTest:!1}),o=new K(i);o.scale.set(.12,.12,1),o.userData.isBubble=!0,o.position.copy(t.position),o.position.y=2,o.position.x+=.15,this.scene.add(o),s.push(o),this.sleepingEffects.push({sprites:s,agentId:e,startTime:performance.now()}),this.markDirty()}removeSleepingEffect(e){const t=this.sleepingEffects.findIndex(s=>s.agentId===e);if(t!==-1){const s=this.sleepingEffects[t];for(const i of s.sprites)this.scene.remove(i),i.material.dispose();this.sleepingEffects.splice(t,1),this.markDirty()}}createWaitingPermissionEffect(e){const t=this.agentMeshes.get(e);if(!t||!this.waitingPermissionTexture)return;const s=[],i=new J({map:this.waitingPermissionTexture,transparent:!0,opacity:.95,depthTest:!1}),o=new K(i);o.scale.set(.12,.12,1),o.userData.isBubble=!0,o.position.copy(t.position),o.position.y=2,o.position.x+=.15,this.scene.add(o),s.push(o),this.waitingPermissionEffects.push({sprites:s,agentId:e,startTime:performance.now()}),this.markDirty()}removeWaitingPermissionEffect(e){const t=this.waitingPermissionEffects.findIndex(s=>s.agentId===e);if(t!==-1){const s=this.waitingPermissionEffects[t];for(const i of s.sprites)this.scene.remove(i),i.material.dispose();this.waitingPermissionEffects.splice(t,1),this.markDirty()}}createDelegationEffect(e,t){if(this.performanceProfile.reduceTransientEffects)return;const s=this.agentMeshes.get(e),i=this.agentMeshes.get(t);if(!s||!i||!this.delegationPaperTexture){console.log("[EffectsManager] Cannot create delegation effect - missing agent meshes or texture");return}const o=this.getDelegationSprite(),n=new T(s.position.x,s.position.y+1.5,s.position.z),r=new T(i.position.x,i.position.y+1.2,i.position.z);o.position.copy(n),this.scene.add(o),this.delegationEffects.push({sprite:o,startPosition:n.clone(),endPosition:r.clone(),startTime:performance.now(),duration:800}),this.markDirty()}createSpeechBubble(e,t,s){if(this.performanceProfile.reduceTransientEffects)return;const i=this.agentMeshes.get(e);if(!i)return;this.removeSpeechBubble(e);const o=Fs[t]||"🔧",n=this.formatToolParams(t,s),r=document.createElement("canvas"),l=r.getContext("2d");r.width=400,r.height=100;const c=n?`${o} ${t}: ${n}`:`${o} ${t}`;l.font="bold 32px Arial";const g=Math.min(l.measureText(c).width,r.width-40)+16*2,f=48,p=(r.width-g)/2,m=(r.height-f)/2,b=f/2;l.fillStyle="rgba(15, 15, 25, 0.85)",l.strokeStyle="#4a9eff",l.lineWidth=2,l.beginPath(),l.moveTo(p+b,m),l.lineTo(p+g-b,m),l.arc(p+g-b,m+b,b,-Math.PI/2,Math.PI/2),l.lineTo(p+b,m+f),l.arc(p+b,m+b,b,Math.PI/2,-Math.PI/2),l.closePath(),l.fill(),l.stroke(),l.fillStyle="#ffffff",l.font="bold 30px Arial",l.textAlign="center",l.textBaseline="middle";let w=c;const M=r.width-40;for(;l.measureText(w).width>M&&w.length>3;)w=w.slice(0,-4)+"...";l.fillText(w,r.width/2,r.height/2);const S=new se(r);S.minFilter=te,S.magFilter=te,S.needsUpdate=!0;const P=new J({map:S,transparent:!0,opacity:0,depthTest:!1}),C=new K(P);C.scale.set(2.4,.6,1),C.renderOrder=1e3;const x=!!i.userData._cachedTaskLabel,B=i.position.y-(x?2:1.3);C.position.copy(i.position),C.position.y=B,this.scene.add(C),this.speechBubbles.push({sprite:C,agentId:e,startTime:performance.now(),duration:4e3,baseY:B})}formatToolParams(e,t){if(!t)return"";switch(e){case"WebSearch":return t.query||"";case"WebFetch":return t.url||"";case"Read":case"Write":case"Edit":const s=t.file_path||t.path||"";return s.length>40?".../"+s.split("/").slice(-2).join("/"):s;case"Bash":const i=(t.command||"").slice(0,60);return i+(i.length>=60?"...":"");case"Grep":return`"${t.pattern||""}"`;case"Glob":return t.pattern||"";case"Task":return(t.description||"").slice(0,50);default:for(const[o,n]of Object.entries(t))if(typeof n=="string"&&n.length>0&&n.length<100)return n.slice(0,50);return""}}removeSpeechBubble(e){var s;const t=this.speechBubbles.findIndex(i=>i.agentId===e);if(t!==-1){const i=this.speechBubbles[t];this.scene.remove(i.sprite),(s=i.sprite.material.map)==null||s.dispose(),i.sprite.material.dispose(),this.speechBubbles.splice(t,1)}}createMoveOrderEffect(e){const t=this.getMoveOrderGroup();t.position.copy(e),t.position.y=.05;for(let o=0;o<3;o++){const n=t.getObjectByName(`chevron${o}`);n&&(n.position.y=.5+o*.25)}const s=t.getObjectByName("ring");s&&s.scale.setScalar(1);const i=t.getObjectByName("pulse");i&&i.scale.setScalar(1),this.scene.add(t),this.moveOrderEffects.push({group:t,startTime:performance.now(),duration:800}),this.markDirty()}setScale3D(e){this.scale3d=e}update(){const e=performance.now();this.updateMoveOrderEffects(e),this.updateSpeechBubbles(e),this.updateSleepingEffects(),this.updateWaitingPermissionEffects(),this.updateDelegationEffects(e),this.updateSubagentEffects(e)}updateWithCamera(e){this.camera=e}calculateZoomScale(e){if(!this.camera)return this.scale3d;const t=this.camera.position.distanceTo(e);return Math.max(.5,Math.min(2.5,t/15))*this.scale3d}shouldRenderOverlay(e,t=this.performanceProfile.overlayEffectDistance){return this.camera?this.camera.position.distanceTo(e)>t?!1:(this.tempProjectedPosition.copy(e).project(this.camera),this.tempProjectedPosition.z>=-1&&this.tempProjectedPosition.z<=1&&this.tempProjectedPosition.x>=-1.2&&this.tempProjectedPosition.x<=1.2&&this.tempProjectedPosition.y>=-1.2&&this.tempProjectedPosition.y<=1.2):!0}updateSleepingEffects(){const e=performance.now();for(const t of this.sleepingEffects){const s=this.agentMeshes.get(t.agentId);if(!s)continue;const i=e-t.startTime,o=this.calculateZoomScale(s.position),n=this.shouldRenderOverlay(s.position);for(const r of t.sprites){if(r.visible=n,!n)continue;r.position.x=s.position.x+.25*o,r.position.z=s.position.z;const l=.002,c=.04*o;r.position.y=2+Math.sin(i*l)*c;const d=.35*o,h=Math.sin(i*.003)*.015*o;r.scale.set(d+h,d+h,1);const g=Math.min(i/500,1);r.material.opacity=.95*g}}}updateWaitingPermissionEffects(){const e=performance.now();for(const t of this.waitingPermissionEffects){const s=this.agentMeshes.get(t.agentId);if(!s)continue;const i=e-t.startTime,o=this.calculateZoomScale(s.position),n=this.shouldRenderOverlay(s.position);for(const r of t.sprites){if(r.visible=n,!n)continue;r.position.x=s.position.x+.25*o,r.position.z=s.position.z;const l=.004,c=.06*o;r.position.y=2+Math.sin(i*l)*c;const d=.38*o,h=Math.sin(i*.006)*.03*o;r.scale.set(d+h,d+h,1);const g=Math.min(i/300,1),f=.85+Math.sin(i*.005)*.1;r.material.opacity=f*g}}}updateDelegationEffects(e){const t=[];for(let s=0;s<this.delegationEffects.length;s++){const i=this.delegationEffects[s],o=Math.min((e-i.startTime)/i.duration,1),n=1-(1-o)*(1-o),r=i.endPosition.x-i.startPosition.x,l=i.endPosition.y-i.startPosition.y,c=i.endPosition.z-i.startPosition.z,d=4*o*(1-o)*.8;i.sprite.position.x=i.startPosition.x+r*n,i.sprite.position.y=i.startPosition.y+l*n+d,i.sprite.position.z=i.startPosition.z+c*n,i.sprite.material.rotation=o*Math.PI*1.5,i.sprite.material.opacity=o>.8?(1-o)*5:1,o>=1&&t.push(s)}for(let s=t.length-1;s>=0;s--){const i=t[s],o=this.delegationEffects[i];this.returnDelegationSprite(o.sprite),this.delegationEffects.splice(i,1)}}updateMoveOrderEffects(e){const t=[];for(let s=0;s<this.moveOrderEffects.length;s++){const i=this.moveOrderEffects[s],o=e-i.startTime,n=Math.min(o/i.duration,1),r=1-n,l=i.group.getObjectByName("ring");l&&(l.scale.setScalar(1+n*1.5),l.material.opacity=r*.8);const c=i.group.getObjectByName("pulse");if(c){const d=(Math.sin(n*Math.PI*4)+1)/2;c.scale.setScalar(.8+d*.4),c.material.opacity=r*.6}for(let d=0;d<3;d++){const h=i.group.getObjectByName(`chevron${d}`);if(h){const g=d*.15,f=Math.max(0,Math.min((n-g)/(1-g),1));h.position.y=.5+d*.25-f*(.4+d*.15),h.material.opacity=(1-f)*.9}}n>=1&&t.push(s)}for(let s=t.length-1;s>=0;s--){const i=t[s];this.returnMoveOrderGroup(this.moveOrderEffects[i].group),this.moveOrderEffects.splice(i,1)}}updateSpeechBubbles(e){var s;const t=[];for(let i=0;i<this.speechBubbles.length;i++){const o=this.speechBubbles[i],n=e-o.startTime,r=Math.min(n/o.duration,1),l=this.agentMeshes.get(o.agentId);if(l){o.sprite.position.x=l.position.x,o.sprite.position.z=l.position.z;const f=this.calculateZoomScale(l.position);o.sprite.scale.set(2.4*f,.6*f,1)}const c=Math.min(n/200,1),d=r>.7?1-(r-.7)/.3:1;o.sprite.material.opacity=c*d;const h=l?l.position.y:0,g=l?!!l.userData._cachedTaskLabel:!1;o.sprite.position.y=h-(g?2:1.3),r>=1&&t.push(i)}for(let i=t.length-1;i>=0;i--){const o=t[i],n=this.speechBubbles[o];this.scene.remove(n.sprite),(s=n.sprite.material.map)==null||s.dispose(),n.sprite.material.dispose(),this.speechBubbles.splice(o,1)}}disposeEffect(e){this.scene.remove(e.group),e.group.traverse(t=>{t instanceof y&&t.material.dispose()})}addSubagentEffect(e,t,s,i){if(this.performanceProfile.reduceTransientEffects)return;const o=this.agentMeshes.get(t);if(!o){console.warn(`[EffectsManager] Cannot add subagent effect: parent agent ${t} not found`);return}if(this.subagentEffects.find(w=>w.subagentId===e))return;const n=document.createElement("canvas");n.width=256,n.height=64;const r=n.getContext("2d");r.fillStyle="rgba(30, 30, 60, 0.85)";const l=12;r.beginPath(),r.moveTo(l,0),r.lineTo(n.width-l,0),r.quadraticCurveTo(n.width,0,n.width,l),r.lineTo(n.width,n.height-l),r.quadraticCurveTo(n.width,n.height,n.width-l,n.height),r.lineTo(l,n.height),r.quadraticCurveTo(0,n.height,0,n.height-l),r.lineTo(0,l),r.quadraticCurveTo(0,0,l,0),r.closePath(),r.fill(),r.strokeStyle="rgba(100, 180, 255, 0.8)",r.lineWidth=2,r.stroke(),r.fillStyle="#64b4ff",r.font="bold 28px monospace",r.fillText("⑂",8,40),r.fillStyle="#ffffff",r.font="22px sans-serif";const c=s.length>14?s.slice(0,12)+"..":s;r.fillText(c,40,38);const d=new se(n);d.needsUpdate=!0;const h=new J({map:d,transparent:!0,opacity:.85,depthTest:!1}),g=new K(h);g.scale.set(1.5,.4,1);const f=this.subagentEffects.filter(w=>w.parentAgentId===t&&!w.completed).length,p=f*Math.PI/4-Math.PI/4,m=1.5,b=o.position;g.position.set(b.x+Math.sin(p)*m,b.y+2.5+f*.5,b.z+Math.cos(p)*m),this.scene.add(g),this.subagentEffects.push({sprite:g,subagentId:e,parentAgentId:t,name:s,subagentType:i,startTime:performance.now(),completed:!1,completedAt:0}),this.markDirty(),console.log(`[EffectsManager] Added subagent effect: ${s} (${e}) near ${t}`)}completeSubagentEffect(e){const t=this.subagentEffects.find(s=>s.subagentId===e);t?(t.completed=!0,t.completedAt=performance.now(),this.markDirty(),console.log(`[EffectsManager] Marked subagent effect completed: ${t.name} (${e})`)):console.warn(`[EffectsManager] completeSubagentEffect: no effect found for subagentId=${e}`)}removeSubagentEffect(e){var s;const t=this.subagentEffects.findIndex(i=>i.subagentId===e);if(t!==-1){const i=this.subagentEffects[t];this.scene.remove(i.sprite),(s=i.sprite.material.map)==null||s.dispose(),i.sprite.material.dispose(),this.subagentEffects.splice(t,1),this.markDirty()}}updateSubagentEffects(e){var s;const t=[];for(let i=0;i<this.subagentEffects.length;i++){const o=this.subagentEffects[i],n=this.agentMeshes.get(o.parentAgentId);if(!n){t.push(i);continue}const r=this.subagentEffects.slice(0,i).filter(g=>g.parentAgentId===o.parentAgentId&&!g.completed).length,l=r*Math.PI/4-Math.PI/4,c=1.5,d=n.position;o.sprite.position.set(d.x+Math.sin(l)*c,d.y+2.5+r*.5,d.z+Math.cos(l)*c);const h=(e-o.startTime)/1e3;if(o.sprite.position.y+=Math.sin(h*1.5)*.05,o.completed&&o.completedAt>0){const g=(e-o.completedAt)/1e3;if(g>2){const f=Math.max(0,.85-(g-2)*.3);o.sprite.material.opacity=f,f<=0&&t.push(i)}}o.completed||(o.sprite.material.opacity=.75+Math.sin(h*2)*.1)}for(let i=t.length-1;i>=0;i--){const o=t[i],n=this.subagentEffects[o];this.scene.remove(n.sprite),(s=n.sprite.material.map)==null||s.dispose(),n.sprite.material.dispose(),this.subagentEffects.splice(o,1)}}removeAgentEffects(e){this.removeSleepingEffect(e),this.removeWaitingPermissionEffect(e),this.removeSpeechBubble(e);const t=this.subagentEffects.filter(s=>s.parentAgentId===e).map(s=>s.subagentId);for(const s of t)this.removeSubagentEffect(s);this.agentMeshes.delete(e)}clear(){var e,t;for(const s of this.moveOrderEffects)this.returnMoveOrderGroup(s.group);this.moveOrderEffects=[];for(const s of this.sleepingEffects)for(const i of s.sprites)this.scene.remove(i),i.material.dispose();this.sleepingEffects=[];for(const s of this.waitingPermissionEffects)for(const i of s.sprites)this.scene.remove(i),i.material.dispose();this.waitingPermissionEffects=[];for(const s of this.delegationEffects)this.returnDelegationSprite(s.sprite);this.delegationEffects=[];for(const s of this.speechBubbles)this.scene.remove(s.sprite),(e=s.sprite.material.map)==null||e.dispose(),s.sprite.material.dispose();this.speechBubbles=[];for(const s of this.subagentEffects)this.scene.remove(s.sprite),(t=s.sprite.material.map)==null||t.dispose(),s.sprite.material.dispose();this.subagentEffects=[]}dispose(){var e,t,s,i,o,n;this.clear(),(e=this.ringGeometry)==null||e.dispose(),(t=this.pulseGeometry)==null||t.dispose(),(s=this.chevronGeometry)==null||s.dispose(),this.ringGeometry=null,this.pulseGeometry=null,this.chevronGeometry=null,(i=this.delegationPaperTexture)==null||i.dispose(),(o=this.sleepingBubbleTexture)==null||o.dispose(),(n=this.waitingPermissionTexture)==null||n.dispose(),this.delegationPaperTexture=null,this.sleepingBubbleTexture=null,this.waitingPermissionTexture=null;for(const r of this.delegationSpritePool)r.sprite.material.dispose();this.delegationSpritePool=[];for(const r of this.moveOrderGroupPool)r.traverse(l=>{l instanceof y&&l.material.dispose()});this.moveOrderGroupPool=[],this.agentMeshes.clear()}};u(De,"POOL_SIZE",10);let ct=De;class oi{constructor(){u(this,"animations",new Map)}register(e,t,s="idle"){this.animations.set(e,{state:s,time:Math.random()*Math.PI*2,basePosition:t.position.clone(),baseRotation:t.rotation.clone(),baseScale:t.scale.clone()})}unregister(e){this.animations.delete(e)}has(e){return this.animations.has(e)}setState(e,t){const s=this.animations.get(e);s&&s.state!==t&&(s.state=t,s.time=0)}updateBasePosition(e,t){const s=this.animations.get(e);s&&s.basePosition.copy(t)}update(e,t){for(const[s,i]of this.animations){const o=t.get(s);if(o)switch(i.time+=e,i.state){case"idle":this.applyIdleAnimation(o,i);break;case"working":this.applyWorkingAnimation(o,i);break;case"waiting":this.applyWaitingAnimation(o,i);break;case"error":this.applyErrorAnimation(o,i);break;case"static":this.resetToBase(o,i);break}}}applyIdleAnimation(e,t){const s=t.time,n=Math.sin(s*1.5)*.02,c=Math.sin(s*.8)*.01;e.position.set(t.basePosition.x+c,t.basePosition.y+n,t.basePosition.z)}applyWorkingAnimation(e,t){const s=t.time,n=Math.abs(Math.sin(s*6))*.25,r=.15,l=3,c=Math.sin(s*l)*r,g=Math.sin(s*3)*.22,p=Math.sin(s*l*.7)*.1,w=Math.sin(s*4)*.12;e.position.set(t.basePosition.x+c,t.basePosition.y+n,t.basePosition.z+p),e.rotation.set(t.baseRotation.x+g,t.baseRotation.y+w,t.baseRotation.z)}applyWaitingAnimation(e,t){const s=t.time,i=.02,o=1.2,n=Math.sin(s*o)*i,l=Math.sin(s*o)*.03,h=Math.sin(s*2)*.01;e.position.set(t.basePosition.x+n,t.basePosition.y+h,t.basePosition.z),e.rotation.set(t.baseRotation.x,t.baseRotation.y,t.baseRotation.z+l)}applyErrorAnimation(e,t){const s=t.time,i=.015,o=15,n=Math.sin(s*o)*i,r=Math.cos(s*o*1.3)*i*.5;e.position.set(t.basePosition.x+n,t.basePosition.y,t.basePosition.z+r)}resetToBase(e,t){e.position.copy(t.basePosition),e.rotation.copy(t.baseRotation),e.scale.copy(t.baseScale)}clear(){this.animations.clear()}}function Bt(a){const e=document.createElement("canvas"),t=e.getContext("2d"),s=a==="pokemon-stadium"?1024:512;switch(e.width=s,e.height=s,a){case"galactic":ai(t,e.width,e.height);break;case"metal":ri(t,e.width,e.height);break;case"hex":li(t,e.width,e.height);break;case"circuit":ci(t,e.width,e.height);break;case"pokemon-stadium":hi(t,e.width,e.height);break;default:ni(t,e.width,e.height)}return new se(e)}function ni(a,e,t){a.fillStyle="#4a4a4a",a.fillRect(0,0,e,t);for(let s=0;s<5e3;s++){const i=Math.random()*e,o=Math.random()*t,n=60+Math.random()*40;a.fillStyle=`rgba(${n}, ${n}, ${n}, 0.3)`,a.fillRect(i,o,2,2)}a.strokeStyle="rgba(30, 30, 30, 0.4)",a.lineWidth=1;for(let s=0;s<8;s++){a.beginPath();let i=Math.random()*e,o=Math.random()*t;a.moveTo(i,o);for(let n=0;n<5;n++)i+=(Math.random()-.5)*100,o+=(Math.random()-.5)*100,a.lineTo(i,o);a.stroke()}}function ai(a,e,t){const s=a.createRadialGradient(e/2,t/2,0,e/2,t/2,e/1.5);s.addColorStop(0,"#1a0a30"),s.addColorStop(.5,"#0d0520"),s.addColorStop(1,"#050210"),a.fillStyle=s,a.fillRect(0,0,e,t);for(let i=0;i<3;i++){const o=Math.random()*e,n=Math.random()*t,r=100+Math.random()*150,l=["#ff00ff","#00ffff","#ff6600","#6600ff","#00ff66"],c=l[Math.floor(Math.random()*l.length)],d=a.createRadialGradient(o,n,0,o,n,r);d.addColorStop(0,c.replace("ff","66")+"40"),d.addColorStop(.5,c+"20"),d.addColorStop(1,"transparent"),a.fillStyle=d,a.fillRect(0,0,e,t)}for(let i=0;i<300;i++){const o=Math.random()*e,n=Math.random()*t,r=Math.random()*2,l=150+Math.random()*105;if(Math.random()>.8){const c=a.createRadialGradient(o,n,0,o,n,r*4);c.addColorStop(0,`rgba(${l}, ${l}, 255, 0.8)`),c.addColorStop(1,"transparent"),a.fillStyle=c,a.fillRect(o-r*4,n-r*4,r*8,r*8)}a.fillStyle=`rgba(${l}, ${l}, 255, 1)`,a.beginPath(),a.arc(o,n,r,0,Math.PI*2),a.fill()}a.strokeStyle="rgba(100, 50, 150, 0.15)",a.lineWidth=20,a.beginPath();for(let i=0;i<Math.PI*4;i+=.1){const o=20+i*30,n=e/2+Math.cos(i)*o,r=t/2+Math.sin(i)*o;i===0?a.moveTo(n,r):a.lineTo(n,r)}a.stroke()}function ri(a,e,t){a.fillStyle="#3a3a44",a.fillRect(0,0,e,t);for(let i=0;i<200;i++){const o=Math.random()*t,n=50+Math.random()*30;a.strokeStyle=`rgba(${n+20}, ${n+20}, ${n+30}, 0.3)`,a.lineWidth=1,a.beginPath(),a.moveTo(0,o),a.lineTo(e,o+(Math.random()-.5)*4),a.stroke()}a.strokeStyle="rgba(20, 20, 25, 0.8)",a.lineWidth=3;const s=e/4;for(let i=0;i<=e;i+=s)a.beginPath(),a.moveTo(i,0),a.lineTo(i,t),a.stroke();for(let i=0;i<=t;i+=s)a.beginPath(),a.moveTo(0,i),a.lineTo(e,i),a.stroke();a.fillStyle="#555566";for(let i=0;i<=e;i+=s)for(let o=0;o<=t;o+=s)a.beginPath(),a.arc(i,o,8,0,Math.PI*2),a.fill(),a.fillStyle="#666677",a.beginPath(),a.arc(i-2,o-2,4,0,Math.PI*2),a.fill(),a.fillStyle="#555566"}function li(a,e,t){a.fillStyle="#1a2530",a.fillRect(0,0,e,t);const s=30,i=s*Math.sqrt(3);for(let o=-1;o<t/i+1;o++)for(let n=-1;n<e/(s*1.5)+1;n++){const r=n*s*1.5,l=o*i+(n%2===0?0:i/2),c=30+Math.random()*20;a.fillStyle=`rgb(${c}, ${c+20}, ${c+40})`,a.beginPath();for(let d=0;d<6;d++){const h=Math.PI/3*d+Math.PI/6,g=r+Math.cos(h)*(s-2),f=l+Math.sin(h)*(s-2);d===0?a.moveTo(g,f):a.lineTo(g,f)}if(a.closePath(),a.fill(),a.strokeStyle="rgba(80, 150, 200, 0.5)",a.lineWidth=2,a.stroke(),Math.random()>.85){const d=a.createRadialGradient(r,l,0,r,l,s);d.addColorStop(0,"rgba(100, 200, 255, 0.3)"),d.addColorStop(1,"transparent"),a.fillStyle=d,a.fill()}}}function ci(a,e,t){a.fillStyle="#0a1a0f",a.fillRect(0,0,e,t),a.strokeStyle="#00ff66",a.lineWidth=2,a.shadowColor="#00ff66",a.shadowBlur=4;for(let s=20;s<t;s+=40){a.beginPath();let i=0;for(a.moveTo(i,s);i<e;){const o=20+Math.random()*60;if(i+=o,a.lineTo(i,s),Math.random()>.7&&i<e-40){const n=s+(Math.random()>.5?20:-20);a.lineTo(i,n),a.lineTo(i+20,n),i+=20}}a.stroke()}for(let s=20;s<e;s+=40)if(Math.random()>.5){a.beginPath(),a.moveTo(s,0);let i=0;for(;i<t;){const o=20+Math.random()*60;if(i+=o,a.lineTo(s,i),Math.random()>.7&&i<t-40){const n=s+(Math.random()>.5?20:-20);a.lineTo(n,i),a.lineTo(n,i+20),i+=20,a.lineTo(s,i)}}a.stroke()}a.shadowBlur=0,a.fillStyle="#111";for(let s=0;s<6;s++){const i=50+Math.random()*(e-100),o=50+Math.random()*(t-100),n=30+Math.random()*40,r=20+Math.random()*30;a.fillRect(i-n/2,o-r/2,n,r),a.fillStyle="#888";for(let l=0;l<n;l+=8)a.fillRect(i-n/2+l,o-r/2-4,4,4),a.fillRect(i-n/2+l,o+r/2,4,4);a.fillStyle="#111"}a.fillStyle="#997700";for(let s=0;s<50;s++){const i=Math.random()*e,o=Math.random()*t;a.beginPath(),a.arc(i,o,4,0,Math.PI*2),a.fill()}}function hi(a,e,t){const s=e/2,i=t/2;a.fillStyle="#2E4F2C",a.fillRect(0,0,e,t);for(let m=0;m<6e3;m++){const b=Math.random()*e,w=Math.random()*t,M=Math.random()>.5;a.fillStyle=M?"rgba(30, 50, 28, 0.3)":"rgba(55, 90, 52, 0.12)",a.fillRect(b,w,2,4)}const o=e*.05,n=30;a.strokeStyle="#ffffff",a.lineWidth=6,a.beginPath(),a.roundRect(o,o,e-o*2,t-o*2,n),a.stroke(),a.lineWidth=4,a.beginPath(),a.moveTo(o,i),a.lineTo(e-o,i),a.stroke();const r=Math.min(e,t)*.2;a.beginPath(),a.arc(s,i,r,0,Math.PI*2),a.stroke();const l=r*.6;a.fillStyle="#cc3333",a.beginPath(),a.arc(s,i,l,Math.PI,0),a.closePath(),a.fill(),a.fillStyle="#f0f0f0",a.beginPath(),a.arc(s,i,l,0,Math.PI),a.closePath(),a.fill(),a.fillStyle="#1a1a1a",a.fillRect(s-l,i-5,l*2,10),a.strokeStyle="#1a1a1a",a.lineWidth=4,a.beginPath(),a.arc(s,i,l,0,Math.PI*2),a.stroke();const c=l*.28;a.fillStyle="#f0f0f0",a.beginPath(),a.arc(s,i,c,0,Math.PI*2),a.fill(),a.strokeStyle="#1a1a1a",a.lineWidth=4,a.stroke(),a.fillStyle="#ffffff",a.beginPath(),a.arc(s,i,c*.5,0,Math.PI*2),a.fill();const d=e*.08,h=t*.05,g=r+t*.08;a.strokeStyle="#ffffff",a.lineWidth=3,a.strokeRect(s-d/2,i-g-h,d,h),a.strokeRect(s-d/2,i+g,d,h);const f=e*.05,p=o+15;a.lineWidth=3,a.beginPath(),a.moveTo(p,p+f),a.lineTo(p,p),a.lineTo(p+f,p),a.stroke(),a.beginPath(),a.moveTo(e-p-f,p),a.lineTo(e-p,p),a.lineTo(e-p,p+f),a.stroke(),a.beginPath(),a.moveTo(p,t-p-f),a.lineTo(p,t-p),a.lineTo(p+f,t-p),a.stroke(),a.beginPath(),a.moveTo(e-p-f,t-p),a.lineTo(e-p,t-p),a.lineTo(e-p,t-p-f),a.stroke()}function di(a){const e=new Y;e.name="galacticFloor";const t=[];ui(e);const s=gi(e);return pi(e,t),mi(e),fi(e),a.add(e),console.log("[Battlefield] Galactic group added to scene:",e),{group:e,stars:s,nebulas:t,time:0}}function ui(a){const e=document.createElement("canvas"),t=e.getContext("2d");e.width=2048,e.height=2048;const s=t.createRadialGradient(1024,1024,0,1024,1024,1024);s.addColorStop(0,"#2a1050"),s.addColorStop(.2,"#1a0a40"),s.addColorStop(.5,"#0d0525"),s.addColorStop(.8,"#060215"),s.addColorStop(1,"#020108"),t.fillStyle=s,t.fillRect(0,0,2048,2048),t.save(),t.translate(1024,1024);for(let d=0;d<3;d++){const h=d/3*Math.PI*2;t.save(),t.rotate(h);for(let g=0;g<1500;g++){const f=g/1500*800,p=f*.012,m=f*.15,b=Math.cos(p)*f+(Math.random()-.5)*m,w=Math.sin(p)*f+(Math.random()-.5)*m,M=1-f/800*.6,S=(1-f/800)*4+Math.random()*3,P=Math.floor(220*M+35),C=Math.floor(200*M+55),x=Math.floor(255);if(t.fillStyle=`rgba(${P}, ${C}, ${x}, ${M})`,t.beginPath(),t.arc(b,w,S,0,Math.PI*2),t.fill(),M>.7&&Math.random()>.5){const B=t.createRadialGradient(b,w,0,b,w,S*3);B.addColorStop(0,`rgba(${P}, ${C}, ${x}, 0.6)`),B.addColorStop(1,"transparent"),t.fillStyle=B,t.beginPath(),t.arc(b,w,S*3,0,Math.PI*2),t.fill()}}t.restore()}const i=t.createRadialGradient(0,0,0,0,0,200);i.addColorStop(0,"rgba(255, 255, 255, 1)"),i.addColorStop(.1,"rgba(255, 240, 220, 0.95)"),i.addColorStop(.3,"rgba(255, 200, 150, 0.7)"),i.addColorStop(.6,"rgba(200, 150, 255, 0.4)"),i.addColorStop(1,"transparent"),t.fillStyle=i,t.beginPath(),t.arc(0,0,200,0,Math.PI*2),t.fill(),t.restore();for(let d=0;d<1e3;d++){const h=Math.random()*2048,g=Math.random()*2048,f=.5+Math.random()*2.5,p=150+Math.random()*105,m=Math.random();let b,w,M;if(m<.6?(b=p,w=p,M=255):m<.8?(b=255,w=p,M=p*.7):(b=255,w=p*.6,M=p),t.fillStyle=`rgba(${b}, ${w}, ${M}, 1)`,t.beginPath(),t.arc(h,g,f,0,Math.PI*2),t.fill(),Math.random()>.85){const S=t.createRadialGradient(h,g,0,h,g,f*6);S.addColorStop(0,`rgba(${b}, ${w}, ${M}, 0.7)`),S.addColorStop(.5,`rgba(${b}, ${w}, ${M}, 0.2)`),S.addColorStop(1,"transparent"),t.fillStyle=S,t.beginPath(),t.arc(h,g,f*6,0,Math.PI*2),t.fill()}}const o=["#ff00ff","#00ffff","#ff6600","#6600ff"];for(let d=0;d<8;d++){const h=300+Math.random()*1448,g=300+Math.random()*1448,f=100+Math.random()*200,p=o[d%o.length],m=t.createRadialGradient(h,g,0,h,g,f);m.addColorStop(0,p+"40"),m.addColorStop(.5,p+"15"),m.addColorStop(1,"transparent"),t.fillStyle=m,t.beginPath(),t.arc(h,g,f,0,Math.PI*2),t.fill()}const n=new se(e);n.colorSpace=Wt;const r=new pe(30,30),l=new v({map:n,side:oe}),c=new y(r,l);c.rotation.x=-Math.PI/2,c.position.y=.01,c.name="galaxyPlane",c.receiveShadow=!0,a.add(c),console.log("[Battlefield] Galaxy plane created:",c.position)}function gi(a){const e=new le,t=500,s=new Float32Array(t*3),i=new Float32Array(t*3);for(let r=0;r<t;r++){const l=Math.random()*Math.PI*2,c=Math.random()*14;s[r*3]=Math.cos(l)*c,s[r*3+1]=.05+Math.random()*.3,s[r*3+2]=Math.sin(l)*c;const d=Math.random();d<.4?(i[r*3]=.9,i[r*3+1]=.9,i[r*3+2]=1):d<.6?(i[r*3]=1,i[r*3+1]=.8,i[r*3+2]=.4):d<.8?(i[r*3]=1,i[r*3+1]=.4,i[r*3+2]=.8):(i[r*3]=.4,i[r*3+1]=1,i[r*3+2]=1)}e.setAttribute("position",new Ae(s,3)),e.setAttribute("color",new Ae(i,3));const o=new pt({size:.15,transparent:!0,opacity:.9,vertexColors:!0,blending:Me,depthWrite:!1}),n=new Ye(e,o);return n.name="galacticStars",n.renderOrder=5,a.add(n),n}function pi(a,e){const t=[16711935,65535,16737792,6684927,65382];for(let s=0;s<4;s++){const i=document.createElement("canvas"),o=i.getContext("2d");i.width=256,i.height=256;const n=o.createRadialGradient(128,128,0,128,128,128);n.addColorStop(0,"rgba(255, 255, 255, 0.6)"),n.addColorStop(.3,"rgba(255, 255, 255, 0.3)"),n.addColorStop(.6,"rgba(255, 255, 255, 0.1)"),n.addColorStop(1,"transparent"),o.fillStyle=n,o.fillRect(0,0,256,256);const r=new se(i),l=6+Math.random()*6,c=new pe(l,l),d=new v({map:r,color:t[s%t.length],transparent:!0,opacity:.25,blending:Me,depthWrite:!1,side:oe}),h=new y(c,d);h.rotation.x=-Math.PI/2,h.position.set((Math.random()-.5)*20,.03+s*.01,(Math.random()-.5)*20),h.name=`nebula_${s}`,h.renderOrder=2+s,e.push(h),a.add(h)}}function fi(a){const e=new le,t=150,s=new Float32Array(t*3);for(let n=0;n<t;n++){const r=Math.random()*Math.PI*2,l=Math.random()*14;s[n*3]=Math.cos(r)*l,s[n*3+1]=.1+Math.random()*2,s[n*3+2]=Math.sin(r)*l}e.setAttribute("position",new Ae(s,3));const i=new pt({size:.15,color:8947967,transparent:!0,opacity:.5,blending:Me,depthWrite:!1}),o=new Ye(e,i);o.name="cosmicDust",a.add(o)}function mi(a){const e=new ke(14.5,15.5,64),t=new v({color:4491519,transparent:!0,opacity:.6,side:oe,blending:Me}),s=new y(e,t);s.rotation.x=-Math.PI/2,s.position.y=.02,s.name="portalRim",a.add(s);const i=new ke(13.5,14.5,64),o=new v({color:8930559,transparent:!0,opacity:.3,side:oe,blending:Me}),n=new y(i,o);n.rotation.x=-Math.PI/2,n.position.y=.01,n.name="portalInnerRim",a.add(n)}function Tt(a,e,t){e&&(e.group.traverse(s=>{var i,o;s instanceof y?((i=s.geometry)==null||i.dispose(),s.material instanceof Pe?t(s.material):Array.isArray(s.material)&&s.material.forEach(n=>t(n))):s instanceof Ye&&((o=s.geometry)==null||o.dispose(),s.material instanceof Pe&&s.material.dispose())}),a.remove(e.group))}function wi(a,e){a.time+=e;const t=a.group.getObjectByName("galaxyPlane");t&&(t.rotation.z=a.time*.02),a.nebulas.forEach((n,r)=>{n.rotation.z+=e*.03*(r%2===0?1:-1),n.position.x+=Math.sin(a.time*.2+r*2)*e*.1,n.position.z+=Math.cos(a.time*.15+r*2)*e*.1,Math.abs(n.position.x)>12&&(n.position.x*=.9),Math.abs(n.position.z)>12&&(n.position.z*=.9);const l=n.material;l.opacity=.15+Math.sin(a.time*.5+r)*.1});const s=a.group.getObjectByName("portalRim");if(s){const n=s.material;n.opacity=.5+Math.sin(a.time*2)*.3}const i=a.group.getObjectByName("portalInnerRim");if(i){const n=i.material;n.opacity=.3+Math.sin(a.time*3+1)*.2}const o=a.group.getObjectByName("cosmicDust");if(o){const n=o.geometry.attributes.position.array;for(let r=0;r<n.length;r+=3)if(n[r+1]+=e*.15,n[r+1]>3){n[r+1]=.1;const l=Math.random()*Math.PI*2,c=Math.random()*14;n[r]=Math.cos(l)*c,n[r+2]=Math.sin(l)*c}o.geometry.attributes.position.needsUpdate=!0}if(a.stars){const n=a.stars.material;n.opacity=.7+Math.sin(a.time*4)*.2,a.stars.rotation.y=a.time*.01}}const It=new T,Dt=new T;function Lt(){return{phase:"dawn",sunPosition:new T(50,10,-60),moonPosition:new T(-40,15,-50),ambientColor:10075101,ambientIntensity:.6,hemiSkyColor:6724044,hemiGroundColor:4478310,hemiIntensity:.75,mainLightColor:12312063,mainLightIntensity:1.1,fogColor:4487082,fogDensity:.008,skyColor:3368618,starsOpacity:.2,moonOpacity:.3,sunOpacity:.9,lampIntensity:.5,windowEmissive:.3}}function Et(){return{phase:"dusk",sunPosition:new T(-50,8,-60),moonPosition:new T(40,12,-50),ambientColor:7833787,ambientIntensity:.55,hemiSkyColor:4482747,hemiGroundColor:3359829,hemiIntensity:.65,mainLightColor:10075118,mainLightIntensity:.9,fogColor:2245802,fogDensity:.01,skyColor:2245802,starsOpacity:.3,moonOpacity:.4,sunOpacity:.8,lampIntensity:1.5,windowEmissive:.5}}function tt(){return{phase:"night",sunPosition:new T(30,-20,-50),moonPosition:new T(-30,35,-50),ambientColor:5596842,ambientIntensity:.5,hemiSkyColor:3359863,hemiGroundColor:2236996,hemiIntensity:.6,mainLightColor:13426175,mainLightIntensity:.9,fogColor:662058,fogDensity:.012,skyColor:662058,starsOpacity:.9,moonOpacity:1,sunOpacity:0,lampIntensity:2.5,windowEmissive:.8}}function st(){return{phase:"day",sunPosition:new T(30,50,-30),moonPosition:new T(-30,-20,-50),ambientColor:16777215,ambientIntensity:.85,hemiSkyColor:5939433,hemiGroundColor:5596791,hemiIntensity:1,mainLightColor:16777198,mainLightIntensity:1.5,fogColor:6990048,fogDensity:.005,skyColor:4886745,starsOpacity:0,moonOpacity:0,sunOpacity:1,lampIntensity:0,windowEmissive:.1}}function Re(a,e,t,s){const i=(n,r)=>n+(r-n)*t,o=(n,r)=>{const l=n>>16&255,c=n>>8&255,d=n&255,h=r>>16&255,g=r>>8&255,f=r&255,p=Math.round(i(l,h)),m=Math.round(i(c,g)),b=Math.round(i(d,f));return p<<16|m<<8|b};return It.lerpVectors(a.sunPosition,e.sunPosition,t),Dt.lerpVectors(a.moonPosition,e.moonPosition,t),{phase:s,sunPosition:It,moonPosition:Dt,ambientColor:o(a.ambientColor,e.ambientColor),ambientIntensity:i(a.ambientIntensity,e.ambientIntensity),hemiSkyColor:o(a.hemiSkyColor,e.hemiSkyColor),hemiGroundColor:o(a.hemiGroundColor,e.hemiGroundColor),hemiIntensity:i(a.hemiIntensity,e.hemiIntensity),mainLightColor:o(a.mainLightColor,e.mainLightColor),mainLightIntensity:i(a.mainLightIntensity,e.mainLightIntensity),fogColor:o(a.fogColor,e.fogColor),fogDensity:i(a.fogDensity,e.fogDensity),skyColor:o(a.skyColor,e.skyColor),starsOpacity:i(a.starsOpacity,e.starsOpacity),moonOpacity:i(a.moonOpacity,e.moonOpacity),sunOpacity:i(a.sunOpacity,e.sunOpacity),lampIntensity:i(a.lampIntensity,e.lampIntensity),windowEmissive:i(a.windowEmissive,e.windowEmissive)}}function bi(a){if(a>=5&&a<6){const e=a-5;return Re(tt(),Lt(),e,"dawn")}else if(a>=6&&a<7){const e=a-6;return Re(Lt(),st(),e,"dawn")}else{if(a>=7&&a<18)return st();if(a>=18&&a<19.5){const e=(a-18)/1.5;return Re(st(),Et(),e,"dusk")}else if(a>=19.5&&a<21){const e=(a-19.5)/1.5;return Re(Et(),tt(),e,"dusk")}else return tt()}}function yi(){const a=document.createElement("canvas"),e=a.getContext("2d");a.width=512,a.height=512;const t=256,s=256,i=e.createRadialGradient(t,s,50,t,s,256);i.addColorStop(0,"rgba(255, 255, 200, 1)"),i.addColorStop(.2,"rgba(255, 240, 150, 0.8)"),i.addColorStop(.4,"rgba(255, 220, 100, 0.4)"),i.addColorStop(.7,"rgba(255, 200, 80, 0.1)"),i.addColorStop(1,"rgba(255, 180, 50, 0)"),e.fillStyle=i,e.fillRect(0,0,512,512);const o=e.createRadialGradient(t,s,0,t,s,80);o.addColorStop(0,"rgba(255, 255, 255, 1)"),o.addColorStop(.5,"rgba(255, 255, 220, 1)"),o.addColorStop(1,"rgba(255, 240, 150, 0.8)"),e.fillStyle=o,e.beginPath(),e.arc(t,s,80,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(t,s,60,0,Math.PI*2),e.fillStyle="#ffffee",e.fill();const n=new se(a),r=new J({map:n,transparent:!0,depthWrite:!1,blending:Me}),l=new K(r);return l.position.set(30,50,-30),l.scale.set(50,50,1),l.name="sun",l.visible=!1,l}function Mi(){const a=document.createElement("canvas"),e=a.getContext("2d");a.width=512,a.height=512;const t=256,s=256,i=e.createRadialGradient(t,s,60,t,s,256);i.addColorStop(0,"rgba(200, 220, 255, 1)"),i.addColorStop(.2,"rgba(180, 200, 240, 0.8)"),i.addColorStop(.4,"rgba(150, 180, 220, 0.5)"),i.addColorStop(.7,"rgba(120, 150, 200, 0.2)"),i.addColorStop(1,"rgba(100, 130, 180, 0)"),e.fillStyle=i,e.fillRect(0,0,512,512);const o=e.createRadialGradient(t,s,0,t,s,100);o.addColorStop(0,"rgba(255, 255, 255, 1)"),o.addColorStop(.5,"rgba(230, 240, 255, 0.9)"),o.addColorStop(1,"rgba(200, 220, 255, 0.3)"),e.fillStyle=o,e.beginPath(),e.arc(t,s,100,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(t,s,70,0,Math.PI*2),e.fillStyle="#e8eeff",e.fill(),e.fillStyle="rgba(180, 190, 210, 0.6)",e.beginPath(),e.arc(t-25,s-20,18,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(t+25,s+15,12,0,Math.PI*2),e.fill(),e.beginPath(),e.arc(t-5,s+30,10,0,Math.PI*2),e.fill();const n=new se(a),r=new J({map:n,transparent:!0,depthWrite:!1,blending:Me}),l=new K(r);return l.position.set(-30,35,-50),l.scale.set(40,40,1),l.name="moon",l}function Si(a=1){const e=new Y,t=new A({color:16777215,transparent:!0,opacity:.85,roughness:1,metalness:0,depthWrite:!1}),s=new O(1,16,12);return[{x:0,y:0,z:0,scale:1.2},{x:-1,y:.1,z:.2,scale:1},{x:1,y:.15,z:-.1,scale:1.1},{x:-.5,y:.3,z:.4,scale:.8},{x:.6,y:.35,z:.3,scale:.9},{x:-1.5,y:-.1,z:0,scale:.7},{x:1.5,y:-.05,z:.1,scale:.75},{x:0,y:.4,z:0,scale:.7}].forEach(o=>{const n=new y(s,t);n.position.set(o.x*a,o.y*a,o.z*a),n.scale.setScalar(o.scale*a),e.add(n)}),e.userData.material=t,e}function vi(){const a=new Y;a.name="clouds";const e=[];return[{x:-25,y:35,z:-20,scale:3.5,speed:.8},{x:15,y:40,z:-35,scale:4,speed:1},{x:-40,y:38,z:10,scale:3,speed:.9},{x:30,y:42,z:15,scale:3.8,speed:1.1},{x:0,y:36,z:-45,scale:3.2,speed:.85},{x:-15,y:44,z:30,scale:2.8,speed:1.05},{x:45,y:37,z:-10,scale:3.6,speed:.95},{x:-35,y:41,z:-30,scale:2.5,speed:1.15}].forEach((s,i)=>{const o=Si(s.scale);o.position.set(s.x,s.y,s.z),o.userData.baseX=s.x,o.userData.speed=s.speed,o.userData.index=i,a.add(o),e.push(o)}),{group:a,clouds:e,time:0}}function Ci(a,e){a.time+=e,a.clouds.forEach(t=>{const s=t.userData.baseX,i=t.userData.speed,o=t.userData.index,n=60,r=.015*i,l=o*.7,c=Math.sin(a.time*r+l)*n*.5;t.position.x=s+c;const d=.3*i,h=.5;t.position.y+=Math.sin(a.time*d+l)*h*e})}function Pi(a,e){a.clouds.forEach(t=>{const s=t.userData.material;s&&(s.opacity=e*.85)})}function ki(){const a=new le,e=300,t=new Float32Array(e*3);for(let o=0;o<e;o++){const n=Math.random()*Math.PI*2,r=Math.random()*Math.PI*.5,l=80+Math.random()*40;t[o*3]=l*Math.sin(r)*Math.cos(n),t[o*3+1]=l*Math.cos(r)+20,t[o*3+2]=l*Math.sin(r)*Math.sin(n)}a.setAttribute("position",new Ae(t,3));const s=new pt({color:16777215,size:.5,transparent:!0,opacity:.8}),i=new Ye(a,s);return i.name="stars",i}function Ai(a){const t=a/2+5;return[{x:-t,z:-t+2,scale:1.2},{x:-t+2,z:-t,scale:1.4},{x:t,z:-t+2,scale:1.3},{x:t-2,z:-t,scale:1},{x:-t,z:t-2,scale:1.1},{x:-t+2,z:t,scale:1.5},{x:t,z:t-2,scale:1.25},{x:t-2,z:t,scale:1.35}]}function xi(a){const e=a/2,t=e+3,s=e*.5;return[{x:-t,z:-s},{x:-t,z:0},{x:-t,z:s},{x:t,z:-s},{x:t,z:0},{x:t,z:s},{x:-s,z:-t},{x:0,z:-t},{x:s,z:-t},{x:-s,z:t},{x:0,z:t},{x:s,z:t},{x:-t-5,z:s+2},{x:-t-8,z:s+5}]}function Bi(a){const e=a/2+2;return[{x:-e,z:-e},{x:e,z:-e},{x:-e,z:e},{x:e,z:e}]}function _t(a,e=ft){const t=Ti(a,e),s=Ii(a,e),{house:i,windowMaterials:o}=Di(a,e),{lamps:n,lampLights:r}=Li(a,e);return{trees:t,bushes:s,house:i,lamps:n,lampLights:r,windowMaterials:o}}function Ti(a,e){const t=new Y;t.name="trees_instanced";const s=Ai(e),i=s.length,o=new A({color:4863784,roughness:.9}),n=new A({color:2972199,roughness:.8}),r=new j(.3,.5,3,8),l=new O(2,8,6),c=new O(1.5,8,6),d=new me(r,o,i),h=new me(l,n,i),g=new me(c,n,i);d.castShadow=!0,d.receiveShadow=!0,h.castShadow=!0,g.castShadow=!0,d.name="trees_trunks",h.name="trees_foliage1",g.name="trees_foliage2";const f=new Xe,p=new T,m=new Ee,b=new T;return s.forEach((w,M)=>{const S=w.scale,P=Math.random()*Math.PI*2;p.set(w.x,1.5*S,w.z),m.setFromEuler(new Ft(0,P,0)),b.set(S,S,S),f.compose(p,m,b),d.setMatrixAt(M,f),p.set(w.x,4*S,w.z),b.set(S,S*.8,S),f.compose(p,m,b),h.setMatrixAt(M,f),p.set(w.x,5.5*S,w.z),b.set(S,S,S),f.compose(p,m,b),g.setMatrixAt(M,f)}),d.instanceMatrix.needsUpdate=!0,h.instanceMatrix.needsUpdate=!0,g.instanceMatrix.needsUpdate=!0,t.add(d),t.add(h),t.add(g),a.add(t),t}function Ii(a,e){const t=xi(e),s=[],i=g=>{const f=Math.sin(g)*1e4;return f-Math.floor(f)};t.forEach((g,f)=>{const p=2+Math.floor(i(f*100)*2);for(let m=0;m<p;m++){const b=f*100+m,w=.6+i(b)*.4,M=(i(b+1)-.5)*.8,S=(i(b+2)-.5)*.8,P=.7+i(b+3)*.2;s.push({x:g.x+M,y:w*.7,z:g.z+S,scaleX:w,scaleY:w*P,scaleZ:w})}});const o=new A({color:4024887,roughness:.85}),n=new O(1,8,6),r=new me(n,o,s.length);r.castShadow=!0,r.receiveShadow=!0,r.name="bushes_instanced";const l=new Xe,c=new T,d=new Ee,h=new T;return s.forEach((g,f)=>{c.set(g.x,g.y,g.z),d.identity(),h.set(g.scaleX,g.scaleY,g.scaleZ),l.compose(c,d,h),r.setMatrixAt(f,l)}),r.instanceMatrix.needsUpdate=!0,a.add(r),r}function Di(a,e){const t=new Y,s=[],i=new z(6,4,5),o=new A({color:13935988,roughness:.8}),n=new y(i,o);n.position.y=2,n.castShadow=!0,n.receiveShadow=!0,t.add(n);const r=new xe(5,3,4),l=new A({color:9127187,roughness:.7}),c=new y(r,l);c.position.y=5.5,c.rotation.y=Math.PI/4,c.castShadow=!0,t.add(c);const d=new z(1.2,2,.1),h=new A({color:6045747,roughness:.6}),g=new y(d,h);g.position.set(0,1,2.55),t.add(g);const f=new z(.8,.8,.1),p=new A({color:16777130,emissive:16755268,emissiveIntensity:.5,roughness:.3});s.push(p);const m=new y(f,p);m.position.set(-1.5,2.5,2.55),t.add(m);const b=new y(f,p);b.position.set(1.5,2.5,2.55),t.add(b);const w=new z(.8,2,.8),M=new A({color:9127187,roughness:.8}),S=new y(w,M);S.position.set(1.5,6,-1),S.castShadow=!0,t.add(S);const P=e/2;return t.position.set(-P-5,0,P-5),t.rotation.y=Math.PI/6,t.name="house",a.add(t),{house:t,windowMaterials:s}}function Li(a,e){const t=new Y;t.name="lamps_instanced";const s=[],i=Bi(e),o=i.length,n=new A({color:3355443,roughness:.5,metalness:.5}),r=new A({color:2236962,roughness:.4,metalness:.6}),l=new A({color:16772778,emissive:16755268,emissiveIntensity:2,roughness:.2}),c=new j(.1,.15,5,8),d=new j(.05,.05,1,8),h=new j(.4,.3,.6,8),g=new O(.25,8,8),f=new me(c,n,o),p=new me(d,n,o),m=new me(h,r,o),b=new me(g,l,o);f.castShadow=!0,f.name="lamps_poles",p.name="lamps_arms",m.name="lamps_housings",b.name="lamps_bulbs";const w=new Xe,M=new T,S=new Ee,P=new T(1,1,1);return i.forEach((C,x)=>{M.set(C.x,2.5,C.z),S.identity(),w.compose(M,S,P),f.setMatrixAt(x,w),M.set(C.x+.4,4.8,C.z),S.setFromEuler(new Ft(0,0,Math.PI/2)),w.compose(M,S,P),p.setMatrixAt(x,w),M.set(C.x+.8,4.8,C.z),S.identity(),w.compose(M,S,P),m.setMatrixAt(x,w),M.set(C.x+.8,4.5,C.z),w.compose(M,S,P),b.setMatrixAt(x,w);const B=new us(16755285,1.5,15);B.position.set(C.x,5,C.z),s.push(B),a.add(B)}),f.instanceMatrix.needsUpdate=!0,p.instanceMatrix.needsUpdate=!0,m.instanceMatrix.needsUpdate=!0,b.instanceMatrix.needsUpdate=!0,t.add(f),t.add(p),t.add(m),t.add(b),a.add(t),{lamps:t,lampLights:s}}function Ot(a,e=ft){const t=e*1.5,s=new pe(t,t),i=new A({color:2972199,roughness:.9,metalness:0}),o=new y(s,i);return o.rotation.x=-Math.PI/2,o.position.y=-.05,o.receiveShadow=!0,o.name="grass",a.add(o),o}class Ei{constructor(e){u(this,"scene");u(this,"ground",null);u(this,"gridHelper",null);u(this,"sun",null);u(this,"moon",null);u(this,"stars",null);u(this,"ambientLight",null);u(this,"hemiLight",null);u(this,"mainLight",null);u(this,"fillLight",null);u(this,"lampLights",[]);u(this,"windowMaterials",[]);u(this,"trees",null);u(this,"bushes",null);u(this,"house",null);u(this,"lamps",null);u(this,"grass",null);u(this,"baseFogDensity",.01);u(this,"brightness",1);u(this,"skyColorOverride",null);u(this,"currentFloorStyle","concrete");u(this,"galacticState",null);u(this,"cloudState",null);u(this,"cloudsVisible",!0);u(this,"debugHourOverride",null);u(this,"tempColor",new H);u(this,"currentSize",ft);u(this,"terrainVisibility",{trees:!0,bushes:!0,house:!0,lamps:!0,grass:!0});u(this,"gridVisible",!0);u(this,"simpleMode",!1);this.scene=e}setGridVisible(e){this.gridVisible=e,this.gridHelper&&(this.gridHelper.visible=e)}create(){this.createGround(),this.grass=Ot(this.scene,this.currentSize),this.createGrid(),this.sun=yi(),this.scene.add(this.sun),this.moon=Mi(),this.scene.add(this.moon),this.stars=ki(),this.scene.add(this.stars),this.cloudState=vi(),this.scene.add(this.cloudState.group);const e=_t(this.scene,this.currentSize);this.trees=e.trees,this.bushes=e.bushes,this.house=e.house,this.lamps=e.lamps,this.lampLights=e.lampLights,this.windowMaterials=e.windowMaterials,this.createLighting(),this.createFog(),this.updateTimeOfDay()}updateTimeOfDay(){const e=bi(this.getCurrentHour());this.applyTimeConfig(e)}getCurrentHour(){if(this.debugHourOverride!==null)return this.debugHourOverride;const e=new Date;return e.getHours()+e.getMinutes()/60}setDebugTime(e){this.debugHourOverride=e,this.updateTimeOfDay(),console.log(`[Battlefield] Time set to: ${e!==null?`${e}:00`:"real time"}`)}setTimeMode(e){const s={auto:null,day:12,night:23,dawn:6,dusk:19.5}[e]??null;this.debugHourOverride=s,this.updateTimeOfDay(),console.log(`[Battlefield] Time mode set to: ${e} (${s!==null?`${s}:00`:"real time"})`)}setTerrainConfig(e){if(e.battlefieldSize!==void 0&&e.battlefieldSize!==this.currentSize&&this.resizeBattlefield(e.battlefieldSize),this.terrainVisibility={trees:e.showTrees,bushes:e.showBushes,house:e.showHouse,lamps:e.showLamps,grass:e.showGrass},this.trees&&(this.trees.visible=e.showTrees),this.bushes&&(this.bushes.visible=e.showBushes),this.house&&(this.house.visible=e.showHouse),this.lamps&&(this.lamps.visible=e.showLamps),this.lampLights.forEach(t=>{t.visible=e.showLamps}),this.grass&&(this.grass.visible=e.showGrass),e.showClouds!==void 0&&(this.cloudsVisible=e.showClouds,this.cloudState&&(this.cloudState.group.visible=e.showClouds)),this.baseFogDensity=e.fogDensity*.008,e.brightness!==void 0&&(this.brightness=e.brightness),e.skyColor!==void 0&&(this.skyColorOverride=e.skyColor),e.simpleMode!==void 0){const t=this.simpleMode;this.simpleMode=e.simpleMode,t&&!this.simpleMode&&this.setFloorStyle(this.currentFloorStyle,!0)}this.updateTimeOfDay()}resizeBattlefield(e){this.currentSize=e,console.log(`[Battlefield] Resizing to ${e}x${e}`),this.ground&&(this.ground.geometry.dispose(),this.disposeMaterial(this.ground.material),this.scene.remove(this.ground),this.ground=null),this.createGround(),this.setFloorStyle(this.currentFloorStyle,!0),this.gridHelper&&(this.gridHelper.geometry.dispose(),this.gridHelper.material instanceof Pe&&this.gridHelper.material.dispose(),this.scene.remove(this.gridHelper),this.gridHelper=null),this.createGrid(),this.grass&&(this.grass.geometry.dispose(),this.disposeMaterial(this.grass.material),this.scene.remove(this.grass)),this.grass=Ot(this.scene,this.currentSize),this.grass.visible=this.terrainVisibility.grass,this.disposeTerrainElements();const t=_t(this.scene,this.currentSize);if(this.trees=t.trees,this.bushes=t.bushes,this.house=t.house,this.lamps=t.lamps,this.lampLights=t.lampLights,this.windowMaterials=t.windowMaterials,this.trees&&(this.trees.visible=this.terrainVisibility.trees),this.bushes&&(this.bushes.visible=this.terrainVisibility.bushes),this.house&&(this.house.visible=this.terrainVisibility.house),this.lamps&&(this.lamps.visible=this.terrainVisibility.lamps),this.lampLights.forEach(s=>{s.visible=this.terrainVisibility.lamps}),this.mainLight){const s=this.currentSize*.6;this.mainLight.shadow.camera.left=-s,this.mainLight.shadow.camera.right=s,this.mainLight.shadow.camera.top=s,this.mainLight.shadow.camera.bottom=-s,this.mainLight.shadow.camera.updateProjectionMatrix()}}disposeTerrainElements(){this.trees&&(this.disposeGroup(this.trees),this.scene.remove(this.trees),this.trees=null),this.bushes&&(this.bushes.geometry.dispose(),this.bushes.material.dispose(),this.scene.remove(this.bushes),this.bushes=null),this.house&&(this.disposeGroup(this.house),this.scene.remove(this.house),this.house=null),this.lamps&&(this.disposeGroup(this.lamps),this.scene.remove(this.lamps),this.lamps=null);for(const e of this.lampLights)this.scene.remove(e),e.dispose();this.lampLights=[],this.windowMaterials=[]}setFloorStyle(e,t=!1){if(this.currentFloorStyle===e&&!t)return;const s=this.currentFloorStyle;if(this.currentFloorStyle=e,typeof window<"u"&&window.__TIDE_MEMORY_DEBUG__&&console.log(`[Battlefield] Memory: Switching floor from ${s} to ${e}`),s==="galactic"&&(Tt(this.scene,this.galacticState,this.disposeMaterial.bind(this)),this.galacticState=null,this.ground&&(this.ground.visible=!0)),this.ground){const i=this.ground.material;if(e==="galactic")console.log("[Battlefield] Creating galactic floor..."),this.ground.visible=!1,this.galacticState=di(this.scene),console.log("[Battlefield] Galactic elements created");else{this.ground.visible=!0,i.transparent=!1,i.opacity=1,i.side=gs,i.depthWrite=!0,this.ground.renderOrder=0;const o=i.map;if(e==="none")i.map=null,i.color.setHex(2972199),i.roughness=.9,i.metalness=0,i.emissive.setHex(0),i.emissiveIntensity=0,i.needsUpdate=!0;else{const n=Bt(e);n.wrapS=Ge,n.wrapT=Ge;const r=e==="pokemon-stadium"?1:Math.round(this.currentSize/5);n.repeat.set(r,r),i.map=n,i.needsUpdate=!0}switch(o&&(o.dispose(),typeof window<"u"&&window.__TIDE_MEMORY_DEBUG__&&console.log("[Battlefield] Memory: Disposed old floor texture")),e){case"none":break;case"metal":i.color.setHex(8947865),i.roughness=.4,i.metalness=.8,i.emissive.setHex(0),i.emissiveIntensity=0;break;case"hex":i.color.setHex(4482696),i.roughness=.6,i.metalness=.4,i.emissive.setHex(1122867),i.emissiveIntensity=.2;break;case"circuit":i.color.setHex(2245683),i.roughness=.7,i.metalness=.3,i.emissive.setHex(13090),i.emissiveIntensity=.4;break;case"pokemon-stadium":i.color.setHex(11184810),i.roughness=1,i.metalness=0,i.emissive.setHex(0),i.emissiveIntensity=0;break;default:i.color.setHex(5592405),i.roughness=.8,i.metalness=.1,i.emissive.setHex(0),i.emissiveIntensity=0}}}console.log(`[Battlefield] Floor style set to: ${e}`)}updateGalacticAnimation(e){this.currentFloorStyle!=="galactic"||!this.galacticState||wi(this.galacticState,e)}updateCloudAnimation(e){!this.cloudState||!this.cloudsVisible||Ci(this.cloudState,e)}disposeMaterial(e){var t;(e instanceof v||e instanceof A||e instanceof J)&&((t=e.map)==null||t.dispose()),e.dispose()}applyTimeConfig(e){if(this.simpleMode){this.scene.background instanceof H?this.scene.background.setHex(657935):this.scene.background=new H(657935),this.scene.fog instanceof Je&&(this.scene.fog.density=0),this.sun&&(this.sun.visible=!1),this.moon&&(this.moon.visible=!1),this.stars&&(this.stars.visible=!1),this.cloudState&&(this.cloudState.group.visible=!1),this.trees&&(this.trees.visible=!1),this.bushes&&(this.bushes.visible=!1),this.house&&(this.house.visible=!1),this.lamps&&(this.lamps.visible=!1),this.lampLights.forEach(s=>{s.visible=!1}),this.grass&&(this.grass.visible=!1),this.ground&&this.currentFloorStyle!=="galactic"&&(this.ground.visible=!0,this.ground.material.color.setHex(855314)),this.ambientLight&&(this.ambientLight.color.setHex(16777215),this.ambientLight.intensity=.85*this.brightness),this.hemiLight&&(this.hemiLight.intensity=1*this.brightness),this.mainLight&&(this.mainLight.intensity=1.5*this.brightness);return}const t=this.skyColorOverride?parseInt(this.skyColorOverride.replace("#",""),16):e.skyColor;if(this.scene.background instanceof H?this.scene.background.setHex(t):this.scene.background=this.tempColor.setHex(t).clone(),this.scene.fog instanceof Je){const s=this.skyColorOverride?parseInt(this.skyColorOverride.replace("#",""),16):e.fogColor;this.scene.fog.color.setHex(s);const i=this.baseFogDensity>0?this.baseFogDensity/.008:0;this.scene.fog.density=e.fogDensity*i}if(this.sun&&(this.sun.position.copy(e.sunPosition),this.sun.material.opacity=e.sunOpacity,this.sun.visible=e.sunOpacity>.01),this.moon&&(this.moon.position.copy(e.moonPosition),this.moon.material.opacity=e.moonOpacity,this.moon.visible=e.moonOpacity>.01),this.stars&&(this.stars.material.opacity=e.starsOpacity,this.stars.visible=e.starsOpacity>.01),this.ambientLight&&(this.ambientLight.color.setHex(e.ambientColor),this.ambientLight.intensity=e.ambientIntensity*this.brightness),this.hemiLight&&(this.hemiLight.color.setHex(e.hemiSkyColor),this.hemiLight.groundColor.setHex(e.hemiGroundColor),this.hemiLight.intensity=e.hemiIntensity*this.brightness),this.mainLight&&(this.mainLight.color.setHex(e.mainLightColor),this.mainLight.intensity=e.mainLightIntensity*this.brightness,e.sunOpacity>e.moonOpacity?this.mainLight.position.copy(e.sunPosition):this.mainLight.position.copy(e.moonPosition)),this.lampLights.forEach(s=>{s.intensity=e.lampIntensity}),this.windowMaterials.forEach(s=>{s.emissiveIntensity=e.windowEmissive}),this.cloudState&&this.cloudsVisible){let s;switch(e.phase){case"day":s=1;break;case"dawn":case"dusk":s=.7;break;case"night":s=.2;break;default:s=1}Pi(this.cloudState,s)}}getGround(){return this.ground}createGround(){const e=new pe(this.currentSize,this.currentSize),t=Bt(this.currentFloorStyle);t.wrapS=Ge,t.wrapT=Ge;const s=this.currentFloorStyle==="galactic"?1:Math.round(this.currentSize/5);t.repeat.set(s,s);const i=new A({map:t,color:5592405,roughness:.8,metalness:.1});this.ground=new y(e,i),this.ground.rotation.x=-Math.PI/2,this.ground.receiveShadow=!0,this.ground.name="ground",this.scene.add(this.ground)}createGrid(){const e=Math.round(this.currentSize/2);this.gridHelper=new ps(this.currentSize,e,2763322,1710634),this.gridHelper.position.y=.01,this.gridHelper.visible=this.gridVisible,this.scene.add(this.gridHelper)}createLogo(){const t=new Nt().load("/assets/textures/logo-blanco.png"),s=10,i=4,o=new pe(s,i),n=new v({map:t,transparent:!0,opacity:.8,side:oe,depthWrite:!1}),r=new y(o,n);r.rotation.x=-Math.PI/2,r.position.set(0,.02,0),r.name="tideLogo",this.scene.add(r)}createFog(){this.scene.fog=new Je(662058,.01),this.scene.background=new H(662058)}createLighting(){this.ambientLight=new jt(16777215,.6),this.scene.add(this.ambientLight),this.hemiLight=new fs(16777198,5596791,.7),this.hemiLight.position.set(0,20,0),this.scene.add(this.hemiLight),this.mainLight=new et(16777215,1.2),this.mainLight.position.set(30,50,-30),this.mainLight.castShadow=!0,this.mainLight.shadow.mapSize.width=2048,this.mainLight.shadow.mapSize.height=2048,this.mainLight.shadow.camera.near=.5,this.mainLight.shadow.camera.far=200;const e=this.currentSize*.6;this.mainLight.shadow.camera.left=-e,this.mainLight.shadow.camera.right=e,this.mainLight.shadow.camera.top=e,this.mainLight.shadow.camera.bottom=-e,this.scene.add(this.mainLight),this.fillLight=new et(16777215,.6),this.fillLight.position.set(-10,15,10),this.scene.add(this.fillLight);const t=new et(11193599,.5);t.position.set(0,20,30),this.scene.add(t)}dispose(){var t,s;Tt(this.scene,this.galacticState,this.disposeMaterial.bind(this)),this.galacticState=null;const e=this.scene.getObjectByName("tideLogo");e&&((t=e.geometry)==null||t.dispose(),this.disposeMaterial(e.material),this.scene.remove(e)),this.ground&&(this.ground.geometry.dispose(),this.disposeMaterial(this.ground.material),this.scene.remove(this.ground)),this.gridHelper&&(this.gridHelper.geometry.dispose(),this.gridHelper.material instanceof Pe&&this.gridHelper.material.dispose(),this.scene.remove(this.gridHelper)),this.grass&&(this.grass.geometry.dispose(),this.disposeMaterial(this.grass.material),this.scene.remove(this.grass)),this.sun&&(this.disposeMaterial(this.sun.material),this.scene.remove(this.sun)),this.moon&&(this.disposeMaterial(this.moon.material),this.scene.remove(this.moon)),this.stars&&(this.stars.geometry.dispose(),this.stars.material.dispose(),this.scene.remove(this.stars)),this.trees&&(this.disposeGroup(this.trees),this.scene.remove(this.trees),this.trees=null),this.bushes&&(this.bushes.geometry.dispose(),this.bushes.material.dispose(),this.scene.remove(this.bushes),this.bushes=null),this.house&&(this.disposeGroup(this.house),this.scene.remove(this.house),this.house=null),this.lamps&&(this.disposeGroup(this.lamps),this.scene.remove(this.lamps),this.lamps=null);for(const i of this.lampLights)this.scene.remove(i),i.dispose();this.lampLights=[],this.windowMaterials=[],this.ambientLight&&this.scene.remove(this.ambientLight),this.hemiLight&&this.scene.remove(this.hemiLight),this.mainLight&&((s=this.mainLight.shadow.map)==null||s.dispose(),this.scene.remove(this.mainLight)),this.fillLight&&this.scene.remove(this.fillLight)}disposeGroup(e){e.traverse(t=>{var s;t instanceof y&&((s=t.geometry)==null||s.dispose(),t.material instanceof Pe?this.disposeMaterial(t.material):Array.isArray(t.material)&&t.material.forEach(i=>this.disposeMaterial(i)))})}}class Te{constructor(e=200){u(this,"lastClickTime",0);u(this,"lastClickId",null);u(this,"clickTimer",null);u(this,"threshold");this.threshold=e}handleClick(e){const t=performance.now(),s=t-this.lastClickTime;return this.lastClickTime>0&&this.lastClickId===e&&s<this.threshold?(this.clearTimer(),this.reset(),"double"):(this.lastClickId=e,this.lastClickTime=t,this.clearTimer(),this.clickTimer=setTimeout(()=>{this.clickTimer=null,this.lastClickId=null,this.lastClickTime=0},this.threshold),"single")}reset(){this.clearTimer(),this.lastClickId=null,this.lastClickTime=0}clearTimer(){this.clickTimer&&(clearTimeout(this.clickTimer),this.clickTimer=null)}dispose(){this.clearTimer()}}const Ue=class Ue{constructor(e,t,s){u(this,"canvas");u(this,"controls");u(this,"callbacks");u(this,"activePointers",new Map);u(this,"touchStartTime",0);u(this,"touchStartPos",{x:0,y:0});u(this,"isTouchDragging",!1);u(this,"isTouchPanning",!1);u(this,"touchPanStart",{x:0,y:0});u(this,"longPressTimer",null);u(this,"longPressTriggered",!1);u(this,"isPinching",!1);u(this,"lastPinchDistance",0);u(this,"twoFingerPanStart",{x:0,y:0});u(this,"lastTwoFingerAngle",0);u(this,"isThreeFingerDrag",!1);u(this,"threeFingerStart",{x:0,y:0});this.canvas=e,this.controls=t,this.callbacks=s}onTouchStart(e){for(let t=0;t<e.changedTouches.length;t++){const s=e.changedTouches[t];this.activePointers.set(s.identifier,{x:s.clientX,y:s.clientY})}this.clearLongPressTimer(),this.longPressTriggered=!1,e.touches.length===1?this.handleSingleTouchStart(e.touches[0]):e.touches.length===2?this.handleTwoTouchStart(e):e.touches.length>=3&&this.handleThreeTouchStart(e)}onTouchMove(e){for(let t=0;t<e.changedTouches.length;t++){const s=e.changedTouches[t];this.activePointers.set(s.identifier,{x:s.clientX,y:s.clientY})}e.touches.length>=3&&this.isThreeFingerDrag?this.handleThreeTouchMove(e):e.touches.length===2&&this.isPinching?this.handleTwoTouchMove(e):e.touches.length===1&&!this.isPinching&&this.handleSingleTouchMove(e.touches[0])}onTouchEnd(e){this.clearLongPressTimer();for(let t=0;t<e.changedTouches.length;t++){const s=e.changedTouches[t];this.activePointers.delete(s.identifier)}return e.touches.length===0?this.handleAllTouchesEnd(e):(e.touches.length===2?this.transitionToTwoTouches(e):e.touches.length===1&&this.transitionToOneTouch(e.touches[0]),!1)}onPointerCancel(e){this.activePointers.delete(e),this.reset()}reset(){this.isTouchPanning=!1,this.isPinching=!1,this.isThreeFingerDrag=!1,this.lastPinchDistance=0,this.isTouchDragging=!1,this.longPressTriggered=!1,this.clearLongPressTimer()}get isDragging(){return this.isTouchDragging}get wasLongPress(){return this.longPressTriggered}dispose(){this.clearLongPressTimer(),this.activePointers.clear()}reattach(e,t){this.canvas=e,this.controls=t}handleSingleTouchStart(e){this.touchStartTime=performance.now(),this.touchStartPos={x:e.clientX,y:e.clientY},this.isTouchDragging=!1,this.isTouchPanning=!1;const t=e.clientX,s=e.clientY;this.longPressTimer=setTimeout(()=>{this.longPressTriggered=!0,this.longPressTimer=null,this.callbacks.onLongPress(t,s),navigator.vibrate&&navigator.vibrate(50)},Ue.LONG_PRESS_DURATION)}handleTwoTouchStart(e){e.preventDefault(),this.isPinching=!0,this.isTouchPanning=!1,this.isThreeFingerDrag=!1,this.lastPinchDistance=this.getTouchDistance(e.touches[0],e.touches[1]);const t=this.getTouchCenter(e.touches[0],e.touches[1]);this.twoFingerPanStart={x:t.x,y:t.y},this.lastTwoFingerAngle=this.getTwoFingerAngle(e.touches[0],e.touches[1])}handleThreeTouchStart(e){e.preventDefault(),this.isPinching=!1,this.isThreeFingerDrag=!0,this.controls.enableRotate=!0;const t=this.getMultiTouchCenter(e.touches);this.threeFingerStart={x:t.x,y:t.y}}handleSingleTouchMove(e){const t=e.clientX-this.touchStartPos.x,s=e.clientY-this.touchStartPos.y;if(!this.isTouchPanning&&(Math.abs(t)>Ce||Math.abs(s)>Ce)&&(this.clearLongPressTimer(),this.isTouchPanning=!0,this.isTouchDragging=!0,this.touchPanStart={x:e.clientX,y:e.clientY}),this.isTouchPanning){const i=e.clientX-this.touchPanStart.x,o=e.clientY-this.touchPanStart.y;this.callbacks.onPan(i,o),this.touchPanStart={x:e.clientX,y:e.clientY}}}handleTwoTouchMove(e){this.clearLongPressTimer(),e.preventDefault();const t=this.getTouchDistance(e.touches[0],e.touches[1]),s=this.getTouchCenter(e.touches[0],e.touches[1]),i=this.getTwoFingerAngle(e.touches[0],e.touches[1]);if(this.lastPinchDistance>0){const l=this.lastPinchDistance/t;this.callbacks.onPinchZoom(l,s)}this.lastPinchDistance=t;const o=s.x-this.twoFingerPanStart.x,n=s.y-this.twoFingerPanStart.y;(Math.abs(o)>1||Math.abs(n)>1)&&(this.callbacks.onOrbit(o,n),this.twoFingerPanStart={x:s.x,y:s.y});let r=i-this.lastTwoFingerAngle;r>Math.PI&&(r-=2*Math.PI),r<-Math.PI&&(r+=2*Math.PI),Math.abs(r)>.01&&(this.callbacks.onRotation(r),this.lastTwoFingerAngle=i)}handleThreeTouchMove(e){this.clearLongPressTimer(),e.preventDefault();const t=this.getMultiTouchCenter(e.touches),s=t.x-this.threeFingerStart.x,i=t.y-this.threeFingerStart.y;(Math.abs(s)>1||Math.abs(i)>1)&&(this.callbacks.onOrbit(s,i),this.threeFingerStart={x:t.x,y:t.y})}handleAllTouchesEnd(e){const t=performance.now()-this.touchStartTime,s=!this.isTouchDragging&&!this.longPressTriggered&&t<400,i=this.isTouchPanning;if(s&&e.changedTouches.length>0){const o=e.changedTouches[0];this.callbacks.onTap(o.clientX,o.clientY)}return i&&this.callbacks.onPanEnd(),this.reset(),s}transitionToTwoTouches(e){this.isThreeFingerDrag=!1,this.isPinching=!0,this.lastPinchDistance=this.getTouchDistance(e.touches[0],e.touches[1]);const t=this.getTouchCenter(e.touches[0],e.touches[1]);this.twoFingerPanStart={x:t.x,y:t.y}}transitionToOneTouch(e){this.isPinching=!1,this.isThreeFingerDrag=!1,this.lastPinchDistance=0,this.touchPanStart={x:e.clientX,y:e.clientY},this.touchStartPos={x:e.clientX,y:e.clientY}}clearLongPressTimer(){this.longPressTimer&&(clearTimeout(this.longPressTimer),this.longPressTimer=null)}getTouchDistance(e,t){const s=t.clientX-e.clientX,i=t.clientY-e.clientY;return Math.sqrt(s*s+i*i)}getTouchCenter(e,t){return{x:(e.clientX+t.clientX)/2,y:(e.clientY+t.clientY)/2}}getTwoFingerAngle(e,t){const s=t.clientX-e.clientX,i=t.clientY-e.clientY;return Math.atan2(i,s)}getMultiTouchCenter(e){let t=0,s=0;for(let i=0;i<e.length;i++)t+=e[i].clientX,s+=e[i].clientY;return{x:t/e.length,y:s/e.length}}};u(Ue,"LONG_PRESS_DURATION",500);let ht=Ue;function _i(a){const e=Math.abs(a.deltaX),t=Math.abs(a.deltaY);return a.ctrlKey||e>1?!0:t>80&&e<1?!1:t>0&&t<=80}class Oi{constructor(e,t,s){u(this,"cameraController");u(this,"callbacks");u(this,"canvas");u(this,"isGestureActive",!1);u(this,"gestureScale",1);u(this,"onGestureStart",e=>{const t=e;t.preventDefault(),k.getTrackpadConfig().enabled&&(this.isGestureActive=!0,this.gestureScale=t.scale)});u(this,"onGestureChange",e=>{const t=e;t.preventDefault();const s=k.getTrackpadConfig();if(!(!s.enabled||!this.isGestureActive)&&s.pinchToZoom&&t.scale!==this.gestureScale){const i=t.scale-this.gestureScale;this.callbacks.onZoom(i*s.sensitivity.zoom,t.clientX,t.clientY),this.gestureScale=t.scale}});u(this,"onGestureEnd",e=>{e.preventDefault(),this.isGestureActive=!1,this.gestureScale=1});this.cameraController=e,this.canvas=t,this.callbacks=s,this.setupGestureEvents()}setupGestureEvents(){"GestureEvent"in window&&(this.canvas.addEventListener("gesturestart",this.onGestureStart),this.canvas.addEventListener("gesturechange",this.onGestureChange),this.canvas.addEventListener("gestureend",this.onGestureEnd))}handleWheel(e){const t=k.getTrackpadConfig();if(!t.enabled||!_i(e))return!1;if(e.ctrlKey&&t.pinchToZoom){e.preventDefault();const s=-e.deltaY*.01*t.sensitivity.zoom;return this.callbacks.onZoom(s,e.clientX,e.clientY),!0}if(e.shiftKey&&t.shiftTwoFingerOrbit){e.preventDefault();const s=-e.deltaX*t.sensitivity.orbit,i=-e.deltaY*t.sensitivity.orbit;return this.callbacks.onOrbit(s,i),!0}if(t.twoFingerPan){e.preventDefault();const s=-e.deltaX*t.sensitivity.pan,i=-e.deltaY*t.sensitivity.pan;return this.callbacks.onPan(s,i),!0}return!1}setCameraController(e){this.cameraController=e}setCanvas(e){"GestureEvent"in window&&(this.canvas.removeEventListener("gesturestart",this.onGestureStart),this.canvas.removeEventListener("gesturechange",this.onGestureChange),this.canvas.removeEventListener("gestureend",this.onGestureEnd)),this.canvas=e,this.setupGestureEvents()}dispose(){"GestureEvent"in window&&(this.canvas.removeEventListener("gesturestart",this.onGestureStart),this.canvas.removeEventListener("gesturechange",this.onGestureChange),this.canvas.removeEventListener("gestureend",this.onGestureEnd))}}class zi{constructor(e,t){u(this,"camera");u(this,"canvas");u(this,"raycaster",new ms);u(this,"mouse",new re);u(this,"ground",null);u(this,"agentMeshes",new Map);u(this,"agentHitboxes",[]);u(this,"resizeHandlesGetter",()=>[]);u(this,"folderIconMeshesGetter",()=>[]);this.camera=e,this.canvas=t}setReferences(e,t){this.ground=e,this.agentMeshes=t,this.agentHitboxes=[];for(const s of t.values()){const i=s.group.getObjectByName("clickHitbox");this.agentHitboxes.push(i??s.group)}}setResizeHandlesGetter(e){this.resizeHandlesGetter=e}setFolderIconMeshesGetter(e){this.folderIconMeshesGetter=e}setCanvas(e){this.canvas=e}raycastGroundFromEvent(e){if(this.updateMouseFromEvent(e),this.raycaster.setFromCamera(this.mouse,this.camera),this.ground){const i=this.raycaster.intersectObject(this.ground);if(i.length>0){const o=i[0].point;return{x:o.x,z:o.z}}}const t=new Fe(new T(0,1,0),0),s=new T;return this.raycaster.ray.intersectPlane(t,s)?{x:s.x,z:s.z}:null}raycastGroundFromPoint(e,t){if(this.updateMouseFromPoint(e,t),this.raycaster.setFromCamera(this.mouse,this.camera),this.ground){const o=this.raycaster.intersectObject(this.ground);if(o.length>0){const n=o[0].point;return{x:n.x,z:n.z}}}const s=new Fe(new T(0,1,0),0),i=new T;return this.raycaster.ray.intersectPlane(s,i)?{x:i.x,z:i.z}:null}checkResizeHandleClick(e){const t=this.resizeHandlesGetter();if(t.length===0)return null;this.updateMouseFromEvent(e),this.raycaster.setFromCamera(this.mouse,this.camera);const s=this.raycaster.intersectObjects(t);return s.length>0?s[0].object:null}checkFolderIconClick(e){const t=this.folderIconMeshesGetter();if(t.length===0)return null;this.updateMouseFromEvent(e),this.raycaster.setFromCamera(this.mouse,this.camera);const s=this.raycaster.intersectObjects(t);return s.length>0?s[0].object:null}findAgentAtPosition(e){if(this.updateMouseFromEvent(e),this.raycaster.setFromCamera(this.mouse,this.camera),this.agentHitboxes.length===0)return null;const t=this.raycaster.intersectObjects(this.agentHitboxes,!1);if(t.length>0){let s=t[0].object;for(;s&&!s.userData.agentId;)s=s.parent;if(s&&s.userData.agentId){const i=s.userData.agentId;return this.isAgentPickable(i)?i:null}}return null}findAgentAtPoint(e,t){if(this.updateMouseFromPoint(e,t),this.raycaster.setFromCamera(this.mouse,this.camera),this.agentHitboxes.length===0)return null;const s=this.raycaster.intersectObjects(this.agentHitboxes,!1);if(s.length>0){let i=s[0].object;for(;i&&!i.userData.agentId;)i=i.parent;if(i&&i.userData.agentId){const o=i.userData.agentId;return this.isAgentPickable(o)?o:null}}return null}isAgentPickable(e){if(!$e())return!0;const t=k.getAreaForAgent(e);return lt((t==null?void 0:t.id)??null)}raycastToPlane(e,t){if(this.mouse.set(e,t),this.raycaster.setFromCamera(this.mouse,this.camera),this.ground){const o=this.raycaster.intersectObject(this.ground);if(o.length>0)return o[0].point}const s=new Fe(new T(0,1,0),0),i=new T;return this.raycaster.ray.intersectPlane(s,i)?i:null}projectToScreen(e){const t=this.canvas.getBoundingClientRect(),s=e.clone().project(this.camera);return{x:(s.x+1)/2*t.width+t.left,y:(-s.y+1)/2*t.height+t.top}}getNormalizedMouseFromEvent(e){return this.updateMouseFromEvent(e),this.mouse.clone()}getNormalizedMouseFromPoint(e,t){return this.updateMouseFromPoint(e,t),this.mouse.clone()}getAgentMeshes(){return this.agentMeshes}updateMouseFromEvent(e){const t=this.canvas.getBoundingClientRect();this.mouse.x=(e.clientX-t.left)/t.width*2-1,this.mouse.y=-((e.clientY-t.top)/t.height)*2+1}updateMouseFromPoint(e,t){const s=this.canvas.getBoundingClientRect();this.mouse.x=(e-s.left)/s.width*2-1,this.mouse.y=-((t-s.top)/s.height)*2+1}}const be=class be{constructor(e,t,s){u(this,"camera");u(this,"controls");u(this,"canvas");u(this,"raycastProvider",null);u(this,"goalCameraPos",null);u(this,"goalOrbitTarget",null);u(this,"panInertiaVelocity",new T);u(this,"lastPanEventTime",0);u(this,"panInertiaActive",!1);this.camera=e,this.controls=t,this.canvas=s}setRaycastProvider(e){this.raycastProvider=e}setControls(e){this.controls=e}setCanvas(e){this.canvas=e}handleWheelZoom(e,t=1){var S,P;this.stopPanInertia(),e.preventDefault();const s=Math.sign(e.deltaY)*Math.min(Math.abs(e.deltaY),100)/100,i=s<0,o=.08*Math.abs(s)*t,n=((S=this.goalOrbitTarget)==null?void 0:S.clone())??this.controls.target.clone(),l=(((P=this.goalCameraPos)==null?void 0:P.clone())??this.camera.position.clone()).clone().sub(n),c=l.length(),d=this.controls.minDistance,h=this.controls.maxDistance,g=i?Math.max(d,c*(1-o)):Math.min(h,c*(1+o));if(g===c)return;let f=null;if(this.raycastProvider){const C=this.raycastProvider.getNormalizedMouseFromEvent(e);f=this.raycastProvider.raycastToPlane(C.x,C.y)}if(!f){const C=l.normalize();this.goalCameraPos=n.clone().add(C.multiplyScalar(g)),this.goalOrbitTarget=n.clone();return}const p=g/c,m=f.clone().sub(n),b=1-p,w=n.clone().add(m.multiplyScalar(b));w.y=Math.max(0,w.y);const M=l.normalize();this.goalCameraPos=w.clone().add(M.multiplyScalar(g)),this.goalOrbitTarget=w}handlePinchZoom(e,t){this.stopPanInertia(),this.goalCameraPos=null,this.goalOrbitTarget=null;const s=this.camera.position.clone().sub(this.controls.target),i=s.length(),o=this.controls.minDistance,n=this.controls.maxDistance,r=Math.max(o,Math.min(n,i*e));if(r===i)return;const l=this.canvas.getBoundingClientRect(),c=(t.x-l.left)/l.width*2-1,d=-((t.y-l.top)/l.height)*2+1;let h=null;if(this.raycastProvider&&(h=this.raycastProvider.raycastToPlane(c,d)),!h){const w=s.normalize();this.camera.position.copy(this.controls.target).add(w.multiplyScalar(r));return}const g=r/i,f=h.clone().sub(this.controls.target),p=1-g,m=this.controls.target.clone().add(f.multiplyScalar(p));m.y=Math.max(0,m.y),this.controls.target.copy(m);const b=s.normalize();this.camera.position.copy(m).add(b.multiplyScalar(r))}handlePan(e,t){this.panInertiaActive=!1,this.goalCameraPos=null,this.goalOrbitTarget=null;const s=new T;this.camera.getWorldDirection(s);const i=new T(-s.z,0,s.x).normalize(),o=new T(s.x,0,s.z).normalize(),r=this.camera.position.distanceTo(this.controls.target)*.005,l=new T;l.add(i.multiplyScalar(-e*r)),l.add(o.multiplyScalar(t*r)),this.controls.target.add(l),this.camera.position.add(l);const c=performance.now(),d=this.lastPanEventTime>0?Math.max(.001,(c-this.lastPanEventTime)/1e3):1/60;this.lastPanEventTime=c,this.panInertiaVelocity.copy(l).divideScalar(d)}handleOrbit(e,t){this.stopPanInertia(),this.goalCameraPos=null,this.goalOrbitTarget=null;const s=.005,i=-e*s,o=-t*s,n=this.camera.position.clone().sub(this.controls.target),r=new je;r.setFromVector3(n),r.theta+=i,r.phi+=o,r.phi=Math.max(.1,Math.min(Math.PI-.1,r.phi)),n.setFromSpherical(r),this.camera.position.copy(this.controls.target).add(n),this.camera.lookAt(this.controls.target)}handleTwistRotation(e){this.stopPanInertia(),this.goalCameraPos=null,this.goalOrbitTarget=null;const t=this.camera.position.clone().sub(this.controls.target),s=new je;s.setFromVector3(t),s.theta+=e,s.phi=Math.max(.1,Math.min(Math.PI-.1,s.phi)),t.setFromSpherical(s),this.camera.position.copy(this.controls.target).add(t),this.camera.lookAt(this.controls.target)}updateSmoothZoom(e){if(this.updatePanInertia(e),!this.goalCameraPos||!this.goalOrbitTarget)return;const t=k.getMouseControls().sensitivity.smoothing;if(t<=0){this.camera.position.copy(this.goalCameraPos),this.controls.target.copy(this.goalOrbitTarget),this.goalCameraPos=null,this.goalOrbitTarget=null;return}const s=$t.lerp(20,3,t),i=1-Math.exp(-s*e);this.camera.position.lerp(this.goalCameraPos,i),this.controls.target.lerp(this.goalOrbitTarget,i),this.camera.position.distanceTo(this.goalCameraPos)<.005&&this.controls.target.distanceTo(this.goalOrbitTarget)<.005&&(this.camera.position.copy(this.goalCameraPos),this.controls.target.copy(this.goalOrbitTarget),this.goalCameraPos=null,this.goalOrbitTarget=null)}get isZoomAnimating(){return this.goalCameraPos!==null}endPanWithInertia(){if(this.lastPanEventTime=0,this.panInertiaVelocity.length()<be.PAN_INERTIA_MIN_SPEED){this.stopPanInertia();return}this.panInertiaActive=!0}stopPanInertia(){this.panInertiaActive=!1,this.panInertiaVelocity.set(0,0,0),this.lastPanEventTime=0}updatePanInertia(e){if(!this.panInertiaActive)return;const t=this.panInertiaVelocity.clone().multiplyScalar(e);this.controls.target.add(t),this.camera.position.add(t);const s=Math.pow(be.PAN_INERTIA_DECAY,e*60);this.panInertiaVelocity.multiplyScalar(s),this.panInertiaVelocity.length()<be.PAN_INERTIA_MIN_SPEED&&this.stopPanInertia()}};u(be,"PAN_INERTIA_DECAY",.9),u(be,"PAN_INERTIA_MIN_SPEED",.6);let dt=be;class Gi{constructor(e,t){u(this,"cameraController");u(this,"callbacks");u(this,"activeDragAction",null);u(this,"activeBinding",null);u(this,"dragStartPos",{x:0,y:0});u(this,"lastDragPos",{x:0,y:0});this.cameraController=e,this.callbacks=t}setCameraController(e){this.cameraController=e}findBinding(e,t){const s=k.getMouseControls(),i=js[t];if(!i)return null;const o=s.bindings.filter(n=>n.enabled&&n.button===i).sort((n,r)=>{const l=Object.values(n.modifiers).filter(Boolean).length;return Object.values(r.modifiers).filter(Boolean).length-l});for(const n of o)if(Ns(e,n.modifiers))return n;return null}isCameraAction(e){return e==="camera-pan"||e==="camera-orbit"||e==="camera-rotate"||e==="camera-tilt"}handlePointerDown(e){const t=this.findBinding(e,e.button);return t?(this.dragStartPos={x:e.clientX,y:e.clientY},this.lastDragPos={x:e.clientX,y:e.clientY},this.isCameraAction(t.action)?(this.activeDragAction=t.action,this.activeBinding=t,!0):!1):!1}handlePointerMove(e){if(!this.activeDragAction||!this.activeBinding)return!1;const t=e.clientX-this.lastDragPos.x,s=e.clientY-this.lastDragPos.y,i=k.getMouseControls().sensitivity;switch(this.activeDragAction){case"camera-pan":{const o=(i.invertPanX?-t:t)*i.panSpeed,n=(i.invertPanY?-s:s)*i.panSpeed;this.cameraController.handlePan(o,n);break}case"camera-orbit":{const o=(i.invertOrbitX?-t:t)*i.orbitSpeed,n=(i.invertOrbitY?-s:s)*i.orbitSpeed;this.cameraController.handleOrbit(o,n);break}case"camera-rotate":this.cameraController.handleOrbit(t*i.orbitSpeed,0);break;case"camera-tilt":this.cameraController.handleOrbit(0,s*i.orbitSpeed);break;case"selection-box":this.callbacks.onSelectionBoxMove(e.clientX,e.clientY);break}return this.lastDragPos={x:e.clientX,y:e.clientY},!0}handlePointerUp(e){const t=this.activeDragAction!==null;return this.activeDragAction==="selection-box"&&this.callbacks.onSelectionBoxEnd(e.clientX,e.clientY),this.activeDragAction=null,this.activeBinding=null,t}handleWheel(e){const t=k.getMouseControls();if(!t.bindings.find(o=>o.enabled&&o.action==="camera-zoom"))return!1;const i=t.sensitivity;return this.cameraController.handleWheelZoom(e,i.zoomSpeed),!0}get isDragging(){return this.activeDragAction!==null}get currentAction(){return this.activeDragAction}cancelDrag(){this.activeDragAction=null,this.activeBinding=null}}const de=class de{constructor(e,t,s,i,o){u(this,"canvas");u(this,"camera");u(this,"controls");u(this,"selectionBox");u(this,"callbacks");u(this,"raycaster");u(this,"cameraController");u(this,"mouseControlHandler");u(this,"trackpadHandler");u(this,"touchHandler");u(this,"agentClickDetector");u(this,"agentTapDetector");u(this,"buildingClickDetector");u(this,"workflowClickDetector");u(this,"areaClickDetector");u(this,"isDragging",!1);u(this,"dragStart",{x:0,y:0});u(this,"dragCurrent",{x:0,y:0});u(this,"pointerDownOnCanvas",!1);u(this,"isRightDragging",!1);u(this,"rightDragStart",{x:0,y:0});u(this,"isDrawing",!1);u(this,"drawingModeChecker",()=>!1);u(this,"isResizing",!1);u(this,"resizeModeChecker",()=>!1);u(this,"areaAtPositionGetter",()=>null);u(this,"buildingAtPositionGetter",()=>null);u(this,"buildingPositionsGetter",()=>new Map);u(this,"workflowAtPositionGetter",()=>null);u(this,"workflowPositionsGetter",()=>new Map);u(this,"isDraggingBuilding",!1);u(this,"draggingBuildingId",null);u(this,"buildingDragStartPos",null);u(this,"isDraggingWorkflow",!1);u(this,"draggingWorkflowId",null);u(this,"workflowDragStartPos",null);u(this,"hoveredAgentId",null);u(this,"hoverTimer",null);u(this,"lastMousePos",{x:0,y:0});u(this,"lastHoverCheckTime",0);u(this,"hoveredBuildingId",null);u(this,"buildingHoverTimer",null);u(this,"hoveredWorkflowId",null);u(this,"workflowHoverTimer",null);u(this,"onPointerDown",e=>{var s,i,o,n,r,l;if(!document.hasFocus()||document.visibilityState==="hidden")return;(i=(s=this.callbacks).onActivity)==null||i.call(s);const t=e.pointerType==="touch";if(e.button===0){this.controls.mouseButtons.LEFT=null;const c=this.raycaster.checkResizeHandleClick(e);if(c){const h=this.raycaster.raycastGroundFromEvent(e);h&&(this.isResizing=!0,t&&this.touchHandler.reset(),(n=(o=this.callbacks).onResizeStart)==null||n.call(o,c,h));return}if(this.drawingModeChecker()){const h=this.raycaster.raycastGroundFromEvent(e);h&&(this.isDrawing=!0,(l=(r=this.callbacks).onDrawStart)==null||l.call(r,h));return}const d=this.raycaster.raycastGroundFromEvent(e);if(d){const h=this.buildingAtPositionGetter(d);if(h&&!t){this.draggingBuildingId=h.id,this.buildingDragStartPos=d,this.isDraggingBuilding=!1;return}const g=this.workflowAtPositionGetter(d);if(g&&!t){this.draggingWorkflowId=g.id,this.workflowDragStartPos=d,this.isDraggingWorkflow=!1;return}}this.isDragging=!1,this.dragStart={x:e.clientX,y:e.clientY},this.dragCurrent={x:e.clientX,y:e.clientY},this.pointerDownOnCanvas=!0}if(e.button===2){if(this.mouseControlHandler.handlePointerDown(e)){this.controls.mouseButtons.RIGHT=null;return}this.controls.mouseButtons.RIGHT=null,this.isRightDragging=!1,this.rightDragStart={x:e.clientX,y:e.clientY}}if(e.button===1&&this.mouseControlHandler.handlePointerDown(e)){this.controls.mouseButtons.MIDDLE=null;return}});u(this,"onPointerMove",e=>{var t,s,i,o,n,r,l,c,d,h,g,f;if(!document.hasFocus()||document.hidden){this.isDragging&&(this.isDragging=!1,this.selectionBox.classList.remove("active"),this.pointerDownOnCanvas=!1);return}if(e.buttons&1){if(this.isResizing){const b=this.raycaster.raycastGroundFromEvent(e);b&&((s=(t=this.callbacks).onResizeMove)==null||s.call(t,b));return}if(this.isDrawing){const b=this.raycaster.raycastGroundFromEvent(e);b&&((o=(i=this.callbacks).onDrawMove)==null||o.call(i,b));return}if(this.draggingBuildingId&&this.buildingDragStartPos){const b=this.raycaster.raycastGroundFromEvent(e);if(b){const w=b.x-this.buildingDragStartPos.x,M=b.z-this.buildingDragStartPos.z,S=Math.sqrt(w*w+M*M);!this.isDraggingBuilding&&S>.2&&(this.isDraggingBuilding=!0,(r=(n=this.callbacks).onBuildingDragStart)==null||r.call(n,this.draggingBuildingId,this.buildingDragStartPos)),this.isDraggingBuilding&&((c=(l=this.callbacks).onBuildingDragMove)==null||c.call(l,this.draggingBuildingId,b))}return}if(this.draggingWorkflowId&&this.workflowDragStartPos){const b=this.raycaster.raycastGroundFromEvent(e);if(b){const w=b.x-this.workflowDragStartPos.x,M=b.z-this.workflowDragStartPos.z,S=Math.sqrt(w*w+M*M);!this.isDraggingWorkflow&&S>.2&&(this.isDraggingWorkflow=!0,(h=(d=this.callbacks).onWorkflowDragStart)==null||h.call(d,this.draggingWorkflowId,this.workflowDragStartPos)),this.isDraggingWorkflow&&((f=(g=this.callbacks).onWorkflowDragMove)==null||f.call(g,this.draggingWorkflowId,b))}return}if(e.pointerType==="touch"||!this.pointerDownOnCanvas||k.getState().terminalResizing)return;const p=e.clientX-this.dragStart.x,m=e.clientY-this.dragStart.y;!this.isDragging&&(Math.abs(p)>Ce||Math.abs(m)>Ce)&&(this.isDragging=!0,this.selectionBox.classList.add("active")),this.isDragging&&(this.dragCurrent={x:e.clientX,y:e.clientY},this.updateSelectionBox())}if(e.buttons&2){if(this.mouseControlHandler.handlePointerMove(e))return;const p=e.clientX-this.rightDragStart.x,m=e.clientY-this.rightDragStart.y;!this.isRightDragging&&(Math.abs(p)>Ce||Math.abs(m)>Ce)&&(this.isRightDragging=!0)}if(!(e.buttons&4&&this.mouseControlHandler.handlePointerMove(e))&&e.buttons===0&&e.pointerType!=="touch"){const p=performance.now();p-this.lastHoverCheckTime>de.HOVER_CHECK_INTERVAL&&(this.handleHoverDetection(e),this.lastHoverCheckTime=p)}});u(this,"onPointerUp",e=>{var t,s,i,o,n,r,l,c;if(e.button===0){if(this.controls.mouseButtons.LEFT=null,e.pointerType==="touch"&&!this.isDrawing&&!this.isResizing){this.pointerDownOnCanvas=!1;return}if(this.isResizing){(s=(t=this.callbacks).onResizeEnd)==null||s.call(t),this.isResizing=!1;return}if(this.isDrawing){const d=this.raycaster.raycastGroundFromEvent(e);d&&((o=(i=this.callbacks).onDrawEnd)==null||o.call(i,d)),this.isDrawing=!1;return}if(this.draggingBuildingId){const d=this.draggingBuildingId,h=this.raycaster.raycastGroundFromEvent(e),g={x:e.clientX,y:e.clientY};this.isDraggingBuilding&&h?(r=(n=this.callbacks).onBuildingDragEnd)==null||r.call(n,d,h):this.handleBuildingClick(d,g),this.draggingBuildingId=null,this.buildingDragStartPos=null,this.isDraggingBuilding=!1;return}if(this.draggingWorkflowId){const d=this.draggingWorkflowId,h=this.raycaster.raycastGroundFromEvent(e),g={x:e.clientX,y:e.clientY};this.isDraggingWorkflow&&h?(c=(l=this.callbacks).onWorkflowDragEnd)==null||c.call(l,d,h):this.handleWorkflowClick(d,g),this.draggingWorkflowId=null,this.workflowDragStartPos=null,this.isDraggingWorkflow=!1;return}if(this.isDragging){this.isDragging=!1,this.selectionBox.classList.remove("active");const d=Math.sqrt(Math.pow(this.dragCurrent.x-this.dragStart.x,2)+Math.pow(this.dragCurrent.y-this.dragStart.y,2));console.log("[3D InputHandler] pointerUp isDragging",{dragDist:d,shiftKey:e.shiftKey,ctrlKey:e.ctrlKey}),d<15?this.handleSingleClick(e):this.selectAgentsInBox(this.dragStart,this.dragCurrent,e.shiftKey)}else e.ctrlKey?console.log("[3D InputHandler] pointerUp BLOCKED by ctrlKey",{shiftKey:e.shiftKey,ctrlKey:e.ctrlKey,metaKey:e.metaKey}):(console.log("[3D InputHandler] pointerUp singleClick",{shiftKey:e.shiftKey,ctrlKey:e.ctrlKey}),this.handleSingleClick(e));this.pointerDownOnCanvas=!1}e.button===2&&(this.mouseControlHandler.handlePointerUp(e),this.controls.mouseButtons.RIGHT=null,this.isRightDragging=!1),e.button===1&&(this.mouseControlHandler.handlePointerUp(e),this.controls.mouseButtons.MIDDLE=null)});u(this,"onPointerCancel",e=>{this.touchHandler.onPointerCancel(e.pointerId)});u(this,"onPointerLeave",e=>{this.clearHoverState(),this.clearBuildingHoverState(),this.clearWorkflowHoverState()});u(this,"onWindowBlur",()=>{this.cancelAllDragStates()});u(this,"onVisibilityChange",()=>{document.hidden&&this.cancelAllDragStates()});u(this,"onKeyDown",e=>{var g,f;const t=e.target,s=k.getState(),i=t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.isContentEditable,o=t.closest(".guake-terminal"),n=o==null?void 0:o.classList.contains("collapsed"),r=k.getShortcuts(),l=r.find(p=>p.id==="toggle-spotlight"),c=r.find(p=>p.id==="next-agent"),d=r.find(p=>p.id==="prev-agent"),h=r.find(p=>p.id==="open-terminal");if(!he(e,l)){if(i){const p=k.getShortcuts();if((he(e,p.find(b=>b.id==="next-agent"))||he(e,p.find(b=>b.id==="prev-agent"))||he(e,p.find(b=>b.id==="next-working-agent"))||he(e,p.find(b=>b.id==="prev-working-agent")))&&n)t.blur();else if(he(e,h)&&n)t.blur();else return}if((he(e,c)||he(e,d))&&!s.terminalOpen){const p=this.getOrderedAgents(s.agents);if(p.length<=1)return;const m=s.selectedAgentIds.size===1?Array.from(s.selectedAgentIds)[0]:null,b=m?p.findIndex(M=>M.id===m):-1;let w;he(e,c)?w=b===-1?0:(b+1)%p.length:w=b===-1?p.length-1:(b-1+p.length)%p.length,e.preventDefault(),k.selectAgent(p[w].id),(f=(g=this.callbacks).onActivity)==null||f.call(g);return}if(he(e,h)){if(o&&!n||t.tagName==="BUTTON"||t.tagName==="A")return;if(s.terminalOpen)if(o&&n)k.setTerminalOpen(!1);else return;const p=document.querySelector(".guake-terminal");if(p&&p.classList.contains("collapsed")&&s.terminalOpen&&k.setTerminalOpen(!1),s.selectedBuildingIds.size>0||s.selectedAreaId!==null)return;if(s.selectedAgentIds.size===0){const m=s.lastSelectedAgentId;m&&s.agents.has(m)&&(e.preventDefault(),k.selectAgent(m),k.setTerminalOpen(!0));return}e.preventDefault(),k.setTerminalOpen(!0)}}});u(this,"onContextMenu",e=>{var i,o;if(e.preventDefault(),e.altKey)return;if(this.controls.mouseButtons.RIGHT=null,this.isRightDragging){this.isRightDragging=!1;return}const t=k.getState(),s=this.raycaster.raycastGroundFromEvent(e);if(s){if(t.selectedAgentIds.size>0){this.callbacks.onAreaRightClick&&this.callbacks.onAreaRightClick(s);const n=Array.from(t.selectedAgentIds),r=new T(s.x,0,s.z);this.callbacks.onMoveCommand(r,n);return}if(this.callbacks.onContextMenu){const n=this.raycaster.findAgentAtPosition(e),r=(i=this.areaAtPositionGetter)==null?void 0:i.call(this,s),l=(o=this.buildingAtPositionGetter)==null?void 0:o.call(this,s);let c;n?c={type:"agent",id:n}:l?c={type:"building",id:l.id}:r?c={type:"area",id:r.id}:c={type:"ground"},this.callbacks.onContextMenu({x:e.clientX,y:e.clientY},s,c)}}});u(this,"onWheel",e=>{var t,s;(s=(t=this.callbacks).onActivity)==null||s.call(t),!this.trackpadHandler.handleWheel(e)&&this.mouseControlHandler.handleWheel(e)});u(this,"onTouchStart",e=>{if(this.cameraController.stopPanInertia(),this.drawingModeChecker()){e.preventDefault();return}this.touchHandler.onTouchStart(e)});u(this,"onTouchMove",e=>{if(this.isDrawing||this.isResizing){e.preventDefault();return}this.touchHandler.onTouchMove(e)});u(this,"onTouchEnd",e=>{this.isDrawing||this.isResizing||this.touchHandler.onTouchEnd(e)});u(this,"handleTouchTap",(e,t)=>{var o,n,r,l,c,d;const s=this.raycaster.findAgentAtPoint(e,t);if(s){this.agentTapDetector.handleClick(s)==="double"?this.callbacks.onAgentDoubleClick(s):this.callbacks.onAgentClick(s,!1);return}const i=this.raycaster.raycastGroundFromPoint(e,t);if(i){const h=this.buildingAtPositionGetter(i);if(h){const p={x:e,y:t};this.handleBuildingClick(h.id,p);return}const g=this.workflowAtPositionGetter(i);if(g){const p={x:e,y:t};this.handleWorkflowClick(g.id,p);return}const f=this.areaAtPositionGetter(i);if(f){this.areaClickDetector.handleClick(f.id)==="double"?(n=(o=this.callbacks).onAreaDoubleClick)==null||n.call(o,f.id):(l=(r=this.callbacks).onAreaClick)==null||l.call(r,f.id);return}}this.agentClickDetector.reset(),this.callbacks.onGroundClick(),(d=(c=this.callbacks).onGroundClickOutsideArea)==null||d.call(c)});u(this,"handleLongPress",(e,t)=>{var c,d,h;const s=k.getState(),i=this.raycaster.raycastGroundFromPoint(e,t);if(!i)return;const o=this.raycaster.findAgentAtPoint(e,t);if(o){this.callbacks.onContextMenu&&this.callbacks.onContextMenu({x:e,y:t},i,{type:"agent",id:o});return}const n=(c=this.buildingAtPositionGetter)==null?void 0:c.call(this,i);if(n){this.callbacks.onContextMenu&&this.callbacks.onContextMenu({x:e,y:t},i,{type:"building",id:n.id});return}const r=(d=this.workflowAtPositionGetter)==null?void 0:d.call(this,i);if(r){this.callbacks.onContextMenu&&this.callbacks.onContextMenu({x:e,y:t},i,{type:"building",id:r.id});return}const l=(h=this.areaAtPositionGetter)==null?void 0:h.call(this,i);if(l){this.callbacks.onContextMenu&&this.callbacks.onContextMenu({x:e,y:t},i,{type:"area",id:l.id});return}if(s.selectedAgentIds.size>0){const g=Array.from(s.selectedAgentIds),f=new T(i.x,0,i.z);this.callbacks.onMoveCommand(f,g);return}this.callbacks.onContextMenu&&this.callbacks.onContextMenu({x:e,y:t},i,{type:"ground"})});this.canvas=e,this.camera=t,this.controls=s,this.selectionBox=i,this.callbacks=o,this.raycaster=new zi(t,e),this.cameraController=new dt(t,s,e),this.cameraController.setRaycastProvider(this.raycaster),this.mouseControlHandler=new Gi(this.cameraController,{onSelectionBoxStart:(n,r)=>{this.dragStart={x:n,y:r},this.dragCurrent={x:n,y:r},this.isDragging=!0,this.selectionBox.classList.add("active")},onSelectionBoxMove:(n,r)=>{this.dragCurrent={x:n,y:r},this.updateSelectionBox()},onSelectionBoxEnd:(n,r)=>{this.isDragging=!1,this.selectionBox.classList.remove("active"),this.selectAgentsInBox(this.dragStart,{x:n,y:r},!1)}}),this.trackpadHandler=new Oi(this.cameraController,e,{onPan:(n,r)=>{this.cameraController.handlePan(n,r)},onZoom:(n,r,l)=>{const c=1-n;this.cameraController.handlePinchZoom(c,{x:r,y:l})},onOrbit:(n,r)=>{this.cameraController.handleOrbit(n,r)}}),this.agentClickDetector=new Te(300),this.agentTapDetector=new Te(450),this.buildingClickDetector=new Te(300),this.workflowClickDetector=new Te(300),this.areaClickDetector=new Te(300),this.touchHandler=new ht(e,s,{onTap:this.handleTouchTap,onLongPress:this.handleLongPress,onPan:(n,r)=>this.cameraController.handlePan(n,r),onPanEnd:()=>this.cameraController.endPanWithInertia(),onPinchZoom:(n,r)=>this.cameraController.handlePinchZoom(n,r),onOrbit:(n,r)=>this.cameraController.handleOrbit(n,r),onRotation:n=>this.cameraController.handleTwistRotation(n)}),this.setupEventListeners()}setReferences(e,t){this.raycaster.setReferences(e,t)}setDrawingModeChecker(e){this.drawingModeChecker=e}setResizeHandlers(e,t){this.raycaster.setResizeHandlesGetter(e),this.resizeModeChecker=t}setFolderIconMeshesGetter(e){this.raycaster.setFolderIconMeshesGetter(e)}setAreaAtPositionGetter(e){this.areaAtPositionGetter=e}setBuildingAtPositionGetter(e){this.buildingAtPositionGetter=e}setBuildingPositionsGetter(e){this.buildingPositionsGetter=e}setWorkflowAtPositionGetter(e){this.workflowAtPositionGetter=e}setWorkflowPositionsGetter(e){this.workflowPositionsGetter=e}raycastGround(e){return this.raycaster.raycastGroundFromEvent(e)}dispose(){this.canvas.removeEventListener("pointerdown",this.onPointerDown,!0),this.canvas.removeEventListener("pointermove",this.onPointerMove),this.canvas.removeEventListener("pointerup",this.onPointerUp),this.canvas.removeEventListener("pointercancel",this.onPointerCancel),this.canvas.removeEventListener("pointerleave",this.onPointerLeave),this.canvas.removeEventListener("contextmenu",this.onContextMenu),this.canvas.removeEventListener("wheel",this.onWheel),this.canvas.removeEventListener("touchstart",this.onTouchStart),this.canvas.removeEventListener("touchmove",this.onTouchMove),this.canvas.removeEventListener("touchend",this.onTouchEnd),this.agentClickDetector.dispose(),this.agentTapDetector.dispose(),this.buildingClickDetector.dispose(),this.workflowClickDetector.dispose(),this.areaClickDetector.dispose(),this.touchHandler.dispose(),this.trackpadHandler.dispose(),this.clearHoverTimer(),this.clearBuildingHoverTimer(),this.clearWorkflowHoverTimer(),window.removeEventListener("blur",this.onWindowBlur),document.removeEventListener("visibilitychange",this.onVisibilityChange),document.removeEventListener("keydown",this.onKeyDown,!0)}reattach(e,t,s){this.dispose(),this.canvas=e,this.selectionBox=t,this.controls=s,this.raycaster.setCanvas(e),this.cameraController.setCanvas(e),this.cameraController.setControls(s),this.mouseControlHandler.setCameraController(this.cameraController),this.trackpadHandler.setCameraController(this.cameraController),this.trackpadHandler.setCanvas(e),this.touchHandler.reattach(e,s),this.setupEventListeners()}updateSmoothZoom(e){this.cameraController.updateSmoothZoom(e)}get isZoomAnimating(){return this.cameraController.isZoomAnimating}calculateFormationPositions(e,t){const s=[];if(t===1)return[{x:e.x,y:0,z:e.z}];if(t<=6){const i=Be*Math.max(1,t/3);for(let o=0;o<t;o++){const n=o/t*Math.PI*2-Math.PI/2;s.push({x:e.x+Math.cos(n)*i,y:0,z:e.z+Math.sin(n)*i})}}else{const i=Math.ceil(Math.sqrt(t)),o=Math.ceil(t/i),n=(i-1)*Be/2,r=(o-1)*Be/2;for(let l=0;l<t;l++){const c=l%i,d=Math.floor(l/i);s.push({x:e.x+c*Be-n,y:0,z:e.z+d*Be-r})}}return s}setupEventListeners(){this.canvas.addEventListener("pointerdown",this.onPointerDown,!0),this.canvas.addEventListener("pointermove",this.onPointerMove),this.canvas.addEventListener("pointerup",this.onPointerUp),this.canvas.addEventListener("pointercancel",this.onPointerCancel),this.canvas.addEventListener("pointerleave",this.onPointerLeave),this.canvas.addEventListener("contextmenu",this.onContextMenu),this.canvas.addEventListener("wheel",this.onWheel,{passive:!1}),this.canvas.addEventListener("touchstart",this.onTouchStart,{passive:!1}),this.canvas.addEventListener("touchmove",this.onTouchMove,{passive:!1}),this.canvas.addEventListener("touchend",this.onTouchEnd,{passive:!1}),window.addEventListener("blur",this.onWindowBlur),document.addEventListener("visibilitychange",this.onVisibilityChange),document.addEventListener("keydown",this.onKeyDown,!0)}cancelAllDragStates(){this.clearHoverState(),this.clearBuildingHoverState(),this.clearWorkflowHoverState(),this.isDragging&&(this.isDragging=!1,this.selectionBox.classList.remove("active")),this.pointerDownOnCanvas=!1}clearHoverState(){var e,t;this.clearHoverTimer(),this.hoveredAgentId!==null&&(this.hoveredAgentId=null,(t=(e=this.callbacks).onAgentHover)==null||t.call(e,null,null))}handleSingleClick(e){var o,n,r,l,c,d,h,g;console.log("[3D InputHandler] handleSingleClick",{shiftKey:e.shiftKey,pointerType:e.pointerType,button:e.button});const t=this.raycaster.checkFolderIconClick(e);if(t){const f=t.userData.areaId,p=t.userData.folderPath;if(f){(n=(o=this.callbacks).onFolderIconClick)==null||n.call(o,f,p);return}}const s=this.raycaster.findAgentAtPosition(e);if(console.log("[3D InputHandler] handleSingleClick agentId:",s,"shiftKey:",e.shiftKey),s){this.agentClickDetector.handleClick(s)==="double"?this.callbacks.onAgentDoubleClick(s):(console.log("[3D InputHandler] calling onAgentClick",{agentId:s,shiftKey:e.shiftKey}),this.callbacks.onAgentClick(s,e.shiftKey));return}this.agentClickDetector.reset();const i=this.raycaster.raycastGroundFromEvent(e);if(i){const f=this.areaAtPositionGetter(i);if(f){this.areaClickDetector.handleClick(f.id)==="double"?(l=(r=this.callbacks).onAreaDoubleClick)==null||l.call(r,f.id):(d=(c=this.callbacks).onAreaClick)==null||d.call(c,f.id);return}}this.areaClickDetector.reset(),e.shiftKey||(this.callbacks.onGroundClick(),(g=(h=this.callbacks).onGroundClickOutsideArea)==null||g.call(h))}handleBuildingClick(e,t){var i,o,n,r;if(this.buildingClickDetector.handleClick(e)==="double")(o=(i=this.callbacks).onBuildingDoubleClick)==null||o.call(i,e);else{const l=t||{x:window.innerWidth/2,y:window.innerHeight/2};(r=(n=this.callbacks).onBuildingClick)==null||r.call(n,e,l)}}handleWorkflowClick(e,t){var i,o,n,r;if(this.workflowClickDetector.handleClick(e)==="double")(o=(i=this.callbacks).onWorkflowDoubleClick)==null||o.call(i,e);else{const l=t||{x:window.innerWidth/2,y:window.innerHeight/2};(r=(n=this.callbacks).onWorkflowClick)==null||r.call(n,e,l)}}updateSelectionBox(){const e=Math.min(this.dragStart.x,this.dragCurrent.x),t=Math.min(this.dragStart.y,this.dragCurrent.y),s=Math.abs(this.dragCurrent.x-this.dragStart.x),i=Math.abs(this.dragCurrent.y-this.dragStart.y);this.selectionBox.style.left=`${e}px`,this.selectionBox.style.top=`${t}px`,this.selectionBox.style.width=`${s}px`,this.selectionBox.style.height=`${i}px`}selectAgentsInBox(e,t,s=!1){this.canvas.getBoundingClientRect();const i=Math.min(e.x,t.x),o=Math.max(e.x,t.x),n=Math.min(e.y,t.y),r=Math.max(e.y,t.y),l=[],c=[];for(const[h,g]of this.raycaster.getAgentMeshes()){const f=this.raycaster.projectToScreen(g.group.position);f.x>=i&&f.x<=o&&f.y>=n&&f.y<=r&&l.push(h)}const d=this.buildingPositionsGetter();for(const[h,g]of d){const f=this.raycaster.projectToScreen(g);f.x>=i&&f.x<=o&&f.y>=n&&f.y<=r&&c.push(h)}this.callbacks.onSelectionBox(l,c,s)}handleHoverDetection(e){var l,c,d,h,g,f;this.lastMousePos={x:e.clientX,y:e.clientY};const t=this.raycaster.findAgentAtPosition(e);t!==this.hoveredAgentId&&(this.clearHoverTimer(),this.hoveredAgentId!==null&&((c=(l=this.callbacks).onAgentHover)==null||c.call(l,null,null)),this.hoveredAgentId=t,t&&(this.hoverTimer=setTimeout(()=>{this.triggerHoverCallback()},de.HOVER_DELAY)));const s=this.raycaster.raycastGroundFromEvent(e),i=s?this.buildingAtPositionGetter(s):null,o=(i==null?void 0:i.id)??null,n=s?this.workflowAtPositionGetter(s):null,r=(n==null?void 0:n.id)??null;r!==this.hoveredWorkflowId&&(this.clearWorkflowHoverTimer(),this.hoveredWorkflowId!==null&&((h=(d=this.callbacks).onWorkflowHover)==null||h.call(d,null,null)),this.hoveredWorkflowId=r,r&&(this.workflowHoverTimer=setTimeout(()=>{this.triggerWorkflowHoverCallback()},de.WORKFLOW_HOVER_DELAY))),o!==this.hoveredBuildingId&&(this.clearBuildingHoverTimer(),this.hoveredBuildingId!==null&&((f=(g=this.callbacks).onBuildingHover)==null||f.call(g,null,null)),this.hoveredBuildingId=o,o&&(this.buildingHoverTimer=setTimeout(()=>{this.triggerBuildingHoverCallback()},de.BUILDING_HOVER_DELAY)))}triggerHoverCallback(){if(this.hoveredAgentId&&this.callbacks.onAgentHover){const e=this.raycaster.getAgentMeshes().get(this.hoveredAgentId);if(e){const t=this.raycaster.projectToScreen(e.group.position);this.callbacks.onAgentHover(this.hoveredAgentId,t)}}}clearHoverTimer(){this.hoverTimer&&(clearTimeout(this.hoverTimer),this.hoverTimer=null)}triggerBuildingHoverCallback(){if(this.hoveredBuildingId&&this.callbacks.onBuildingHover){const t=this.buildingPositionsGetter().get(this.hoveredBuildingId);if(t){const s=this.raycaster.projectToScreen(t);this.callbacks.onBuildingHover(this.hoveredBuildingId,s)}}}clearBuildingHoverTimer(){this.buildingHoverTimer&&(clearTimeout(this.buildingHoverTimer),this.buildingHoverTimer=null)}clearBuildingHoverState(){var e,t;this.clearBuildingHoverTimer(),this.hoveredBuildingId!==null&&(this.hoveredBuildingId=null,(t=(e=this.callbacks).onBuildingHover)==null||t.call(e,null,null))}triggerWorkflowHoverCallback(){if(this.hoveredWorkflowId&&this.callbacks.onWorkflowHover){const t=this.workflowPositionsGetter().get(this.hoveredWorkflowId);if(t){const s=this.raycaster.projectToScreen(t);this.callbacks.onWorkflowHover(this.hoveredWorkflowId,s)}}}clearWorkflowHoverTimer(){this.workflowHoverTimer&&(clearTimeout(this.workflowHoverTimer),this.workflowHoverTimer=null)}clearWorkflowHoverState(){var e,t;this.clearWorkflowHoverTimer(),this.hoveredWorkflowId!==null&&(this.hoveredWorkflowId=null,(t=(e=this.callbacks).onWorkflowHover)==null||t.call(e,null,null))}getOrderedAgents(e){const t=Array.from(e.values()),s=new Set(t.map(f=>f.id)),o=$s(Us.AGENT_ORDER,[]).filter(f=>s.has(f)),r=t.filter(f=>!o.includes(f.id)).sort((f,p)=>(f.createdAt||0)-(p.createdAt||0)).map(f=>f.id),l=[...o,...r],c=new Map(t.map(f=>[f.id,f])),d=l.map(f=>c.get(f)).filter(f=>f!==void 0),h=new Map;for(const f of d){const p=k.getAreaForAgent(f.id),m=(p==null?void 0:p.id)||null;h.has(m)||h.set(m,{area:p?{name:p.name}:null,agents:[]}),h.get(m).agents.push(f)}const g=Array.from(h.values());return g.sort((f,p)=>{var m,b;return!f.area&&p.area?1:f.area&&!p.area?-1:!f.area&&!p.area?0:(((m=f.area)==null?void 0:m.name)||"").localeCompare(((b=p.area)==null?void 0:b.name)||"")}),g.flatMap(f=>f.agents)}};u(de,"HOVER_DELAY",400),u(de,"HOVER_CHECK_INTERVAL",50),u(de,"BUILDING_HOVER_DELAY",5e3),u(de,"WORKFLOW_HOVER_DELAY",5e3);let ut=de;class Ri{constructor(e){u(this,"scene");u(this,"areaMeshes",new Map);u(this,"previewMesh",null);u(this,"isDrawing",!1);u(this,"drawStartPos",null);u(this,"currentTool",null);u(this,"resizeHandles",[]);u(this,"selectedAreaId",null);u(this,"isResizing",!1);u(this,"resizeHandleType",null);u(this,"resizeStartPos",null);u(this,"resizeOriginalArea",null);u(this,"areaDragAgentStartPositions",new Map);u(this,"areaDragBuildingStartPositions",new Map);u(this,"onAreaCreated",null);u(this,"onFolderIconClick",null);u(this,"folderIconMeshes",[]);u(this,"brightness",1);u(this,"logoTextures",new Map);u(this,"loadingLogoTextures",new Set);this.scene=e}setOnAreaCreated(e){this.onAreaCreated=e}setOnFolderIconClick(e){this.onFolderIconClick=e}getFolderIconMeshes(){return this.folderIconMeshes}handleFolderIconClick(e){const t=e.userData.areaId,s=e.userData.folderPath;t&&this.onFolderIconClick&&this.onFolderIconClick(t,s)}setBrightness(e){this.brightness=e;for(const[t,s]of this.areaMeshes){const i=t===this.selectedAreaId;s.traverse(o=>{if(o instanceof y&&o.name!=="resizeHandle"&&o.name!=="areaLogo"){const n=o.material,r=i?.3:.15;n.opacity=r*this.brightness}})}}setTool(e){this.currentTool=e,(!e||e==="select")&&this.cancelDrawing()}getTool(){return this.currentTool}isInDrawingMode(){return this.currentTool==="rectangle"||this.currentTool==="circle"}startDrawing(e){this.isInDrawingMode()&&(this.isDrawing=!0,this.drawStartPos=e,this.createPreview(e))}updateDrawing(e){!this.isDrawing||!this.drawStartPos||!this.previewMesh||this.updatePreview(e)}finishDrawing(e){var s;if(!this.isDrawing||!this.drawStartPos)return this.cancelDrawing(),null;const t=this.createAreaFromDraw(this.drawStartPos,e);return this.cancelDrawing(),t&&(k.addArea(t),this.renderArea(t),(s=this.onAreaCreated)==null||s.call(this,t)),t}cancelDrawing(){this.isDrawing=!1,this.drawStartPos=null,this.previewMesh&&(this.scene.remove(this.previewMesh),this.disposeGroup(this.previewMesh),this.previewMesh=null)}isCurrentlyDrawing(){return this.isDrawing}renderAllAreas(){const e=k.getState();for(const t of e.areas.values()){if(t.archived){this.areaMeshes.has(t.id)&&this.removeAreaMesh(t.id);continue}this.areaMeshes.has(t.id)||this.renderArea(t)}}renderArea(e){var n;this.removeAreaMesh(e.id);const t=new Y;t.userData.areaId=e.id,t.userData.zIndex=e.zIndex??0;const s=new H(e.color),i=(e.zIndex??0)*.001;if(e.type==="rectangle"&&e.width&&e.height){const r=new pe(e.width,e.height),l=new v({color:s,transparent:!0,opacity:.15*this.brightness,side:oe}),c=new y(r,l);c.rotation.x=-Math.PI/2,c.position.y=.02+i,t.add(c);const d=[new T(-e.width/2,0,-e.height/2),new T(e.width/2,0,-e.height/2),new T(e.width/2,0,e.height/2),new T(-e.width/2,0,e.height/2),new T(-e.width/2,0,-e.height/2)],h=new le().setFromPoints(d),g=new ge({color:s,linewidth:2}),f=new ce(h,g);f.position.y=.03+i,t.add(f)}else if(e.type==="circle"&&e.radius){const r=new yt(e.radius,32),l=new v({color:s,transparent:!0,opacity:.15*this.brightness,side:oe}),c=new y(r,l);c.rotation.x=-Math.PI/2,c.position.y=.02+i,t.add(c);const d=[];for(let p=0;p<=32;p++){const m=p/32*Math.PI*2;d.push(new T(Math.cos(m)*e.radius,0,Math.sin(m)*e.radius))}const h=new le().setFromPoints(d),g=new ge({color:s,linewidth:2}),f=new ce(h,g);f.position.y=.03+i,t.add(f)}const o=this.createTextLabel(e.name,e.color);if(o.position.y=.05+i,o.name="areaLabel",t.add(o),e.directories&&e.directories.length>0){let c=0,d=0,h=3;if(e.type==="rectangle"&&e.width&&e.height)c=-e.width/2+.4,d=-e.height/2+.4,h=Math.max(1,Math.floor((e.width-.6)/.81));else if(e.type==="circle"&&e.radius){const g=e.radius*.707;c=-g+.3,d=-g+.3,h=Math.max(1,Math.floor((e.radius*1.414-.5)/.81))}e.directories.forEach((g,f)=>{var C;const p=Math.floor(f/h),m=f%h,b=((C=e.directoryGitCounts)==null?void 0:C[f])??0,w=this.createFolderIconSprite(e.color,b);w.name="folderIcon",w.userData.areaId=e.id,w.userData.folderPath=g,w.userData.isFolderIcon=!0,w.position.set(c+m*.81,.3+i,d+p*.81),t.add(w);const M=new O(.3,8,8),S=new v({visible:!1}),P=new y(M,S);P.position.copy(w.position),P.position.x+=e.center.x,P.position.z+=e.center.z,P.name="folderIconHit",P.userData.areaId=e.id,P.userData.folderPath=g,P.userData.isFolderIcon=!0,this.scene.add(P),this.folderIconMeshes.push(P)})}(n=e.logo)!=null&&n.filename&&this.addLogoToGroup(t,e,i),t.position.set(e.center.x,0,e.center.z),this.scene.add(t),this.areaMeshes.set(e.id,t)}createTextLabel(e,t){const s=document.createElement("canvas"),i=s.getContext("2d"),o=32,n=20,r=64;s.width=1024,s.height=r,i.font=`bold ${o}px Arial`;const l=i.measureText(e).width,c=256;s.width=Math.max(c,l+n*2),i.clearRect(0,0,s.width,s.height),i.font=`bold ${o}px Arial`,i.textAlign="center",i.textBaseline="middle",i.strokeStyle="#000000",i.lineWidth=4,i.strokeText(e,s.width/2,s.height/2),i.fillStyle=t,i.fillText(e,s.width/2,s.height/2);const d=new se(s);d.needsUpdate=!0;const h=new J({map:d,transparent:!0,depthTest:!1}),g=new K(h),f=.5,p=2*(s.width/256);return g.scale.set(p,f,1),g}createFolderIconSprite(e,t=0){const s=document.createElement("canvas"),i=128;s.width=i,s.height=i;const o=s.getContext("2d");o.fillStyle="rgba(0, 0, 0, 0.6)",o.beginPath(),o.arc(i/2,i/2,i*.45,0,Math.PI*2),o.fill(),o.strokeStyle=e,o.lineWidth=3,o.beginPath(),o.arc(i/2,i/2,i*.45,0,Math.PI*2),o.stroke();const n=i*.5,r=i*.35,l=(i-n)/2,c=(i-r)/2+2,d=n*.35,h=r*.22;if(o.fillStyle=e,o.beginPath(),o.moveTo(l+4,c+h),o.lineTo(l+d,c+h),o.lineTo(l+d+h,c),o.lineTo(l+4,c),o.moveTo(l,c+h),o.lineTo(l,c+r),o.lineTo(l+n,c+r),o.lineTo(l+n,c+h),o.closePath(),o.fill(),o.strokeStyle="rgba(255, 255, 255, 0.3)",o.lineWidth=1.5,o.beginPath(),o.moveTo(l+4,c+h+3),o.lineTo(l+n-4,c+h+3),o.stroke(),t>0){const m=i*.16,b=i*.78,w=i*.78;o.fillStyle="#e8943a",o.beginPath(),o.arc(b,w,m,0,Math.PI*2),o.fill(),o.strokeStyle="rgba(0, 0, 0, 0.7)",o.lineWidth=2,o.beginPath(),o.arc(b,w,m,0,Math.PI*2),o.stroke();const M=t>99?"99+":String(t),S=m*1.3;o.font=`bold ${S}px "Segoe UI", Arial, sans-serif`,o.fillStyle="#ffffff",o.textAlign="center",o.textBaseline="middle",o.fillText(M,b,w)}const g=new se(s);g.needsUpdate=!0;const f=new J({map:g,transparent:!0,depthTest:!1}),p=new K(f);return p.scale.set(.6,.6,1),p}addLogoToGroup(e,t,s){const i=t.logo,o=Vt(Zt(`/api/areas/logos/${i.filename}`)),n=this.logoTextures.get(i.filename);if(n){this.createLogoMesh(e,t,n,s);return}if(this.loadingLogoTextures.has(i.filename))return;this.loadingLogoTextures.add(i.filename);const r=t.id;new Nt().load(o,c=>{var g;this.logoTextures.set(i.filename,c),this.loadingLogoTextures.delete(i.filename);const d=this.areaMeshes.get(r),h=k.getState().areas.get(r);if(d&&((g=h==null?void 0:h.logo)!=null&&g.filename)){const f=(h.zIndex??0)*.001;this.createLogoMesh(d,h,c,f)}},void 0,()=>{this.loadingLogoTextures.delete(i.filename)})}createLogoMesh(e,t,s,i){const o=t.logo,n=new pe(o.width,o.height),r=new v({map:s,transparent:!0,opacity:o.opacity??.8,side:oe,depthWrite:!0,alphaTest:.01}),l=new y(n,r);l.rotation.x=-Math.PI/2,l.name="areaLogo",l.renderOrder=-1;const c=this.calculateLogoOffset(t,o.position,o.width,o.height);l.position.set(c.x,.04+i,c.z),e.add(l)}calculateLogoOffset(e,t,s,i){if(t==="center")return{x:0,z:0};let o=0,n=0;e.type==="rectangle"&&e.width&&e.height?(o=e.width,n=e.height):e.type==="circle"&&e.radius&&(o=e.radius*1.414,n=e.radius*1.414);const r=s/2+.2,l=i/2+.2;switch(t){case"top-left":return{x:-o/2+r,z:-n/2+l};case"top-right":return{x:o/2-r,z:-n/2+l};case"bottom-left":return{x:-o/2+r,z:n/2-l};case"bottom-right":return{x:o/2-r,z:n/2-l};default:return{x:0,z:0}}}updateAreaMesh(e){this.renderArea(e)}removeAreaMesh(e){const t=this.areaMeshes.get(e);t&&(this.scene.remove(t),this.disposeGroup(t),this.areaMeshes.delete(e)),this.folderIconMeshes=this.folderIconMeshes.filter(s=>s.userData.areaId===e?(this.scene.remove(s),s.geometry.dispose(),s.material.dispose(),!1):!0)}highlightArea(e){this.selectedAreaId=e,this.removeResizeHandles();for(const[t,s]of this.areaMeshes){const i=t===e;s.traverse(o=>{if(o instanceof y&&o.name!=="resizeHandle"&&o.name!=="areaLogo"){const n=o.material,r=i?.3:.15;n.opacity=r*this.brightness}if(o instanceof ce){const n=o.material;n.opacity=i?1:.8}})}if(e){const t=k.getState().areas.get(e);t&&this.createResizeHandles(t)}}createResizeHandles(e){const t=new O(.15,16,16),s=new v({color:16777215,transparent:!0,opacity:.9}),i=new v({color:16763904,transparent:!0,opacity:.9}),o=(e.zIndex??0)*.001,n=new y(t.clone(),i.clone());if(n.position.set(e.center.x,.25+o,e.center.z),n.name="resizeHandle",n.userData.handleType="move",n.userData.areaId=e.id,this.scene.add(n),this.resizeHandles.push(n),e.type==="rectangle"&&e.width&&e.height){const r=[{type:"nw",x:-e.width/2,z:-e.height/2},{type:"ne",x:e.width/2,z:-e.height/2},{type:"sw",x:-e.width/2,z:e.height/2},{type:"se",x:e.width/2,z:e.height/2}];for(const h of r){const g=new y(t.clone(),s.clone());g.position.set(e.center.x+h.x,.2+o,e.center.z+h.z),g.name="resizeHandle",g.userData.handleType=h.type,g.userData.areaId=e.id,this.scene.add(g),this.resizeHandles.push(g)}const l=new v({color:11197951,transparent:!0,opacity:.9}),c=new O(.12,16,16),d=[{type:"n",x:0,z:-e.height/2},{type:"s",x:0,z:e.height/2},{type:"e",x:e.width/2,z:0},{type:"w",x:-e.width/2,z:0}];for(const h of d){const g=new y(c.clone(),l.clone());g.position.set(e.center.x+h.x,.2+o,e.center.z+h.z),g.name="resizeHandle",g.userData.handleType=h.type,g.userData.areaId=e.id,this.scene.add(g),this.resizeHandles.push(g)}l.dispose(),c.dispose()}else if(e.type==="circle"&&e.radius){const r=new y(t.clone(),s.clone());r.position.set(e.center.x+e.radius,.2+o,e.center.z),r.name="resizeHandle",r.userData.handleType="radius",r.userData.areaId=e.id,this.scene.add(r),this.resizeHandles.push(r)}t.dispose(),s.dispose(),i.dispose()}removeResizeHandles(){for(const e of this.resizeHandles)this.scene.remove(e),e.geometry.dispose(),e.material.dispose();this.resizeHandles=[]}getResizeHandles(){return this.resizeHandles}isCurrentlyResizing(){return this.isResizing}startResize(e,t){const s=e.userData.areaId,i=e.userData.handleType,o=k.getState().areas.get(s);if(o&&(this.isResizing=!0,this.resizeHandleType=i,this.resizeStartPos=t,this.resizeOriginalArea={...o},this.areaDragAgentStartPositions.clear(),this.areaDragBuildingStartPositions.clear(),i==="move")){const n=k.getState();for(const r of n.agents.values())this.isPointInsideArea(r.position.x,r.position.z,o)&&this.areaDragAgentStartPositions.set(r.id,{...r.position});for(const r of n.buildings.values())this.isPointInsideArea(r.position.x,r.position.z,o)&&this.areaDragBuildingStartPositions.set(r.id,{...r.position})}}updateResize(e){if(!this.isResizing||!this.resizeOriginalArea||!this.resizeHandleType||!this.resizeStartPos)return;const t=this.resizeOriginalArea;let s={};if(this.resizeHandleType==="move"){const i=e.x-this.resizeStartPos.x,o=e.z-this.resizeStartPos.z;s={center:{x:t.center.x+i,z:t.center.z+o}};for(const[n,r]of this.areaDragAgentStartPositions)k.moveAgentLocal(n,{x:r.x+i,y:r.y,z:r.z+o});for(const[n,r]of this.areaDragBuildingStartPositions)k.updateBuildingLocal(n,{position:{x:r.x+i,z:r.z+o}})}else if(t.type==="rectangle"&&t.width&&t.height){const i=e.x-this.resizeStartPos.x,o=e.z-this.resizeStartPos.z,n=t.width,r=t.height,l=t.center.x,c=t.center.z,d=p=>{const m=Math.max(.5,n+p);return{width:m,cx:l+(m-n)/2}},h=p=>{const m=Math.max(.5,n-p);return{width:m,cx:l+(n-m)/2}},g=p=>{const m=Math.max(.5,r+p);return{height:m,cz:c+(m-r)/2}},f=p=>{const m=Math.max(.5,r-p);return{height:m,cz:c+(r-m)/2}};switch(this.resizeHandleType){case"se":{const p=d(i),m=g(o);s={width:p.width,height:m.height,center:{x:p.cx,z:m.cz}};break}case"sw":{const p=h(i),m=g(o);s={width:p.width,height:m.height,center:{x:p.cx,z:m.cz}};break}case"ne":{const p=d(i),m=f(o);s={width:p.width,height:m.height,center:{x:p.cx,z:m.cz}};break}case"nw":{const p=h(i),m=f(o);s={width:p.width,height:m.height,center:{x:p.cx,z:m.cz}};break}case"e":{const p=d(i);s={width:p.width,center:{x:p.cx,z:c}};break}case"w":{const p=h(i);s={width:p.width,center:{x:p.cx,z:c}};break}case"s":{const p=g(o);s={height:p.height,center:{x:l,z:p.cz}};break}case"n":{const p=f(o);s={height:p.height,center:{x:l,z:p.cz}};break}}}else if(t.type==="circle"&&this.resizeHandleType==="radius"){const i=e.x-t.center.x,o=e.z-t.center.z;s={radius:Math.max(.5,Math.sqrt(i*i+o*o))}}Object.keys(s).length>0&&k.updateArea(t.id,s)}finishResize(){if(this.resizeHandleType==="move"&&this.resizeOriginalArea&&this.resizeStartPos){const t=k.getState().areas.get(this.resizeOriginalArea.id);if(t){const s=t.center.x-this.resizeOriginalArea.center.x,i=t.center.z-this.resizeOriginalArea.center.z;if(s!==0||i!==0){for(const[o,n]of this.areaDragAgentStartPositions)k.moveAgent(o,{x:n.x+s,y:n.y,z:n.z+i});for(const[o,n]of this.areaDragBuildingStartPositions)k.moveBuilding(o,{x:n.x+s,z:n.z+i})}}}if(this.isResizing=!1,this.resizeHandleType=null,this.resizeStartPos=null,this.resizeOriginalArea=null,this.areaDragAgentStartPositions.clear(),this.areaDragBuildingStartPositions.clear(),this.selectedAreaId){this.removeResizeHandles();const e=k.getState().areas.get(this.selectedAreaId);e&&this.createResizeHandles(e)}}isPointInsideArea(e,t,s){if(s.type==="rectangle"&&s.width&&s.height){const i=s.width/2,o=s.height/2;return e>=s.center.x-i&&e<=s.center.x+i&&t>=s.center.z-o&&t<=s.center.z+o}if(s.type==="circle"&&s.radius){const i=e-s.center.x,o=t-s.center.z;return i*i+o*o<=s.radius*s.radius}return!1}getAreaAtPosition(e){const t=k.getState(),s=Array.from(t.areas.values()).filter(i=>!i.archived&&Ne(i.id)).sort((i,o)=>(o.zIndex??0)-(i.zIndex??0));for(const i of s)if(i.type==="rectangle"&&i.width&&i.height){const o=i.width/2,n=i.height/2;if(e.x>=i.center.x-o&&e.x<=i.center.x+o&&e.z>=i.center.z-n&&e.z<=i.center.z+n)return i}else if(i.type==="circle"&&i.radius){const o=e.x-i.center.x,n=e.z-i.center.z;if(Math.sqrt(o*o+n*n)<=i.radius)return i}return null}syncFromStore(){const e=k.getState();for(const t of this.areaMeshes.keys()){const s=e.areas.get(t);(!s||s.archived||!Ne(t))&&this.removeAreaMesh(t)}for(const t of e.areas.values())!t.archived&&Ne(t.id)&&this.renderArea(t)}createPreview(e){this.previewMesh=new Y,this.scene.add(this.previewMesh)}updatePreview(e){if(!this.previewMesh||!this.drawStartPos)return;for(;this.previewMesh.children.length>0;){const s=this.previewMesh.children[0];this.previewMesh.remove(s),(s instanceof y||s instanceof ce)&&(s.geometry.dispose(),s.material.dispose())}const t=new H("#4a9eff");if(this.currentTool==="rectangle"){const s=Math.abs(e.x-this.drawStartPos.x),i=Math.abs(e.z-this.drawStartPos.z),o=(e.x+this.drawStartPos.x)/2,n=(e.z+this.drawStartPos.z)/2;if(s>.1&&i>.1){const r=new pe(s,i),l=new v({color:t,transparent:!0,opacity:.2,side:oe}),c=new y(r,l);c.rotation.x=-Math.PI/2,c.position.set(o,.02,n),this.previewMesh.add(c);const d=[new T(this.drawStartPos.x,.03,this.drawStartPos.z),new T(e.x,.03,this.drawStartPos.z),new T(e.x,.03,e.z),new T(this.drawStartPos.x,.03,e.z),new T(this.drawStartPos.x,.03,this.drawStartPos.z)],h=new le().setFromPoints(d),g=new ge({color:t}),f=new ce(h,g);this.previewMesh.add(f)}}else if(this.currentTool==="circle"){const s=e.x-this.drawStartPos.x,i=e.z-this.drawStartPos.z,o=Math.sqrt(s*s+i*i);if(o>.1){const n=new yt(o,32),r=new v({color:t,transparent:!0,opacity:.2,side:oe}),l=new y(n,r);l.rotation.x=-Math.PI/2,l.position.set(this.drawStartPos.x,.02,this.drawStartPos.z),this.previewMesh.add(l);const c=[];for(let f=0;f<=32;f++){const p=f/32*Math.PI*2;c.push(new T(this.drawStartPos.x+Math.cos(p)*o,.03,this.drawStartPos.z+Math.sin(p)*o))}const d=new le().setFromPoints(c),h=new ge({color:t}),g=new ce(d,h);this.previewMesh.add(g)}}}createAreaFromDraw(e,t){const s=`area_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,i=k.getState().areas.size,o=k.getNextZIndex();if(this.currentTool==="rectangle"){const n=Math.abs(t.x-e.x),r=Math.abs(t.z-e.z);return n<.5||r<.5?null:{id:s,name:`Area ${i+1}`,type:"rectangle",center:{x:(e.x+t.x)/2,z:(e.z+t.z)/2},width:n,height:r,color:"#4a9eff",zIndex:o,assignedAgentIds:[],directories:[]}}else if(this.currentTool==="circle"){const n=t.x-e.x,r=t.z-e.z,l=Math.sqrt(n*n+r*r);return l<.5?null:{id:s,name:`Area ${i+1}`,type:"circle",center:{x:e.x,z:e.z},radius:l,color:"#4a9eff",zIndex:o,assignedAgentIds:[],directories:[]}}return null}disposeGroup(e){e.traverse(t=>{if(t instanceof y&&(t.geometry.dispose(),Array.isArray(t.material)?t.material.forEach(s=>s.dispose()):t.material.dispose()),t instanceof ce&&(t.geometry.dispose(),t.material.dispose()),t instanceof K){const s=t.material;s.map&&s.map.dispose(),s.dispose()}})}dispose(){this.cancelDrawing(),this.removeResizeHandles();for(const e of this.areaMeshes.keys())this.removeAreaMesh(e);for(const e of this.folderIconMeshes)this.scene.remove(e),e.geometry.dispose(),e.material.dispose();this.folderIconMeshes=[]}}const ee={running:4915102,stopped:8947848,error:16730698,unknown:16755200,starting:4890367,stopping:16755200},_e={desktop:{primary:7438486,secondary:4871528,accent:6534125,glow:4915102},"filing-cabinet":{primary:6869905,secondary:4766584,accent:10151604,glow:4915102},satellite:{primary:8411861,secondary:7030465,accent:12031220,glow:4890367},crystal:{primary:15557798,secondary:13975436,accent:16156595,glow:10451690},factory:{primary:15567158,secondary:14510880,accent:16166229,glow:16755200}};function ue(a){return a.name}function ne(a){const e=document.createElement("canvas"),t=e.getContext("2d"),s=56,i=28,o=72,n=144;e.width=1024,e.height=n,t.font=`bold ${s}px Arial`;const r=t.measureText(a).width,l=256,c=r+i*2+16;e.width=Math.max(l,c),t.clearRect(0,0,e.width,e.height),t.font=`bold ${s}px Arial`;const d=r+i*2,h=(e.width-d)/2,g=(e.height-o)/2;t.fillStyle="rgba(0, 0, 0, 0.8)",t.beginPath(),t.roundRect(h,g,d,o,10),t.fill(),t.textAlign="center",t.textBaseline="middle",t.fillStyle="#ffffff",t.fillText(a,e.width/2,e.height/2);const f=new se(e);f.minFilter=te,f.magFilter=te,f.needsUpdate=!0;const p=new J({map:f,transparent:!0,depthTest:!1}),m=new K(p),b=.5,w=e.width/e.height;return m.scale.set(b*w,b,1),m.userData.aspectRatio=w,m}function Qt(a){const e=document.createElement("canvas"),t=e.getContext("2d");e.width=64,e.height=64,t.fillStyle="#c89a5a",t.beginPath(),t.arc(32,32,28,0,Math.PI*2),t.fill(),t.strokeStyle="rgba(0, 0, 0, 0.5)",t.lineWidth=3,t.beginPath(),t.arc(32,32,28,0,Math.PI*2),t.stroke(),t.fillStyle="#ffffff",t.font="bold 28px Arial",t.textAlign="center",t.textBaseline="middle",t.fillText(a>99?"99+":String(a),32,32);const s=new se(e);s.minFilter=te,s.magFilter=te;const i=new J({map:s,transparent:!0,depthTest:!1}),o=new K(i);return o.scale.set(.35,.35,1),o.name="gitIndicator",o}function Hi(a,e){const t=a.material;t.map&&t.map.dispose(),t.dispose();const s=Qt(e);a.material=s.material}function Jt(a,e){const t=a.label,s=ne(e);s.position.copy(t.position),s.name="buildingLabel",a.group.remove(t),t.material instanceof J&&(t.material.map&&t.material.map.dispose(),t.material.dispose()),a.group.add(s),a.label=s}function Wi(a){const e=new Y;e.userData.buildingId=a.id,e.userData.isBuilding=!0;const t=a.color?new H(a.color):new H(2763322),s=new z(1.2,2.5,.8),i=new A({color:t,metalness:.7,roughness:.3}),o=new y(s,i);o.position.y=1.25,o.castShadow=!0,o.receiveShadow=!0,o.name="buildingBody",e.add(o);for(let S=0;S<5;S++){const P=new z(1.1,.02,.75),C=new A({color:1710634,metalness:.5,roughness:.5}),x=new y(P,C);x.position.set(0,.5+S*.45,.03),e.add(x)}for(let S=0;S<5;S++){const P=new z(.08,.08,.05),C=new v({color:4915102,transparent:!0,opacity:.9}),x=new y(P,C);x.position.set(-.45,.5+S*.45,.43),x.name=`led_${S}`,e.add(x);const B=new y(P.clone(),C.clone());B.position.set(-.3,.5+S*.45,.43),B.name=`activityLed_${S}`,e.add(B)}const n=new z(1,.1,.6),r=new A({color:1710634,metalness:.3,roughness:.7}),l=new y(n,r);l.position.set(0,2.55,0),e.add(l);const c=new O(.15,16,16),d=new v({color:ee[a.status],transparent:!0,opacity:.95}),h=new y(c,d);h.position.set(0,2.75,0),h.name="statusLight",e.add(h);const g=new O(.25,16,16),f=new v({color:ee[a.status],transparent:!0,opacity:.3}),p=new y(g,f);p.position.set(0,2.75,0),p.name="statusGlow",e.add(p);const m=new z(1.5,.1,1.1),b=new A({color:3816010,metalness:.5,roughness:.5}),w=new y(m,b);w.position.y=.05,w.receiveShadow=!0,e.add(w);const M=ne(ue(a));return M.position.set(0,3.2,0),M.name="buildingLabel",e.add(M),e.position.set(a.position.x,0,a.position.z),{group:e,statusLight:h,label:M}}function Fi(a,e){for(let t=0;t<5;t++){const s=a.group.getObjectByName(`led_${t}`);if(s&&s.material instanceof v){const o=Math.sin(e*.8+t*1.2);s.material.opacity=o>.3?.6:.15}const i=a.group.getObjectByName(`activityLed_${t}`);i&&i.material instanceof v&&(i.material.opacity=Math.random()>.97?.5:.1)}}function Ni(a,e){for(let t=0;t<5;t++){const s=a.group.getObjectByName(`activityLed_${t}`);s&&s.material instanceof v&&Math.random()>.95&&(s.material.opacity=s.material.opacity>.5?.2:.9)}}function ji(a){const e=new Y;e.userData.buildingId=a.id,e.userData.isBuilding=!0;const t=a.color?new H(a.color):new H(2767434),s=new j(.5,.7,3,8),i=new A({color:t,metalness:.6,roughness:.4}),o=new y(s,i);o.position.y=1.5,o.castShadow=!0,o.receiveShadow=!0,o.name="buildingBody",e.add(o);for(let D=0;D<4;D++){const $=new j(.52-D*.03,.62-D*.03,.1,8),G=new v({color:4890367,transparent:!0,opacity:.7}),W=new y($,G);W.position.y=.7+D*.6,W.name=`windowBand_${D}`,e.add(W)}const n=new j(.6,.5,.2,8),r=new A({color:3816010,metalness:.7,roughness:.3}),l=new y(n,r);l.position.y=3.1,e.add(l);const c=new j(.15,.2,.3,6),d=new A({color:4868698,metalness:.8,roughness:.2}),h=new y(c,d);h.position.y=3.35,e.add(h);const g=new Y;g.position.y=3.6,g.name="antenna";const f=new z(.05,.6,.05),p=new A({color:6974074,metalness:.9,roughness:.1}),m=new y(f,p);m.position.y=.3,g.add(m);const b=new xe(.15,.1,8);for(let D=0;D<2;D++){const $=new y(b,p);$.rotation.x=Math.PI/2,$.position.set(D===0?.2:-.2,.4,0),$.rotation.z=D===0?Math.PI/2:-Math.PI/2,g.add($)}e.add(g);const w=new O(.12,16,16),M=new v({color:ee[a.status],transparent:!0,opacity:.95}),S=new y(w,M);S.position.set(0,4.3,0),S.name="statusLight",e.add(S);const P=new O(.2,16,16),C=new v({color:ee[a.status],transparent:!0,opacity:.3}),x=new y(P,C);x.position.set(0,4.3,0),x.name="statusGlow",e.add(x);const B=new j(.9,1,.15,8),I=new A({color:3816010,metalness:.5,roughness:.5}),L=new y(B,I);L.position.y=.075,L.receiveShadow=!0,e.add(L);const E=ne(ue(a));return E.position.set(0,4.7,0),E.name="buildingLabel",e.add(E),e.position.set(a.position.x,0,a.position.z),{group:e,statusLight:S,label:E}}function $i(a,e,t){const s=a.group.getObjectByName("antenna");s&&(s.rotation.y+=t*.3);for(let i=0;i<4;i++){const o=a.group.getObjectByName(`windowBand_${i}`);o&&o.material instanceof v&&(o.material.opacity=.3+Math.sin(e*.5+i*.4)*.15)}}function Ui(a,e,t){const s=a.group.getObjectByName("antenna");s&&(s.rotation.y+=t*2);for(let i=0;i<4;i++){const o=a.group.getObjectByName(`windowBand_${i}`);if(o&&o.material instanceof v){const n=Math.sin(e*4+i*.5)*.3+.7;o.material.opacity=n}}}function Yi(a){const e=new Y;e.userData.buildingId=a.id,e.userData.isBuilding=!0;const t=a.color?new H(a.color):new H(2763338),s=new O(1.2,32,16,0,Math.PI*2,0,Math.PI/2),i=new A({color:t,metalness:.4,roughness:.6,transparent:!0,opacity:.9}),o=new y(s,i);o.position.y=.15,o.castShadow=!0,o.receiveShadow=!0,o.name="buildingBody",e.add(o);const n=new O(.8,24,12,0,Math.PI*2,0,Math.PI/2),r=new v({color:4890367,transparent:!0,opacity:.3}),l=new y(n,r);l.position.y=.15,l.name="innerDome",e.add(l);const c=new we(1,.05,8,32),d=new v({color:4915102,transparent:!0,opacity:.8}),h=new y(c,d);h.position.y=.6,h.rotation.x=Math.PI/2,h.name="energyRing",e.add(h);const g=new y(c.clone(),d.clone());g.position.y=.8,g.rotation.x=Math.PI/3,g.name="energyRing2",e.add(g);for(let B=0;B<4;B++){const I=new j(.03,.03,1.2,8),L=new v({color:4890367,transparent:!0,opacity:.6}),E=new y(I,L),D=B/4*Math.PI*2;E.position.set(Math.cos(D)*.5,.75,Math.sin(D)*.5),E.name=`beam_${B}`,e.add(E)}const f=new O(.15,16,16),p=new v({color:ee[a.status],transparent:!0,opacity:.95}),m=new y(f,p);m.position.set(0,1.4,0),m.name="statusLight",e.add(m);const b=new O(.25,16,16),w=new v({color:ee[a.status],transparent:!0,opacity:.3}),M=new y(b,w);M.position.set(0,1.4,0),M.name="statusGlow",e.add(M);const S=new j(1.4,1.5,.15,32),P=new A({color:3816010,metalness:.6,roughness:.4}),C=new y(S,P);C.position.y=.075,C.receiveShadow=!0,e.add(C);const x=ne(ue(a));return x.position.set(0,1.9,0),x.name="buildingLabel",e.add(x),e.position.set(a.position.x,0,a.position.z),{group:e,statusLight:m,label:x}}function Xi(a,e,t){const s=a.group.getObjectByName("energyRing"),i=a.group.getObjectByName("energyRing2");s&&(s.rotation.z+=t*.2),i&&(i.rotation.z-=t*.15);const o=a.group.getObjectByName("innerDome");o&&o.material instanceof v&&(o.material.opacity=.15+Math.sin(e*.6)*.1);for(let n=0;n<4;n++){const r=a.group.getObjectByName(`beam_${n}`);r&&r.material instanceof v&&(r.material.opacity=.2+Math.sin(e*.5+n*.3)*.1)}}function Vi(a,e,t){const s=a.group.getObjectByName("energyRing"),i=a.group.getObjectByName("energyRing2");s&&(s.rotation.z+=t*1.5),i&&(i.rotation.z-=t*1.2);const o=a.group.getObjectByName("innerDome");o&&o.material instanceof v&&(o.material.opacity=.2+Math.sin(e*2)*.15);for(let n=0;n<4;n++){const r=a.group.getObjectByName(`beam_${n}`);if(r&&r.material instanceof v){const l=Math.sin(e*5+n*1.5)*.3+.6;r.material.opacity=l}}}function Zi(a){const e=new Y;e.userData.buildingId=a.id,e.userData.isBuilding=!0;const t=a.color?new H(a.color):new H(3815978),s=new xe(1.3,2.5,4),i=new A({color:t,metalness:.3,roughness:.7}),o=new y(s,i);o.position.y=1.25,o.rotation.y=Math.PI/4,o.castShadow=!0,o.receiveShadow=!0,o.name="buildingBody",e.add(o);const n=new xe(.6,1.2,4),r=new v({color:16755200,transparent:!0,opacity:.6}),l=new y(n,r);l.position.y=.8,l.rotation.y=Math.PI/4,l.name="pyramidCore",e.add(l);const c=[{x:.9,z:0},{x:-.9,z:0},{x:0,z:.9},{x:0,z:-.9}];for(let E=0;E<4;E++){const D=new j(.02,.02,2.7,8),$=new v({color:4915102,transparent:!0,opacity:.7}),G=new y(D,$),W=c[E];G.position.set(W.x*.5,1.25,W.z*.5);const Z=Math.atan2(1.25,.65);E<2?G.rotation.z=E===0?-Z:Z:G.rotation.x=E===2?Z:-Z,G.name=`edgeLine_${E}`,e.add(G)}const d=new O(.15,16,16),h=new v({color:16755200,transparent:!0,opacity:.9}),g=new y(d,h);g.position.y=2.7,g.name="pyramidEye",e.add(g);const f=new O(.25,16,16),p=new v({color:16755200,transparent:!0,opacity:.3}),m=new y(f,p);m.position.y=2.7,m.name="pyramidEyeGlow",e.add(m);const b=new O(.12,16,16),w=new v({color:ee[a.status],transparent:!0,opacity:.95}),M=new y(b,w);M.position.set(1.2,.3,0),M.name="statusLight",e.add(M);const S=new O(.2,16,16),P=new v({color:ee[a.status],transparent:!0,opacity:.3}),C=new y(S,P);C.position.set(1.2,.3,0),C.name="statusGlow",e.add(C);const x=new z(2.8,.15,2.8),B=new A({color:4868666,metalness:.2,roughness:.8}),I=new y(x,B);I.position.y=.075,I.receiveShadow=!0,e.add(I);const L=ne(ue(a));return L.position.set(0,3.2,0),L.name="buildingLabel",e.add(L),e.position.set(a.position.x,0,a.position.z),{group:e,statusLight:M,label:L}}function Ki(a,e){const t=a.group.getObjectByName("pyramidEye"),s=a.group.getObjectByName("pyramidEyeGlow");t&&(t.position.y=2.7+Math.sin(e*.5)*.03,t.material instanceof v&&(t.material.opacity=.4+Math.sin(e*.7)*.2)),s&&(s.position.y=2.7+Math.sin(e*.5)*.03,s.material instanceof v&&(s.material.opacity=.15+Math.sin(e*.7)*.1));const i=a.group.getObjectByName("pyramidCore");i&&i.material instanceof v&&(i.material.opacity=.2+Math.sin(e*.5)*.1)}function qi(a,e){const t=a.group.getObjectByName("pyramidCore");t&&t.material instanceof v&&(t.material.opacity=.4+Math.sin(e*2)*.2);const s=a.group.getObjectByName("pyramidEye"),i=a.group.getObjectByName("pyramidEyeGlow");s&&s.material instanceof v&&(s.material.opacity=.7+Math.sin(e*3)*.3),i&&i.material instanceof v&&(i.material.opacity=.2+Math.sin(e*3)*.15),s&&(s.position.y=2.7+Math.sin(e*1.5)*.1),i&&(i.position.y=2.7+Math.sin(e*1.5)*.1)}function Qi(a){const e=new Y;e.userData.buildingId=a.id,e.userData.isBuilding=!0;const t=_e.desktop,s=a.color?new H(a.color):new H(t.primary),i=new z(1.4,1,.15),o=new A({color:s,metalness:.4,roughness:.6}),n=new y(i,o);n.position.set(0,1.4,0),n.castShadow=!0,n.name="buildingBody",e.add(n);const r=new z(1.2,.8,.02),l=new v({color:661032,transparent:!0,opacity:.95}),c=new y(r,l);c.position.set(0,1.4,.09),c.name="screen",e.add(c);for(let R=0;R<6;R++){const _=new z(.8-R%3*.2,.05,.01),U=new v({color:t.glow,transparent:!0,opacity:.9}),q=new y(_,U);q.position.set(-.1+R%2*.1,1.65-R*.1,.1),q.name=`codeLine_${R}`,e.add(q)}const d=new z(.15,.6,.15),h=new A({color:t.secondary,metalness:.5,roughness:.5}),g=new y(d,h);g.position.set(0,.6,0),e.add(g);const f=new z(.6,.08,.4),p=new y(f,h);p.position.set(0,.25,0),e.add(p);const m=new z(1,.08,.35),b=new A({color:t.secondary,metalness:.3,roughness:.7}),w=new y(m,b);w.position.set(0,.2,.6),w.rotation.x=-.1,e.add(w);for(let R=0;R<3;R++)for(let _=0;_<10;_++){const U=new z(.07,.03,.07),q=new A({color:t.accent,metalness:.2,roughness:.8}),V=new y(U,q);V.position.set(-.38+_*.085,.25,.45+R*.1),e.add(V)}const M=new z(.4,.9,.8),S=new A({color:s,metalness:.4,roughness:.6}),P=new y(M,S);P.position.set(-1.1,.55,0),P.castShadow=!0,e.add(P);const C=new z(.05,.05,.02),x=new v({color:4915102,transparent:!0,opacity:.9}),B=new y(C,x);B.position.set(-.88,.7,.3),B.name="cpuLed",e.add(B);const I=new O(.1,16,16),L=new v({color:ee[a.status],transparent:!0,opacity:.95}),E=new y(I,L);E.position.set(.6,1.85,.1),E.name="statusLight",e.add(E);const D=new O(.18,16,16),$=new v({color:ee[a.status],transparent:!0,opacity:.3}),G=new y(D,$);G.position.set(.6,1.85,.1),G.name="statusGlow",e.add(G);const W=new z(2.6,.1,1.4),Z=new A({color:3816010,metalness:.5,roughness:.5}),N=new y(W,Z);N.position.y=.05,N.receiveShadow=!0,e.add(N);const F=ne(ue(a));return F.position.set(0,2.3,0),F.name="buildingLabel",e.add(F),e.position.set(a.position.x,0,a.position.z),{group:e,statusLight:E,label:F}}function Ji(a,e){const t=a.group.getObjectByName("buildingBody");t&&(t.rotation.y=Math.sin(e*.3)*.01);for(let s=0;s<6;s++){const i=a.group.getObjectByName(`codeLine_${s}`);i&&i.material instanceof v&&(i.material.opacity=.3+Math.sin(e*.4+s*.2)*.1)}}function eo(a,e){for(let s=0;s<6;s++){const i=a.group.getObjectByName(`codeLine_${s}`);if(i&&i.material instanceof v){const o=Math.random()>.98?.4:.8;i.material.opacity=o}}const t=a.group.getObjectByName("cpuLed");if(t&&t.material instanceof v){const s=Math.sin(e*6)>0?.9:.3;t.material.opacity=s}}function to(a){const e=new Y;e.userData.buildingId=a.id,e.userData.isBuilding=!0;const t=_e["filing-cabinet"],s=a.color?new H(a.color):new H(t.primary),i=new z(1,2.4,.8),o=new A({color:s,metalness:.5,roughness:.5}),n=new y(i,o);n.position.y=1.2,n.castShadow=!0,n.name="buildingBody",e.add(n);for(let w=0;w<4;w++){const M=new z(.9,.5,.05),S=new A({color:t.secondary,metalness:.4,roughness:.6}),P=new y(M,S);P.position.set(0,.35+w*.55,.4),P.name=`drawer_${w}`,e.add(P);const C=new z(.3,.06,.05),x=new A({color:t.accent,metalness:.7,roughness:.3}),B=new y(C,x);B.position.set(0,.35+w*.55,.47),B.name=`handle_${w}`,e.add(B);const I=new z(.4,.15,.02),L=new v({color:16777198}),E=new y(I,L);E.position.set(0,.45+w*.55,.44),e.add(E)}for(let w=0;w<4;w++){const M=new z(.06,.06,.02),S=new v({color:w%2===0?t.glow:t.accent,transparent:!0,opacity:.9}),P=new y(M,S);P.position.set(-.38,.35+w*.55,.42),P.name=`indicator_${w}`,e.add(P)}const r=new O(.12,16,16),l=new v({color:ee[a.status],transparent:!0,opacity:.95}),c=new y(r,l);c.position.set(0,2.55,0),c.name="statusLight",e.add(c);const d=new O(.2,16,16),h=new v({color:ee[a.status],transparent:!0,opacity:.3}),g=new y(d,h);g.position.set(0,2.55,0),g.name="statusGlow",e.add(g);const f=new z(1.3,.1,1.1),p=new A({color:3816010,metalness:.5,roughness:.5}),m=new y(f,p);m.position.y=.05,m.receiveShadow=!0,e.add(m);const b=ne(ue(a));return b.position.set(0,3,0),b.name="buildingLabel",e.add(b),e.position.set(a.position.x,0,a.position.z),{group:e,statusLight:c,label:b}}function so(a,e){a.group.rotation.y=Math.sin(e*.5)*.005;for(let t=0;t<4;t++){const s=a.group.getObjectByName(`indicator_${t}`);s&&s.material instanceof v&&(s.material.opacity=.3+Math.sin(e*.6+t*.4)*.15)}}function io(a,e){for(let t=0;t<4;t++){const s=a.group.getObjectByName(`indicator_${t}`);if(s&&s.material instanceof v){const i=Math.sin(e*3+t*.8)*.3+.7;s.material.opacity=i}}for(let t=0;t<4;t++){const s=a.group.getObjectByName(`handle_${t}`);s&&(s.position.z=.47+Math.sin(e*8+t)*.005)}}function oo(a){const e=new Y;e.userData.buildingId=a.id,e.userData.isBuilding=!0;const t=_e.satellite,s=a.color?new H(a.color):new H(t.primary),i=new j(.1,.15,2,8),o=new A({color:t.secondary,metalness:.6,roughness:.4}),n=new y(i,o);n.position.y=1,n.castShadow=!0,e.add(n);const r=new z(.3,.2,.3),l=new y(r,o);l.position.y=2.1,e.add(l);const c=new Y;c.position.y=2.3,c.name="dishGroup";const d=new O(1,32,16,0,Math.PI*2,0,Math.PI/3),h=new A({color:s,metalness:.5,roughness:.5,side:oe}),g=new y(d,h);g.rotation.x=Math.PI/2+.3,g.name="buildingBody",c.add(g);const f=new O(.95,32,16,0,Math.PI*2,0,Math.PI/3),p=new A({color:t.accent,metalness:.3,roughness:.7,side:Ut}),m=new y(f,p);m.rotation.x=Math.PI/2+.3,c.add(m);const b=new j(.03,.03,.8,8),w=new A({color:t.secondary,metalness:.6,roughness:.4}),M=new y(b,w);M.position.set(0,.1,.5),M.rotation.x=-.6,c.add(M);const S=new xe(.1,.2,8),P=new A({color:t.accent,metalness:.4,roughness:.6}),C=new y(S,P);C.position.set(0,.5,.85),C.rotation.x=Math.PI/2-.6,c.add(C);const x=new O(.08,16,16),B=new v({color:t.glow,transparent:!0,opacity:.9}),I=new y(x,B);I.position.set(0,.55,.92),I.name="signal",c.add(I),e.add(c);for(let _=0;_<3;_++){const U=new ke(.2+_*.15,.22+_*.15,16),q=new v({color:t.glow,transparent:!0,opacity:.6-_*.15,side:oe}),V=new y(U,q);V.position.set(0,2.85+_*.1,.92+_*.1),V.rotation.x=-.6,V.name=`wave_${_}`,e.add(V)}const L=new O(.1,16,16),E=new v({color:ee[a.status],transparent:!0,opacity:.95}),D=new y(L,E);D.position.set(0,.3,.5),D.name="statusLight",e.add(D);const $=new O(.18,16,16),G=new v({color:ee[a.status],transparent:!0,opacity:.3}),W=new y($,G);W.position.set(0,.3,.5),W.name="statusGlow",e.add(W);const Z=new j(.6,.7,.15,16),N=new A({color:t.secondary,metalness:.5,roughness:.5}),F=new y(Z,N);F.position.y=.075,F.receiveShadow=!0,e.add(F);const R=ne(ue(a));return R.position.set(0,3.8,0),R.name="buildingLabel",e.add(R),e.position.set(a.position.x,0,a.position.z),{group:e,statusLight:D,label:R}}function no(a,e,t){const s=a.group.getObjectByName("dishGroup");s&&(s.rotation.y+=t*.1);for(let i=0;i<3;i++){const o=a.group.getObjectByName(`wave_${i}`);o&&o.material instanceof v&&(o.material.opacity=.15+Math.sin(e*.5+i*.3)*.1)}}function ao(a,e,t){const s=a.group.getObjectByName("dishGroup");s&&(s.rotation.y+=t*.5);const i=a.group.getObjectByName("signal");i&&i.material instanceof v&&(i.material.opacity=.6+Math.sin(e*8)*.4);for(let o=0;o<3;o++){const n=a.group.getObjectByName(`wave_${o}`);if(n&&n.material instanceof v){const r=1+Math.sin(e*4+o)*.1;n.scale.set(r,r,1),n.material.opacity=(.5-o*.15)*(.5+Math.sin(e*4+o)*.5)}}}function ro(a){const e=new Y;e.userData.buildingId=a.id,e.userData.isBuilding=!0;const t=_e.crystal,s=a.color?new H(a.color):new H(t.primary),i=new Mt(.8),o=new A({color:s,metalness:.3,roughness:.2,transparent:!0,opacity:.85}),n=new y(i,o);n.position.y=1.8,n.castShadow=!0,n.name="buildingBody",e.add(n);const r=new Mt(.5),l=new v({color:t.glow,transparent:!0,opacity:.6}),c=new y(r,l);c.position.y=1.8,c.name="crystalInner",e.add(c);for(let G=0;G<6;G++){const W=new O(.06,8,8),Z=new v({color:G%2===0?t.accent:t.glow,transparent:!0,opacity:.9}),N=new y(W,Z),F=G/6*Math.PI*2;N.position.set(Math.cos(F)*1.2,1.8+Math.sin(F*2)*.3,Math.sin(F)*1.2),N.name=`particle_${G}`,e.add(N)}const d=new ws(1.3,1),h=new v({color:t.accent,wireframe:!0,transparent:!0,opacity:.4}),g=new y(d,h);g.position.y=1.8,g.name="energyField",e.add(g);const f=new j(.3,.5,.8,6),p=new A({color:t.secondary,metalness:.5,roughness:.5}),m=new y(f,p);m.position.y=.4,e.add(m);const b=new j(.05,.05,.9,8),w=new v({color:t.glow,transparent:!0,opacity:.7}),M=new y(b,w);M.position.y=1.25,M.name="energyBeam",e.add(M);const S=new O(.1,16,16),P=new v({color:ee[a.status],transparent:!0,opacity:.95}),C=new y(S,P);C.position.set(.7,.5,0),C.name="statusLight",e.add(C);const x=new O(.18,16,16),B=new v({color:ee[a.status],transparent:!0,opacity:.3}),I=new y(x,B);I.position.set(.7,.5,0),I.name="statusGlow",e.add(I);const L=new j(.8,.9,.1,6),E=new A({color:t.secondary,metalness:.6,roughness:.4}),D=new y(L,E);D.position.y=.05,D.receiveShadow=!0,e.add(D);const $=ne(ue(a));return $.position.set(0,3,0),$.name="buildingLabel",e.add($),e.position.set(a.position.x,0,a.position.z),{group:e,statusLight:C,label:$}}function lo(a,e,t){const s=a.group.getObjectByName("buildingBody");s&&(s.rotation.y+=t*.2,s.position.y=1.8+Math.sin(e*.8)*.05);const i=a.group.getObjectByName("crystalInner");i&&(i.rotation.y-=t*.3,i.position.y=1.8+Math.sin(e*.8)*.05,i.material instanceof v&&(i.material.opacity=.25+Math.sin(e*.6)*.15));const o=a.group.getObjectByName("energyField");o&&(o.rotation.y+=t*.1,o.position.y=1.8+Math.sin(e*.8)*.05,o.material instanceof v&&(o.material.opacity=.15+Math.sin(e*.5)*.1));for(let r=0;r<6;r++){const l=a.group.getObjectByName(`particle_${r}`);if(l){const c=r/6*Math.PI*2+e*.3;l.position.x=Math.cos(c)*1.2,l.position.z=Math.sin(c)*1.2,l.position.y=1.8+Math.sin(e*.8)*.05+Math.sin(c*2)*.2}}const n=a.group.getObjectByName("energyBeam");n&&n.material instanceof v&&(n.material.opacity=.2+Math.sin(e*.7)*.15)}function co(a,e,t){const s=a.group.getObjectByName("buildingBody"),i=a.group.getObjectByName("crystalInner"),o=a.group.getObjectByName("energyField");s&&(s.rotation.y+=t*.8,s.position.y=1.8+Math.sin(e*1.5)*.1),i&&(i.rotation.y-=t*1.2,i.position.y=1.8+Math.sin(e*1.5)*.1,i.material instanceof v&&(i.material.opacity=.4+Math.sin(e*3)*.2)),o&&(o.rotation.y+=t*.3,o.rotation.x+=t*.2,o.position.y=1.8+Math.sin(e*1.5)*.1);for(let r=0;r<6;r++){const l=a.group.getObjectByName(`particle_${r}`);if(l){const c=r/6*Math.PI*2+e*1.5,d=1.2+Math.sin(e*2+r)*.1;l.position.x=Math.cos(c)*d,l.position.z=Math.sin(c)*d,l.position.y=1.8+Math.sin(e*1.5)*.1+Math.sin(c*2)*.3}}const n=a.group.getObjectByName("energyBeam");n&&n.material instanceof v&&(n.material.opacity=.4+Math.sin(e*4)*.3)}function ho(a){const e=new Y;e.userData.buildingId=a.id,e.userData.isBuilding=!0;const t=_e.factory,s=a.color?new H(a.color):new H(t.primary),i=new z(1.8,1.2,1.2),o=new A({color:s,metalness:.4,roughness:.6}),n=new y(i,o);n.position.set(0,.6,0),n.castShadow=!0,n.name="buildingBody",e.add(n);const r=new z(2,.15,1.4),l=new A({color:t.secondary,metalness:.5,roughness:.5}),c=new y(r,l);c.position.set(0,1.25,0),c.rotation.z=.05,e.add(c);const d=new j(.15,.18,1.2,8),h=new A({color:t.secondary,metalness:.5,roughness:.5}),g=new y(d,h);g.position.set(.5,1.8,.3),e.add(g);const f=new we(.17,.03,8,16),p=new y(f,h);p.position.set(.5,2.4,.3),p.rotation.x=Math.PI/2,e.add(p);for(let _=0;_<4;_++){const U=new O(.08+_*.03,8,8),q=new v({color:11184810,transparent:!0,opacity:.7-_*.12}),V=new y(U,q);V.position.set(.5,2.5+_*.25,.3),V.name=`smoke_${_}`,e.add(V)}for(let _=0;_<3;_++){const U=new z(.25,.35,.05),q=new v({color:t.glow,transparent:!0,opacity:.9}),V=new y(U,q);V.position.set(-.6+_*.5,.7,.63),V.name=`window_${_}`,e.add(V)}const m=new z(.4,.6,.05),b=new A({color:t.secondary,metalness:.4,roughness:.6}),w=new y(m,b);w.position.set(.6,.35,.63),e.add(w);const M=new z(.3,.1,1.6),S=new A({color:t.secondary,metalness:.6,roughness:.4}),P=new y(M,S);P.position.set(-1,.25,0),e.add(P);for(let _=0;_<3;_++){const U=new z(.15,.15,.15),q=new v({color:_%2===0?t.accent:t.glow}),V=new y(U,q);V.position.set(-1,.38,-.5+_*.4),V.name=`conveyorItem_${_}`,e.add(V)}const C=new we(.2,.05,6,8),x=new A({color:t.accent,metalness:.6,roughness:.4}),B=new y(C,x);B.position.set(-.8,.9,.63),B.name="gear1",e.add(B);const I=new y(C.clone(),x.clone());I.position.set(-.5,1.05,.63),I.name="gear2",e.add(I);const L=new O(.12,16,16),E=new v({color:ee[a.status],transparent:!0,opacity:.95}),D=new y(L,E);D.position.set(.85,1,.65),D.name="statusLight",e.add(D);const $=new O(.2,16,16),G=new v({color:ee[a.status],transparent:!0,opacity:.3}),W=new y($,G);W.position.set(.85,1,.65),W.name="statusGlow",e.add(W);const Z=new z(2.4,.1,1.8),N=new A({color:4868682,metalness:.4,roughness:.6}),F=new y(Z,N);F.position.y=.05,F.receiveShadow=!0,e.add(F);const R=ne(ue(a));return R.position.set(0,2.9,0),R.name="buildingLabel",e.add(R),e.position.set(a.position.x,0,a.position.z),{group:e,statusLight:D,label:R}}function uo(a,e,t){const s=a.group.getObjectByName("gear1"),i=a.group.getObjectByName("gear2");s&&(s.rotation.z+=t*.3),i&&(i.rotation.z-=t*.4);for(let o=0;o<3;o++){const n=a.group.getObjectByName(`window_${o}`);n&&n.material instanceof v&&(n.material.opacity=.3+Math.sin(e*.4+o*.5)*.15)}for(let o=0;o<3;o++){const n=a.group.getObjectByName(`conveyorItem_${o}`);n&&(n.position.z=(n.position.z+t*.05+.5)%1.2-.5)}for(let o=0;o<4;o++){const n=a.group.getObjectByName(`smoke_${o}`);if(n){const r=2.5+o*.25,l=(e*.15+o*.3)%1.5;n.position.y=r+l,n.position.x=.5+Math.sin(e*.3+o)*.05,n.material instanceof v&&(n.material.opacity=Math.max(0,(.25-o*.05)*(1-l/1.5)))}}}function go(a,e,t){for(let o=0;o<4;o++){const n=a.group.getObjectByName(`smoke_${o}`);if(n){const r=2.5+o*.25,l=(e*.5+o*.3)%1.5;n.position.y=r+l,n.position.x=.5+Math.sin(e+o)*.1,n.material instanceof v&&(n.material.opacity=Math.max(0,(.6-o*.12)*(1-l/1.5))),l>1.4&&(n.position.y=r)}}const s=a.group.getObjectByName("gear1"),i=a.group.getObjectByName("gear2");s&&(s.rotation.z+=t*2),i&&(i.rotation.z-=t*2.5);for(let o=0;o<3;o++){const n=a.group.getObjectByName(`conveyorItem_${o}`);n&&(n.position.z=(n.position.z+t*.3+.5)%1.2-.5)}for(let o=0;o<3;o++){const n=a.group.getObjectByName(`window_${o}`);if(n&&n.material instanceof v){const r=Math.random()>.99?.5:.8;n.material.opacity=r}}}function po(a){const e=new Y;e.userData.buildingId=a.id,e.userData.isBuilding=!0;const t=a.color?new H(a.color):new H(2763322),s=16766720,i=new j(1.8,2,.3,6),o=new A({color:t,metalness:.7,roughness:.3}),n=new y(i,o);n.position.y=.15,n.receiveShadow=!0,e.add(n);const r=new j(1.2,1.4,.2,6),l=new A({color:3816010,metalness:.8,roughness:.2}),c=new y(r,l);c.position.y=.4,e.add(c);const d=new j(.4,.6,2,6),h=new A({color:t,metalness:.6,roughness:.4}),g=new y(d,h);g.position.y=1.5,g.castShadow=!0,g.receiveShadow=!0,g.name="buildingBody",e.add(g);const f=new j(.5,.4,.3,6),p=new A({color:s,metalness:.9,roughness:.1,emissive:new H(s),emissiveIntensity:.3}),m=new y(f,p);m.position.y=2.65,m.name="crownBase",e.add(m);for(let N=0;N<5;N++){const F=N/5*Math.PI*2,R=new xe(.08,.4,4),_=new y(R,p);_.position.set(Math.cos(F)*.35,2.95,Math.sin(F)*.35),_.name=`crownSpike_${N}`,e.add(_)}const b=new we(.8,.03,8,32),w=new v({color:s,transparent:!0,opacity:.6}),M=new y(b,w);M.position.y=1.2,M.rotation.x=Math.PI/2,M.name="holoRing1",e.add(M);const S=new we(1.1,.02,8,32),P=new v({color:4915102,transparent:!0,opacity:.5}),C=new y(S,P);C.position.y=1.5,C.rotation.x=Math.PI/2,C.name="holoRing2",e.add(C);const x=new we(1.4,.02,8,32),B=new v({color:4890367,transparent:!0,opacity:.4}),I=new y(x,B);I.position.y=1.8,I.rotation.x=Math.PI/2,I.name="holoRing3",e.add(I);for(let N=0;N<6;N++){const F=N/6*Math.PI*2,R=new Y,_=new z(.3,.25,.2),U=new A({color:3816010,metalness:.6,roughness:.4}),q=new y(_,U);q.position.y=.45,R.add(q);const V=new pe(.25,.15),Se=new v({color:4890367,transparent:!0,opacity:.8}),fe=new y(V,Se);fe.position.y=.52,fe.position.z=.11,fe.rotation.x=-.3,fe.name=`consoleScreen_${N}`,R.add(fe),R.position.set(Math.cos(F)*1.5,0,Math.sin(F)*1.5),R.rotation.y=-F+Math.PI,e.add(R)}const L=new O(.15,16,16),E=new v({color:ee[a.status],transparent:!0,opacity:.95}),D=new y(L,E);D.position.set(0,3.3,0),D.name="statusLight",e.add(D);const $=new O(.25,16,16),G=new v({color:ee[a.status],transparent:!0,opacity:.3}),W=new y($,G);W.position.set(0,3.3,0),W.name="statusGlow",e.add(W);for(let N=0;N<6;N++){const F=N/6*Math.PI*2+Math.PI/6,R=new j(.06,.08,1,6),_=new A({color:s,metalness:.8,roughness:.2,emissive:new H(s),emissiveIntensity:.2}),U=new y(R,_);U.position.set(Math.cos(F)*1.85,.8,Math.sin(F)*1.85),U.name=`energyPillar_${N}`,e.add(U);const q=new O(.08,8,8),V=new v({color:s,transparent:!0,opacity:.8}),Se=new y(q,V);Se.position.set(Math.cos(F)*1.85,1.35,Math.sin(F)*1.85),Se.name=`pillarLight_${N}`,e.add(Se)}const Z=ne(ue(a));return Z.position.set(0,3.8,0),Z.name="buildingLabel",e.add(Z),e.position.set(a.position.x,0,a.position.z),{group:e,statusLight:D,label:Z}}function fo(a,e,t){const s=a.group.getObjectByName("holoRing1"),i=a.group.getObjectByName("holoRing2"),o=a.group.getObjectByName("holoRing3");s&&(s.rotation.z+=t*.3,s.material instanceof v&&(s.material.opacity=.3+Math.sin(e*.5)*.1)),i&&(i.rotation.z-=t*.2,i.material instanceof v&&(i.material.opacity=.25+Math.sin(e*.7+1)*.1)),o&&(o.rotation.z+=t*.1,o.material instanceof v&&(o.material.opacity=.2+Math.sin(e*.4+2)*.1));for(let n=0;n<6;n++){const r=a.group.getObjectByName(`pillarLight_${n}`);r&&r.material instanceof v&&(r.material.opacity=.4+Math.sin(e*.5+n*.5)*.2)}for(let n=0;n<6;n++){const r=a.group.getObjectByName(`consoleScreen_${n}`);r&&r.material instanceof v&&(r.material.opacity=.4+Math.sin(e*.3+n*.3)*.1)}}function mo(a,e,t){const s=a.group.getObjectByName("holoRing1"),i=a.group.getObjectByName("holoRing2"),o=a.group.getObjectByName("holoRing3");s&&(s.rotation.z+=t*1.5,s.rotation.x=Math.PI/2+Math.sin(e*2)*.1,s.material instanceof v&&(s.material.opacity=.5+Math.sin(e*3)*.2)),i&&(i.rotation.z-=t*1,i.rotation.x=Math.PI/2+Math.sin(e*1.5+1)*.15,i.material instanceof v&&(i.material.opacity=.4+Math.sin(e*2.5+1)*.15)),o&&(o.rotation.z+=t*.5,o.rotation.x=Math.PI/2+Math.sin(e*1+2)*.1,o.material instanceof v&&(o.material.opacity=.35+Math.sin(e*2+2)*.15));for(let r=0;r<6;r++){const l=a.group.getObjectByName(`pillarLight_${r}`);if(l&&l.material instanceof v){const c=(e*2+r*.3)%(Math.PI*2);l.material.opacity=.6+Math.sin(c)*.3}}for(let r=0;r<6;r++){const l=a.group.getObjectByName(`consoleScreen_${r}`);if(l&&l.material instanceof v){l.material.opacity=.7+Math.sin(e*4+r*.5)*.2;const c=(e*.1+r*.1)%1;l.material.color.setHSL(c*.2+.5,.8,.5)}}const n=a.group.getObjectByName("crownBase");n&&n.material instanceof A&&(n.material.emissiveIntensity=.4+Math.sin(e*2)*.2)}function wo(a){switch(a.style||"server-rack"){case"tower":return ji(a);case"dome":return Yi(a);case"pyramid":return Zi(a);case"desktop":return Qi(a);case"filing-cabinet":return to(a);case"satellite":return oo(a);case"crystal":return ro(a);case"factory":return ho(a);case"command-center":return po(a);case"server-rack":default:return Wi(a)}}function bo(a,e,t,s){switch(e.style||"server-rack"){case"server-rack":Fi(a,t);break;case"desktop":Ji(a,t);break;case"filing-cabinet":so(a,t);break;case"satellite":no(a,t,s);break;case"crystal":lo(a,t,s);break;case"factory":uo(a,t,s);break;case"tower":$i(a,t,s);break;case"dome":Xi(a,t,s);break;case"pyramid":Ki(a,t);break;case"command-center":fo(a,t,s);break}}function yo(a,e,t,s){const i=e.style||"server-rack",o=a.group.getObjectByName("statusGlow"),n=Math.sin(t*3)*.2+.8;switch(o&&o.material instanceof v&&(o.material.opacity=.3*n),i){case"server-rack":Ni(a);break;case"tower":Ui(a,t,s);break;case"dome":Vi(a,t,s);break;case"pyramid":qi(a,t);break;case"desktop":eo(a,t);break;case"filing-cabinet":io(a,t);break;case"satellite":ao(a,t,s);break;case"crystal":co(a,t,s);break;case"factory":go(a,t,s);break;case"command-center":mo(a,t,s);break}}function Mo(a,e){const t=a.group.getObjectByName("statusGlow"),s=Math.sin(e*8)*.5+.5;t&&t.material instanceof v&&(t.material.opacity=.5*s)}function So(a,e){const t=a.group.getObjectByName("statusGlow"),s=Math.sin(e*2)*.5+.5;t&&t.material instanceof v&&(t.material.opacity=.4*s)}class vo{constructor(e){u(this,"scene");u(this,"buildingMeshes",new Map);u(this,"selectedBuildingIds",new Set);u(this,"animationTime",0);u(this,"brightness",1);u(this,"bossSubordinateLines",null);u(this,"bossSubordinateMaterial",null);u(this,"cachedBossConnections",[]);u(this,"maxLineSegments",50);u(this,"onBuildingClick",null);u(this,"onBuildingDoubleClick",null);this.scene=e}setOnBuildingClick(e){this.onBuildingClick=e}setOnBuildingDoubleClick(e){this.onBuildingDoubleClick=e}setBrightness(e){this.brightness=e;for(const t of this.buildingMeshes.values()){const s=t.group.getObjectByName("statusGlow");s&&s.material instanceof v&&(s.material.opacity=.3*e),t.group.traverse(i=>{if(i instanceof y&&i.material instanceof A){const o=i.material;o.emissiveIntensity!==void 0&&(o.userData.baseEmissiveIntensity===void 0&&(o.userData.baseEmissiveIntensity=o.emissiveIntensity||1),o.emissiveIntensity=o.userData.baseEmissiveIntensity*e)}})}}addBuilding(e){this.removeBuilding(e.id);const t=wo(e);t.group.userData.style=e.style,t.group.userData.color=e.color||"";const s=e.scale||1;t.group.scale.setScalar(s),this.scene.add(t.group),this.buildingMeshes.set(e.id,t)}removeBuilding(e){const t=this.buildingMeshes.get(e);t&&(this.scene.remove(t.group),this.disposeGroup(t.group),this.buildingMeshes.delete(e))}setBuildingPosition(e,t){const s=this.buildingMeshes.get(e);s&&(s.group.position.set(t.x,0,t.z),this.updateBossLinePositions())}updateBuilding(e){var f;const t=this.buildingMeshes.get(e.id);if(!t){this.addBuilding(e);return}const s=t.group.userData.style,i=t.group.userData.color;if(s!==e.style||i!==(e.color||"")){this.removeBuilding(e.id),this.addBuilding(e);return}t.group.position.set(e.position.x,0,e.position.z);const o=e.scale||1;t.group.scale.setScalar(o);const n=ee[e.status],r=t.group.getObjectByName("statusLight");r&&r.material instanceof v&&r.material.color.setHex(n);const l=t.group.getObjectByName("statusGlow");l&&l.material instanceof v&&l.material.color.setHex(n),((f=t.label.material.map)==null?void 0:f.image)&&Jt(t,e.name);const h=e.gitChangesCount||0,g=t.group.getObjectByName("gitIndicator");if(h>0){if(g)g.userData.gitCount!==h&&(Hi(g,h),g.userData.gitCount=h);else{const p=Qt(h),m=t.label.position;p.position.set(m.x+.6,m.y+.15,m.z),t.group.add(p),t.gitIndicator=p}t.gitIndicator&&(t.gitIndicator.userData.gitCount=h)}else if(g){t.group.remove(g);const p=g.material;p.map&&p.map.dispose(),p.dispose(),t.gitIndicator=void 0}}highlightBuilding(e){for(const t of this.selectedBuildingIds){const s=this.buildingMeshes.get(t);if(s){const i=s.group.getObjectByName("buildingBody");i&&i.material instanceof A&&i.material.emissive.setHex(0)}}if(this.selectedBuildingIds.clear(),e){this.selectedBuildingIds.add(e);const t=this.buildingMeshes.get(e);if(t){const s=t.group.getObjectByName("buildingBody");s&&s.material instanceof A&&s.material.emissive.setHex(2236996)}}this.updateBossConnectionLines()}highlightBuildings(e){for(const t of this.selectedBuildingIds){const s=this.buildingMeshes.get(t);if(s){const i=s.group.getObjectByName("buildingBody");i&&i.material instanceof A&&i.material.emissive.setHex(0)}}this.selectedBuildingIds.clear();for(const t of e){this.selectedBuildingIds.add(t);const s=this.buildingMeshes.get(t);if(s){const i=s.group.getObjectByName("buildingBody");i&&i.material instanceof A&&i.material.emissive.setHex(2236996)}}this.updateBossConnectionLines()}getBuildingMeshData(){return this.buildingMeshes}getHitboxForStyle(e){switch(e){case"desktop":return{halfWidth:2,halfDepth:2};case"filing-cabinet":return{halfWidth:1.8,halfDepth:1.2};case"factory":return{halfWidth:1.5,halfDepth:1.2};case"satellite":return{halfWidth:1.2,halfDepth:1.2};case"crystal":return{halfWidth:1.5,halfDepth:1.5};case"tower":return{halfWidth:1.2,halfDepth:1};case"dome":return{halfWidth:1.5,halfDepth:1.5};case"pyramid":return{halfWidth:1.5,halfDepth:1.5};case"command-center":return{halfWidth:2.2,halfDepth:2.2};case"server-rack":default:return{halfWidth:1.2,halfDepth:1}}}getBuildingAtPosition(e){const t=k.getState();for(const s of t.buildings.values()){if(!this.isBuildingVisibleInWorkspace(s,t.areas))continue;const i=this.getHitboxForStyle(s.style),o=s.scale||1,n={halfWidth:i.halfWidth*o,halfDepth:i.halfDepth*o},r=Math.abs(e.x-s.position.x),l=Math.abs(e.z-s.position.z);if(r<=n.halfWidth&&l<=n.halfDepth)return s}return null}getBuildingMeshes(){return Array.from(this.buildingMeshes.values()).map(e=>e.group)}isBuildingVisibleInWorkspace(e,t){if(!$e())return!0;for(const s of t.values())if(!s.archived&&this.isPointInsideArea(e.position.x,e.position.z,s))return Ne(s.id);return!0}isPointInsideArea(e,t,s){if(s.type==="rectangle"&&s.width&&s.height){const i=s.width/2,o=s.height/2;return e>=s.center.x-i&&e<=s.center.x+i&&t>=s.center.z-o&&t<=s.center.z+o}if(s.type==="circle"&&s.radius){const i=e-s.center.x,o=t-s.center.z;return i*i+o*o<=s.radius*s.radius}return!1}syncFromStore(){const e=k.getState();for(const t of this.buildingMeshes.keys()){const s=e.buildings.get(t);(!s||!this.isBuildingVisibleInWorkspace(s,e.areas))&&this.removeBuilding(t)}for(const t of e.buildings.values())this.isBuildingVisibleInWorkspace(t,e.areas)&&(this.buildingMeshes.has(t.id)?this.updateBuilding(t):this.addBuilding(t))}update(e){this.animationTime+=e;const t=k.getState();for(const[s,i]of this.buildingMeshes){const o=t.buildings.get(s);o&&(bo(i,o,this.animationTime,e),o.status==="running"?yo(i,o,this.animationTime,e):o.status==="starting"||o.status==="stopping"?Mo(i,this.animationTime):o.status==="error"&&So(i,this.animationTime))}}updateBossConnectionLines(){var i;const e=k.getState(),t=[],s=new Set;for(const o of this.selectedBuildingIds){const n=e.buildings.get(o);if(n&&n.type==="boss"&&n.subordinateBuildingIds){t.push(n);for(const r of n.subordinateBuildingIds)s.add(r)}if(n){for(const[,r]of e.buildings)if(r.type==="boss"&&((i=r.subordinateBuildingIds)!=null&&i.includes(n.id))&&!t.find(l=>l.id===r.id)){t.push(r);for(const l of r.subordinateBuildingIds||[])s.add(l)}}}this.cachedBossConnections=[];for(const o of t)if(!(!this.buildingMeshes.get(o.id)||!o.subordinateBuildingIds))for(const r of o.subordinateBuildingIds)this.buildingMeshes.get(r)&&this.cachedBossConnections.push({bossId:o.id,subId:r});if(this.cachedBossConnections.length>0){if(!this.bossSubordinateLines){const r=new Float32Array(this.maxLineSegments*6),l=new le;l.setAttribute("position",new Ae(r,3)),l.setDrawRange(0,0),this.bossSubordinateMaterial=new ge({color:16766720,transparent:!0,opacity:.4}),this.bossSubordinateLines=new Yt(l,this.bossSubordinateMaterial),this.bossSubordinateLines.frustumCulled=!1,this.scene.add(this.bossSubordinateLines)}const o=this.bossSubordinateLines.geometry.attributes.position,n=o.array;for(let r=0;r<this.cachedBossConnections.length&&r<this.maxLineSegments;r++){const{bossId:l,subId:c}=this.cachedBossConnections[r],d=this.buildingMeshes.get(l),h=this.buildingMeshes.get(c);if(d&&h){const g=r*6;n[g]=d.group.position.x,n[g+1]=.1,n[g+2]=d.group.position.z,n[g+3]=h.group.position.x,n[g+4]=.1,n[g+5]=h.group.position.z}}o.needsUpdate=!0,this.bossSubordinateLines.geometry.setDrawRange(0,this.cachedBossConnections.length*2),this.bossSubordinateLines.visible=!0}else this.bossSubordinateLines&&(this.bossSubordinateLines.visible=!1);for(const[o,n]of this.buildingMeshes){if(!e.buildings.get(o))continue;const l=s.has(o),c=n.group.getObjectByName("buildingBody");c&&c.material instanceof A&&(l&&!this.selectedBuildingIds.has(o)?c.material.emissive.setHex(3351040):this.selectedBuildingIds.has(o)||c.material.emissive.setHex(0))}}updateBossLinePositions(){if(!this.bossSubordinateLines||this.cachedBossConnections.length===0)return;const e=this.bossSubordinateLines.geometry.attributes.position,t=e.array;for(let s=0;s<this.cachedBossConnections.length&&s<this.maxLineSegments;s++){const{bossId:i,subId:o}=this.cachedBossConnections[s],n=this.buildingMeshes.get(i),r=this.buildingMeshes.get(o);if(!n||!r)continue;const l=s*6;t[l]=n.group.position.x,t[l+1]=.1,t[l+2]=n.group.position.z,t[l+3]=r.group.position.x,t[l+4]=.1,t[l+5]=r.group.position.z}e.needsUpdate=!0}disposeGroup(e){e.traverse(t=>{if(t instanceof y&&(t.geometry.dispose(),Array.isArray(t.material)?t.material.forEach(s=>s.dispose()):t.material.dispose()),t instanceof K){const s=t.material;s.map&&s.map.dispose(),s.dispose()}})}dispose(){var e;for(const t of this.buildingMeshes.keys())this.removeBuilding(t);this.bossSubordinateLines&&(this.scene.remove(this.bossSubordinateLines),this.bossSubordinateLines.geometry.dispose(),(e=this.bossSubordinateMaterial)==null||e.dispose(),this.bossSubordinateLines=null,this.bossSubordinateMaterial=null),this.cachedBossConnections=[]}}const es={idle:8947848,running:4915102,completed:4890367,error:16730698},ts={flowchart:{primary:5924824,secondary:5001663,accent:10451690,glow:4890367},"circuit-board":{primary:3715756,secondary:2914939,accent:5231045,glow:4915102},constellation:{primary:8411861,secondary:7030465,accent:14073082,glow:12031220},helix:{primary:15557798,secondary:13975436,accent:16156595,glow:10451690},clockwork:{primary:14065198,secondary:12024095,accent:15518027,glow:16755200}};function Oe(a,e,t){const s=es[e],i=new O(.12,16,16),o=new v({color:s,transparent:!0,opacity:.95}),n=new y(i,o);n.position.set(0,t,0),n.name="statusLight",a.add(n);const r=new O(.2,16,16),l=new v({color:s,transparent:!0,opacity:.3}),c=new y(r,l);return c.position.set(0,t,0),c.name="statusGlow",a.add(c),n}function Ze(a){if(a.color)return new H(a.color);const e=ts[a.style||"flowchart"];return new H(e.primary)}function ze(a){const e=ts[a.style||"flowchart"];return new H(e.accent)}function Co(a,e){var m,b;const t=new Y;t.userData.workflowId=a.id,t.userData.isWorkflow=!0;const s=Ze(a),i=ze(a),o=Math.min(a.states.length,8),n=new j(1.3,1.4,.1,32),r=new A({color:2763322,metalness:.6,roughness:.4}),l=new y(n,r);l.position.y=.05,l.receiveShadow=!0,t.add(l);const c=.8;for(let w=0;w<o;w++){const M=w/o*Math.PI*2,S=Math.cos(M)*c,P=Math.sin(M)*c,C=new z(.22,.15,.22),x=new A({color:s,metalness:.3,roughness:.7,emissive:i,emissiveIntensity:.15}),B=new y(C,x);if(B.position.set(S,.55,P),B.castShadow=!0,B.name=`node_${w}`,w===0&&(B.name="buildingBody"),t.add(B),w<o-1){const I=(w+1)/o*Math.PI*2,L=Math.cos(I)*c,E=Math.sin(I)*c,D=[new T(S,.55,P),new T(L,.55,E)],$=new le().setFromPoints(D),G=new ge({color:i.getHex(),transparent:!0,opacity:.6}),W=new ce($,G);W.name=`conn_${w}`,t.add(W)}}const d=new O(.18,16,16),h=new v({color:i.getHex(),transparent:!0,opacity:.5}),g=new y(d,h);g.position.y=.55,g.name="hub",t.add(g);const f=Oe(t,e,1.1),p=ne(a.name);return p.position.set(0,1.5,0),p.name="workflowLabel",t.add(p),t.position.set(((m=a.position)==null?void 0:m.x)||0,0,((b=a.position)==null?void 0:b.z)||0),{group:t,statusLight:f,label:p}}function Po(a,e){const t=a.group.getObjectByName("hub");t&&t.material instanceof v&&(t.material.opacity=.3+Math.sin(e*.8)*.15)}function ko(a,e,t){for(let i=0;i<t;i++){const o=a.group.getObjectByName(i===0?"buildingBody":`node_${i}`);if(o&&o.material instanceof A){const n=(e*2+i*.5)%(Math.PI*2);o.material.emissiveIntensity=.15+Math.sin(n)*.25}}const s=a.group.getObjectByName("hub");s&&(s.rotation.y+=.02)}function Ao(a,e){var m,b;const t=new Y;t.userData.workflowId=a.id,t.userData.isWorkflow=!0;const s=Ze(a),i=ze(a),o=new z(2.2,.12,1.6),n=new A({color:s,metalness:.2,roughness:.8}),r=new y(o,n);r.position.y=.06,r.castShadow=!0,r.receiveShadow=!0,r.name="buildingBody",t.add(r);const l=new ge({color:i.getHex(),transparent:!0,opacity:.7}),c=Math.min(a.states.length,6);for(let w=0;w<c;w++){const S=-.9+w/c*1.8,P=[new T(S,.13,-.6),new T(S,.13,0),new T(S+.3,.13,.3),new T(S+.3,.13,.6)],C=new le().setFromPoints(P),x=new ce(C,l.clone());x.name=`trace_${w}`,t.add(x);const B=new z(.15,.08,.1),I=new A({color:2763322,metalness:.5,roughness:.3,emissive:i,emissiveIntensity:.1}),L=new y(B,I);L.position.set(S+.3,.16,.6),L.name=`chip_${w}`,t.add(L)}const d=new O(.06,8,8),h=new v({color:i.getHex(),transparent:!0,opacity:.8}),g=new y(d,h);g.position.set(-.9,.18,-.6),g.name="dataFlow",t.add(g);const f=Oe(t,e,.7),p=ne(a.name);return p.position.set(0,1.1,0),p.name="workflowLabel",t.add(p),t.position.set(((m=a.position)==null?void 0:m.x)||0,0,((b=a.position)==null?void 0:b.z)||0),{group:t,statusLight:f,label:p}}function xo(a,e,t){for(let s=0;s<t;s++){const i=a.group.getObjectByName(`chip_${s}`);i&&i.material instanceof A&&(i.material.emissiveIntensity=.05+Math.sin(e*.5+s*.4)*.05)}}function Bo(a,e,t){const s=a.group.getObjectByName("dataFlow");if(s){const i=e*.8%1;s.position.x=-.9+i*1.8,s.position.z=-.6+i*1.2}for(let i=0;i<t;i++){const o=a.group.getObjectByName(`chip_${i}`);o&&o.material instanceof A&&(o.material.emissiveIntensity=.1+Math.sin(e*3+i*.8)*.2)}}function To(a,e){var g,f;const t=new Y;t.userData.workflowId=a.id,t.userData.isWorkflow=!0;const s=ze(a),i=new j(1.2,1.3,.05,32),o=new A({color:1710638,metalness:.7,roughness:.3}),n=new y(i,o);n.position.y=.025,n.receiveShadow=!0,n.name="buildingBody",t.add(n);const r=Math.min(a.states.length,8),l=[];for(let p=0;p<r;p++){const m=p/r*Math.PI*2+p*.3,b=.4+p%3*.25,w=.4+p%2*.4,M=new T(Math.cos(m)*b,w,Math.sin(m)*b);l.push(M);const S=new O(.08,12,12),P=new v({color:s.getHex(),transparent:!0,opacity:.9}),C=new y(S,P);C.position.copy(M),C.name=`star_${p}`,t.add(C)}const c=new ge({color:s.getHex(),transparent:!0,opacity:.25});for(let p=0;p<l.length-1;p++){const m=[l[p],l[p+1]],b=new le().setFromPoints(m),w=new ce(b,c.clone());w.name=`link_${p}`,t.add(w)}const d=Oe(t,e,1.2),h=ne(a.name);return h.position.set(0,1.6,0),h.name="workflowLabel",t.add(h),t.position.set(((g=a.position)==null?void 0:g.x)||0,0,((f=a.position)==null?void 0:f.z)||0),{group:t,statusLight:d,label:h}}function Io(a,e,t){for(let s=0;s<t;s++){const i=a.group.getObjectByName(`star_${s}`);i&&i.material instanceof v&&(i.material.opacity=.5+Math.sin(e*.4+s*1.1)*.3)}}function Do(a,e,t){for(let s=0;s<t;s++){const i=a.group.getObjectByName(`star_${s}`);i&&i.material instanceof v&&(i.material.opacity=.6+Math.sin(e*2.5+s*.7)*.35,i.position.y+=Math.sin(e*1.5+s)*.001)}}function Lo(a,e){var m,b;const t=new Y;t.userData.workflowId=a.id,t.userData.isWorkflow=!0;const s=Ze(a),i=ze(a),o=new j(.8,.9,.1,24),n=new A({color:2763322,metalness:.6,roughness:.4}),r=new y(o,n);r.position.y=.05,r.receiveShadow=!0,t.add(r);const l=new Y;l.name="helixGroup";const c=24,d=1.6,h=.4;for(let w=0;w<2;w++){const M=w*Math.PI,S=[];for(let L=0;L<=c;L++){const E=L/c,D=E*Math.PI*4+M;S.push(new T(Math.cos(D)*h,.2+E*d,Math.sin(D)*h))}const P=S,C=new bs(P),x=new ys(C,c,.04,8,!1),B=new A({color:w===0?s:i,metalness:.3,roughness:.6,emissive:w===0?s:i,emissiveIntensity:.1}),I=new y(x,B);I.castShadow=!0,I.name=w===0?"buildingBody":`strand_${w}`,l.add(I)}const g=Math.min(a.states.length,8);for(let w=0;w<g;w++){const M=(w+.5)/g,S=M*Math.PI*4,P=S+Math.PI,C=.2+M*d,x=new T(Math.cos(S)*h,C,Math.sin(S)*h),B=new T(Math.cos(P)*h,C,Math.sin(P)*h),I=new j(.02,.02,x.distanceTo(B),6),L=new v({color:16777215,transparent:!0,opacity:.3}),E=new y(I,L);E.position.copy(x.clone().add(B).multiplyScalar(.5)),E.lookAt(B),E.rotateX(Math.PI/2),E.name=`rung_${w}`,l.add(E)}t.add(l);const f=Oe(t,e,d+.5),p=ne(a.name);return p.position.set(0,d+.9,0),p.name="workflowLabel",t.add(p),t.position.set(((m=a.position)==null?void 0:m.x)||0,0,((b=a.position)==null?void 0:b.z)||0),{group:t,statusLight:f,label:p}}function Eo(a,e,t){const s=a.group.getObjectByName("helixGroup");s&&(s.rotation.y+=t*.15)}function _o(a,e,t,s){const i=a.group.getObjectByName("helixGroup");i&&(i.rotation.y+=t*.6);for(let o=0;o<s;o++){const n=a.group.getObjectByName(`rung_${o}`);n&&n.material instanceof v&&(n.material.opacity=.2+Math.sin(e*3+o*.8)*.3)}}function Oo(a,e){var C,x;const t=new Y;t.userData.workflowId=a.id,t.userData.isWorkflow=!0;const s=Ze(a),i=ze(a),o=new j(1.3,1.4,.12,32),n=new A({color:3815978,metalness:.7,roughness:.3}),r=new y(o,n);r.position.y=.06,r.receiveShadow=!0,t.add(r);const l=new we(.7,.08,8,24),c=new A({color:s,metalness:.8,roughness:.2}),d=new y(l,c);d.position.y=.5,d.rotation.x=Math.PI/2,d.castShadow=!0,d.name="buildingBody",t.add(d);const h=new Y;h.name="mainGearTeeth";const g=16;for(let B=0;B<g;B++){const I=B/g*Math.PI*2,L=new z(.06,.06,.18),E=new A({color:s,metalness:.8,roughness:.2}),D=new y(L,E);D.position.set(Math.cos(I)*.78,.5,Math.sin(I)*.78),D.lookAt(new T(0,.5,0)),h.add(D)}t.add(h);const f=new we(.35,.06,8,16),p=new A({color:i,metalness:.7,roughness:.3,emissive:i,emissiveIntensity:.1}),m=new y(f,p);m.position.set(.85,.5,.4),m.rotation.x=Math.PI/2,m.name="secGear",t.add(m);const b=new j(.08,.08,.6,12),w=new A({color:8947848,metalness:.9,roughness:.1}),M=new y(b,w);M.position.y=.4,t.add(M);const S=Oe(t,e,1),P=ne(a.name);return P.position.set(0,1.4,0),P.name="workflowLabel",t.add(P),t.position.set(((C=a.position)==null?void 0:C.x)||0,0,((x=a.position)==null?void 0:x.z)||0),{group:t,statusLight:S,label:P}}function zo(a,e,t){const s=a.group.getObjectByName("mainGearTeeth");s&&(s.rotation.y+=t*.1);const i=a.group.getObjectByName("secGear");i&&(i.rotation.z-=t*.15)}function Go(a,e,t){const s=a.group.getObjectByName("mainGearTeeth");s&&(s.rotation.y+=t*.5);const i=a.group.getObjectByName("secGear");i&&(i.rotation.z-=t*.75)}function Ro(a,e){switch(a.style||"flowchart"){case"circuit-board":return Ao(a,e);case"constellation":return To(a,e);case"helix":return Lo(a,e);case"clockwork":return Oo(a,e);case"flowchart":default:return Co(a,e)}}function Ho(a,e,t,s){const i=e.style||"flowchart",o=Math.min(e.states.length,8);switch(i){case"flowchart":Po(a,t);break;case"circuit-board":xo(a,t,o);break;case"constellation":Io(a,t,o);break;case"helix":Eo(a,t,s);break;case"clockwork":zo(a,t,s);break}}function Wo(a,e,t,s){const i=e.style||"flowchart",o=Math.min(e.states.length,8),n=a.group.getObjectByName("statusGlow"),r=Math.sin(t*3)*.2+.8;switch(n&&n.material instanceof v&&(n.material.opacity=.3*r),i){case"flowchart":ko(a,t,o);break;case"circuit-board":Bo(a,t,o);break;case"constellation":Do(a,t,o);break;case"helix":_o(a,t,s,o);break;case"clockwork":Go(a,t,s);break}}function Fo(a,e){const t=a.group.getObjectByName("statusGlow"),s=Math.sin(e*2)*.5+.5;t&&t.material instanceof v&&(t.material.opacity=.4*s)}class No{constructor(e){u(this,"scene");u(this,"workflowMeshes",new Map);u(this,"animationTime",0);u(this,"brightness",1);u(this,"statusProvider",null);u(this,"onWorkflowClick",null);u(this,"onWorkflowDoubleClick",null);this.scene=e}setOnWorkflowClick(e){this.onWorkflowClick=e}setOnWorkflowDoubleClick(e){this.onWorkflowDoubleClick=e}setStatusProvider(e){this.statusProvider=e}setBrightness(e){this.brightness=e;for(const t of this.workflowMeshes.values()){const s=t.group.getObjectByName("statusGlow");s&&s.material instanceof v&&(s.material.opacity=.3*e),t.group.traverse(i=>{if(i instanceof y&&i.material instanceof A){const o=i.material;o.userData.baseEmissiveIntensity===void 0&&(o.userData.baseEmissiveIntensity=o.emissiveIntensity||1),o.emissiveIntensity=o.userData.baseEmissiveIntensity*e}})}}addWorkflow(e){var o;this.removeWorkflow(e.id);const t=((o=this.statusProvider)==null?void 0:o.call(this,e.id))||"idle",s=Ro(e,t);s.group.userData.style=e.style||"flowchart",s.group.userData.color=e.color||"";const i=e.scale||1;s.group.scale.setScalar(i),this.scene.add(s.group),this.workflowMeshes.set(e.id,s)}removeWorkflow(e){const t=this.workflowMeshes.get(e);t&&(this.scene.remove(t.group),this.disposeGroup(t.group),this.workflowMeshes.delete(e))}updateWorkflow(e){var g,f,p,m;const t=this.workflowMeshes.get(e.id);if(!t){this.addWorkflow(e);return}const s=t.group.userData.style,i=t.group.userData.color;if(s!==(e.style||"flowchart")||i!==(e.color||"")){this.removeWorkflow(e.id),this.addWorkflow(e);return}t.group.position.set(((g=e.position)==null?void 0:g.x)||0,0,((f=e.position)==null?void 0:f.z)||0);const o=e.scale||1;t.group.scale.setScalar(o);const n=((p=this.statusProvider)==null?void 0:p.call(this,e.id))||"idle",r=es[n],l=t.group.getObjectByName("statusLight");l&&l.material instanceof v&&l.material.color.setHex(r);const c=t.group.getObjectByName("statusGlow");c&&c.material instanceof v&&c.material.color.setHex(r),((m=t.label.material.map)==null?void 0:m.image)&&Jt(t,e.name)}setWorkflowPosition(e,t){const s=this.workflowMeshes.get(e);s&&s.group.position.set(t.x,0,t.z)}getWorkflowAtPosition(e,t){for(const[s,i]of this.workflowMeshes){const o=t.get(s);if(!o)continue;const n=o.scale||1,r=1.5*n,l=1.5*n,c=Math.abs(e.x-i.group.position.x),d=Math.abs(e.z-i.group.position.z);if(c<=r&&d<=l)return o}return null}getWorkflowMeshes(){return Array.from(this.workflowMeshes.values()).map(e=>e.group)}getWorkflowMeshData(){return this.workflowMeshes}highlightWorkflow(e){for(const t of this.workflowMeshes.values()){const s=t.group.getObjectByName("buildingBody");s&&s.material instanceof A&&s.material.emissive.setHex(0)}if(e){const t=this.workflowMeshes.get(e);if(t){const s=t.group.getObjectByName("buildingBody");s&&s.material instanceof A&&s.material.emissive.setHex(2236996)}}}syncFromDefinitions(e){for(const t of this.workflowMeshes.keys())e.has(t)||this.removeWorkflow(t);for(const t of e.values())this.workflowMeshes.has(t.id)?this.updateWorkflow(t):this.addWorkflow(t)}update(e,t){var s;this.animationTime+=e;for(const[i,o]of this.workflowMeshes){const n=t.get(i);if(!n)continue;const r=((s=this.statusProvider)==null?void 0:s.call(this,i))||"idle";Ho(o,n,this.animationTime,e),r==="running"?Wo(o,n,this.animationTime,e):r==="error"&&Fo(o,this.animationTime)}}disposeGroup(e){e.traverse(t=>{if(t instanceof y&&(t.geometry.dispose(),Array.isArray(t.material)?t.material.forEach(s=>s.dispose()):t.material.dispose()),t instanceof K){const s=t.material;s.map&&s.map.dispose(),s.dispose()}t instanceof ce&&(t.geometry.dispose(),t.material instanceof Pe&&t.material.dispose())})}dispose(){for(const e of this.workflowMeshes.keys())this.removeWorkflow(e)}}const Le=class Le{constructor(e,t,s,i,o,n){u(this,"scene");u(this,"characterLoader");u(this,"characterFactory");u(this,"movementAnimator");u(this,"proceduralAnimator");u(this,"effectsManager");u(this,"agentMeshes",new Map);u(this,"pendingAgents",[]);u(this,"modelsReady",!1);u(this,"characterScale",.5);u(this,"brightness",1);u(this,"idleAnimation",Q.SIT);u(this,"workingAnimation",Q.WALK);u(this,"previousAgentStatuses",new Map);u(this,"modelStyle",{saturation:1,roughness:-1,metalness:-1,emissiveBoost:0,envMapIntensity:-1,wireframe:!1,colorMode:"normal"});u(this,"onAgentMeshesChanged",null);u(this,"onProceduralCacheInvalidated",null);u(this,"onToast",null);this.scene=e,this.characterLoader=t,this.characterFactory=s,this.movementAnimator=i,this.proceduralAnimator=o,this.effectsManager=n}setOnAgentMeshesChanged(e){this.onAgentMeshesChanged=e}setOnProceduralCacheInvalidated(e){this.onProceduralCacheInvalidated=e}setOnToast(e){this.onToast=e}getAgentMeshes(){return this.agentMeshes}isModelsReady(){return this.modelsReady}setCharacterScale(e){this.characterScale=e;for(const t of this.agentMeshes.values()){const s=t.group.getObjectByName("characterBody");if(s){const i=s.userData.customModelScale??1,o=t.group.userData.isBoss===!0,n=o?1.5:1;s.scale.setScalar(i*e*n);const r=t.group.getObjectByName("statusBar");if(r){const c=new nt().setFromObject(s).max.y,d=o?.2:.3,h=o?3:2.2;r.position.y=Math.min(Math.max(c,1)+d,h)}}}}setBrightness(e){this.brightness=e;for(const t of this.agentMeshes.values())this.applyStyleToMesh(t.group)}setModelStyle(e){Object.assign(this.modelStyle,e);for(const t of this.agentMeshes.values())this.applyStyleToMesh(t.group)}getModelStyle(){return{...this.modelStyle}}injectColorShader(e){const t=this.modelStyle.saturation,s=Le.COLOR_MODE_INDEX[this.modelStyle.colorMode]??0;if(e.userData.hasColorShader)e.userData.shader&&(e.userData.shader.uniforms.uSaturation.value=t,e.userData.shader.uniforms.uColorMode.value=s);else{e.userData.hasColorShader=!0;const i=this;e.onBeforeCompile=o=>{o.uniforms.uSaturation={value:i.modelStyle.saturation},o.uniforms.uColorMode={value:Le.COLOR_MODE_INDEX[i.modelStyle.colorMode]??0},o.fragmentShader=o.fragmentShader.replace("#include <common>",`#include <common>
|
|
2
2
|
uniform float uSaturation;
|
|
3
3
|
uniform int uColorMode;
|
|
4
4
|
|