gaesup-world 1.0.19 → 1.0.21

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/runtime.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("reflect-metadata");const m=require("./index-CHw7l-nB.cjs"),le=require("./runtimeFilter-W6iMw1pL.cjs"),b=require("./index-BOdJzeGD.cjs"),de=require("three"),p=require("./gaesupStore-2zKBYTYo.cjs"),W=require("./index-B0m-VWUU.cjs"),d=require("react/jsx-runtime"),x=require("./index-B414uKZc.cjs"),g=require("react"),ue=require("@react-three/fiber"),U=require("@react-three/rapier"),I=require("./index-CeK0uKiq.cjs");function fe(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const F=fe(de);class T{cellSize;cells=new Map;objectPositions=new Map;constructor(e={}){this.cellSize=e.cellSize??10}static zigZag(e){return e>=0?e*2:-e*2-1}static pair(e,t){const r=T.zigZag(e),a=T.zigZag(t),n=r+a;return n*(n+1)/2+a}getCellKey(e,t){const r=Math.floor(e/this.cellSize),a=Math.floor(t/this.cellSize);return T.pair(r,a)}add(e,t){this.remove(e);const r=this.getCellKey(t.x,t.z);this.cells.has(r)||this.cells.set(r,new Set),this.cells.get(r).add(e),this.objectPositions.set(e,t.clone())}remove(e){const t=this.objectPositions.get(e);if(t){const r=this.getCellKey(t.x,t.z),a=this.cells.get(r);a&&(a.delete(e),a.size===0&&this.cells.delete(r)),this.objectPositions.delete(e)}}update(e,t){const r=this.objectPositions.get(e);if(!r){this.add(e,t);return}if(r.equals(t))return;const a=this.getCellKey(r.x,r.z),n=this.getCellKey(t.x,t.z);if(a!==n){const i=this.cells.get(a);i&&(i.delete(e),i.size===0&&this.cells.delete(a));const o=this.cells.get(n)??new Set;o.add(e),this.cells.set(n,o)}r.copy(t)}getNearby(e,t,r){const a=r??[];r&&(r.length=0);const n=Math.ceil(t/this.cellSize),i=Math.floor(e.x/this.cellSize),o=Math.floor(e.z/this.cellSize),l=t*t;for(let f=i-n;f<=i+n;f++)for(let u=o-n;u<=o+n;u++){const h=T.pair(f,u),v=this.cells.get(h);if(v)for(const R of v){const S=this.objectPositions.get(R);if(!S)continue;const D=e.x-S.x,C=e.y-S.y,B=e.z-S.z;D*D+C*C+B*B<=l&&a.push(R)}}return a}clear(){this.cells.clear(),this.objectPositions.clear()}get size(){return this.objectPositions.size}}var pe=Object.defineProperty,ye=Object.getOwnPropertyDescriptor,L=(s,e,t,r)=>{for(var a=r>1?void 0:r?ye(e,t):e,n=s.length-1,i;n>=0;n--)(i=s[n])&&(a=(r?i(e,t,a):i(a))||a);return r&&a&&pe(e,t,a),a};exports.WorldSystem=class{objects=new Map;interactionEvents=[];spatial=new T({cellSize:10});raycaster=new F.Raycaster;tempVector=new F.Vector3;nearbyIds=[];nearbyIds2=[];async init(){}update(e){}dispose(){this.cleanup()}addObject(e){this.objects.set(e.id,e),this.spatial.add(e.id,e.position)}removeObject(e){return this.objects.get(e)&&this.spatial.remove(e),this.objects.delete(e)}getObject(e){return this.objects.get(e)}getAllObjects(){return Array.from(this.objects.values())}getObjectsByType(e){return this.getAllObjects().filter(t=>t.type===e)}updateObject(e,t){const r=this.objects.get(e);return r?(Object.assign(r,t),t.position&&this.spatial.update(e,t.position),!0):!1}getObjectsInRadius(e,t){const r=this.spatial.getNearby(e,t,this.nearbyIds),a=[];for(const n of r){const i=this.objects.get(n);i&&a.push(i)}return a}checkCollisions(e){const t=this.objects.get(e);if(!t||!t.boundingBox)return[];const r=t.boundingBox.max.distanceTo(t.boundingBox.min),a=this.spatial.getNearby(t.position,r,this.nearbyIds2),n=[];for(const i of a){if(i===e)continue;const o=this.objects.get(i);!o||!o.boundingBox||t.boundingBox.intersectsBox(o.boundingBox)&&n.push(o)}return n}processInteraction(e){this.interactionEvents.push(e),this.interactionEvents.length>1e3&&(this.interactionEvents=this.interactionEvents.slice(-500))}getRecentEvents(e=1e3){const t=Date.now();return this.interactionEvents.filter(r=>t-r.timestamp<=e)}raycast(e,t,r=100){this.raycaster.set(e,t),this.raycaster.near=0,this.raycaster.far=r;const a=this.spatial.getNearby(e,r,this.nearbyIds);for(const n of a){const i=this.objects.get(n);if(i&&i.boundingBox){const o=this.raycaster.ray.intersectBox(i.boundingBox,this.tempVector);if(o)return{object:i,distance:e.distanceTo(o),point:o.clone()}}}return null}cleanup(){this.objects.clear(),this.interactionEvents.length=0,this.spatial.clear()}};L([p.HandleError()],exports.WorldSystem.prototype,"init",1);L([p.Profile(),p.HandleError()],exports.WorldSystem.prototype,"update",1);L([p.HandleError()],exports.WorldSystem.prototype,"dispose",1);exports.WorldSystem=L([p.RegisterSystem("world")],exports.WorldSystem);var me=Object.defineProperty,ge=Object.getOwnPropertyDescriptor,z=(s,e,t,r)=>{for(var a=r>1?void 0:r?ge(e,t):e,n=s.length-1,i;n>=0;n--)(i=s[n])&&(a=(r?i(e,t,a):i(a))||a);return r&&a&&me(e,t,a),a};exports.WorldBridge=class extends b.CoreBridge{buildEngine(e,t){const r=new exports.WorldSystem,a={...t?.selectedObjectId!==void 0?{selectedObjectId:t.selectedObjectId}:{},interactionMode:t?.interactionMode??"view",showDebugInfo:t?.showDebugInfo??!1};return{system:r,state:a,dispose:()=>r.dispose()}}executeCommand(e,t,r){const{system:a,state:n}=e;switch(t.type){case"addObject":const{id:i,...o}=t.data,l=typeof i=="string"&&i.length>0?i:this.generateId(),f={...o,id:l};a.addObject(f);break;case"removeObject":a.removeObject(t.data.id),n.selectedObjectId===t.data.id&&delete n.selectedObjectId;break;case"updateObject":a.updateObject(t.data.id,t.data.updates);break;case"selectObject":t.data.id!==void 0?n.selectedObjectId=t.data.id:delete n.selectedObjectId;break;case"setInteractionMode":n.interactionMode=t.data.mode;break;case"toggleDebugInfo":n.showDebugInfo=!n.showDebugInfo;break;case"interact":const u=a.getObject(t.data.objectId);if(u&&u.canInteract){const h={type:"custom",object1Id:t.data.objectId,timestamp:Date.now(),data:{action:t.data.action}};a.processInteraction(h)}break;case"cleanup":a.cleanup(),delete n.selectedObjectId,n.interactionMode="view",n.showDebugInfo=!1;break}}createSnapshot(e,t){const{system:r,state:a}=e;return{objects:r.getAllObjects(),...a.selectedObjectId!==void 0?{selectedObjectId:a.selectedObjectId}:{},interactionMode:a.interactionMode,showDebugInfo:a.showDebugInfo,events:r.getRecentEvents(),objectsInRadius:(n,i)=>r.getObjectsInRadius(n,i),objectsByType:n=>r.getObjectsByType(n),raycast:(n,i)=>r.raycast(n,i)?.object||null}}addObject(e,t){const r=t.id,a=typeof r=="string"&&r.length>0?r:this.generateId();return this.execute(e,{type:"addObject",data:{...t,id:a}}),a}removeObject(e,t){this.execute(e,{type:"removeObject",data:{id:t}})}updateObject(e,t,r){this.execute(e,{type:"updateObject",data:{id:t,updates:r}})}selectObject(e,t){this.execute(e,{type:"selectObject",data:t!==void 0?{id:t}:{}})}setInteractionMode(e,t){this.execute(e,{type:"setInteractionMode",data:{mode:t}})}toggleDebugInfo(e){this.execute(e,{type:"toggleDebugInfo"})}interact(e,t,r){this.execute(e,{type:"interact",data:{objectId:t,action:r}})}cleanup(e){this.execute(e,{type:"cleanup"})}getObjectsInRadius(e,t,r){const a=this.getEngine(e);return a?a.system.getObjectsInRadius(t,r):[]}getObjectsByType(e,t){const r=this.getEngine(e);return r?r.system.getObjectsByType(t):[]}raycast(e,t,r){const a=this.getEngine(e);return a&&a.system.raycast(t,r)?.object||null}generateId(){return`world_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}};z([b.ValidateCommand()],exports.WorldBridge.prototype,"executeCommand",1);z([b.LogSnapshot(),b.CacheSnapshot(16)],exports.WorldBridge.prototype,"createSnapshot",1);exports.WorldBridge=z([b.DomainBridge("world"),b.EnableEventLog()],exports.WorldBridge);const he={isRiderOn:!1,position:U.vec3(),rotation:U.euler(),offset:U.vec3(),visible:!0};function ve(){const{gameStates:s,updateGameStates:e,activeState:t}=b.useStateSystem(),r=p.useGaesupStore(c=>c.rideable),a=p.useGaesupStore(c=>c.urls),n=p.useGaesupStore(c=>c.setMode),i=p.useGaesupStore(c=>c.setRideable),o=p.useGaesupStore(c=>c.setUrls),{getSizesByUrls:l}=b.useGaesupGltf(),f=g.useCallback(c=>c==="airplane"?"airplane":"vehicle",[]),u=g.useCallback(c=>{const y={},j=c.ridingUrl??a.characterUrl;if(typeof j=="string"&&j.length>0&&(y.ridingUrl=j),c.objectType==="airplane"){y.airplaneUrl=c.url??"",o(y);return}c.objectType&&(y.vehicleUrl=c.url??"",y.wheelUrl=c.wheelUrl??""),o(y)},[o,a]),h=g.useCallback(c=>{const y=r[c];if(!y?.position)return;const j=y.objectType,{vehicleUrl:ie,airplaneUrl:oe,characterUrl:ce}=l({...a});!(j==="airplane"?oe:ie)||!ce||(e({canRide:!1,isRiding:!1,currentRideable:void 0}),i(c,{...y,visible:!0,position:t.position.clone()}))},[r,l,a,e,i,t.position]),v=g.useCallback(async()=>{if(s.canRide&&s.nearbyRideable&&!s.isRiding){const{objectkey:c,objectType:y}=s.nearbyRideable,j=r[c];if(!j)return;u(j),n({type:f(y)}),e({currentRideable:s.nearbyRideable,isRiding:!0,canRide:!1,nearbyRideable:void 0}),i(c,{...j,visible:!1})}},[s.canRide,s.nearbyRideable,s.isRiding,r,u,n,f,e,i]),R=g.useCallback(async()=>{s.isRiding&&s.currentRideable&&(h(s.currentRideable.objectkey),n({type:"character"}),e({isRiding:!1,currentRideable:void 0}))},[s.isRiding,s.currentRideable,h,n,e]);g.useEffect(()=>{const c=y=>{y.code==="KeyF"&&(s.canRide&&s.nearbyRideable?v():s.isRiding&&R())};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[s.canRide,s.nearbyRideable,s.isRiding,v,R]);const S=g.useCallback(c=>{i(c.objectkey,{...he,...c})},[i]),D=g.useCallback(c=>{i(c.objectkey,c)},[i]),C=c=>r[c],B=g.useCallback(async(c,y)=>{if((c.other.rigidBodyObject&&c.other.rigidBodyObject.name==="character"||c.other.rigidBodyObject&&!c.other.rigidBodyObject.name||c.other.rigidBody)&&!s.isRiding){if(!y.objectType)return;e({nearbyRideable:{id:y.objectkey,objectkey:y.objectkey,objectType:y.objectType,type:"rideable",maxSpeed:0,acceleration:0,deceleration:0,isOccupied:!1,controls:{forward:!1,backward:!1,left:!1,right:!1,brake:!1},name:y.objectType==="vehicle"?"차량":"비행기",...y.rideMessage?{rideMessage:y.rideMessage}:{},...y.exitMessage?{exitMessage:y.exitMessage}:{},...y.displayName?{displayName:y.displayName}:{}},canRide:!0})}},[s.isRiding,e]),M=g.useCallback(async c=>{(c.other.rigidBodyObject&&c.other.rigidBodyObject.name==="character"||c.other.rigidBodyObject&&!c.other.rigidBodyObject.name||c.other.rigidBody)&&e({nearbyRideable:void 0,canRide:!1})},[e]);return{initRideable:S,updateRideable:D,getRideable:C,onRideableNear:B,onRideableLeave:M,enterRideable:v,exitRideable:R,landing:h}}const E="default",be=s=>{const e=p.BridgeFactory.getOrCreate("world");if(e){e.register(E);const t=e;t.__gaesupWorldSliceUnsubscribe?.(),t.__gaesupWorldSliceUnsubscribe=e.subscribe(r=>{s({objects:r.objects,selectedObjectId:r.selectedObjectId,interactionMode:r.interactionMode,showDebugInfo:r.showDebugInfo,events:r.events,loading:!1,error:void 0})})}return{objects:[],selectedObjectId:void 0,interactionMode:"view",showDebugInfo:!1,events:[],loading:!1,error:void 0,addObject:t=>{if(!e)return"";s({loading:!0,error:void 0});try{const r=e.addObject(E,t);return s({loading:!1}),r}catch(r){return s({loading:!1,error:r instanceof Error?r.message:"Unknown error"}),""}},removeObject:t=>{if(!e)return!1;s({loading:!0,error:void 0});try{return e.removeObject(E,t),s({loading:!1}),!0}catch(r){return s({loading:!1,error:r instanceof Error?r.message:"Unknown error"}),!1}},updateObject:(t,r)=>{if(!e)return!1;s({loading:!0,error:void 0});try{return e.updateObject(E,t,r),s({loading:!1}),!0}catch(a){return s({loading:!1,error:a instanceof Error?a.message:"Unknown error"}),!1}},selectObject:t=>{e&&e.selectObject(E,t)},setInteractionMode:t=>{e&&e.setInteractionMode(E,t)},toggleDebugInfo:()=>{e&&e.toggleDebugInfo(E)},setLoading:t=>{s({loading:t})},setError:t=>{s({error:t})},clearEvents:()=>{s({events:[]})},getBridge:()=>e,getObjectsInRadius:(t,r)=>e?e.getObjectsInRadius(E,t,r):[],getObjectsByType:t=>e?e.getObjectsByType(E,t):[],raycast:(t,r)=>e?e.raycast(E,t,r):null,interact:(t,r)=>{e&&e.interact(E,t,r)},cleanup:()=>{e&&e.cleanup(E)}}};var Se=Object.defineProperty,Re=Object.getOwnPropertyDescriptor,O=(s,e,t,r)=>{for(var a=Re(e,t),n=s.length-1,i;n>=0;n--)(i=s[n])&&(a=i(e,t,a)||a);return a&&Se(e,t,a),a};const we="1.0.0",P="gaesup_world_save_",G="base64-json:",Z="gaesup-world:gzip-json:v1";class w{version;storage;fileWriter;now;constructor(e={}){this.version=e.version??we,this.storage=e.storage,this.fileWriter=e.fileWriter,this.now=e.now??Date.now}async save(e,t,r={}){try{const a=this.createSaveData(e,t,r);return r.compress?await this.saveCompressed(a):await this.saveUncompressed(a)}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error occurred"}}}async load(e,t={}){try{const r=`${P}${e}`,a=this.getStorage().getItem(r);if(!a)throw new Error(`Save data not found: ${e}`);const n=await this.parseStoredSaveData(a);if(!this.validateSaveData(n))throw new Error("Invalid save data format");return{success:!0,data:{...n,world:this.filterWorldData(n.world,t)}}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Failed to load save data"}}}async saveToFile(e,t,r,a={}){try{const n=this.createSaveData(e,r,a);return await this.writeFile(t,n),{success:!0,data:n}}catch(n){return{success:!1,error:n instanceof Error?n.message:"Failed to save file"}}}async loadFromFile(e,t={}){try{const r=await e.text(),a=JSON.parse(r);if(!this.validateSaveData(a))throw new Error("Invalid save file format");return{success:!0,data:{...a,world:this.filterWorldData(a.world,t)}}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Failed to load file"}}}listSaves(){const e=[];let t;try{t=this.getStorage()}catch(r){return console.error("Failed to list saves:",r),e}for(let r=0;r<t.length;r++){const a=t.key(r);if(a&&a.startsWith(P))try{const n=a.substring(P.length),i=t.getItem(a);if(i){const o=this.parseStoredSaveDataSync(i);e.push({id:n,timestamp:o.timestamp,...o.metadata?{metadata:o.metadata}:{}})}}catch(n){console.error(`Failed to parse save: ${a}`,n)}}return e.sort((r,a)=>a.timestamp-r.timestamp)}deleteSave(e){try{const t=`${P}${e}`;return this.getStorage().removeItem(t),!0}catch(t){return console.error("Failed to delete save:",t),!1}}filterWorldData(e,t){const r={...e};return t.includeBuildings===!1&&(r.buildings={wallGroups:[],tileGroups:[],blocks:[],meshes:[]}),t.includeNPCs===!1&&(r.npcs=[]),t.includeEnvironment===!1&&(r.environment={lighting:{ambientIntensity:1,directionalIntensity:1,directionalPosition:{x:0,y:10,z:0}}}),t.includeCamera===!1&&delete r.camera,r}createSaveData(e,t,r={}){const a=this.now();return{version:this.version,timestamp:a,world:this.filterWorldData(e,r),...t?{metadata:{...t,createdAt:t.createdAt||a,updatedAt:a}}:{}}}getStorage(){if(this.storage)return this.storage;if(typeof localStorage>"u")throw new Error("Legacy save storage is not available in this environment");return localStorage}async writeFile(e,t){if(this.fileWriter){await this.fileWriter(e,t);return}if(typeof document>"u"||typeof URL>"u"||typeof Blob>"u")throw new Error("File download is not available in this environment");const r=new Blob([JSON.stringify(t,null,2)],{type:"application/json"}),a=URL.createObjectURL(r),n=document.createElement("a");n.href=a,n.download=e.endsWith(".json")?e:`${e}.json`,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(a)}async saveUncompressed(e){const t=`${e.world.id}_${e.timestamp}`,r=`${P}${t}`;try{return this.getStorage().setItem(r,JSON.stringify(e)),{success:!0,data:e}}catch(a){throw a instanceof Error&&a.name==="QuotaExceededError"?new Error("Storage quota exceeded. Please delete some saves."):a}}async saveCompressed(e){const t=await this.compressData(e),r=`${e.world.id}_${e.timestamp}`,a=`${P}${r}`;try{return this.getStorage().setItem(a,t),{success:!0,data:e}}catch(n){throw n instanceof Error&&n.name==="QuotaExceededError"?new Error("Storage quota exceeded. Please delete some saves."):n}}async compressData(e){const t=JSON.stringify(e);if(!H())return`${G}${$(V(t))}`;const r=await this.gzipBytes(V(t)),a={encoding:Z,version:e.version,timestamp:e.timestamp,worldId:e.world.id,worldName:e.world.name,...e.metadata?{metadata:e.metadata}:{},payload:$(r)};return JSON.stringify(a)}async decompressData(e){const t=X(e),r=await this.gunzipBytes(t),a=Q(r);return JSON.parse(a)}async parseStoredSaveData(e){if(e.startsWith("{")){const t=JSON.parse(e);return q(t)?this.decompressData(t.payload):t}return e.startsWith(G)?_(e.slice(G.length)):_(e)}parseStoredSaveDataSync(e){if(e.startsWith("{")){const t=JSON.parse(e);return q(t)?{version:t.version,timestamp:t.timestamp,world:{id:t.worldId,name:t.worldName,buildings:{wallGroups:[],tileGroups:[],blocks:[],meshes:[]},npcs:[],environment:{lighting:{ambientIntensity:1,directionalIntensity:1,directionalPosition:{x:0,y:10,z:0}}}},...t.metadata?{metadata:t.metadata}:{}}:t}return e.startsWith(G)?_(e.slice(G.length)):_(e)}async gzipBytes(e){if(!H())return e;const t=new Blob([e]).stream().pipeThrough(new CompressionStream("gzip"));return new Uint8Array(await new Response(t).arrayBuffer())}async gunzipBytes(e){if(!Ee())return e;const t=new Blob([e]).stream().pipeThrough(new DecompressionStream("gzip"));return new Uint8Array(await new Response(t).arrayBuffer())}validateSaveData(e){return e!==null&&typeof e=="object"&&"version"in e&&"timestamp"in e&&"world"in e&&typeof e.version=="string"&&typeof e.timestamp=="number"&&e.world&&typeof e.world.id=="string"&&typeof e.world.name=="string"}}O([p.HandleError(),p.Profile(),p.Timeout(5e3)],w.prototype,"save");O([p.HandleError(),p.Profile(),p.Timeout(5e3)],w.prototype,"load");O([p.HandleError(),p.Profile()],w.prototype,"saveToFile");O([p.HandleError(),p.Profile()],w.prototype,"loadFromFile");O([p.MonitorMemory(10)],w.prototype,"listSaves");O([p.HandleError()],w.prototype,"deleteSave");O([p.Profile()],w.prototype,"filterWorldData");O([p.Profile()],w.prototype,"createSaveData");O([p.HandleError()],w.prototype,"saveUncompressed");O([p.HandleError()],w.prototype,"saveCompressed");O([p.Profile()],w.prototype,"compressData");O([p.Profile()],w.prototype,"decompressData");function $(s){let e="";for(let r=0;r<s.length;r+=32768)e+=String.fromCharCode(...s.subarray(r,r+32768));return btoa(e)}function X(s){const e=atob(s),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}function _(s){return JSON.parse(Q(X(s)))}function V(s){if(typeof TextEncoder<"u")return new TextEncoder().encode(s);const e=unescape(encodeURIComponent(s)),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}function Q(s){if(typeof TextDecoder<"u")return new TextDecoder().decode(s);let e="";const t=32768;for(let r=0;r<s.length;r+=t)e+=String.fromCharCode(...s.subarray(r,r+t));return decodeURIComponent(escape(e))}function H(){return typeof CompressionStream<"u"&&typeof Blob<"u"&&typeof Response<"u"&&typeof new Blob().stream=="function"}function Ee(){return typeof DecompressionStream<"u"&&typeof Blob<"u"&&typeof Response<"u"&&typeof new Blob().stream=="function"}function q(s){if(!s||typeof s!="object")return!1;const e=s;return e.encoding===Z&&typeof e.version=="string"&&typeof e.timestamp=="number"&&typeof e.worldId=="string"&&typeof e.worldName=="string"&&typeof e.payload=="string"}const Oe=()=>({});function J(s,e,t){const{buildingStore:r,npcStore:a,cameraStore:n}=s;if(!r)throw new Error("Building store not initialized");const i=r.getState(),o=n?.getState(),l=o?{position:o.position,rotation:o.rotation,mode:o.mode,...o.settings?{settings:o.settings}:{}}:void 0;return{id:e,name:t,buildings:{wallGroups:Array.from(i.wallGroups.values()),tileGroups:Array.from(i.tileGroups.values()),blocks:Array.from(i.blocks),meshes:Array.from(i.meshes.values())},npcs:a?Array.from(a.getState().instances.values()):[],environment:m.DEFAULT_WORLD_SAVE_ENVIRONMENT,...l?{camera:l}:{}}}function je(s,e){if(!s||!e)return;const t=s.getState();if(typeof t.hydrate=="function"){t.hydrate(e);return}t.wallGroups.clear(),t.tileGroups.clear(),t.meshes.clear(),t.blocks=[],e.wallGroups.forEach(r=>{t.wallGroups.set(r.id,r)}),e.tileGroups.forEach(r=>{t.tileGroups.set(r.id,r)}),e.meshes.forEach(r=>{t.meshes.set(r.id,r)}),t.blocks=[...e.blocks??[]]}function xe(s,e){if(!s||!e)return;const t=s.getState();t.instances.clear(),e.forEach(r=>{t.instances.set(r.id,r)})}function Ie(s,e){!s||!e||s.setState({position:e.position,rotation:e.rotation,mode:e.mode,settings:e.settings||{}})}function K(s,e){je(s.buildingStore,e.buildings),xe(s.npcStore,e.npcs),Ie(s.cameraStore,e.camera)}function k(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function De(s){return s.replace(/\.json$/i,"")}function Y(s){return k(s)&&typeof s.version=="number"&&typeof s.savedAt=="number"&&k(s.domains)}function A(s){return k(s)&&s.kind==="gaesup.save-system"&&typeof s.worldId=="string"&&typeof s.worldName=="string"&&Y(s.blob)}async function N(s){return(await s.list()).map(t=>({id:t,timestamp:m.parseWorldSaveTimestamp(t)})).sort((t,r)=>r.timestamp-t.timestamp)}function Ce(s,e){if(typeof document>"u"||typeof URL>"u"||typeof Blob>"u")throw new Error("File download is not available in this environment");const t=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),r=URL.createObjectURL(t),a=document.createElement("a");a.href=r,a.download=s.endsWith(".json")?s:`${s}.json`,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(r)}async function Be(s){const e=JSON.parse(await s.text());if(A(e)||Y(e))return e;throw new Error("Invalid SaveSystem file format")}function ee(s={}){const e=s.getStores??Oe,t=s.saveSystem;return(r,a)=>({saveLoadManager:s.saveLoadManager??new w,currentSaveId:null,saves:[],isSaving:!1,isLoading:!1,lastError:null,saveWorld:async(n,i,o,l)=>{r({isSaving:!0,lastError:null});try{if(t){const h=Date.now(),v=`${n}_${h}`;await t.save(v),r({currentSaveId:v,saves:await N(t)});return}const f=J(e(),n,i),u=await a().saveLoadManager.save(f,o,l);if(u.success){const h=`${n}_${u.data.timestamp}`;r({currentSaveId:h}),a().refreshSaveList()}else throw new Error(u.error)}catch(f){throw r({lastError:f instanceof Error?f.message:"Save failed"}),f}finally{r({isSaving:!1})}},loadWorld:async(n,i)=>{r({isLoading:!0,lastError:null});try{if(t){if(!await t.load(n))throw new Error(`Save data not found: ${n}`);return r({currentSaveId:n}),m.createSaveDataFromSaveSystem(t,n)}const o=await a().saveLoadManager.load(n,i);if(o.success&&o.data)return K(e(),o.data.world),r({currentSaveId:n}),o.data;throw new Error(o.error)}catch(o){return r({lastError:o instanceof Error?o.message:"Load failed"}),null}finally{r({isLoading:!1})}},saveToFile:async(n,i,o,l,f)=>{r({isSaving:!0,lastError:null});try{if(t){const v={kind:"gaesup.save-system",version:1,worldId:n,worldName:i,blob:t.createBlob(o),...l?{metadata:l}:{}};Ce(o,v);return}const u=J(e(),n,i),h=await a().saveLoadManager.saveToFile(u,o,l,f);if(!h.success)throw new Error(h.error)}catch(u){throw r({lastError:u instanceof Error?u.message:"Save to file failed"}),u}finally{r({isSaving:!1})}},loadFromFile:async(n,i)=>{r({isLoading:!0,lastError:null});try{if(t){const l=await Be(n),f=A(l)?l.blob:l;t.hydrateBlob(f,n.name);const u=A(l)?l.worldId:De(n.name),h=A(l)?l.worldName:u,v=f.savedAt,R={version:String(f.version),timestamp:v,world:m.createWorldDataFromSaveDomains(f.domains,u,h)},S=A(l)?m.normalizeSaveMetadata(l.metadata,v):void 0;return S?{...R,metadata:S}:R}const o=await a().saveLoadManager.loadFromFile(n,i);if(o.success&&o.data)return K(e(),o.data.world),o.data;throw new Error(o.error)}catch(o){return r({lastError:o instanceof Error?o.message:"Load from file failed"}),null}finally{r({isLoading:!1})}},refreshSaveList:()=>{if(t){N(t).then(i=>r({saves:i})).catch(i=>{r({lastError:i instanceof Error?i.message:"Failed to list saves"})});return}const n=a().saveLoadManager.listSaves();r({saves:n})},deleteSave:n=>{if(t){(async()=>{try{await t.remove(n);const o=await N(t);r({saves:o,...a().currentSaveId===n?{currentSaveId:null}:{}})}catch(o){r({lastError:o instanceof Error?o.message:"Failed to delete save"})}})();return}a().saveLoadManager.deleteSave(n)&&(a().refreshSaveList(),a().currentSaveId===n&&r({currentSaveId:null}))},clearError:()=>{r({lastError:null})}})}const Pe=ee();function te({object:s,selected:e=!1,onSelect:t,showDebugInfo:r=!1}){const a=x.useGenericRefs(),n=s.metadata?.airplaneUrl??s.metadata?.modelUrl,i=typeof n=="string"?n:void 0;if(typeof i!="string"||i.length===0)return null;const o=s.metadata?.ridingUrl,l=typeof o=="string"?o:void 0,f=s.metadata?.currentAnimation,u=typeof f=="string"?f:"idle";return d.jsx(b.PhysicsEntity,{url:i,isActive:!1,componentType:"airplane",name:`active-airplane-${s.id}`,position:s.position,rotation:s.rotation,scale:s.scale,currentAnimation:u,...l?{ridingUrl:l}:{},ref:a.rigidBodyRef,outerGroupRef:a.outerGroupRef,innerGroupRef:a.innerGroupRef,colliderRef:a.colliderRef,userData:{id:s.id,type:"active",subType:"airplane",health:s.health,maxHealth:s.maxHealth,energy:s.energy,maxEnergy:s.maxEnergy},onCollisionEnter:()=>{t&&t(s.id)},children:e&&r&&d.jsxs("mesh",{position:[0,3,0],children:[d.jsx("boxGeometry",{args:[.5,.5,.5]}),d.jsx("meshStandardMaterial",{color:"#00ffff",transparent:!0,opacity:.6})]})})}function re({object:s,selected:e=!1,onSelect:t,showDebugInfo:r=!1}){const a=x.useGenericRefs();g.useEffect(()=>{a.rigidBodyRef&&a.rigidBodyRef.current&&a.rigidBodyRef.current.setEnabledRotations(!1,!1,!1,!1)},[a.rigidBodyRef]);const n=s.metadata?.characterUrl;if(typeof n!="string"||n.length===0)return null;const i=s.metadata?.currentAnimation,o=typeof i=="string"?i:"idle",l=s.metadata?.nameTag,f=typeof l=="string"?l:void 0;return d.jsx(b.PhysicsEntity,{url:n,isActive:!1,componentType:"character",name:`active-character-${s.id}`,position:s.position,rotation:s.rotation,scale:s.scale,currentAnimation:o,ref:a.rigidBodyRef,outerGroupRef:a.outerGroupRef,innerGroupRef:a.innerGroupRef,colliderRef:a.colliderRef,userData:{id:s.id,type:"active",subType:"character",health:s.health,maxHealth:s.maxHealth,energy:s.energy,maxEnergy:s.maxEnergy,nameTag:f},onCollisionEnter:()=>{t&&t(s.id)},children:e&&r&&d.jsxs("mesh",{position:[0,3,0],children:[d.jsx("boxGeometry",{args:[.5,.5,.5]}),d.jsx("meshStandardMaterial",{color:"#ff0000",transparent:!0,opacity:.6})]})})}function se({object:s,selected:e=!1,onSelect:t,showDebugInfo:r=!1}){const a=x.useGenericRefs(),n=s.metadata?.vehicleUrl??s.metadata?.modelUrl,i=typeof n=="string"?n:void 0;if(typeof i!="string"||i.length===0)return null;const o=s.metadata?.ridingUrl,l=typeof o=="string"?o:void 0,f=s.metadata?.currentAnimation,u=typeof f=="string"?f:"idle";return d.jsx(b.PhysicsEntity,{url:i,isActive:!1,componentType:"vehicle",name:`active-vehicle-${s.id}`,position:s.position,rotation:s.rotation,scale:s.scale,currentAnimation:u,...l?{ridingUrl:l}:{},ref:a.rigidBodyRef,outerGroupRef:a.outerGroupRef,innerGroupRef:a.innerGroupRef,colliderRef:a.colliderRef,userData:{id:s.id,type:"active",subType:"vehicle",health:s.health,maxHealth:s.maxHealth,energy:s.energy,maxEnergy:s.maxEnergy},onCollisionEnter:()=>{t&&t(s.id)},children:e&&r&&d.jsxs("mesh",{position:[0,3,0],children:[d.jsx("boxGeometry",{args:[.5,.5,.5]}),d.jsx("meshStandardMaterial",{color:"#0000ff",transparent:!0,opacity:.6})]})})}function Te({objects:s,selectedId:e,onSelect:t,showDebugInfo:r=!1}){const{gameStates:a}=b.useStateSystem(),n=p.useGaesupStore(i=>i.mode);return d.jsx("group",{name:"active-objects",children:s.map(i=>{const o=i.id===e;if(i.type==="character"&&a?.isRiding&&n?.type!=="character")return null;switch(i.type){case"vehicle":return d.jsx(se,{object:i,selected:o,...t?{onSelect:t}:{},showDebugInfo:r},i.id);case"airplane":return d.jsx(te,{object:i,selected:o,...t?{onSelect:t}:{},showDebugInfo:r},i.id);case"character":return d.jsx(re,{object:i,selected:o,...t?{onSelect:t}:{},showDebugInfo:r},i.id);default:return null}})})}function ae(s){const{children:e,visible:t=!0,...r}=s,a=x.useGenericRefs();return d.jsx("group",{visible:t,children:d.jsx(b.PhysicsEntity,{...r,url:r.url||"",isActive:!1,componentType:"vehicle",name:r.name??"vehicle",ref:a.rigidBodyRef,outerGroupRef:a.outerGroupRef,innerGroupRef:a.innerGroupRef,colliderRef:a.colliderRef,children:e})})}function ne(s){const{children:e,visible:t=!0,...r}=s,a=x.useGenericRefs();return d.jsx("group",{visible:t,children:d.jsx(b.PhysicsEntity,{...r,url:r.url||"",isActive:!1,componentType:"airplane",name:r.name??"airplane",ref:a.rigidBodyRef,outerGroupRef:a.outerGroupRef,innerGroupRef:a.innerGroupRef,colliderRef:a.colliderRef,children:e})})}function Ge(s){const{children:e,visible:t=!0,...r}=s,a=x.useGenericRefs();g.useEffect(()=>{a.rigidBodyRef&&a.rigidBodyRef.current&&a.rigidBodyRef.current.setEnabledRotations(!1,!1,!1,!1)},[a.rigidBodyRef]);const n=r.controllerOptions??{lerp:{cameraTurn:1,cameraPosition:1}};return d.jsx("group",{visible:t,children:d.jsx(b.PhysicsEntity,{...r,url:r.url||"",isActive:!1,componentType:"character",controllerOptions:n,ref:a.rigidBodyRef,outerGroupRef:a.outerGroupRef,innerGroupRef:a.innerGroupRef,colliderRef:a.colliderRef,children:e})})}const Ae=150*150,Ue=g.memo(function({object:e,isSelected:t,onSelect:r,showDebugInfo:a=!1,enableInteraction:n=!0}){const i=x.useGenericRefs(),o=e.metadata?.modelUrl,l=typeof o=="string"?o:void 0,f=g.useCallback(()=>{n&&e.interactable&&r&&r(e.id)},[n,e.interactable,e.id,r]),u=g.useCallback(v=>{n&&e.interactable&&(v.stopPropagation(),document.body.style.cursor="pointer")},[n,e.interactable]),h=g.useCallback(()=>{document.body.style.cursor="default"},[]);return l?d.jsx(b.PhysicsEntity,{url:l,isActive:!1,componentType:e.type,name:`passive-${e.type}-${e.id}`,position:e.position,rotation:e.rotation,scale:e.scale,ref:i.rigidBodyRef,outerGroupRef:i.outerGroupRef,innerGroupRef:i.innerGroupRef,colliderRef:i.colliderRef,userData:{id:e.id,type:"passive",subType:e.type,interactable:e.interactable,onNear:e.metadata?.onNear,onLeave:e.metadata?.onLeave,onInteract:e.metadata?.onInteract},onCollisionEnter:()=>{n&&e.interactable&&r&&r(e.id)},children:t&&a&&d.jsxs("mesh",{position:[0,3,0],children:[d.jsx("boxGeometry",{args:[.5,.5,.5]}),d.jsx("meshStandardMaterial",{color:"#00ff00",transparent:!0,opacity:.6})]})}):d.jsxs(U.RigidBody,{type:"fixed",position:e.position,rotation:e.rotation,colliders:!1,children:[d.jsx(U.CapsuleCollider,{args:[1,.5],position:[0,1,0]}),d.jsx("group",{scale:e.scale,onClick:f,onPointerEnter:u,onPointerLeave:h})]})}),Me=g.memo(function({objects:e,selectedId:t,onSelect:r,showDebugInfo:a=!1,enableInteraction:n=!0}){const[i,o]=g.useState(()=>new Set),l=g.useRef(0);ue.useFrame((u,h)=>{if(l.current+=h,l.current<.5)return;l.current=0;const v=u.camera.position,R=new Set;for(const S of e){const D=S.position.x,C=S.position.y,B=S.position.z,M=D-v.x,c=C-v.y,y=B-v.z;M*M+c*c+y*y<=Ae&&R.add(S.id)}(R.size!==i.size||[...R].some(S=>!i.has(S)))&&o(R)});const f=g.useMemo(()=>e.filter(u=>i.has(u.id)).map(u=>d.jsx(Ue,{object:u,isSelected:u.id===t,...r?{onSelect:r}:{},showDebugInfo:a,enableInteraction:n},u.id)),[e,t,r,a,n,i]);return d.jsx("group",{name:"passive-objects",children:f})});function _e({states:s}){if(!s||!s.canRide&&!s.isRiding)return null;const e=s.nearbyRideable?.rideMessage??`Press F to ride ${s.nearbyRideable?.displayName??s.nearbyRideable?.name??"vehicle"}`,t=s.nearbyRideable?.exitMessage??"Press F to exit";return d.jsx("div",{className:"rideable-ui-container",children:d.jsxs("div",{className:"message-box",children:[s.canRide&&d.jsx("div",{children:e}),s.isRiding&&d.jsx("div",{children:t})]})})}function We(s){const e=p.useGaesupStore(u=>u.rideable),{initRideable:t,onRideableNear:r,onRideableLeave:a,landing:n}=ve();g.useEffect(()=>{t(s)},[s,t]);const{controllerOptions:i,...o}=s,l=i?.lerp?{lerp:{cameraTurn:i.lerp.cameraTurn??1,cameraPosition:i.lerp.cameraPosition??1}}:void 0,f={objectType:s.objectType,objectkey:s.objectkey,rideable:!0,init:t,onNear:r,onLeave:a,landing:n,rideMessage:s.rideMessage,exitMessage:s.exitMessage,displayName:s.displayName};return d.jsxs(d.Fragment,{children:[s.objectType==="vehicle"&&d.jsx(ae,{...o,...l?{controllerOptions:l}:{},userData:f,sensor:!0,visible:!e[s.objectkey]?.isOccupied}),s.objectType==="airplane"&&d.jsx(ne,{...o,...l?{controllerOptions:l}:{},userData:f,sensor:!0,visible:!e[s.objectkey]?.isOccupied})]})}exports.BugSpot=m.BugSpot;exports.DEFAULT_RUNTIME_SAVE_DIAGNOSTICS_SERVICE_ID=m.DEFAULT_RUNTIME_SAVE_DIAGNOSTICS_SERVICE_ID;exports.DEFAULT_WORLD_SAVE_ENVIRONMENT=m.DEFAULT_WORLD_SAVE_ENVIRONMENT;exports.FishSpot=m.FishSpot;exports.RUNTIME_SAVE_DIAGNOSTIC_EVENT=m.RUNTIME_SAVE_DIAGNOSTIC_EVENT;exports.TreeObject=m.TreeObject;exports.createCameraSaveDataFromDomain=m.createCameraSaveDataFromDomain;exports.createGaesupRuntime=m.createGaesupRuntime;exports.createRuntimeSaveDiagnostics=m.createRuntimeSaveDiagnostics;exports.createSaveDataFromSaveSystem=m.createSaveDataFromSaveSystem;exports.createWorldDataFromSaveDomains=m.createWorldDataFromSaveDomains;exports.formatRuntimeSaveDiagnostic=m.formatRuntimeSaveDiagnostic;exports.normalizeSaveMetadata=m.normalizeSaveMetadata;exports.parseWorldSaveId=m.parseWorldSaveId;exports.parseWorldSaveTimestamp=m.parseWorldSaveTimestamp;exports.useAutoSave=m.useAutoSave;exports.useLoadOnMount=m.useLoadOnMount;exports.shouldSetupPluginForRuntime=le.shouldSetupPluginForRuntime;exports.GaesupRuntimeProvider=b.GaesupRuntimeProvider;exports.useGaesupRuntime=b.useGaesupRuntime;exports.useGaesupRuntimeRevision=b.useGaesupRuntimeRevision;exports.GaesupWorldContent=W.GaesupWorldContent;exports.World=W.WorldContainer;exports.WorldConfigProvider=W.WorldConfigProvider;exports.WorldContainer=W.WorldContainer;exports.DuplicateSaveDomainBindingError=I.DuplicateSaveDomainBindingError;exports.IndexedDBAdapter=I.IndexedDBAdapter;exports.LocalStorageAdapter=I.LocalStorageAdapter;exports.SaveSystem=I.SaveSystem;exports.WorldProps=I.WorldProps;exports.createDefaultSaveSystem=I.createDefaultSaveSystem;exports.getSaveSystem=I.getSaveSystem;exports.ActiveObjects=Te;exports.Airplane=te;exports.Character=re;exports.PassiveAirplane=ne;exports.PassiveCharacter=Ge;exports.PassiveObjects=Me;exports.PassiveVehicle=ae;exports.Rideable=We;exports.RideableUI=_e;exports.SaveLoadManager=w;exports.Vehicle=se;exports.createPersistenceSlice=Pe;exports.createPersistenceSliceWithOptions=ee;exports.createWorldSlice=be;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("reflect-metadata");const m=require("./index-DHZJyO9k.cjs"),le=require("./runtimeFilter-W6iMw1pL.cjs"),b=require("./index-CJj-Z7Jr.cjs"),de=require("three"),p=require("./gaesupStore-2zKBYTYo.cjs"),W=require("./index-syAx2qzT.cjs"),d=require("react/jsx-runtime"),x=require("./index-D1hpjfAw.cjs"),g=require("react"),ue=require("@react-three/fiber"),U=require("@react-three/rapier"),I=require("./index-co-QAQz9.cjs");function fe(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const F=fe(de);class T{cellSize;cells=new Map;objectPositions=new Map;constructor(e={}){this.cellSize=e.cellSize??10}static zigZag(e){return e>=0?e*2:-e*2-1}static pair(e,t){const r=T.zigZag(e),a=T.zigZag(t),n=r+a;return n*(n+1)/2+a}getCellKey(e,t){const r=Math.floor(e/this.cellSize),a=Math.floor(t/this.cellSize);return T.pair(r,a)}add(e,t){this.remove(e);const r=this.getCellKey(t.x,t.z);this.cells.has(r)||this.cells.set(r,new Set),this.cells.get(r).add(e),this.objectPositions.set(e,t.clone())}remove(e){const t=this.objectPositions.get(e);if(t){const r=this.getCellKey(t.x,t.z),a=this.cells.get(r);a&&(a.delete(e),a.size===0&&this.cells.delete(r)),this.objectPositions.delete(e)}}update(e,t){const r=this.objectPositions.get(e);if(!r){this.add(e,t);return}if(r.equals(t))return;const a=this.getCellKey(r.x,r.z),n=this.getCellKey(t.x,t.z);if(a!==n){const i=this.cells.get(a);i&&(i.delete(e),i.size===0&&this.cells.delete(a));const o=this.cells.get(n)??new Set;o.add(e),this.cells.set(n,o)}r.copy(t)}getNearby(e,t,r){const a=r??[];r&&(r.length=0);const n=Math.ceil(t/this.cellSize),i=Math.floor(e.x/this.cellSize),o=Math.floor(e.z/this.cellSize),l=t*t;for(let f=i-n;f<=i+n;f++)for(let u=o-n;u<=o+n;u++){const h=T.pair(f,u),v=this.cells.get(h);if(v)for(const R of v){const S=this.objectPositions.get(R);if(!S)continue;const D=e.x-S.x,C=e.y-S.y,B=e.z-S.z;D*D+C*C+B*B<=l&&a.push(R)}}return a}clear(){this.cells.clear(),this.objectPositions.clear()}get size(){return this.objectPositions.size}}var pe=Object.defineProperty,ye=Object.getOwnPropertyDescriptor,L=(s,e,t,r)=>{for(var a=r>1?void 0:r?ye(e,t):e,n=s.length-1,i;n>=0;n--)(i=s[n])&&(a=(r?i(e,t,a):i(a))||a);return r&&a&&pe(e,t,a),a};exports.WorldSystem=class{objects=new Map;interactionEvents=[];spatial=new T({cellSize:10});raycaster=new F.Raycaster;tempVector=new F.Vector3;nearbyIds=[];nearbyIds2=[];async init(){}update(e){}dispose(){this.cleanup()}addObject(e){this.objects.set(e.id,e),this.spatial.add(e.id,e.position)}removeObject(e){return this.objects.get(e)&&this.spatial.remove(e),this.objects.delete(e)}getObject(e){return this.objects.get(e)}getAllObjects(){return Array.from(this.objects.values())}getObjectsByType(e){return this.getAllObjects().filter(t=>t.type===e)}updateObject(e,t){const r=this.objects.get(e);return r?(Object.assign(r,t),t.position&&this.spatial.update(e,t.position),!0):!1}getObjectsInRadius(e,t){const r=this.spatial.getNearby(e,t,this.nearbyIds),a=[];for(const n of r){const i=this.objects.get(n);i&&a.push(i)}return a}checkCollisions(e){const t=this.objects.get(e);if(!t||!t.boundingBox)return[];const r=t.boundingBox.max.distanceTo(t.boundingBox.min),a=this.spatial.getNearby(t.position,r,this.nearbyIds2),n=[];for(const i of a){if(i===e)continue;const o=this.objects.get(i);!o||!o.boundingBox||t.boundingBox.intersectsBox(o.boundingBox)&&n.push(o)}return n}processInteraction(e){this.interactionEvents.push(e),this.interactionEvents.length>1e3&&(this.interactionEvents=this.interactionEvents.slice(-500))}getRecentEvents(e=1e3){const t=Date.now();return this.interactionEvents.filter(r=>t-r.timestamp<=e)}raycast(e,t,r=100){this.raycaster.set(e,t),this.raycaster.near=0,this.raycaster.far=r;const a=this.spatial.getNearby(e,r,this.nearbyIds);for(const n of a){const i=this.objects.get(n);if(i&&i.boundingBox){const o=this.raycaster.ray.intersectBox(i.boundingBox,this.tempVector);if(o)return{object:i,distance:e.distanceTo(o),point:o.clone()}}}return null}cleanup(){this.objects.clear(),this.interactionEvents.length=0,this.spatial.clear()}};L([p.HandleError()],exports.WorldSystem.prototype,"init",1);L([p.Profile(),p.HandleError()],exports.WorldSystem.prototype,"update",1);L([p.HandleError()],exports.WorldSystem.prototype,"dispose",1);exports.WorldSystem=L([p.RegisterSystem("world")],exports.WorldSystem);var me=Object.defineProperty,ge=Object.getOwnPropertyDescriptor,z=(s,e,t,r)=>{for(var a=r>1?void 0:r?ge(e,t):e,n=s.length-1,i;n>=0;n--)(i=s[n])&&(a=(r?i(e,t,a):i(a))||a);return r&&a&&me(e,t,a),a};exports.WorldBridge=class extends b.CoreBridge{buildEngine(e,t){const r=new exports.WorldSystem,a={...t?.selectedObjectId!==void 0?{selectedObjectId:t.selectedObjectId}:{},interactionMode:t?.interactionMode??"view",showDebugInfo:t?.showDebugInfo??!1};return{system:r,state:a,dispose:()=>r.dispose()}}executeCommand(e,t,r){const{system:a,state:n}=e;switch(t.type){case"addObject":const{id:i,...o}=t.data,l=typeof i=="string"&&i.length>0?i:this.generateId(),f={...o,id:l};a.addObject(f);break;case"removeObject":a.removeObject(t.data.id),n.selectedObjectId===t.data.id&&delete n.selectedObjectId;break;case"updateObject":a.updateObject(t.data.id,t.data.updates);break;case"selectObject":t.data.id!==void 0?n.selectedObjectId=t.data.id:delete n.selectedObjectId;break;case"setInteractionMode":n.interactionMode=t.data.mode;break;case"toggleDebugInfo":n.showDebugInfo=!n.showDebugInfo;break;case"interact":const u=a.getObject(t.data.objectId);if(u&&u.canInteract){const h={type:"custom",object1Id:t.data.objectId,timestamp:Date.now(),data:{action:t.data.action}};a.processInteraction(h)}break;case"cleanup":a.cleanup(),delete n.selectedObjectId,n.interactionMode="view",n.showDebugInfo=!1;break}}createSnapshot(e,t){const{system:r,state:a}=e;return{objects:r.getAllObjects(),...a.selectedObjectId!==void 0?{selectedObjectId:a.selectedObjectId}:{},interactionMode:a.interactionMode,showDebugInfo:a.showDebugInfo,events:r.getRecentEvents(),objectsInRadius:(n,i)=>r.getObjectsInRadius(n,i),objectsByType:n=>r.getObjectsByType(n),raycast:(n,i)=>r.raycast(n,i)?.object||null}}addObject(e,t){const r=t.id,a=typeof r=="string"&&r.length>0?r:this.generateId();return this.execute(e,{type:"addObject",data:{...t,id:a}}),a}removeObject(e,t){this.execute(e,{type:"removeObject",data:{id:t}})}updateObject(e,t,r){this.execute(e,{type:"updateObject",data:{id:t,updates:r}})}selectObject(e,t){this.execute(e,{type:"selectObject",data:t!==void 0?{id:t}:{}})}setInteractionMode(e,t){this.execute(e,{type:"setInteractionMode",data:{mode:t}})}toggleDebugInfo(e){this.execute(e,{type:"toggleDebugInfo"})}interact(e,t,r){this.execute(e,{type:"interact",data:{objectId:t,action:r}})}cleanup(e){this.execute(e,{type:"cleanup"})}getObjectsInRadius(e,t,r){const a=this.getEngine(e);return a?a.system.getObjectsInRadius(t,r):[]}getObjectsByType(e,t){const r=this.getEngine(e);return r?r.system.getObjectsByType(t):[]}raycast(e,t,r){const a=this.getEngine(e);return a&&a.system.raycast(t,r)?.object||null}generateId(){return`world_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}};z([b.ValidateCommand()],exports.WorldBridge.prototype,"executeCommand",1);z([b.LogSnapshot(),b.CacheSnapshot(16)],exports.WorldBridge.prototype,"createSnapshot",1);exports.WorldBridge=z([b.DomainBridge("world"),b.EnableEventLog()],exports.WorldBridge);const he={isRiderOn:!1,position:U.vec3(),rotation:U.euler(),offset:U.vec3(),visible:!0};function ve(){const{gameStates:s,updateGameStates:e,activeState:t}=b.useStateSystem(),r=p.useGaesupStore(c=>c.rideable),a=p.useGaesupStore(c=>c.urls),n=p.useGaesupStore(c=>c.setMode),i=p.useGaesupStore(c=>c.setRideable),o=p.useGaesupStore(c=>c.setUrls),{getSizesByUrls:l}=b.useGaesupGltf(),f=g.useCallback(c=>c==="airplane"?"airplane":"vehicle",[]),u=g.useCallback(c=>{const y={},j=c.ridingUrl??a.characterUrl;if(typeof j=="string"&&j.length>0&&(y.ridingUrl=j),c.objectType==="airplane"){y.airplaneUrl=c.url??"",o(y);return}c.objectType&&(y.vehicleUrl=c.url??"",y.wheelUrl=c.wheelUrl??""),o(y)},[o,a]),h=g.useCallback(c=>{const y=r[c];if(!y?.position)return;const j=y.objectType,{vehicleUrl:ie,airplaneUrl:oe,characterUrl:ce}=l({...a});!(j==="airplane"?oe:ie)||!ce||(e({canRide:!1,isRiding:!1,currentRideable:void 0}),i(c,{...y,visible:!0,position:t.position.clone()}))},[r,l,a,e,i,t.position]),v=g.useCallback(async()=>{if(s.canRide&&s.nearbyRideable&&!s.isRiding){const{objectkey:c,objectType:y}=s.nearbyRideable,j=r[c];if(!j)return;u(j),n({type:f(y)}),e({currentRideable:s.nearbyRideable,isRiding:!0,canRide:!1,nearbyRideable:void 0}),i(c,{...j,visible:!1})}},[s.canRide,s.nearbyRideable,s.isRiding,r,u,n,f,e,i]),R=g.useCallback(async()=>{s.isRiding&&s.currentRideable&&(h(s.currentRideable.objectkey),n({type:"character"}),e({isRiding:!1,currentRideable:void 0}))},[s.isRiding,s.currentRideable,h,n,e]);g.useEffect(()=>{const c=y=>{y.code==="KeyF"&&(s.canRide&&s.nearbyRideable?v():s.isRiding&&R())};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[s.canRide,s.nearbyRideable,s.isRiding,v,R]);const S=g.useCallback(c=>{i(c.objectkey,{...he,...c})},[i]),D=g.useCallback(c=>{i(c.objectkey,c)},[i]),C=c=>r[c],B=g.useCallback(async(c,y)=>{if((c.other.rigidBodyObject&&c.other.rigidBodyObject.name==="character"||c.other.rigidBodyObject&&!c.other.rigidBodyObject.name||c.other.rigidBody)&&!s.isRiding){if(!y.objectType)return;e({nearbyRideable:{id:y.objectkey,objectkey:y.objectkey,objectType:y.objectType,type:"rideable",maxSpeed:0,acceleration:0,deceleration:0,isOccupied:!1,controls:{forward:!1,backward:!1,left:!1,right:!1,brake:!1},name:y.objectType==="vehicle"?"차량":"비행기",...y.rideMessage?{rideMessage:y.rideMessage}:{},...y.exitMessage?{exitMessage:y.exitMessage}:{},...y.displayName?{displayName:y.displayName}:{}},canRide:!0})}},[s.isRiding,e]),M=g.useCallback(async c=>{(c.other.rigidBodyObject&&c.other.rigidBodyObject.name==="character"||c.other.rigidBodyObject&&!c.other.rigidBodyObject.name||c.other.rigidBody)&&e({nearbyRideable:void 0,canRide:!1})},[e]);return{initRideable:S,updateRideable:D,getRideable:C,onRideableNear:B,onRideableLeave:M,enterRideable:v,exitRideable:R,landing:h}}const E="default",be=s=>{const e=p.BridgeFactory.getOrCreate("world");if(e){e.register(E);const t=e;t.__gaesupWorldSliceUnsubscribe?.(),t.__gaesupWorldSliceUnsubscribe=e.subscribe(r=>{s({objects:r.objects,selectedObjectId:r.selectedObjectId,interactionMode:r.interactionMode,showDebugInfo:r.showDebugInfo,events:r.events,loading:!1,error:void 0})})}return{objects:[],selectedObjectId:void 0,interactionMode:"view",showDebugInfo:!1,events:[],loading:!1,error:void 0,addObject:t=>{if(!e)return"";s({loading:!0,error:void 0});try{const r=e.addObject(E,t);return s({loading:!1}),r}catch(r){return s({loading:!1,error:r instanceof Error?r.message:"Unknown error"}),""}},removeObject:t=>{if(!e)return!1;s({loading:!0,error:void 0});try{return e.removeObject(E,t),s({loading:!1}),!0}catch(r){return s({loading:!1,error:r instanceof Error?r.message:"Unknown error"}),!1}},updateObject:(t,r)=>{if(!e)return!1;s({loading:!0,error:void 0});try{return e.updateObject(E,t,r),s({loading:!1}),!0}catch(a){return s({loading:!1,error:a instanceof Error?a.message:"Unknown error"}),!1}},selectObject:t=>{e&&e.selectObject(E,t)},setInteractionMode:t=>{e&&e.setInteractionMode(E,t)},toggleDebugInfo:()=>{e&&e.toggleDebugInfo(E)},setLoading:t=>{s({loading:t})},setError:t=>{s({error:t})},clearEvents:()=>{s({events:[]})},getBridge:()=>e,getObjectsInRadius:(t,r)=>e?e.getObjectsInRadius(E,t,r):[],getObjectsByType:t=>e?e.getObjectsByType(E,t):[],raycast:(t,r)=>e?e.raycast(E,t,r):null,interact:(t,r)=>{e&&e.interact(E,t,r)},cleanup:()=>{e&&e.cleanup(E)}}};var Se=Object.defineProperty,Re=Object.getOwnPropertyDescriptor,O=(s,e,t,r)=>{for(var a=Re(e,t),n=s.length-1,i;n>=0;n--)(i=s[n])&&(a=i(e,t,a)||a);return a&&Se(e,t,a),a};const we="1.0.0",P="gaesup_world_save_",G="base64-json:",Z="gaesup-world:gzip-json:v1";class w{version;storage;fileWriter;now;constructor(e={}){this.version=e.version??we,this.storage=e.storage,this.fileWriter=e.fileWriter,this.now=e.now??Date.now}async save(e,t,r={}){try{const a=this.createSaveData(e,t,r);return r.compress?await this.saveCompressed(a):await this.saveUncompressed(a)}catch(a){return{success:!1,error:a instanceof Error?a.message:"Unknown error occurred"}}}async load(e,t={}){try{const r=`${P}${e}`,a=this.getStorage().getItem(r);if(!a)throw new Error(`Save data not found: ${e}`);const n=await this.parseStoredSaveData(a);if(!this.validateSaveData(n))throw new Error("Invalid save data format");return{success:!0,data:{...n,world:this.filterWorldData(n.world,t)}}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Failed to load save data"}}}async saveToFile(e,t,r,a={}){try{const n=this.createSaveData(e,r,a);return await this.writeFile(t,n),{success:!0,data:n}}catch(n){return{success:!1,error:n instanceof Error?n.message:"Failed to save file"}}}async loadFromFile(e,t={}){try{const r=await e.text(),a=JSON.parse(r);if(!this.validateSaveData(a))throw new Error("Invalid save file format");return{success:!0,data:{...a,world:this.filterWorldData(a.world,t)}}}catch(r){return{success:!1,error:r instanceof Error?r.message:"Failed to load file"}}}listSaves(){const e=[];let t;try{t=this.getStorage()}catch(r){return console.error("Failed to list saves:",r),e}for(let r=0;r<t.length;r++){const a=t.key(r);if(a&&a.startsWith(P))try{const n=a.substring(P.length),i=t.getItem(a);if(i){const o=this.parseStoredSaveDataSync(i);e.push({id:n,timestamp:o.timestamp,...o.metadata?{metadata:o.metadata}:{}})}}catch(n){console.error(`Failed to parse save: ${a}`,n)}}return e.sort((r,a)=>a.timestamp-r.timestamp)}deleteSave(e){try{const t=`${P}${e}`;return this.getStorage().removeItem(t),!0}catch(t){return console.error("Failed to delete save:",t),!1}}filterWorldData(e,t){const r={...e};return t.includeBuildings===!1&&(r.buildings={wallGroups:[],tileGroups:[],blocks:[],meshes:[]}),t.includeNPCs===!1&&(r.npcs=[]),t.includeEnvironment===!1&&(r.environment={lighting:{ambientIntensity:1,directionalIntensity:1,directionalPosition:{x:0,y:10,z:0}}}),t.includeCamera===!1&&delete r.camera,r}createSaveData(e,t,r={}){const a=this.now();return{version:this.version,timestamp:a,world:this.filterWorldData(e,r),...t?{metadata:{...t,createdAt:t.createdAt||a,updatedAt:a}}:{}}}getStorage(){if(this.storage)return this.storage;if(typeof localStorage>"u")throw new Error("Legacy save storage is not available in this environment");return localStorage}async writeFile(e,t){if(this.fileWriter){await this.fileWriter(e,t);return}if(typeof document>"u"||typeof URL>"u"||typeof Blob>"u")throw new Error("File download is not available in this environment");const r=new Blob([JSON.stringify(t,null,2)],{type:"application/json"}),a=URL.createObjectURL(r),n=document.createElement("a");n.href=a,n.download=e.endsWith(".json")?e:`${e}.json`,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(a)}async saveUncompressed(e){const t=`${e.world.id}_${e.timestamp}`,r=`${P}${t}`;try{return this.getStorage().setItem(r,JSON.stringify(e)),{success:!0,data:e}}catch(a){throw a instanceof Error&&a.name==="QuotaExceededError"?new Error("Storage quota exceeded. Please delete some saves."):a}}async saveCompressed(e){const t=await this.compressData(e),r=`${e.world.id}_${e.timestamp}`,a=`${P}${r}`;try{return this.getStorage().setItem(a,t),{success:!0,data:e}}catch(n){throw n instanceof Error&&n.name==="QuotaExceededError"?new Error("Storage quota exceeded. Please delete some saves."):n}}async compressData(e){const t=JSON.stringify(e);if(!H())return`${G}${$(V(t))}`;const r=await this.gzipBytes(V(t)),a={encoding:Z,version:e.version,timestamp:e.timestamp,worldId:e.world.id,worldName:e.world.name,...e.metadata?{metadata:e.metadata}:{},payload:$(r)};return JSON.stringify(a)}async decompressData(e){const t=X(e),r=await this.gunzipBytes(t),a=Q(r);return JSON.parse(a)}async parseStoredSaveData(e){if(e.startsWith("{")){const t=JSON.parse(e);return q(t)?this.decompressData(t.payload):t}return e.startsWith(G)?_(e.slice(G.length)):_(e)}parseStoredSaveDataSync(e){if(e.startsWith("{")){const t=JSON.parse(e);return q(t)?{version:t.version,timestamp:t.timestamp,world:{id:t.worldId,name:t.worldName,buildings:{wallGroups:[],tileGroups:[],blocks:[],meshes:[]},npcs:[],environment:{lighting:{ambientIntensity:1,directionalIntensity:1,directionalPosition:{x:0,y:10,z:0}}}},...t.metadata?{metadata:t.metadata}:{}}:t}return e.startsWith(G)?_(e.slice(G.length)):_(e)}async gzipBytes(e){if(!H())return e;const t=new Blob([e]).stream().pipeThrough(new CompressionStream("gzip"));return new Uint8Array(await new Response(t).arrayBuffer())}async gunzipBytes(e){if(!Ee())return e;const t=new Blob([e]).stream().pipeThrough(new DecompressionStream("gzip"));return new Uint8Array(await new Response(t).arrayBuffer())}validateSaveData(e){return e!==null&&typeof e=="object"&&"version"in e&&"timestamp"in e&&"world"in e&&typeof e.version=="string"&&typeof e.timestamp=="number"&&e.world&&typeof e.world.id=="string"&&typeof e.world.name=="string"}}O([p.HandleError(),p.Profile(),p.Timeout(5e3)],w.prototype,"save");O([p.HandleError(),p.Profile(),p.Timeout(5e3)],w.prototype,"load");O([p.HandleError(),p.Profile()],w.prototype,"saveToFile");O([p.HandleError(),p.Profile()],w.prototype,"loadFromFile");O([p.MonitorMemory(10)],w.prototype,"listSaves");O([p.HandleError()],w.prototype,"deleteSave");O([p.Profile()],w.prototype,"filterWorldData");O([p.Profile()],w.prototype,"createSaveData");O([p.HandleError()],w.prototype,"saveUncompressed");O([p.HandleError()],w.prototype,"saveCompressed");O([p.Profile()],w.prototype,"compressData");O([p.Profile()],w.prototype,"decompressData");function $(s){let e="";for(let r=0;r<s.length;r+=32768)e+=String.fromCharCode(...s.subarray(r,r+32768));return btoa(e)}function X(s){const e=atob(s),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}function _(s){return JSON.parse(Q(X(s)))}function V(s){if(typeof TextEncoder<"u")return new TextEncoder().encode(s);const e=unescape(encodeURIComponent(s)),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}function Q(s){if(typeof TextDecoder<"u")return new TextDecoder().decode(s);let e="";const t=32768;for(let r=0;r<s.length;r+=t)e+=String.fromCharCode(...s.subarray(r,r+t));return decodeURIComponent(escape(e))}function H(){return typeof CompressionStream<"u"&&typeof Blob<"u"&&typeof Response<"u"&&typeof new Blob().stream=="function"}function Ee(){return typeof DecompressionStream<"u"&&typeof Blob<"u"&&typeof Response<"u"&&typeof new Blob().stream=="function"}function q(s){if(!s||typeof s!="object")return!1;const e=s;return e.encoding===Z&&typeof e.version=="string"&&typeof e.timestamp=="number"&&typeof e.worldId=="string"&&typeof e.worldName=="string"&&typeof e.payload=="string"}const Oe=()=>({});function J(s,e,t){const{buildingStore:r,npcStore:a,cameraStore:n}=s;if(!r)throw new Error("Building store not initialized");const i=r.getState(),o=n?.getState(),l=o?{position:o.position,rotation:o.rotation,mode:o.mode,...o.settings?{settings:o.settings}:{}}:void 0;return{id:e,name:t,buildings:{wallGroups:Array.from(i.wallGroups.values()),tileGroups:Array.from(i.tileGroups.values()),blocks:Array.from(i.blocks),meshes:Array.from(i.meshes.values())},npcs:a?Array.from(a.getState().instances.values()):[],environment:m.DEFAULT_WORLD_SAVE_ENVIRONMENT,...l?{camera:l}:{}}}function je(s,e){if(!s||!e)return;const t=s.getState();if(typeof t.hydrate=="function"){t.hydrate(e);return}t.wallGroups.clear(),t.tileGroups.clear(),t.meshes.clear(),t.blocks=[],e.wallGroups.forEach(r=>{t.wallGroups.set(r.id,r)}),e.tileGroups.forEach(r=>{t.tileGroups.set(r.id,r)}),e.meshes.forEach(r=>{t.meshes.set(r.id,r)}),t.blocks=[...e.blocks??[]]}function xe(s,e){if(!s||!e)return;const t=s.getState();t.instances.clear(),e.forEach(r=>{t.instances.set(r.id,r)})}function Ie(s,e){!s||!e||s.setState({position:e.position,rotation:e.rotation,mode:e.mode,settings:e.settings||{}})}function K(s,e){je(s.buildingStore,e.buildings),xe(s.npcStore,e.npcs),Ie(s.cameraStore,e.camera)}function k(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function De(s){return s.replace(/\.json$/i,"")}function Y(s){return k(s)&&typeof s.version=="number"&&typeof s.savedAt=="number"&&k(s.domains)}function A(s){return k(s)&&s.kind==="gaesup.save-system"&&typeof s.worldId=="string"&&typeof s.worldName=="string"&&Y(s.blob)}async function N(s){return(await s.list()).map(t=>({id:t,timestamp:m.parseWorldSaveTimestamp(t)})).sort((t,r)=>r.timestamp-t.timestamp)}function Ce(s,e){if(typeof document>"u"||typeof URL>"u"||typeof Blob>"u")throw new Error("File download is not available in this environment");const t=new Blob([JSON.stringify(e,null,2)],{type:"application/json"}),r=URL.createObjectURL(t),a=document.createElement("a");a.href=r,a.download=s.endsWith(".json")?s:`${s}.json`,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(r)}async function Be(s){const e=JSON.parse(await s.text());if(A(e)||Y(e))return e;throw new Error("Invalid SaveSystem file format")}function ee(s={}){const e=s.getStores??Oe,t=s.saveSystem;return(r,a)=>({saveLoadManager:s.saveLoadManager??new w,currentSaveId:null,saves:[],isSaving:!1,isLoading:!1,lastError:null,saveWorld:async(n,i,o,l)=>{r({isSaving:!0,lastError:null});try{if(t){const h=Date.now(),v=`${n}_${h}`;await t.save(v),r({currentSaveId:v,saves:await N(t)});return}const f=J(e(),n,i),u=await a().saveLoadManager.save(f,o,l);if(u.success){const h=`${n}_${u.data.timestamp}`;r({currentSaveId:h}),a().refreshSaveList()}else throw new Error(u.error)}catch(f){throw r({lastError:f instanceof Error?f.message:"Save failed"}),f}finally{r({isSaving:!1})}},loadWorld:async(n,i)=>{r({isLoading:!0,lastError:null});try{if(t){if(!await t.load(n))throw new Error(`Save data not found: ${n}`);return r({currentSaveId:n}),m.createSaveDataFromSaveSystem(t,n)}const o=await a().saveLoadManager.load(n,i);if(o.success&&o.data)return K(e(),o.data.world),r({currentSaveId:n}),o.data;throw new Error(o.error)}catch(o){return r({lastError:o instanceof Error?o.message:"Load failed"}),null}finally{r({isLoading:!1})}},saveToFile:async(n,i,o,l,f)=>{r({isSaving:!0,lastError:null});try{if(t){const v={kind:"gaesup.save-system",version:1,worldId:n,worldName:i,blob:t.createBlob(o),...l?{metadata:l}:{}};Ce(o,v);return}const u=J(e(),n,i),h=await a().saveLoadManager.saveToFile(u,o,l,f);if(!h.success)throw new Error(h.error)}catch(u){throw r({lastError:u instanceof Error?u.message:"Save to file failed"}),u}finally{r({isSaving:!1})}},loadFromFile:async(n,i)=>{r({isLoading:!0,lastError:null});try{if(t){const l=await Be(n),f=A(l)?l.blob:l;t.hydrateBlob(f,n.name);const u=A(l)?l.worldId:De(n.name),h=A(l)?l.worldName:u,v=f.savedAt,R={version:String(f.version),timestamp:v,world:m.createWorldDataFromSaveDomains(f.domains,u,h)},S=A(l)?m.normalizeSaveMetadata(l.metadata,v):void 0;return S?{...R,metadata:S}:R}const o=await a().saveLoadManager.loadFromFile(n,i);if(o.success&&o.data)return K(e(),o.data.world),o.data;throw new Error(o.error)}catch(o){return r({lastError:o instanceof Error?o.message:"Load from file failed"}),null}finally{r({isLoading:!1})}},refreshSaveList:()=>{if(t){N(t).then(i=>r({saves:i})).catch(i=>{r({lastError:i instanceof Error?i.message:"Failed to list saves"})});return}const n=a().saveLoadManager.listSaves();r({saves:n})},deleteSave:n=>{if(t){(async()=>{try{await t.remove(n);const o=await N(t);r({saves:o,...a().currentSaveId===n?{currentSaveId:null}:{}})}catch(o){r({lastError:o instanceof Error?o.message:"Failed to delete save"})}})();return}a().saveLoadManager.deleteSave(n)&&(a().refreshSaveList(),a().currentSaveId===n&&r({currentSaveId:null}))},clearError:()=>{r({lastError:null})}})}const Pe=ee();function te({object:s,selected:e=!1,onSelect:t,showDebugInfo:r=!1}){const a=x.useGenericRefs(),n=s.metadata?.airplaneUrl??s.metadata?.modelUrl,i=typeof n=="string"?n:void 0;if(typeof i!="string"||i.length===0)return null;const o=s.metadata?.ridingUrl,l=typeof o=="string"?o:void 0,f=s.metadata?.currentAnimation,u=typeof f=="string"?f:"idle";return d.jsx(b.PhysicsEntity,{url:i,isActive:!1,componentType:"airplane",name:`active-airplane-${s.id}`,position:s.position,rotation:s.rotation,scale:s.scale,currentAnimation:u,...l?{ridingUrl:l}:{},ref:a.rigidBodyRef,outerGroupRef:a.outerGroupRef,innerGroupRef:a.innerGroupRef,colliderRef:a.colliderRef,userData:{id:s.id,type:"active",subType:"airplane",health:s.health,maxHealth:s.maxHealth,energy:s.energy,maxEnergy:s.maxEnergy},onCollisionEnter:()=>{t&&t(s.id)},children:e&&r&&d.jsxs("mesh",{position:[0,3,0],children:[d.jsx("boxGeometry",{args:[.5,.5,.5]}),d.jsx("meshStandardMaterial",{color:"#00ffff",transparent:!0,opacity:.6})]})})}function re({object:s,selected:e=!1,onSelect:t,showDebugInfo:r=!1}){const a=x.useGenericRefs();g.useEffect(()=>{a.rigidBodyRef&&a.rigidBodyRef.current&&a.rigidBodyRef.current.setEnabledRotations(!1,!1,!1,!1)},[a.rigidBodyRef]);const n=s.metadata?.characterUrl;if(typeof n!="string"||n.length===0)return null;const i=s.metadata?.currentAnimation,o=typeof i=="string"?i:"idle",l=s.metadata?.nameTag,f=typeof l=="string"?l:void 0;return d.jsx(b.PhysicsEntity,{url:n,isActive:!1,componentType:"character",name:`active-character-${s.id}`,position:s.position,rotation:s.rotation,scale:s.scale,currentAnimation:o,ref:a.rigidBodyRef,outerGroupRef:a.outerGroupRef,innerGroupRef:a.innerGroupRef,colliderRef:a.colliderRef,userData:{id:s.id,type:"active",subType:"character",health:s.health,maxHealth:s.maxHealth,energy:s.energy,maxEnergy:s.maxEnergy,nameTag:f},onCollisionEnter:()=>{t&&t(s.id)},children:e&&r&&d.jsxs("mesh",{position:[0,3,0],children:[d.jsx("boxGeometry",{args:[.5,.5,.5]}),d.jsx("meshStandardMaterial",{color:"#ff0000",transparent:!0,opacity:.6})]})})}function se({object:s,selected:e=!1,onSelect:t,showDebugInfo:r=!1}){const a=x.useGenericRefs(),n=s.metadata?.vehicleUrl??s.metadata?.modelUrl,i=typeof n=="string"?n:void 0;if(typeof i!="string"||i.length===0)return null;const o=s.metadata?.ridingUrl,l=typeof o=="string"?o:void 0,f=s.metadata?.currentAnimation,u=typeof f=="string"?f:"idle";return d.jsx(b.PhysicsEntity,{url:i,isActive:!1,componentType:"vehicle",name:`active-vehicle-${s.id}`,position:s.position,rotation:s.rotation,scale:s.scale,currentAnimation:u,...l?{ridingUrl:l}:{},ref:a.rigidBodyRef,outerGroupRef:a.outerGroupRef,innerGroupRef:a.innerGroupRef,colliderRef:a.colliderRef,userData:{id:s.id,type:"active",subType:"vehicle",health:s.health,maxHealth:s.maxHealth,energy:s.energy,maxEnergy:s.maxEnergy},onCollisionEnter:()=>{t&&t(s.id)},children:e&&r&&d.jsxs("mesh",{position:[0,3,0],children:[d.jsx("boxGeometry",{args:[.5,.5,.5]}),d.jsx("meshStandardMaterial",{color:"#0000ff",transparent:!0,opacity:.6})]})})}function Te({objects:s,selectedId:e,onSelect:t,showDebugInfo:r=!1}){const{gameStates:a}=b.useStateSystem(),n=p.useGaesupStore(i=>i.mode);return d.jsx("group",{name:"active-objects",children:s.map(i=>{const o=i.id===e;if(i.type==="character"&&a?.isRiding&&n?.type!=="character")return null;switch(i.type){case"vehicle":return d.jsx(se,{object:i,selected:o,...t?{onSelect:t}:{},showDebugInfo:r},i.id);case"airplane":return d.jsx(te,{object:i,selected:o,...t?{onSelect:t}:{},showDebugInfo:r},i.id);case"character":return d.jsx(re,{object:i,selected:o,...t?{onSelect:t}:{},showDebugInfo:r},i.id);default:return null}})})}function ae(s){const{children:e,visible:t=!0,...r}=s,a=x.useGenericRefs();return d.jsx("group",{visible:t,children:d.jsx(b.PhysicsEntity,{...r,url:r.url||"",isActive:!1,componentType:"vehicle",name:r.name??"vehicle",ref:a.rigidBodyRef,outerGroupRef:a.outerGroupRef,innerGroupRef:a.innerGroupRef,colliderRef:a.colliderRef,children:e})})}function ne(s){const{children:e,visible:t=!0,...r}=s,a=x.useGenericRefs();return d.jsx("group",{visible:t,children:d.jsx(b.PhysicsEntity,{...r,url:r.url||"",isActive:!1,componentType:"airplane",name:r.name??"airplane",ref:a.rigidBodyRef,outerGroupRef:a.outerGroupRef,innerGroupRef:a.innerGroupRef,colliderRef:a.colliderRef,children:e})})}function Ge(s){const{children:e,visible:t=!0,...r}=s,a=x.useGenericRefs();g.useEffect(()=>{a.rigidBodyRef&&a.rigidBodyRef.current&&a.rigidBodyRef.current.setEnabledRotations(!1,!1,!1,!1)},[a.rigidBodyRef]);const n=r.controllerOptions??{lerp:{cameraTurn:1,cameraPosition:1}};return d.jsx("group",{visible:t,children:d.jsx(b.PhysicsEntity,{...r,url:r.url||"",isActive:!1,componentType:"character",controllerOptions:n,ref:a.rigidBodyRef,outerGroupRef:a.outerGroupRef,innerGroupRef:a.innerGroupRef,colliderRef:a.colliderRef,children:e})})}const Ae=150*150,Ue=g.memo(function({object:e,isSelected:t,onSelect:r,showDebugInfo:a=!1,enableInteraction:n=!0}){const i=x.useGenericRefs(),o=e.metadata?.modelUrl,l=typeof o=="string"?o:void 0,f=g.useCallback(()=>{n&&e.interactable&&r&&r(e.id)},[n,e.interactable,e.id,r]),u=g.useCallback(v=>{n&&e.interactable&&(v.stopPropagation(),document.body.style.cursor="pointer")},[n,e.interactable]),h=g.useCallback(()=>{document.body.style.cursor="default"},[]);return l?d.jsx(b.PhysicsEntity,{url:l,isActive:!1,componentType:e.type,name:`passive-${e.type}-${e.id}`,position:e.position,rotation:e.rotation,scale:e.scale,ref:i.rigidBodyRef,outerGroupRef:i.outerGroupRef,innerGroupRef:i.innerGroupRef,colliderRef:i.colliderRef,userData:{id:e.id,type:"passive",subType:e.type,interactable:e.interactable,onNear:e.metadata?.onNear,onLeave:e.metadata?.onLeave,onInteract:e.metadata?.onInteract},onCollisionEnter:()=>{n&&e.interactable&&r&&r(e.id)},children:t&&a&&d.jsxs("mesh",{position:[0,3,0],children:[d.jsx("boxGeometry",{args:[.5,.5,.5]}),d.jsx("meshStandardMaterial",{color:"#00ff00",transparent:!0,opacity:.6})]})}):d.jsxs(U.RigidBody,{type:"fixed",position:e.position,rotation:e.rotation,colliders:!1,children:[d.jsx(U.CapsuleCollider,{args:[1,.5],position:[0,1,0]}),d.jsx("group",{scale:e.scale,onClick:f,onPointerEnter:u,onPointerLeave:h})]})}),Me=g.memo(function({objects:e,selectedId:t,onSelect:r,showDebugInfo:a=!1,enableInteraction:n=!0}){const[i,o]=g.useState(()=>new Set),l=g.useRef(0);ue.useFrame((u,h)=>{if(l.current+=h,l.current<.5)return;l.current=0;const v=u.camera.position,R=new Set;for(const S of e){const D=S.position.x,C=S.position.y,B=S.position.z,M=D-v.x,c=C-v.y,y=B-v.z;M*M+c*c+y*y<=Ae&&R.add(S.id)}(R.size!==i.size||[...R].some(S=>!i.has(S)))&&o(R)});const f=g.useMemo(()=>e.filter(u=>i.has(u.id)).map(u=>d.jsx(Ue,{object:u,isSelected:u.id===t,...r?{onSelect:r}:{},showDebugInfo:a,enableInteraction:n},u.id)),[e,t,r,a,n,i]);return d.jsx("group",{name:"passive-objects",children:f})});function _e({states:s}){if(!s||!s.canRide&&!s.isRiding)return null;const e=s.nearbyRideable?.rideMessage??`Press F to ride ${s.nearbyRideable?.displayName??s.nearbyRideable?.name??"vehicle"}`,t=s.nearbyRideable?.exitMessage??"Press F to exit";return d.jsx("div",{className:"rideable-ui-container",children:d.jsxs("div",{className:"message-box",children:[s.canRide&&d.jsx("div",{children:e}),s.isRiding&&d.jsx("div",{children:t})]})})}function We(s){const e=p.useGaesupStore(u=>u.rideable),{initRideable:t,onRideableNear:r,onRideableLeave:a,landing:n}=ve();g.useEffect(()=>{t(s)},[s,t]);const{controllerOptions:i,...o}=s,l=i?.lerp?{lerp:{cameraTurn:i.lerp.cameraTurn??1,cameraPosition:i.lerp.cameraPosition??1}}:void 0,f={objectType:s.objectType,objectkey:s.objectkey,rideable:!0,init:t,onNear:r,onLeave:a,landing:n,rideMessage:s.rideMessage,exitMessage:s.exitMessage,displayName:s.displayName};return d.jsxs(d.Fragment,{children:[s.objectType==="vehicle"&&d.jsx(ae,{...o,...l?{controllerOptions:l}:{},userData:f,sensor:!0,visible:!e[s.objectkey]?.isOccupied}),s.objectType==="airplane"&&d.jsx(ne,{...o,...l?{controllerOptions:l}:{},userData:f,sensor:!0,visible:!e[s.objectkey]?.isOccupied})]})}exports.BugSpot=m.BugSpot;exports.DEFAULT_RUNTIME_SAVE_DIAGNOSTICS_SERVICE_ID=m.DEFAULT_RUNTIME_SAVE_DIAGNOSTICS_SERVICE_ID;exports.DEFAULT_WORLD_SAVE_ENVIRONMENT=m.DEFAULT_WORLD_SAVE_ENVIRONMENT;exports.FishSpot=m.FishSpot;exports.RUNTIME_SAVE_DIAGNOSTIC_EVENT=m.RUNTIME_SAVE_DIAGNOSTIC_EVENT;exports.TreeObject=m.TreeObject;exports.createCameraSaveDataFromDomain=m.createCameraSaveDataFromDomain;exports.createGaesupRuntime=m.createGaesupRuntime;exports.createRuntimeSaveDiagnostics=m.createRuntimeSaveDiagnostics;exports.createSaveDataFromSaveSystem=m.createSaveDataFromSaveSystem;exports.createWorldDataFromSaveDomains=m.createWorldDataFromSaveDomains;exports.formatRuntimeSaveDiagnostic=m.formatRuntimeSaveDiagnostic;exports.normalizeSaveMetadata=m.normalizeSaveMetadata;exports.parseWorldSaveId=m.parseWorldSaveId;exports.parseWorldSaveTimestamp=m.parseWorldSaveTimestamp;exports.useAutoSave=m.useAutoSave;exports.useLoadOnMount=m.useLoadOnMount;exports.shouldSetupPluginForRuntime=le.shouldSetupPluginForRuntime;exports.GaesupRuntimeProvider=b.GaesupRuntimeProvider;exports.useGaesupRuntime=b.useGaesupRuntime;exports.useGaesupRuntimeRevision=b.useGaesupRuntimeRevision;exports.GaesupWorldContent=W.GaesupWorldContent;exports.World=W.WorldContainer;exports.WorldConfigProvider=W.WorldConfigProvider;exports.WorldContainer=W.WorldContainer;exports.DuplicateSaveDomainBindingError=I.DuplicateSaveDomainBindingError;exports.IndexedDBAdapter=I.IndexedDBAdapter;exports.LocalStorageAdapter=I.LocalStorageAdapter;exports.SaveSystem=I.SaveSystem;exports.WorldProps=I.WorldProps;exports.createDefaultSaveSystem=I.createDefaultSaveSystem;exports.getSaveSystem=I.getSaveSystem;exports.ActiveObjects=Te;exports.Airplane=te;exports.Character=re;exports.PassiveAirplane=ne;exports.PassiveCharacter=Ge;exports.PassiveObjects=Me;exports.PassiveVehicle=ae;exports.Rideable=We;exports.RideableUI=_e;exports.SaveLoadManager=w;exports.Vehicle=se;exports.createPersistenceSlice=Pe;exports.createPersistenceSliceWithOptions=ee;exports.createWorldSlice=be;
package/dist/runtime.js CHANGED
@@ -1,18 +1,18 @@
1
1
  import "reflect-metadata";
2
- import { c as le, n as de, a as ue, p as fe, D as pe } from "./index-BxrA12Fe.js";
3
- import { B as Et, d as Ot, F as It, R as jt, T as Dt, g as xt, b as Bt, e as Tt, f as Ut, h as Ct, u as Mt, i as At } from "./index-BxrA12Fe.js";
2
+ import { c as le, n as de, a as ue, p as fe, D as pe } from "./index-DShLht0Q.js";
3
+ import { B as Et, d as Ot, F as It, R as jt, T as Dt, g as xt, b as Bt, e as Tt, f as Ut, h as Ct, u as Mt, i as At } from "./index-DShLht0Q.js";
4
4
  import { s as Gt } from "./runtimeFilter-CS35UPHd.js";
5
- import { $ as ye, a0 as ge, a1 as me, a2 as he, a3 as ve, a4 as be, V as Y, a5 as Se, _ as D } from "./index-eON1JSxy.js";
6
- import { T as zt, a6 as Lt, a7 as Nt } from "./index-eON1JSxy.js";
5
+ import { $ as ye, a0 as ge, a1 as me, a2 as he, a3 as ve, a4 as be, V as Y, a5 as Se, _ as D } from "./index-C5agFfBe.js";
6
+ import { T as zt, a6 as Lt, a7 as Nt } from "./index-C5agFfBe.js";
7
7
  import * as V from "three";
8
8
  import { H as E, P as O, R as Re, u as I, B as we, T as ee, a as Ee } from "./gaesupStore-DTu0tYBp.js";
9
- import { G as kt, W as Wt, a as $t, W as Vt } from "./index-Dw6Hncw5.js";
9
+ import { G as kt, W as Wt, a as $t, W as Vt } from "./index-Drmv86ws.js";
10
10
  import { jsx as f, jsxs as j, Fragment as Oe } from "react/jsx-runtime";
11
- import { u as x } from "./index-CfiJq_gE.js";
11
+ import { u as x } from "./index-D0Rz5_-J.js";
12
12
  import { useCallback as S, useEffect as N, memo as te, useState as Ie, useRef as je, useMemo as De } from "react";
13
13
  import { useFrame as xe } from "@react-three/fiber";
14
14
  import { vec3 as J, euler as Be, RigidBody as Te, CapsuleCollider as Ue } from "@react-three/rapier";
15
- import { D as Kt, I as Ht, L as Zt, S as qt, W as Xt, c as Qt, g as Yt } from "./index-CauGUCKK.js";
15
+ import { D as Kt, I as Ht, L as Zt, S as qt, W as Xt, c as Qt, g as Yt } from "./index-BUQXtHf3.js";
16
16
  class M {
17
17
  cellSize;
18
18
  cells = /* @__PURE__ */ new Map();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gaesup-world",
3
- "version": "1.0.19",
3
+ "version": "1.0.21",
4
4
  "type": "module",
5
5
  "description": "Web 3D Character Controller and World Platform Library",
6
6
  "exports": {
@@ -1 +0,0 @@
1
- "use strict";const u=require("react"),j=require("@react-three/fiber"),rt=require("three"),q=require("./index-BOdJzeGD.cjs"),C=require("./gaesupStore-2zKBYTYo.cjs");require("reflect-metadata");const at=require("mitt");function ct(o){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(o){for(const t in o)if(t!=="default"){const i=Object.getOwnPropertyDescriptor(o,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:()=>o[t]})}}return e.default=o,Object.freeze(e)}const a=ct(rt);var lt=Object.defineProperty,ut=Object.getOwnPropertyDescriptor,H=(o,e,t,i)=>{for(var n=ut(e,t),r=o.length-1,c;r>=0;r--)(c=o[r])&&(n=c(e,t,n)||n);return n&&lt(e,t,n),n};function _(o){return{...o,distance:{...o.distance},smoothing:{...o.smoothing},...o.focusTarget?{focusTarget:{...o.focusTarget}}:{},...o.offset?{offset:{...o.offset}}:{},...o.lookAt?{lookAt:{...o.lookAt}}:{}}}class I{emitter;config;metrics={frameCount:0,totalFrameTime:0,lastUpdateTime:0};constructor(e){this.emitter=at(),this.config=_(e)}updateConfig(e){const t={...this.config};this.config=_({...this.config,...e}),Object.keys(e).forEach(i=>{this.emitter.emit("configChange",{key:i,value:e[i]})}),t.mode!==this.config.mode&&this.emitter.emit("modeChange",{from:t.mode,to:this.config.mode})}getConfig(){return _(this.config)}getState(){return{config:this.getConfig(),metrics:this.getMetrics()}}getMetrics(){return{frameCount:this.metrics.frameCount,averageFrameTime:this.metrics.frameCount>0?this.metrics.totalFrameTime/this.metrics.frameCount:0,lastUpdateTime:this.metrics.lastUpdateTime}}trackFrameMetrics(e){this.metrics.frameCount++,this.metrics.totalFrameTime+=e,this.metrics.lastUpdateTime=Date.now()}emitError(e,t){this.emitter.emit("error",{message:e,details:t})}destroy(){this.emitter.all.clear()}}H([C.HandleError()],I.prototype,"updateConfig");H([C.Profile()],I.prototype,"trackFrameMetrics");H([C.HandleError()],I.prototype,"destroy");const D=new a.Vector3,B=new a.Vector3,ft=new a.Quaternion,mt=new a.Matrix4,G=new a.Quaternion,R=new a.Vector3,A=new a.Raycaster,U=[],K=new a.Vector3,$=new a.Vector3,dt=new a.Vector3,ht=new a.Euler,gt=new a.Vector3,pt=new a.Vector3;new a.Vector3;let Z=[],J=null,W=-1;function tt(o){const e=[];return o.traverse(t=>{t instanceof a.Mesh&&!t.userData.intangible&&t.geometry?.boundingSphere&&e.push(t)}),e}function yt(o){const e=o._frameId;return e===void 0?tt(o):(o===J&&e-W<60||(J=o,W=e,Z=tt(o)),Z)}function vt(o,e){if(!e||e.length===0)return!1;let t=o;for(;t;){for(let i=0,n=e.length;i<n;i++)if(t===e[i])return!0;t=t.parent}return!1}const v={tempVectors:{temp1:new a.Vector3,temp2:new a.Vector3,temp3:new a.Vector3},clampValue:(o,e,t)=>Math.max(e,Math.min(t,o)),smoothingToSpeed:(o,e=C.CAMERA_CONSTANTS.FRAME_RATE_LERP_SPEED)=>{if(o===void 0||!Number.isFinite(o))return e;if(o<=0)return 0;if(o>=1)return o;const t=v.clampValue(o,.001,.999);return-Math.log(1-t)*60},frameRateIndependentLerpVector3:(o,e,t,i)=>{const n=1-Math.exp(-t*i);o.lerp(e,n)},smoothLookAt:(o,e,t,i)=>{const n=ft.setFromRotationMatrix(mt.lookAt(o.position,e,o.up)).normalize();G.copy(o.quaternion).normalize(),G.dot(n)<0&&(n.x*=-1,n.y*=-1,n.z*=-1,n.w*=-1);const r=1-Math.exp(-t*i);o.quaternion.slerp(n,r).normalize()},preventCameraJitter:(o,e,t,i,n,r=i*.8)=>{v.frameRateIndependentLerpVector3(o.position,e,i,n),v.smoothLookAt(o,t,r,n)},improvedCollisionCheck:(o,e,t,i=.5,n)=>{R.subVectors(e,o);const r=R.length();if(r<=0)return{safe:!0,position:e,obstacles:[]};R.multiplyScalar(1/r),A.set(o,R),A.near=0,A.far=r;const c=[],l=yt(t);for(let d=0,S=l.length;d<S;d++){const w=l[d];if(!w||vt(w,n))continue;U.length=0,A.intersectObject(w,!1,U);const g=U[0];g&&c.push({object:w,distance:g.distance,point:g.point})}if(c.length===0)return{safe:!0,position:e,obstacles:[]};const m=c.reduce((d,S)=>S.distance<d.distance?S:d);return K.copy(o).addScaledVector(R,Math.max(0,m.distance-i)),$.copy(K),{safe:!1,position:$,obstacles:c}},distanceSquared:(o,e)=>D.subVectors(o,e).lengthSq(),safeNormalize:o=>{const e=o.length();return e>0?o.divideScalar(e):o.set(0,0,0)},smoothDamp:(o,e,t,i,n,r)=>{const c=2/i,l=c*n,m=1/(1+l+.48*l*l+.235*l*l*l);D.subVectors(o,e);const d=r?r*i:1/0;D.clampLength(0,d),B.copy(t).addScaledVector(D,c).multiplyScalar(n),t.copy(t).sub(B).multiplyScalar(m),o.copy(e).add(D.add(B).multiplyScalar(m))},calculateBounds:(o,e,t)=>{if(!t)return o;const i=t.minX!==void 0?Math.max(t.minX,o.x):o.x,n=t.minY!==void 0?Math.max(t.minY,o.y):o.y,r=t.minZ!==void 0?Math.max(t.minZ,o.z):o.z,c=t.maxX!==void 0?Math.min(t.maxX,i):i,l=t.maxY!==void 0?Math.min(t.maxY,n):n,m=t.maxZ!==void 0?Math.min(t.maxZ,r):r;return D.set(c,l,m)},fastAtan2:(o,e)=>e===0?o>0?Math.PI/2:o<0?-Math.PI/2:0:e>0?Math.atan(o/e):Math.atan(o/e)+(o>=0?Math.PI:-Math.PI),updateFOV:(o,e,t,i)=>{if(!t||t<=0){if(Math.abs(e-o.fov)<1e-4)return;o.fov=e,o.updateProjectionMatrix();return}const n=i===void 0?t:1-Math.exp(-v.smoothingToSpeed(t)*i),r=n>=1?e:a.MathUtils.lerp(o.fov,e,n);Math.abs(r-o.fov)<1e-4||(o.fov=r,o.updateProjectionMatrix())},clampPosition:(o,e)=>(e&&(o.y=v.clampValue(o.y,e.minY||-1/0,e.maxY||1/0)),o),isPositionEqual:(o,e,t=.001)=>Math.abs(o.x-e.x)<t&&Math.abs(o.y-e.y)<t&&Math.abs(o.z-e.z)<t,pool:{vectors:[],getVector3:()=>v.pool.vectors.pop()||new a.Vector3,releaseVector3:o=>{o.set(0,0,0),v.pool.vectors.push(o)}},calculateSafeDistance:(o,e,t,i)=>{const n=o.distanceTo(e);return a.MathUtils.clamp(n,t,i)},isPositionValid:(o,e)=>e?o.y>=(e.minY??-1/0)&&o.y<=(e.maxY??1/0):!0},y={getPosition:o=>o?.position?o.position:dt.set(0,0,0),getEuler:o=>o?.euler?o.euler:ht.set(0,0,0),getVelocity:o=>o?.velocity?o.velocity:gt.set(0,0,0),calculateCameraOffset:(o,e,t)=>{const{xDistance:i=15,yDistance:n=8,zDistance:r=15,euler:c,mode:l="thirdPerson"}=e,m=t??pt;switch(l){case"chase":if(c){const d=1/Math.SQRT2;return m.set(-i*Math.sin(c.y)*d,n*d,-r*Math.cos(c.y)*d)}return m.set(-i,n,-r);case"thirdPerson":default:return m.set(-i,n,-r)}},getCameraTarget:(o,e)=>{const t=y.getPosition(o);return e.target||t}};var wt=Object.defineProperty,Ct=Object.getOwnPropertyDescriptor,it=(o,e,t,i)=>{for(var n=Ct(e,t),r=o.length-1,c;r>=0;r--)(c=o[r])&&(n=c(e,t,n)||n);return n&&wt(e,t,n),n};class P{focusTarget=new a.Vector3;focusDirection=new a.Vector3;focusBasePosition=new a.Vector3;focusTargetPosition=new a.Vector3;orbitRight=new a.Vector3;orbitYawQuaternion=new a.Quaternion;orbitPitchQuaternion=new a.Quaternion;xAxis=new a.Vector3(1,0,0);yAxis=new a.Vector3(0,1,0);applyDefaults(e){const t=this.defaultConfig,i=e.config;if(t.enableCollision!==void 0&&i.enableCollision===void 0&&(i.enableCollision=t.enableCollision),t.distance){const n=i.distance;n?(n.x===void 0&&t.distance.x!==void 0&&(n.x=t.distance.x),n.y===void 0&&t.distance.y!==void 0&&(n.y=t.distance.y),n.z===void 0&&t.distance.z!==void 0&&(n.z=t.distance.z)):i.distance={...t.distance}}if(t.smoothing){const n=i.smoothing;n?(n.position===void 0&&t.smoothing.position!==void 0&&(n.position=t.smoothing.position),n.rotation===void 0&&t.smoothing.rotation!==void 0&&(n.rotation=t.smoothing.rotation),n.fov===void 0&&t.smoothing.fov!==void 0&&(n.fov=t.smoothing.fov)):i.smoothing={...t.smoothing}}}calculateLookAt(e,t){return y.getPosition(e.activeState)}applyOrbitOffset(e,t){const i=t.config.orbitYaw??0,n=t.config.orbitPitch??0;return i===0&&n===0||(i!==0&&(this.orbitYawQuaternion.setFromAxisAngle(this.yAxis,i),e.applyQuaternion(this.orbitYawQuaternion)),n!==0&&(this.orbitRight.crossVectors(e,this.yAxis),this.orbitRight.lengthSq()<=1e-6?this.orbitRight.copy(this.xAxis):this.orbitRight.normalize(),this.orbitPitchQuaternion.setFromAxisAngle(this.orbitRight,n),e.applyQuaternion(this.orbitPitchQuaternion))),e}update(e,t){const{camera:i,deltaTime:n,activeState:r}=e;if(!r)return;this.applyDefaults(t);const c=t.config;let l,m;if(c.focus&&c.focusTarget){const g=this.focusTarget;g.set(c.focusTarget.x,c.focusTarget.y,c.focusTarget.z),m=g;const z=c.focusDistance||10,E=this.focusBasePosition.copy(this.calculateTargetPosition(e,t)),p=this.focusDirection;p.copy(E).sub(g),p.lengthSq()===0&&p.copy(i.position).sub(g),p.lengthSq()===0&&p.set(1,1,1),p.normalize(),l=this.focusTargetPosition.copy(g).addScaledVector(p,z)}else l=this.calculateTargetPosition(e,t),m=this.calculateLookAt(e,t);c.enableCollision&&(l=v.improvedCollisionCheck(m,l,e.scene,c.collisionMargin??.5,e.excludeObjects).position);const d=c.focusLerpSpeed||10,S=c.focus?d:v.smoothingToSpeed(c.smoothing?.position),w=c.focus?d*.8:v.smoothingToSpeed(c.smoothing?.rotation,S*.8);v.preventCameraJitter(i,l,m,S,n,w),t.config.fov&&i instanceof a.PerspectiveCamera&&v.updateFOV(i,t.config.fov,t.config.smoothing?.fov,n)}}it([C.Profile()],P.prototype,"calculateLookAt");it([C.HandleError(),C.Profile()],P.prototype,"update");class xt extends P{name="thirdPerson";target=new a.Vector3;offset=new a.Vector3;defaultConfig={distance:{x:15,y:8,z:15},smoothing:{position:.1,rotation:.1,fov:.1},enableCollision:!0};calculateTargetPosition(e,t){const i=y.getPosition(e.activeState),n=t.config.zoom||1;return y.calculateCameraOffset(i,{xDistance:t.config.distance.x*n,yDistance:t.config.distance.y*n,zDistance:t.config.distance.z*n,mode:"thirdPerson"},this.offset),this.applyOrbitOffset(this.offset,t),this.target.copy(i).add(this.offset)}}class bt extends P{name="firstPerson";target=new a.Vector3;lookAt=new a.Vector3;lookDirection=new a.Vector3;eyePosition=new a.Vector3;defaultConfig={distance:{x:0,y:2,z:.45},smoothing:{position:.2,rotation:.15,fov:.1},enableCollision:!1};calculateTargetPosition(e,t){const i=y.getPosition(e.activeState),n=y.getEuler(e.activeState),r=t.config.distance.y||this.defaultConfig.distance?.y||2,c=t.config.distance.z||this.defaultConfig.distance?.z||.45,l=this.lookDirection.set(0,0,-1);return n&&l.applyEuler(n),this.target.set(i.x,i.y+r,i.z).addScaledVector(l,c)}calculateLookAt(e,t){const i=this.eyePosition.copy(this.calculateTargetPosition(e,t)),n=y.getEuler(e.activeState),r=this.lookDirection.set(0,0,-1);return n&&r.applyEuler(n),this.lookAt.copy(i).add(r)}}class St extends P{name="chase";target=new a.Vector3;offset=new a.Vector3;defaultConfig={distance:{x:10,y:5,z:10},smoothing:{position:.15,rotation:.1,fov:.1},enableCollision:!0};calculateTargetPosition(e,t){const i=y.getPosition(e.activeState),n=y.getEuler(e.activeState),r=t.config.zoom||-1;return y.calculateCameraOffset(i,{xDistance:t.config.distance.x*r,yDistance:t.config.distance.y*r,zDistance:t.config.distance.z*r,euler:n,mode:"chase"},this.offset),this.applyOrbitOffset(this.offset,t),this.target.copy(i).add(this.offset)}}class Pt extends P{name="topDown";target=new a.Vector3;offset=new a.Vector3;yawQuaternion=new a.Quaternion;pitchQuaternion=new a.Quaternion;topDownXAxis=new a.Vector3(1,0,0);topDownYAxis=new a.Vector3(0,1,0);defaultConfig={distance:{x:0,y:20,z:0},smoothing:{position:.1,rotation:.1,fov:.1},enableCollision:!1};calculateTargetPosition(e,t){const i=y.getPosition(e.activeState),n=t.config.zoom||1,r=this.offset.set(0,t.config.distance.y*n,0),c=t.config.orbitPitch??0,l=t.config.orbitYaw??0;return c!==0&&(this.pitchQuaternion.setFromAxisAngle(this.topDownXAxis,c),r.applyQuaternion(this.pitchQuaternion)),l!==0&&(this.yawQuaternion.setFromAxisAngle(this.topDownYAxis,l),r.applyQuaternion(this.yawQuaternion)),this.target.copy(i).add(r)}}class Mt extends P{name="isometric";target=new a.Vector3;defaultConfig={distance:{x:15,y:15,z:15},smoothing:{position:.1,rotation:.1,fov:.1},enableCollision:!1};calculateTargetPosition(e,t){const i=y.getPosition(e.activeState),n=Math.PI/4,r=Math.sqrt(t.config.distance.x**2+t.config.distance.z**2);return this.target.set(i.x+Math.cos(n)*r,i.y+t.config.distance.y,i.z+Math.sin(n)*r)}}class Et extends P{name="sideScroll";target=new a.Vector3;defaultConfig={distance:{x:0,y:5,z:18},smoothing:{position:.08,rotation:.1,fov:.1},enableCollision:!1};calculateTargetPosition(e,t){const i=y.getPosition(e.activeState);return this.target.set(i.x+t.config.distance.x,i.y+t.config.distance.y,i.z+t.config.distance.z)}}class zt extends P{name="fixed";defaultPosition=new a.Vector3(0,10,10);defaultLookAt=new a.Vector3(0,0,0);defaultConfig={distance:{x:0,y:0,z:0},smoothing:{position:0,rotation:0,fov:0},enableCollision:!1};calculateTargetPosition(e,t){return t.config.fixedPosition||this.defaultPosition}calculateLookAt(e,t){return t.config.fixedLookAt||this.defaultLookAt}}var Tt=Object.getOwnPropertyDescriptor,Dt=(o,e,t,i)=>{for(var n=i>1?void 0:i?Tt(e,t):e,r=o.length-1,c;r>=0;r--)(c=o[r])&&(n=c(n)||n);return n};exports.CameraSystem=class extends I{controllers=new Map;state;cameraStates=new Map;currentCameraStateName="default";cameraTransitions=[];constructor(e){super(e),this.state=this.createInitialState(e),this.registerControllers(),this.initializeCameraStates()}createInitialState(e){return{config:_(e),lastUpdate:Date.now()}}initializeCameraStates(){const e={name:"default",type:"thirdPerson",position:new a.Vector3(0,5,10),rotation:new a.Euler(0,0,0),fov:75,config:{distance:{x:15,y:8,z:15},height:5,followSpeed:.1,rotationSpeed:.1},priority:0,tags:[]};this.cameraStates.set("default",e)}registerController(e){this.controllers.set(e.name,e)}updateConfig(e){super.updateConfig(e),this.state.config=this.getConfig()}update(e){this.trackFrameMetrics(e)}calculate(e){try{const t=this.controllers.get(this.state.config.mode);if(!t)return;this.state.activeController=t,t.update(e,this.state)}catch(t){this.emitError("Camera calculation failed",t instanceof Error?t.message:void 0)}}getCameraState(e){return this.cameraStates.get(e)}getCurrentCameraState(){return this.cameraStates.get(this.currentCameraStateName)}addCameraState(e,t){this.cameraStates.set(e,t)}setCameraTransitions(e){this.cameraTransitions=e,this.cameraTransitions.length}switchCameraState(e){if(this.cameraStates.has(e)){this.currentCameraStateName=e;const t=this.cameraStates.get(e),i={mode:t.type,fov:t.fov};t.config.distance&&(i.distance=t.config.distance),this.updateConfig(i)}}registerControllers(){this.registerController(new xt),this.registerController(new bt),this.registerController(new St),this.registerController(new Pt),this.registerController(new Mt),this.registerController(new Et),this.registerController(new zt)}};exports.CameraSystem=Dt([C.ManageRuntime({autoStart:!1})],exports.CameraSystem);function Rt(o,e,t){const i=u.useRef(null);i.current||(i.current=new o(e));const n=i.current;j.useFrame((m,d)=>{n?.update(d)}),u.useEffect(()=>{},[t,n]),u.useEffect(()=>()=>{n?.destroy()},[n]);const r=u.useCallback(m=>{n?.updateConfig(m)},[n]),c=u.useCallback(()=>n?.getState(),[n]),l=u.useCallback(()=>n?.getMetrics(),[n]);return{system:n,updateConfig:r,getState:c,getMetrics:l}}const et=.0015,ot=10,nt=1e-4,Vt=-.65,Ot=.85,N=o=>{if(!(o instanceof HTMLElement))return!1;const e=o.tagName.toLowerCase();return e==="input"||e==="textarea"||e==="select"||o.isContentEditable};function kt(){const{gl:o}=j.useThree(),{activeState:e}=q.useStateSystem(),t=C.useGaesupStore(s=>s.cameraOption),i=C.useGaesupStore(s=>s.setCameraOption),n=C.useGaesupStore(s=>s.mode),r=q.useBuildingStore(s=>s.isInEditMode()),c=q.useInputBackend(),l=u.useRef(t);u.useEffect(()=>{l.current=t},[t]);const m=u.useRef(n);u.useEffect(()=>{m.current=n},[n]);const d=u.useRef(r);u.useEffect(()=>{d.current=r},[r]);const S=u.useRef([]),w=u.useRef(null),g=u.useRef(new Set),z=u.useRef(!1),E=u.useRef(0),p=u.useRef(0),X=u.useRef(0),Y=u.useRef(0),st=u.useMemo(()=>({mode:n?.control||"thirdPerson",distance:{x:t?.xDistance??0,y:t?.yDistance??0,z:t?.zDistance??0},smoothing:{position:t?.smoothing?.position??.1,rotation:t?.smoothing?.rotation??.1,fov:t?.smoothing?.fov??.1},fov:t?.fov??75,zoom:t?.zoom??1,enableCollision:t?.enableCollision??!0,...t?.collisionMargin!==void 0?{collisionMargin:t.collisionMargin}:{},orbitYaw:E.current,orbitPitch:p.current,...t?.maxDistance!==void 0?{maxDistance:t.maxDistance}:{},...t?.offset?{offset:{x:t.offset.x,y:t.offset.y,z:t.offset.z}}:{},...t?.target?{lookAt:{x:t.target.x,y:t.target.y,z:t.target.z}}:{}}),[]),{system:Q,updateConfig:V}=Rt(exports.CameraSystem,st),O=u.useCallback(()=>{const s=l.current,h=m.current;V({mode:h?.control||"thirdPerson",distance:{x:s?.xDistance??0,y:s?.yDistance??0,z:s?.zDistance??0},smoothing:{position:s?.smoothing?.position??.1,rotation:s?.smoothing?.rotation??.1,fov:s?.smoothing?.fov??.1},fov:s?.fov??75,zoom:s?.zoom??1,enableCollision:s?.enableCollision??!0,...s?.collisionMargin!==void 0?{collisionMargin:s.collisionMargin}:{},orbitYaw:E.current,orbitPitch:p.current,...s?.maxDistance!==void 0?{maxDistance:s.maxDistance}:{},...s?.offset?{offset:{x:s.offset.x,y:s.offset.y,z:s.offset.z}}:{},...s?.target?{lookAt:{x:s.target.x,y:s.target.y,z:s.target.z}}:{},...s?.focus!==void 0?{focus:s.focus}:{},...s?.focusTarget?{focusTarget:{x:s.focusTarget.x,y:s.focusTarget.y,z:s.focusTarget.z}}:{focusTarget:void 0},...s?.focusDistance!==void 0?{focusDistance:s.focusDistance}:{},...s?.focusLerpSpeed!==void 0?{focusLerpSpeed:s.focusLerpSpeed}:{}})},[V]),F=u.useCallback(s=>{const h=l.current;if(!h?.enableZoom)return;s.preventDefault();const x=h.zoomSpeed||.001,M=h.minZoom||.45,b=h.maxZoom||2.4,k=h.zoom||1,T=s.deltaY*x,L=Math.min(Math.max(k+T,M),b);i({zoom:L})},[i]);return u.useEffect(()=>{const s=o.domElement;if(t?.enableZoom)return s.addEventListener("wheel",F,{passive:!1}),()=>{s.removeEventListener("wheel",F)}},[o,F,t?.enableZoom]),u.useEffect(()=>{const s=o.domElement,h=f=>{N(f.target)||(f.code==="ControlLeft"||f.code==="ControlRight")&&g.current.add(f.code)},x=f=>{f.code!=="ControlLeft"&&f.code!=="ControlRight"||g.current.delete(f.code)},M=f=>{!d.current||N(f.target)||f.button!==1&&f.button!==2||(f.preventDefault(),z.current=!0)},b=f=>{f.button!==1&&f.button!==2||(z.current=!1)},k=f=>{!(g.current.size>0||z.current)||N(f.target)||f.movementX===0&&f.movementY===0||(X.current-=f.movementX*et,Y.current=a.MathUtils.clamp(Y.current+f.movementY*et,Vt,Ot))},T=()=>{g.current.clear(),z.current=!1},L=f=>{d.current&&f.preventDefault()};return window.addEventListener("keydown",h),window.addEventListener("keyup",x),window.addEventListener("mousemove",k),window.addEventListener("mouseup",b),window.addEventListener("blur",T),document.addEventListener("visibilitychange",T),s.addEventListener("mousedown",M),s.addEventListener("contextmenu",L),()=>{window.removeEventListener("keydown",h),window.removeEventListener("keyup",x),window.removeEventListener("mousemove",k),window.removeEventListener("mouseup",b),window.removeEventListener("blur",T),document.removeEventListener("visibilitychange",T),s.removeEventListener("mousedown",M),s.removeEventListener("contextmenu",L)}},[o,V]),u.useEffect(()=>{const s=h=>{const x=l.current;h.key==="Escape"&&x?.focus&&i({focus:!1})};if(t?.enableFocus&&!r)return window.addEventListener("keydown",s),()=>{window.removeEventListener("keydown",s)}},[t?.enableFocus,r,i]),u.useLayoutEffect(()=>{c.updateMouse({isLookAround:!1}),O()},[c,O]),u.useLayoutEffect(()=>{O()},[t,n,O]),j.useFrame((s,h)=>{if(!Q)return;const x=a.MathUtils.damp(E.current,X.current,ot,h),M=a.MathUtils.damp(p.current,Y.current,ot,h);if((Math.abs(x-E.current)>nt||Math.abs(M-p.current)>nt)&&(E.current=x,p.current=M,V({orbitYaw:x,orbitPitch:M})),!w.current)w.current={camera:s.camera,scene:s.scene,deltaTime:h,activeState:e,clock:s.clock,excludeObjects:S.current};else{const b=w.current;b.camera=s.camera,b.scene=s.scene,b.deltaTime=h,b.activeState=e,b.clock=s.clock}Q.calculate(w.current)}),{system:Q}}function Lt(){return kt(),null}function At(){const o=u.useRef(null),e=u.useRef(null),t=u.useRef(null),i=u.useRef(null);return{outerGroupRef:o,innerGroupRef:e,rigidBodyRef:t,colliderRef:i}}exports.Camera=Lt;exports.useGenericRefs=At;
@@ -1,318 +0,0 @@
1
- import { jsx as m, jsxs as E, Fragment as B } from "react/jsx-runtime";
2
- import { useRef as P, useState as C, useEffect as K, useMemo as x, useCallback as I, memo as U } from "react";
3
- import * as S from "three";
4
- import { Line as L } from "@react-three/drei";
5
- import { V as T, G as z, W as N, X as F, Y as A, Z as V, U as q, _ as W } from "./index-eON1JSxy.js";
6
- import { useFrame as Z } from "@react-three/fiber";
7
- import { B as j, u as k } from "./gaesupStore-DTu0tYBp.js";
8
- import { vec3 as Y } from "@react-three/rapier";
9
- import { u as _ } from "./index-CfiJq_gE.js";
10
- const H = () => ({
11
- position: new S.Vector3(0, 0, 0),
12
- velocity: new S.Vector3(0, 0, 0),
13
- rotation: new S.Euler(0, 0, 0),
14
- isMoving: !1,
15
- isGrounded: !1,
16
- speed: 0,
17
- height: 2
18
- // Default character height
19
- });
20
- function X(e = {}) {
21
- const { updateInterval: d = 0, entityId: f } = e, l = P(null);
22
- l.current || (l.current = H());
23
- const [, g] = C(0), r = P(0), w = P(0), h = P({ x: 0, y: 0, z: 0 }), y = P(void 0), v = P(null), { activeState: R, gameStates: p } = T(), s = (u) => {
24
- if (f) return f;
25
- if (y.current) return y.current;
26
- const n = u.getActiveEntities();
27
- return y.current = n[0], y.current;
28
- };
29
- return K(() => {
30
- y.current = void 0, v.current = j.getOrCreate("motion");
31
- const u = v.current;
32
- if (!u) return;
33
- const n = u.subscribe((i, t) => {
34
- const a = s(u);
35
- if (!a || t !== a) return;
36
- const c = performance.now();
37
- if (w.current = c, d > 0 && c - r.current < d) return;
38
- r.current = c;
39
- const o = l.current;
40
- o.position.copy(i.position), o.velocity.copy(i.velocity), o.rotation.copy(i.rotation), o.isMoving = i.isMoving, o.isGrounded = i.isGrounded, o.speed = i.speed, o.height = 2, g((b) => b + 1);
41
- });
42
- return () => {
43
- n();
44
- };
45
- }, [f, d]), Z(() => {
46
- const u = performance.now();
47
- if (d > 0 && u - r.current < d) return;
48
- const n = l.current, i = v.current, t = (a) => {
49
- const c = h.current, o = a.x - c.x, b = a.y - c.y, M = a.z - c.z;
50
- return o * o + b * b + M * M > 1e-6 ? (c.x = a.x, c.y = a.y, c.z = a.z, !0) : !1;
51
- };
52
- if (i) {
53
- const a = s(i);
54
- if (!(u - w.current < 16) && a) {
55
- const o = i.snapshot(a);
56
- if (o) {
57
- n.position.copy(o.position), n.velocity.copy(o.velocity), n.rotation.copy(o.rotation), n.isMoving = o.isMoving, n.isGrounded = o.isGrounded, n.speed = o.speed, n.height = 2, r.current = u, t(n.position) && g((b) => b + 1);
58
- return;
59
- }
60
- }
61
- }
62
- R?.position && (n.position.copy(R.position), R.velocity ? n.velocity.copy(R.velocity) : n.velocity.set(0, 0, 0), R.euler ? n.rotation.copy(R.euler) : n.rotation.set(0, 0, 0), n.isMoving = p?.isMoving || !1, n.isGrounded = p?.isOnTheGround || !1, n.speed = R.velocity ? R.velocity.length() : 0, n.height = 2, r.current = u, t(n.position) && g((a) => a + 1));
63
- }), l.current;
64
- }
65
- const $ = {
66
- KeyW: "forward",
67
- KeyA: "leftward",
68
- KeyS: "backward",
69
- KeyD: "rightward",
70
- ShiftLeft: "shift",
71
- Space: "space",
72
- KeyZ: "keyZ",
73
- KeyR: "keyR",
74
- KeyF: "keyF",
75
- KeyE: "keyE",
76
- Escape: "escape"
77
- }, J = (e = !0, d = !0, f) => {
78
- const l = k((s) => s.automation?.queue.isRunning), g = k((s) => s.stopAutomation), r = k((s) => s.interaction?.isActive ?? !0), w = z((s) => s.isInEditMode()), h = N(), y = P(/* @__PURE__ */ new Set()), v = x(() => ({ ...$ }), []), R = I(
79
- (s, u) => {
80
- if (!r) return !1;
81
- try {
82
- return h.updateKeyboard({ [s]: u }), u ? y.current.add(s) : y.current.delete(s), !0;
83
- } catch (n) {
84
- return console.error("Error updating keyboard state:", n), !1;
85
- }
86
- },
87
- [h, r]
88
- ), p = I(() => {
89
- y.current.clear(), h.updateKeyboard({
90
- forward: !1,
91
- backward: !1,
92
- leftward: !1,
93
- rightward: !1,
94
- shift: !1,
95
- space: !1,
96
- keyZ: !1,
97
- keyR: !1,
98
- keyF: !1,
99
- keyE: !1,
100
- escape: !1
101
- });
102
- }, [h]);
103
- return K(() => {
104
- (!r || w) && p();
105
- }, [p, r, w]), K(() => {
106
- const s = (t, a) => {
107
- const c = v[t.code];
108
- if (!c) return;
109
- if (!r || w) {
110
- a && t.preventDefault(), p();
111
- return;
112
- }
113
- const o = y.current.has(t.code);
114
- a && !o ? (y.current.add(t.code), t.code === "Space" && t.preventDefault(), d && l && (c === "forward" || c === "backward" || c === "leftward" || c === "rightward") && (g(), h.updateMouse({ isActive: !1, shouldRun: !1 })), h.updateKeyboard({ [c]: !0 })) : !a && o && (y.current.delete(t.code), h.updateKeyboard({ [c]: !1 }));
115
- }, u = (t) => s(t, !0), n = (t) => s(t, !1), i = () => document.hidden && p();
116
- return window.addEventListener("keydown", u), window.addEventListener("keyup", n), document.addEventListener("visibilitychange", i), () => {
117
- window.removeEventListener("keydown", u), window.removeEventListener("keyup", n), document.removeEventListener("visibilitychange", i);
118
- };
119
- }, [
120
- v,
121
- d,
122
- g,
123
- l,
124
- p,
125
- r,
126
- w,
127
- h
128
- ]), {
129
- pressedKeys: Array.from(y.current),
130
- pushKey: R,
131
- isKeyPressed: (s) => y.current.has(s),
132
- clearAllKeys: p
133
- };
134
- }, D = U(({ points: e, color: d }) => e.length < 2 ? null : /* @__PURE__ */ m(
135
- L,
136
- {
137
- points: e,
138
- color: d,
139
- lineWidth: 2,
140
- dashed: !1
141
- }
142
- ));
143
- D.displayName = "PathLine";
144
- const O = U(() => /* @__PURE__ */ E("group", { children: [
145
- /* @__PURE__ */ E("mesh", { children: [
146
- /* @__PURE__ */ m("sphereGeometry", { args: [0.2, 16, 16] }),
147
- /* @__PURE__ */ m(
148
- "meshStandardMaterial",
149
- {
150
- color: "#00ff88",
151
- emissive: "#00ff88",
152
- emissiveIntensity: 0.5,
153
- transparent: !0,
154
- opacity: 0.9
155
- }
156
- )
157
- ] }),
158
- /* @__PURE__ */ E("mesh", { rotation: [Math.PI / 2, 0, 0], children: [
159
- /* @__PURE__ */ m("ringGeometry", { args: [0.3, 0.5, 8] }),
160
- /* @__PURE__ */ m(
161
- "meshStandardMaterial",
162
- {
163
- color: "#00ff88",
164
- transparent: !0,
165
- opacity: 0.6,
166
- side: S.DoubleSide
167
- }
168
- )
169
- ] })
170
- ] }));
171
- O.displayName = "TargetMarker";
172
- function Q() {
173
- const e = k((t) => t.automation), { position: d } = X(), { mouse: f } = F(), [l, g] = C(() => [...A()]);
174
- K(() => V(() => {
175
- g([...A()]);
176
- }), []);
177
- const r = f?.target || new S.Vector3(), w = f?.isActive || !1, h = e?.queue || { actions: [], currentIndex: 0 }, y = h.actions || [], v = h.currentIndex || 0, p = d.distanceTo(r) < 1, s = w && !p, u = y.map((t) => t.type === "move" && t.target ? new S.Vector3(t.target.x, t.target.y, t.target.z) : null).filter((t) => t !== null), n = l.length > 0 ? l : [r], i = s ? [d, ...n, ...u] : u.length > 0 ? [d, ...u] : [];
178
- return /* @__PURE__ */ E("group", { children: [
179
- s && /* @__PURE__ */ m("group", { position: r, children: /* @__PURE__ */ m(O, {}) }),
180
- i.length > 1 && /* @__PURE__ */ m(
181
- D,
182
- {
183
- points: i,
184
- color: v >= 0 ? "#00ff88" : "#ffaa00"
185
- }
186
- ),
187
- y.map((t, a) => {
188
- if (t.type === "move" && t.target) {
189
- const c = a === v, o = a < v;
190
- return /* @__PURE__ */ m(
191
- "group",
192
- {
193
- position: [t.target.x, t.target.y, t.target.z],
194
- children: /* @__PURE__ */ E("mesh", { children: [
195
- /* @__PURE__ */ m("sphereGeometry", { args: [0.1, 8, 8] }),
196
- /* @__PURE__ */ m(
197
- "meshStandardMaterial",
198
- {
199
- color: o ? "#888" : c ? "#ff4444" : "#ffaa00",
200
- transparent: !0,
201
- opacity: o ? 0.3 : 0.8
202
- }
203
- )
204
- ] })
205
- },
206
- `action-${a}`
207
- );
208
- }
209
- return null;
210
- })
211
- ] });
212
- }
213
- function ee({ clickerOptions: e }) {
214
- const { onClick: d } = q(e), f = (l) => {
215
- l.stopPropagation();
216
- const { cameraOption: g, setCameraOption: r } = k.getState();
217
- if (g?.focus) {
218
- r({ focus: !1 });
219
- return;
220
- }
221
- d(l);
222
- };
223
- return /* @__PURE__ */ E(
224
- "mesh",
225
- {
226
- position: [0, 0, 0],
227
- rotation: [-Math.PI / 2, 0, 0],
228
- onPointerDown: f,
229
- visible: !0,
230
- userData: { intangible: !0 },
231
- children: [
232
- /* @__PURE__ */ m("planeGeometry", { args: [1e3, 1e3] }),
233
- /* @__PURE__ */ m("meshBasicMaterial", { transparent: !0, opacity: 0 })
234
- ]
235
- }
236
- );
237
- }
238
- function te({ props: e, children: d }) {
239
- const f = k((i) => i.mode), { gameStates: l } = T(), g = k((i) => i.rideable), r = k((i) => i.urls), w = z((i) => i.isInEditMode()), h = _();
240
- if (J(), w || !f || !l || !g || !r || f.type === "character" && !r.characterUrl || f.type === "vehicle" && !r.vehicleUrl || f.type === "airplane" && !r.airplaneUrl) return null;
241
- const { canRide: y, isRiding: v, currentRideable: R } = l, p = R?.id, s = x(
242
- () => (p ? g[p]?.offset : void 0) ?? Y(),
243
- [p, g]
244
- ), n = (() => {
245
- const i = e.rigidBodyRef ?? h.rigidBodyRef, t = e.outerGroupRef ?? h.outerGroupRef, a = e.innerGroupRef ?? h.innerGroupRef, c = e.colliderRef ?? h.colliderRef, o = {
246
- isActive: !0,
247
- componentType: f.type,
248
- enableRiding: y,
249
- isRiderOn: v,
250
- offset: s,
251
- ref: i,
252
- outerGroupRef: t,
253
- innerGroupRef: a,
254
- colliderRef: c,
255
- parts: (e.parts || []).filter((G) => !!G.url).map((G) => ({ ...G, url: G.url })),
256
- ...e.onAnimate ? { onAnimate: e.onAnimate } : {},
257
- ...e.onFrame ? { onFrame: e.onFrame } : {},
258
- ...e.onReady ? { onReady: e.onReady } : {},
259
- ...e.onDestroy ? { onDestroy: e.onDestroy } : {},
260
- ...e.onDestory ? { onDestory: e.onDestory } : {},
261
- ...typeof e.baseColor == "string" && e.baseColor.trim().length > 0 ? { baseColor: e.baseColor } : {},
262
- ...Array.isArray(e.excludeBaseNodes) && e.excludeBaseNodes.length > 0 ? { excludeBaseNodes: e.excludeBaseNodes } : {},
263
- ...e.rigidBodyProps ? { rigidBodyProps: e.rigidBodyProps } : {},
264
- ...e.controllerOptions ? { controllerOptions: e.controllerOptions } : {},
265
- ...e.groundRay ? { groundRay: e.groundRay } : {},
266
- ...e.colliderSize ? { colliderSize: e.colliderSize } : {},
267
- ...e.position ? { position: e.position } : {},
268
- ...e.rotation ? { rotation: e.rotation } : {},
269
- ...e.scale ? { scale: e.scale } : {}
270
- }, b = v && f.type !== "character" ? r.ridingUrl : void 0, M = typeof b == "string" && b.length > 0 ? { ridingUrl: b } : {};
271
- switch (f.type) {
272
- case "character":
273
- return {
274
- ...o,
275
- url: r.characterUrl || ""
276
- };
277
- case "vehicle":
278
- return {
279
- ...o,
280
- ...M,
281
- url: r.vehicleUrl || "",
282
- wheelUrl: r.wheelUrl
283
- };
284
- case "airplane":
285
- return {
286
- ...o,
287
- ...M,
288
- url: r.airplaneUrl || ""
289
- };
290
- default:
291
- return {
292
- ...o,
293
- url: r.characterUrl || ""
294
- };
295
- }
296
- })();
297
- return f.type === "character" && l.isRiding ? null : /* @__PURE__ */ m(W, { ...n, children: d });
298
- }
299
- function ue(e) {
300
- const { clickToMove: d, children: f, clickerOptions: l, ...g } = e, r = {
301
- ...l ?? {},
302
- ...l?.agentRadius === void 0 && g.colliderSize?.radius !== void 0 ? { agentRadius: g.colliderSize.radius } : {}
303
- };
304
- return /* @__PURE__ */ m(te, { props: g, children: /* @__PURE__ */ E(B, { children: [
305
- d && /* @__PURE__ */ E(B, { children: [
306
- /* @__PURE__ */ m(ee, { clickerOptions: r }),
307
- /* @__PURE__ */ m(Q, {})
308
- ] }),
309
- f
310
- ] }) });
311
- }
312
- export {
313
- ue as C,
314
- ee as G,
315
- Q as a,
316
- X as b,
317
- J as u
318
- };
@@ -1 +0,0 @@
1
- "use strict";const S=require("react/jsx-runtime"),b=require("react"),O=require("three"),I=require("./index-BOdJzeGD.cjs");require("reflect-metadata");const C=require("./gaesupStore-2zKBYTYo.cjs");function z(n){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const t in n)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(n,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>n[t]})}}return e.default=n,Object.freeze(e)}const v=z(O),_="gaesup-save",j=1,M="slots";function L(){return new Promise((n,e)=>{if(typeof indexedDB>"u"){e(new Error("IndexedDB unavailable"));return}const t=indexedDB.open(_,j);t.onupgradeneeded=()=>{const r=t.result;r.objectStoreNames.contains(M)||r.createObjectStore(M)},t.onsuccess=()=>n(t.result),t.onerror=()=>e(t.error)})}function w(n,e){return L().then(t=>new Promise((r,a)=>{const o=t.transaction(M,n).objectStore(M),c=e(o);if(c instanceof Promise){c.then(r,a);return}c.onsuccess=()=>r(c.result),c.onerror=()=>a(c.error)}))}class R{async read(e){try{return await w("readonly",r=>r.get(e))??null}catch{return null}}async write(e,t){await w("readwrite",r=>r.put(t,e))}async list(){try{return(await w("readonly",t=>t.getAllKeys())).map(String)}catch{return[]}}async remove(e){try{await w("readwrite",t=>t.delete(e))}catch{}}}const y="gaesup:save:";function k(n,e){try{return n()}catch{return e}}class T{async read(e){return typeof localStorage>"u"?null:k(()=>{const t=localStorage.getItem(y+e);return t?JSON.parse(t):null},null)}async write(e,t){typeof localStorage>"u"||k(()=>localStorage.setItem(y+e,JSON.stringify(t)),void 0)}async list(){return typeof localStorage>"u"?[]:k(()=>{const e=[];for(let t=0;t<localStorage.length;t++){const r=localStorage.key(t);r&&r.startsWith(y)&&e.push(r.slice(y.length))}return e},[])}async remove(e){typeof localStorage>"u"||k(()=>localStorage.removeItem(y+e),void 0)}}class B{adapter;bindings=new Map;currentVersion;migrations;defaultSlot;diagnosticListeners=new Set;constructor(e){this.adapter=e.adapter,this.currentVersion=e.currentVersion??1,this.migrations=e.migrations??{},this.defaultSlot=e.defaultSlot??"main",e.onDiagnostic&&this.diagnosticListeners.add(e.onDiagnostic)}register(e){if(this.bindings.has(e.key))throw new E(e.key);const t={key:e.key,serialize:()=>e.serialize(),hydrate:r=>e.hydrate(r)};return this.bindings.set(e.key,t),()=>{this.bindings.get(e.key)===t&&this.bindings.delete(e.key)}}has(e){return this.bindings.has(e)}subscribeDiagnostics(e){return this.diagnosticListeners.add(e),()=>{this.diagnosticListeners.delete(e)}}getBindings(){return this.bindings.values()}createBlob(e=this.defaultSlot){const t={};for(const[r,a]of this.bindings)try{t[r]=a.serialize()}catch(i){t[r]=null,this.reportDiagnostic({phase:"serialize",key:r,slot:e,error:i})}return{version:this.currentVersion,savedAt:Date.now(),domains:t}}hydrateBlob(e,t=this.defaultSlot){let r=e;for(;r.version<this.currentVersion;){const a=this.migrations[r.version];if(!a)break;r=a(r)}for(const[a,i]of this.bindings)try{i.hydrate(r.domains?.[a])}catch(o){this.reportDiagnostic({phase:"hydrate",key:a,slot:t,error:o})}return!0}async save(e=this.defaultSlot){const t=this.createBlob(e);await this.adapter.write(e,t)}async load(e=this.defaultSlot){const t=await this.adapter.read(e);return t?this.hydrateBlob(t,e):!1}async list(){return this.adapter.list()}async remove(e=this.defaultSlot){return this.adapter.remove(e)}reportDiagnostic(e){for(const t of this.diagnosticListeners)t(e)}}class E extends Error{constructor(e){super(`Save domain "${e}" is already registered.`),this.name="DuplicateSaveDomainBindingError"}}let D=null;function A(){const n=typeof indexedDB<"u"?new R:new T;return new B({adapter:n,defaultSlot:"main",currentVersion:1})}function V(){return D||(D=A()),D}var W=Object.defineProperty,N=Object.getOwnPropertyDescriptor,q=(n,e,t)=>e in n?W(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,X=(n,e,t,r)=>{for(var a=r>1?void 0:r?N(e,t):e,i=n.length-1,o;i>=0;i--)(o=n[i])&&(a=o(a)||a);return a},F=(n,e,t)=>q(n,e+"",t);exports.MinimapSystem=class extends C.AbstractSystem{listeners;constructor(){const e={markers:new Map,canvas:null,ctx:null,isDirty:!0,lastPosition:null,lastRotation:null,gradientCache:{background:null,avatar:null},lastUpdate:Date.now()},t={markerCount:0,renderTime:0,frameTime:0};super(e,t),this.listeners=new Set}static getInstance(){return(!exports.MinimapSystem.instance||exports.MinimapSystem.instance.isDisposed)&&(exports.MinimapSystem.instance=new exports.MinimapSystem),exports.MinimapSystem.instance}addMarker(e,t,r,a,i){const o={id:e,type:t,text:r,center:a,size:i};this.state.markers.set(e,o),this.updateMetrics(0),this.notifyListeners()}removeMarker(e){this.state.markers.delete(e),this.updateMetrics(0),this.notifyListeners()}updateMarker(e,t){const r=this.state.markers.get(e);r&&(this.state.markers.set(e,{...r,...t}),this.updateMetrics(0),this.notifyListeners())}getMarkers(){return new Map(this.state.markers)}getMarker(e){return this.state.markers.get(e)}clear(){this.state.markers.clear(),this.updateMetrics(0),this.notifyListeners()}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notifyListeners(){const e=this.getMarkers();this.listeners.forEach(t=>t(e))}setCanvas(e){this.state.canvas=e,this.state.ctx=e?e.getContext("2d"):null,this.state.isDirty=!0,this.state.gradientCache={background:null,avatar:null}}checkForUpdates(e,t,r=.1,a=.01){const i=this.state.lastPosition,o=this.state.lastRotation;if(!i||o===null){this.state.isDirty=!0,this.state.lastPosition={x:e.x,z:e.z},this.state.lastRotation=t;return}const c=Math.abs(e.x-i.x)>r||Math.abs(e.z-i.z)>r,l=Math.abs(t-o)>a;(c||l)&&(this.state.isDirty=!0,this.state.lastPosition={x:e.x,z:e.z},this.state.lastRotation=t)}render(e){if(!this.state.canvas||!this.state.ctx||!this.state.isDirty)return;const t=performance.now(),{size:r,scale:a,position:i,rotation:o,blockRotate:c,tileGroups:l,sceneObjects:h}=e,s=this.state.ctx;if(s.clearRect(0,0,r,r),s.save(),s.beginPath(),s.arc(r/2,r/2,r/2,0,Math.PI*2),s.clip(),!this.state.gradientCache.background){const d=s.createRadialGradient(r/2,r/2,0,r/2,r/2,r/2);d.addColorStop(0,"rgba(20, 30, 40, 0.9)"),d.addColorStop(1,"rgba(10, 20, 30, 0.95)"),this.state.gradientCache.background=d}s.fillStyle=this.state.gradientCache.background,s.fillRect(0,0,r,r);const u=o*180/Math.PI;s.translate(r/2,r/2),s.rotate(-u*Math.PI/180),s.translate(-r/2,-r/2),s.save(),s.strokeStyle="rgba(255, 255, 255, 0.1)",s.lineWidth=1;for(let d=0;d<r;d+=20)s.beginPath(),s.moveTo(d,0),s.lineTo(d,r),s.moveTo(0,d),s.lineTo(r,d),s.stroke();s.restore(),this.renderCompass(s,r,u),l&&l.size>0&&this.renderTiles(s,r,a,i,l),h&&h.size>0&&this.renderSceneObjects(s,r,a,i,h),this.renderMarkers(s,r,a,i,u,c),this.renderAvatar(s,r),s.restore(),this.state.isDirty=!1,this.metrics.renderTime=performance.now()-t}renderCompass(e,t,r){e.save(),e.fillStyle="white",e.font="bold 16px sans-serif",e.shadowColor="rgba(0, 0, 0, 0.8)",e.shadowBlur=3,[{text:"N",x:t/2,y:25,color:"#ff6b6b"},{text:"S",x:t/2,y:t-25,color:"#4ecdc4"},{text:"E",x:t-25,y:t/2,color:"#45b7d1"},{text:"W",x:25,y:t/2,color:"#f9ca24"}].forEach(({text:i,x:o,y:c,color:l})=>{e.save(),e.fillStyle=l,e.translate(o,c),e.rotate(r*Math.PI/180),e.textAlign="center",e.textBaseline="middle",e.fillText(i,0,0),e.restore()}),e.restore()}renderTiles(e,t,r,a,i){Array.from(i.values()).forEach(c=>{c&&c.tiles&&Array.isArray(c.tiles)&&c.tiles.forEach(l=>{if(!l||!l.position)return;const h=(l.position.x-a.x)*r,s=(l.position.z-a.z)*r,u=(l.size||1)*4*r;e.save();const d=t/2-h-u/2,f=t/2-s-u/2;l.objectType==="water"?e.fillStyle="rgba(0, 150, 255, 0.6)":l.objectType==="grass"?e.fillStyle="rgba(50, 200, 50, 0.4)":l.objectType==="sand"?e.fillStyle="rgba(210, 180, 120, 0.45)":l.objectType==="snowfield"?e.fillStyle="rgba(225, 240, 255, 0.5)":e.fillStyle="rgba(150, 150, 150, 0.3)",e.fillRect(d,f,u,u),e.strokeStyle="rgba(255, 255, 255, 0.2)",e.lineWidth=.5,e.strokeRect(d,f,u,u),e.restore()})})}renderSceneObjects(e,t,r,a,i){i.forEach(o=>{if(!o?.position||!o?.size)return;const c=(o.position.x-a.x)*r,l=(o.position.z-a.z)*r,h=o.size.x*r,s=o.size.z*r;e.save();const u=t/2-c-h/2,d=t/2-l-s/2;e.fillStyle="rgba(100, 150, 200, 0.4)",e.fillRect(u,d,h,s),e.strokeStyle="rgba(255, 255, 255, 0.4)",e.lineWidth=1,e.strokeRect(u,d,h,s),e.restore()})}renderMarkers(e,t,r,a,i,o){this.state.markers.size!==0&&this.state.markers.forEach(c=>{if(!c?.center||!c?.size)return;const{center:l,size:h,text:s}=c,u=(l.x-a.x)*r,d=(l.z-a.z)*r;e.save();const f=h.x*r,g=h.z*r,m=t/2-u-f/2,p=t/2-d-g/2;e.shadowColor="rgba(0, 0, 0, 0.6)",e.shadowBlur=4,e.shadowOffsetX=2,e.shadowOffsetY=2,e.fillStyle="rgba(0,0,0,0.3)",e.fillRect(m,p,f,g),e.shadowColor="transparent",e.strokeStyle="rgba(255, 255, 255, 0.3)",e.lineWidth=1,e.strokeRect(m,p,f,g),s&&(e.save(),e.fillStyle="white",e.font="bold 12px sans-serif",e.shadowColor="rgba(0, 0, 0, 0.8)",e.shadowBlur=2,e.translate(m+f/2,p+g/2),o||e.rotate(-i*Math.PI/180),e.textAlign="center",e.textBaseline="middle",e.fillText(s,0,0),e.restore()),e.restore()})}renderAvatar(e,t){if(e.save(),!this.state.gradientCache.avatar){const r=e.createRadialGradient(t/2,t/2,0,t/2,t/2,12);r.addColorStop(0,"#01fff7"),r.addColorStop(.7,"#01fff7"),r.addColorStop(1,"transparent"),this.state.gradientCache.avatar=r}e.fillStyle=this.state.gradientCache.avatar,e.beginPath(),e.arc(t/2,t/2,12,0,Math.PI*2),e.fill(),e.fillStyle="#01fff7",e.shadowColor="0 0 10px rgba(1,255,247,0.7)",e.shadowBlur=8,e.beginPath(),e.arc(t/2,t/2,6,0,Math.PI*2),e.fill(),e.shadowColor="transparent",e.strokeStyle="rgba(255, 255, 255, 0.8)",e.lineWidth=2,e.beginPath(),e.moveTo(t/2,t/2),e.lineTo(t/2,t/2-12),e.stroke(),e.restore()}performUpdate(e){}createUpdateArgs(e){return e}updateMetrics(e){this.metrics.markerCount=this.state.markers.size,this.metrics.frameTime=e}onDispose(){this.clear(),this.listeners.clear(),this.state.canvas=null,this.state.ctx=null,exports.MinimapSystem.instance=null}};F(exports.MinimapSystem,"instance",null);exports.MinimapSystem=X([C.RegisterSystem("minimap"),C.ManageRuntime({autoStart:!1})],exports.MinimapSystem);function U({type:n="normal",text:e,position:t,children:r,interactive:a=!0,showMinimap:i=!0}){const o=b.useRef(null),c=I.useClicker(),l=b.useMemo(()=>`world-prop-${Date.now()}-${Math.random()}`,[]),h=b.useRef({center:new v.Vector3,size:new v.Vector3,positionAdd:new v.Vector3});return b.useEffect(()=>{if(!i||!o.current)return;const s=exports.MinimapSystem.getInstance(),d=setTimeout(()=>{const f=o.current;if(!f)return;const g=new v.Box3;if(g.setFromObject(f),!g.isEmpty()){const{center:m,size:p,positionAdd:P}=h.current;g.getCenter(m),g.getSize(p),t&&(P.set(t[0],t[1],t[2]),m.add(P)),s.addMarker(l,n,e||"",m.clone(),p.clone())}},100);return()=>{clearTimeout(d),s.removeMarker(l)}},[t,n,e,i,l]),S.jsxs("group",{ref:o,...t?{position:t}:{},onClick:s=>{a&&(s.stopPropagation(),c.onClick(s))},children:[r,e&&S.jsx("group",{position:[0,2,0],children:S.jsx("sprite",{scale:[2,.5,1],children:S.jsx("spriteMaterial",{color:"#ffffff",transparent:!0,opacity:.8})})})]})}exports.DuplicateSaveDomainBindingError=E;exports.IndexedDBAdapter=R;exports.LocalStorageAdapter=T;exports.SaveSystem=B;exports.WorldProps=U;exports.createDefaultSaveSystem=A;exports.getSaveSystem=V;
@@ -1 +0,0 @@
1
- "use strict";const i=require("react/jsx-runtime"),h=require("react"),A=require("three"),O=require("@react-three/drei"),S=require("./index-BOdJzeGD.cjs"),T=require("@react-three/fiber"),E=require("./gaesupStore-2zKBYTYo.cjs"),D=require("@react-three/rapier"),z=require("./index-B414uKZc.cjs");function U(e){const c=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const a in e)if(a!=="default"){const u=Object.getOwnPropertyDescriptor(e,a);Object.defineProperty(c,a,u.get?u:{enumerable:!0,get:()=>e[a]})}}return c.default=e,Object.freeze(c)}const k=U(A),q=()=>({position:new k.Vector3(0,0,0),velocity:new k.Vector3(0,0,0),rotation:new k.Euler(0,0,0),isMoving:!1,isGrounded:!1,speed:0,height:2});function G(e={}){const{updateInterval:c=0,entityId:a}=e,u=h.useRef(null);u.current||(u.current=q());const[,p]=h.useState(0),r=h.useRef(0),x=h.useRef(0),m=h.useRef({x:0,y:0,z:0}),g=h.useRef(void 0),R=h.useRef(null),{activeState:b,gameStates:v}=S.useStateSystem(),l=y=>{if(a)return a;if(g.current)return g.current;const n=y.getActiveEntities();return g.current=n[0],g.current};return h.useEffect(()=>{g.current=void 0,R.current=E.BridgeFactory.getOrCreate("motion");const y=R.current;if(!y)return;const n=y.subscribe((s,t)=>{const d=l(y);if(!d||t!==d)return;const f=performance.now();if(x.current=f,c>0&&f-r.current<c)return;r.current=f;const o=u.current;o.position.copy(s.position),o.velocity.copy(s.velocity),o.rotation.copy(s.rotation),o.isMoving=s.isMoving,o.isGrounded=s.isGrounded,o.speed=s.speed,o.height=2,p(w=>w+1)});return()=>{n()}},[a,c]),T.useFrame(()=>{const y=performance.now();if(c>0&&y-r.current<c)return;const n=u.current,s=R.current,t=d=>{const f=m.current,o=d.x-f.x,w=d.y-f.y,P=d.z-f.z;return o*o+w*w+P*P>1e-6?(f.x=d.x,f.y=d.y,f.z=d.z,!0):!1};if(s){const d=l(s);if(!(y-x.current<16)&&d){const o=s.snapshot(d);if(o){n.position.copy(o.position),n.velocity.copy(o.velocity),n.rotation.copy(o.rotation),n.isMoving=o.isMoving,n.isGrounded=o.isGrounded,n.speed=o.speed,n.height=2,r.current=y,t(n.position)&&p(w=>w+1);return}}}b?.position&&(n.position.copy(b.position),b.velocity?n.velocity.copy(b.velocity):n.velocity.set(0,0,0),b.euler?n.rotation.copy(b.euler):n.rotation.set(0,0,0),n.isMoving=v?.isMoving||!1,n.isGrounded=v?.isOnTheGround||!1,n.speed=b.velocity?b.velocity.length():0,n.height=2,r.current=y,t(n.position)&&p(d=>d+1))}),u.current}const N={KeyW:"forward",KeyA:"leftward",KeyS:"backward",KeyD:"rightward",ShiftLeft:"shift",Space:"space",KeyZ:"keyZ",KeyR:"keyR",KeyF:"keyF",KeyE:"keyE",Escape:"escape"},M=(e=!0,c=!0,a)=>{const u=E.useGaesupStore(l=>l.automation?.queue.isRunning),p=E.useGaesupStore(l=>l.stopAutomation),r=E.useGaesupStore(l=>l.interaction?.isActive??!0),x=S.useBuildingStore(l=>l.isInEditMode()),m=S.useInputBackend(),g=h.useRef(new Set),R=h.useMemo(()=>({...N}),[]),b=h.useCallback((l,y)=>{if(!r)return!1;try{return m.updateKeyboard({[l]:y}),y?g.current.add(l):g.current.delete(l),!0}catch(n){return console.error("Error updating keyboard state:",n),!1}},[m,r]),v=h.useCallback(()=>{g.current.clear(),m.updateKeyboard({forward:!1,backward:!1,leftward:!1,rightward:!1,shift:!1,space:!1,keyZ:!1,keyR:!1,keyF:!1,keyE:!1,escape:!1})},[m]);return h.useEffect(()=>{(!r||x)&&v()},[v,r,x]),h.useEffect(()=>{const l=(t,d)=>{const f=R[t.code];if(!f)return;if(!r||x){d&&t.preventDefault(),v();return}const o=g.current.has(t.code);d&&!o?(g.current.add(t.code),t.code==="Space"&&t.preventDefault(),c&&u&&(f==="forward"||f==="backward"||f==="leftward"||f==="rightward")&&(p(),m.updateMouse({isActive:!1,shouldRun:!1})),m.updateKeyboard({[f]:!0})):!d&&o&&(g.current.delete(t.code),m.updateKeyboard({[f]:!1}))},y=t=>l(t,!0),n=t=>l(t,!1),s=()=>document.hidden&&v();return window.addEventListener("keydown",y),window.addEventListener("keyup",n),document.addEventListener("visibilitychange",s),()=>{window.removeEventListener("keydown",y),window.removeEventListener("keyup",n),document.removeEventListener("visibilitychange",s)}},[R,c,p,u,v,r,x,m]),{pressedKeys:Array.from(g.current),pushKey:b,isKeyPressed:l=>g.current.has(l),clearAllKeys:v}},C=h.memo(({points:e,color:c})=>e.length<2?null:i.jsx(O.Line,{points:e,color:c,lineWidth:2,dashed:!1}));C.displayName="PathLine";const K=h.memo(()=>i.jsxs("group",{children:[i.jsxs("mesh",{children:[i.jsx("sphereGeometry",{args:[.2,16,16]}),i.jsx("meshStandardMaterial",{color:"#00ff88",emissive:"#00ff88",emissiveIntensity:.5,transparent:!0,opacity:.9})]}),i.jsxs("mesh",{rotation:[Math.PI/2,0,0],children:[i.jsx("ringGeometry",{args:[.3,.5,8]}),i.jsx("meshStandardMaterial",{color:"#00ff88",transparent:!0,opacity:.6,side:k.DoubleSide})]})]}));K.displayName="TargetMarker";function B(){const e=E.useGaesupStore(t=>t.automation),{position:c}=G(),{mouse:a}=S.useInteractionSystem(),[u,p]=h.useState(()=>[...S.getClickNavigationRoute()]);h.useEffect(()=>S.subscribeClickNavigationRoute(()=>{p([...S.getClickNavigationRoute()])}),[]);const r=a?.target||new k.Vector3,x=a?.isActive||!1,m=e?.queue||{actions:[],currentIndex:0},g=m.actions||[],R=m.currentIndex||0,v=c.distanceTo(r)<1,l=x&&!v,y=g.map(t=>t.type==="move"&&t.target?new k.Vector3(t.target.x,t.target.y,t.target.z):null).filter(t=>t!==null),n=u.length>0?u:[r],s=l?[c,...n,...y]:y.length>0?[c,...y]:[];return i.jsxs("group",{children:[l&&i.jsx("group",{position:r,children:i.jsx(K,{})}),s.length>1&&i.jsx(C,{points:s,color:R>=0?"#00ff88":"#ffaa00"}),g.map((t,d)=>{if(t.type==="move"&&t.target){const f=d===R,o=d<R;return i.jsx("group",{position:[t.target.x,t.target.y,t.target.z],children:i.jsxs("mesh",{children:[i.jsx("sphereGeometry",{args:[.1,8,8]}),i.jsx("meshStandardMaterial",{color:o?"#888":f?"#ff4444":"#ffaa00",transparent:!0,opacity:o?.3:.8})]})},`action-${d}`)}return null})]})}function I({clickerOptions:e}){const{onClick:c}=S.useClicker(e),a=u=>{u.stopPropagation();const{cameraOption:p,setCameraOption:r}=E.useGaesupStore.getState();if(p?.focus){r({focus:!1});return}c(u)};return i.jsxs("mesh",{position:[0,0,0],rotation:[-Math.PI/2,0,0],onPointerDown:a,visible:!0,userData:{intangible:!0},children:[i.jsx("planeGeometry",{args:[1e3,1e3]}),i.jsx("meshBasicMaterial",{transparent:!0,opacity:0})]})}function F({props:e,children:c}){const a=E.useGaesupStore(s=>s.mode),{gameStates:u}=S.useStateSystem(),p=E.useGaesupStore(s=>s.rideable),r=E.useGaesupStore(s=>s.urls),x=S.useBuildingStore(s=>s.isInEditMode()),m=z.useGenericRefs();if(M(),x||!a||!u||!p||!r||a.type==="character"&&!r.characterUrl||a.type==="vehicle"&&!r.vehicleUrl||a.type==="airplane"&&!r.airplaneUrl)return null;const{canRide:g,isRiding:R,currentRideable:b}=u,v=b?.id,l=h.useMemo(()=>(v?p[v]?.offset:void 0)??D.vec3(),[v,p]),n=(()=>{const s=e.rigidBodyRef??m.rigidBodyRef,t=e.outerGroupRef??m.outerGroupRef,d=e.innerGroupRef??m.innerGroupRef,f=e.colliderRef??m.colliderRef,o={isActive:!0,componentType:a.type,enableRiding:g,isRiderOn:R,offset:l,ref:s,outerGroupRef:t,innerGroupRef:d,colliderRef:f,parts:(e.parts||[]).filter(j=>!!j.url).map(j=>({...j,url:j.url})),...e.onAnimate?{onAnimate:e.onAnimate}:{},...e.onFrame?{onFrame:e.onFrame}:{},...e.onReady?{onReady:e.onReady}:{},...e.onDestroy?{onDestroy:e.onDestroy}:{},...e.onDestory?{onDestory:e.onDestory}:{},...typeof e.baseColor=="string"&&e.baseColor.trim().length>0?{baseColor:e.baseColor}:{},...Array.isArray(e.excludeBaseNodes)&&e.excludeBaseNodes.length>0?{excludeBaseNodes:e.excludeBaseNodes}:{},...e.rigidBodyProps?{rigidBodyProps:e.rigidBodyProps}:{},...e.controllerOptions?{controllerOptions:e.controllerOptions}:{},...e.groundRay?{groundRay:e.groundRay}:{},...e.colliderSize?{colliderSize:e.colliderSize}:{},...e.position?{position:e.position}:{},...e.rotation?{rotation:e.rotation}:{},...e.scale?{scale:e.scale}:{}},w=R&&a.type!=="character"?r.ridingUrl:void 0,P=typeof w=="string"&&w.length>0?{ridingUrl:w}:{};switch(a.type){case"character":return{...o,url:r.characterUrl||""};case"vehicle":return{...o,...P,url:r.vehicleUrl||"",wheelUrl:r.wheelUrl};case"airplane":return{...o,...P,url:r.airplaneUrl||""};default:return{...o,url:r.characterUrl||""}}})();return a.type==="character"&&u.isRiding?null:i.jsx(S.PhysicsEntity,{...n,children:c})}function L(e){const{clickToMove:c,children:a,clickerOptions:u,...p}=e,r={...u??{},...u?.agentRadius===void 0&&p.colliderSize?.radius!==void 0?{agentRadius:p.colliderSize.radius}:{}};return i.jsx(F,{props:p,children:i.jsxs(i.Fragment,{children:[c&&i.jsxs(i.Fragment,{children:[i.jsx(I,{clickerOptions:r}),i.jsx(B,{})]}),a]})})}exports.Clicker=B;exports.ControllerWrapper=L;exports.GroundClicker=I;exports.useKeyboard=M;exports.usePlayerPosition=G;