hytopia 0.7.13-dev1v → 0.7.14
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/bun-server.mjs +3 -3
- package/node-server.mjs +2 -2
- package/package.json +1 -1
package/node-server.mjs
CHANGED
|
@@ -457,7 +457,7 @@ qYGMwU/HBVHkLAn5XvT2a9xM0mzZ558d+ahbw8qAgRxg7BZ+2PW/bf7F2WRBUk1f
|
|
|
457
457
|
xauhAoGBALEspoxQozwohGQnP7EMF0/0JoKNpdNv0b0qCVvNiMo0+N297lI2mFQp
|
|
458
458
|
6xYlW/1l9afLokklF/J2IsyBrTCZoY7SaEk/lMMrQSyra+y0z71ogZ8A4ny9fxsj
|
|
459
459
|
0dDYJZGllL+3E/MQfd7k+KnOM/+A+cPoAnci76+L3vdkUb2P8SJk
|
|
460
|
-
-----END RSA PRIVATE KEY-----`;var iS=process.env.PORT??8080,nS="0.7.
|
|
460
|
+
-----END RSA PRIVATE KEY-----`;var iS=process.env.PORT??8080,nS="0.7.14",aS;(($)=>{$.READY="WEBSERVER.READY";$.STOPPED="WEBSERVER.STOPPED";$.ERROR="WEBSERVER.ERROR";$.UPGRADE="WEBSERVER.UPGRADE"})(aS||={});class FG extends M0{static instance=new FG;_webserver=NM.default();_internalHttpServer;constructor(){super();this._webserver.use((Z,J,X)=>{J.header("Access-Control-Allow-Origin","*"),X()}),this._webserver.get("/",(Z,J)=>{J.json({status:"OK",version:nS,runtime:typeof Bun!=="undefined"?"bun":"node"})}),this._webserver.use(NM.default.static("assets"));try{this._webserver.use(NM.default.static(co1.dirname(m.resolve("@hytopia.com/assets"))))}catch{}}start(){if(!this._internalHttpServer)this._internalHttpServer=process.env.NODE_ENV==="production"?uo1.createServer(this._webserver):do1.createServer({key:RM.existsSync("assets/certs/localhost.key")?RM.readFileSync("assets/certs/localhost.key"):_K0,cert:RM.existsSync("assets/certs/localhost.crt")?RM.readFileSync("assets/certs/localhost.crt"):kK0},this._webserver),this._internalHttpServer.on("upgrade",this._onUpgrade),this._internalHttpServer.on("error",this._onError),this._internalHttpServer.on("close",this._onStopped);else c.warning("WebServer.start(): server already started!");this._internalHttpServer.listen(iS,this._onStarted),console.info(`WebServer.start(): Server running on port ${iS}.`)}stop(){if(this._internalHttpServer)return new Promise((Z,J)=>{this._internalHttpServer.close((X)=>{if(X)J(X);else Z(!0)})});else return c.warning("WebServer.stop(): server not started."),Promise.resolve(!1)}_onStarted=()=>{this.emitWithGlobal("WEBSERVER.READY",{})};_onUpgrade=async(Z,J,X)=>{let Y=lo1.parse(Z.url??"",!0).query,$=Y.connectionId?.toString(),Q=Y.sessionToken?.toString()??"";if($&&s7.instance.isValidConnectionId($))Z.connectionId=$;else{let K=await y7.instance.getPlayerSession(Q);if(K?.error){let W=`${K.error.code}: ${K.error.message}`;J.write(`HTTP/1.1 401 Unauthorized\r
|
|
461
461
|
Content-Type: text/plain\r
|
|
462
462
|
Content-Length: ${W.length}\r
|
|
463
463
|
Connection: close\r
|
|
@@ -490,4 +490,4 @@ ${$.stack}`:"unknown"}}}}}var qe1=(Z={})=>{let J=Z.limit??Ke1;return{name:We1,pr
|
|
|
490
490
|
`),U=q.shift();if(!U)return Z.destroy(),X(new Error("No header received from proxy CONNECT response"));let B=U.split(" "),L=+(B[1]||0),w=B.slice(2).join(" "),M={};for(let R of q){if(!R)continue;let N=R.indexOf(":");if(N===-1)return Z.destroy(),X(new Error(`Invalid header from proxy CONNECT response: "${R}"`));let P=R.slice(0,N).toLowerCase(),D=R.slice(N+1).trimStart(),C=M[P];if(typeof C==="string")M[P]=[C,D];else if(Array.isArray(C))C.push(D);else M[P]=D}tj("got proxy server response: %o %o",U,M),K(),J({connect:{statusCode:L,statusText:w,headers:M},buffered:F})}Z.on("error",G),Z.on("end",W),Q()})}function KU(...Z){g.log("[https-proxy-agent]",...Z)}class ej extends Vm{static __initStatic(){this.protocols=["http","https"]}constructor(Z,J){super(J);this.options={},this.proxy=typeof Z==="string"?new URL(Z):Z,this.proxyHeaders=J?.headers??{},KU("Creating new HttpsProxyAgent instance: %o",this.proxy.href);let X=(this.proxy.hostname||this.proxy.host).replace(/^\[|\]$/g,""),Y=this.proxy.port?parseInt(this.proxy.port,10):this.proxy.protocol==="https:"?443:80;this.connectOpts={ALPNProtocols:["http/1.1"],...J?G31(J,"headers"):null,host:X,port:Y}}async connect(Z,J){let{proxy:X}=this;if(!J.host)throw new TypeError('No "host" provided');let Y;if(X.protocol==="https:"){KU("Creating `tls.Socket`: %o",this.connectOpts);let F=this.connectOpts.servername||this.connectOpts.host;Y=Hm.connect({...this.connectOpts,servername:F&&_J.isIP(F)?void 0:F})}else KU("Creating `net.Socket`: %o",this.connectOpts),Y=_J.connect(this.connectOpts);let $=typeof this.proxyHeaders==="function"?this.proxyHeaders():{...this.proxyHeaders},Q=_J.isIPv6(J.host)?`[${J.host}]`:J.host,K=`CONNECT ${Q}:${J.port} HTTP/1.1\r
|
|
491
491
|
`;if(X.username||X.password){let F=`${decodeURIComponent(X.username)}:${decodeURIComponent(X.password)}`;$["Proxy-Authorization"]=`Basic ${Buffer.from(F).toString("base64")}`}if($.Host=`${Q}:${J.port}`,!$["Proxy-Connection"])$["Proxy-Connection"]=this.keepAlive?"Keep-Alive":"close";for(let F of Object.keys($))K+=`${F}: ${$[F]}\r
|
|
492
492
|
`;let W=W31(Y);Y.write(`${K}\r
|
|
493
|
-
`);let{connect:G,buffered:V}=await W;if(Z.emit("proxyConnect",G),this.emit("proxyConnect",G,Z),G.statusCode===200){if(Z.once("socket",RQ6),J.secureEndpoint){KU("Upgrading socket connection to TLS");let F=J.servername||J.host;return Hm.connect({...G31(J,"host","path","port"),socket:Y,servername:_J.isIP(F)?void 0:F})}return Y}Y.destroy();let H=new _J.Socket({writable:!1});return H.readable=!0,Z.once("socket",(F)=>{KU("Replaying proxy buffer for failed request"),F.push(V),F.push(null)}),H}}ej.__initStatic();function RQ6(Z){Z.resume()}function G31(Z,...J){let X={},Y;for(Y in Z)if(!J.includes(Y))X[Y]=Z[Y];return X}var CQ6=32768;function TQ6(Z){return new DQ6({read(){this.push(Z),this.push(null)}})}function ZD(Z){let J;try{J=new URL(Z.url)}catch(G){return Q8(()=>{console.warn("[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.")}),EG(Z,()=>Promise.resolve({}))}let X=J.protocol==="https:",Y=EQ6(J,Z.proxy||(X?process.env.https_proxy:void 0)||process.env.http_proxy),$=X?jQ6:NQ6,Q=Z.keepAlive===void 0?!1:Z.keepAlive,K=Y?new ej(Y):new $.Agent({keepAlive:Q,maxSockets:30,timeout:2000}),W=IQ6(Z,Z.httpModule??$,K);return EG(Z,W)}function EQ6(Z,J){let{no_proxy:X}=process.env;if(X?.split(",").some(($)=>Z.host.endsWith($)||Z.hostname.endsWith($)))return;else return J}function IQ6(Z,J,X){let{hostname:Y,pathname:$,port:Q,protocol:K,search:W}=new URL(Z.url);return function G(V){return new Promise((H,F)=>{EF(()=>{let z=TQ6(V.body),q={...Z.headers};if(V.body.length>CQ6)q["content-encoding"]="gzip",z=z.pipe(PQ6());let U=J.request({method:"POST",agent:X,headers:q,hostname:Y,path:`${$}${W}`,port:Q,protocol:K,ca:Z.caCerts},(B)=>{B.on("data",()=>{}),B.on("end",()=>{}),B.setEncoding("utf8");let L=B.headers["retry-after"]??null,w=B.headers["x-sentry-rate-limits"]??null;H({statusCode:B.statusCode,headers:{"retry-after":L,"x-sentry-rate-limits":Array.isArray(w)?w[0]||null:w}})});U.on("error",F),z.pipe(U)})})}}var kQ6=new Set(["false","f","n","no","off","0"]),_Q6=new Set(["true","t","y","yes","on","1"]);function JD(Z,J){let X=String(Z).toLowerCase();if(kQ6.has(X))return!1;if(_Q6.has(X))return!0;return J?.strict?null:Boolean(Z)}import{posix as vQ6,sep as SQ6}from"node:path";function V31(Z){return Z.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}function XD(Z=process.argv[1]?Fx(process.argv[1]):process.cwd(),J=SQ6==="\\"){let X=J?V31(Z):Z;return(Y)=>{if(!Y)return;let $=J?V31(Y):Y,{dir:Q,base:K,ext:W}=vQ6.parse($);if(W===".js"||W===".mjs"||W===".cjs")K=K.slice(0,W.length*-1);let G=decodeURIComponent(K);if(!Q)Q=".";let V=Q.lastIndexOf("/node_modules");if(V>-1)return`${Q.slice(V+14).replace(/\//g,".")}:${G}`;if(Q.startsWith(X)){let H=Q.slice(X.length+1).replace(/\//g,".");return H?`${H}:${G}`:G}return G}}function YD(Z){if(process.env.SENTRY_RELEASE)return process.env.SENTRY_RELEASE;if(O0.SENTRY_RELEASE?.id)return O0.SENTRY_RELEASE.id;let J=process.env.GITHUB_SHA||process.env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA||process.env.CI_BUILD_REF||process.env.CI_COMMIT_SHA||process.env.BITBUCKET_COMMIT,X=process.env.APPVEYOR_PULL_REQUEST_HEAD_COMMIT||process.env.APPVEYOR_REPO_COMMIT||process.env.CODEBUILD_RESOLVED_SOURCE_VERSION||process.env.AWS_COMMIT_ID||process.env.BUILD_SOURCEVERSION||process.env.GIT_CLONE_COMMIT_HASH||process.env.BUDDY_EXECUTION_REVISION||process.env.BUILDKITE_COMMIT||process.env.CIRCLE_SHA1||process.env.CIRRUS_CHANGE_IN_REPO||process.env.CF_REVISION||process.env.CM_COMMIT||process.env.CF_PAGES_COMMIT_SHA||process.env.DRONE_COMMIT_SHA||process.env.FC_GIT_COMMIT_SHA||process.env.HEROKU_TEST_RUN_COMMIT_VERSION||process.env.HEROKU_SLUG_COMMIT||process.env.RAILWAY_GIT_COMMIT_SHA||process.env.RENDER_GIT_COMMIT||process.env.SEMAPHORE_GIT_SHA||process.env.TRAVIS_PULL_REQUEST_SHA||process.env.VERCEL_GIT_COMMIT_SHA||process.env.VERCEL_GITHUB_COMMIT_SHA||process.env.VERCEL_GITLAB_COMMIT_SHA||process.env.VERCEL_BITBUCKET_COMMIT_SHA||process.env.ZEIT_GITHUB_COMMIT_SHA||process.env.ZEIT_GITLAB_COMMIT_SHA||process.env.ZEIT_BITBUCKET_COMMIT_SHA,Y=process.env.CI_COMMIT_ID||process.env.SOURCE_COMMIT||process.env.SOURCE_VERSION||process.env.GIT_COMMIT||process.env.COMMIT_REF||process.env.BUILD_VCS_NUMBER||process.env.CI_COMMIT_SHA;return J||X||Y||Z}var $D=SM(Px(XD()));var z31=r(X0(),1),F31=r(W1(),1);import*as H31 from"node:os";import{threadId as AQ6,isMainThread as xQ6}from"worker_threads";var hQ6=60000;class WU extends nM{constructor(Z){let J=Z.serverName||global.process.env.SENTRY_NAME||H31.hostname(),X={...Z,platform:"node",runtime:{name:"node",version:global.process.version},serverName:J};if(Z.openTelemetryInstrumentations)F31.registerInstrumentations({instrumentations:Z.openTelemetryInstrumentations});Yx(X,"node"),g.log(`Initializing Sentry: process: ${process.pid}, thread: ${xQ6?"main":`worker-${AQ6}`}.`);super(X);if(this.getOptions()._experiments?.enableLogs){if(this._logOnExitFlushListener=()=>{bX(this)},J)this.on("beforeCaptureLog",(Y)=>{Y.attributes={...Y.attributes,"server.address":J}});process.on("beforeExit",this._logOnExitFlushListener)}}get tracer(){if(this._tracer)return this._tracer;let Z="@sentry/node",J=B8,X=z31.trace.getTracer(Z,J);return this._tracer=X,X}async flush(Z){let X=this.traceProvider?.activeSpanProcessor;if(X)await X.forceFlush();if(this.getOptions().sendClientReports)this._flushOutcomes();return super.flush(Z)}close(Z){if(this._clientReportInterval)clearInterval(this._clientReportInterval);if(this._clientReportOnExitFlushListener)process.off("beforeExit",this._clientReportOnExitFlushListener);if(this._logOnExitFlushListener)process.off("beforeExit",this._logOnExitFlushListener);return super.close(Z)}startClientReportTracking(){let Z=this.getOptions();if(Z.sendClientReports)this._clientReportOnExitFlushListener=()=>{this._flushOutcomes()},this._clientReportInterval=setInterval(()=>{m0&&g.log("Flushing client reports based on interval."),this._flushOutcomes()},Z.clientReportFlushInterval??hQ6).unref(),process.on("beforeExit",this._clientReportOnExitFlushListener)}_getTraceInfoFromScope(Z){if(!Z)return[void 0,void 0];return S41(this,Z)}}var q7=r(X0(),1),q31=r(py(),1),U31=r(ay(),1),M3=r(D1(),1);var L31=r(Yy(),1);import fQ6 from"module";var zm=1e6;function QD(Z,J={}){if(Z.getOptions().debug)w31();let X=bQ6(Z,J);Z.traceProvider=X}function Fm(){let[Z=0,J=0]=process.versions.node.split(".").map(Number);if(Z>=21||Z===20&&J>=6||Z===18&&J>=19){if(!O0._sentryEsmLoaderHookRegistered)try{let{addHookMessagePort:X}=L31.createAddHookMessageChannel();fQ6.register("import-in-the-middle/hook.mjs",import.meta.url,{data:{addHookMessagePort:X,include:[]},transferList:[X]})}catch(X){g.warn("Failed to register ESM hook",X)}}else Q8(()=>{console.warn(`[Sentry] You are using Node.js v${process.versions.node} in ESM mode ("import syntax"). The Sentry Node.js SDK is not compatible with ESM in Node.js versions before 18.19.0 or before 20.6.0. Please either build your application with CommonJS ("require() syntax"), or upgrade your Node.js version.`)})}function B31(Z={}){let{debug:J}=Z;if(J)g.enable(),w31();if(!L4())Fm();yQ6(Z.integrations).forEach((X)=>{if(X(),J)g.log(`[Sentry] Preloaded ${X.id} instrumentation`)})}function yQ6(Z){let J=K31();if(!Z)return J;return J.filter((X)=>Z.includes(X.id))}function bQ6(Z,J={}){let X=new U31.BasicTracerProvider({sampler:new Ub(Z),resource:new q31.Resource({[M3.ATTR_SERVICE_NAME]:"node",[M3.SEMRESATTRS_SERVICE_NAMESPACE]:"sentry",[M3.ATTR_SERVICE_VERSION]:B8}),forceFlushTimeoutMillis:500,spanProcessors:[new qb({timeout:gQ6(Z.getOptions().maxSpanWaitDuration)}),...J.spanProcessors||[]]});return q7.trace.setGlobalTracerProvider(X),q7.propagation.setGlobalPropagator(new Gb),q7.context.setGlobalContextManager(new oj),X}function gQ6(Z){if(Z==null)return;if(Z>zm)return m0&&g.warn(`\`maxSpanWaitDuration\` is too high, using the maximum value of ${zm}`),zm;else if(Z<=0||Number.isNaN(Z)){m0&&g.warn("`maxSpanWaitDuration` must be a positive number, using default value instead.");return}return Z}function w31(){let Z=new Proxy(g,{get(J,X,Y){return Reflect.get(J,X==="verbose"?"debug":X,Y)}});q7.diag.disable(),q7.diag.setLogger(Z,q7.DiagLogLevel.DEBUG)}function mQ6(){return L4()?[dN()]:[]}function qm(){return[fF(),hF(),yF(),bF(),gF(),_N(),xN(),cN(),lN(),bN(),uN(),yN(),aj(),Q31(),...mQ6()]}function Um(Z){return[...qm(),...F5(Z)?rj():[]]}function KD(Z={}){return M31(Z,Um)}function O31(Z={}){return M31(Z,()=>[])}function M31(Z={},J){let X=uQ6(Z,J);if(X.debug===!0)if(m0)g.enable();else Q8(()=>{console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.")});if(!L4()&&X.registerEsmLoaderHooks!==!1)Fm();if(TN(),l0().update(X.initialScope),X.spotlight&&!X.integrations.some(({name:Q})=>Q===sg))X.integrations.push(fj({sidecarUrl:typeof X.spotlight==="string"?X.spotlight:void 0}));let $=new WU(X);if(l0().setClient($),$.init(),g.log(`Running in ${L4()?"CommonJS":"ESM"} mode.`),$.startClientReportTracking(),lQ6(),!X.skipOpenTelemetrySetup)QD($,{spanProcessors:X.openTelemetrySpanProcessors}),Lm();return D41($),A41($),$}function Lm(){if(!m0)return;let Z=E41(),J=["SentryContextManager","SentryPropagator"];if(F5())J.push("SentrySpanProcessor");for(let X of J)if(!Z.includes(X))g.error(`You have to set up the ${X}. Without this, the OpenTelemetry & Sentry integration will not work properly.`);if(!Z.includes("SentrySampler"))g.warn("You have to set up the SentrySampler. Without this, the OpenTelemetry & Sentry integration may still work, but sample rates set for the Sentry SDK will not be respected. If you use a custom sampler, make sure to use `wrapSamplingDecision`.")}function uQ6(Z,J){let X=dQ6(Z.release),Y=Z.spotlight??JD(process.env.SENTRY_SPOTLIGHT,{strict:!0})??process.env.SENTRY_SPOTLIGHT,$=cQ6(Z.tracesSampleRate),Q={...Z,dsn:Z.dsn??process.env.SENTRY_DSN,environment:Z.environment??process.env.SENTRY_ENVIRONMENT,sendClientReports:Z.sendClientReports??!0,transport:Z.transport??ZD,stackParser:qA(Z.stackParser||$D),release:X,tracesSampleRate:$,spotlight:Y,debug:JD(Z.debug??process.env.SENTRY_DEBUG)},K=Z.integrations,W=Z.defaultIntegrations??J(Q);return{...Q,integrations:iA({defaultIntegrations:W,integrations:K})}}function dQ6(Z){if(Z!==void 0)return Z;let J=YD();if(J!==void 0)return J;return}function cQ6(Z){if(Z!==void 0)return Z;let J=process.env.SENTRY_TRACES_SAMPLE_RATE;if(!J)return;let X=parseFloat(J);return isFinite(X)?X:void 0}function lQ6(){if(JD(process.env.SENTRY_USE_ENVIRONMENT)!==!1){let Z=process.env.SENTRY_TRACE,J=process.env.SENTRY_BAGGAGE,X=QQ(Z,J);l0().setPropagationContext(X)}}var pQ6=[["january","1"],["february","2"],["march","3"],["april","4"],["may","5"],["june","6"],["july","7"],["august","8"],["september","9"],["october","10"],["november","11"],["december","12"],["jan","1"],["feb","2"],["mar","3"],["apr","4"],["may","5"],["jun","6"],["jul","7"],["aug","8"],["sep","9"],["oct","10"],["nov","11"],["dec","12"],["sunday","0"],["monday","1"],["tuesday","2"],["wednesday","3"],["thursday","4"],["friday","5"],["saturday","6"],["sun","0"],["mon","1"],["tue","2"],["wed","3"],["thu","4"],["fri","5"],["sat","6"]];function XK(Z){return pQ6.reduce((J,[X,Y])=>J.replace(new RegExp(X,"gi"),Y),Z)}var R31="Automatic instrumentation of CronJob only supports crontab string";function N31(Z,J){let X=!1;return new Proxy(Z,{construct(Y,$){let[Q,K,W,G,V,...H]=$;if(typeof Q!=="string")throw new Error(R31);if(X)throw new Error(`A job named '${J}' has already been scheduled`);X=!0;let F=XK(Q);async function z(q,U){return r7(J,async()=>{try{await K(q,U)}catch(B){throw q1(B),B}},{schedule:{type:"crontab",value:F},timezone:V||void 0})}return new Y(Q,z,W,G,V,...H)},get(Y,$){if($==="from")return(Q)=>{let{cronTime:K,onTick:W,timeZone:G}=Q;if(typeof K!=="string")throw new Error(R31);if(X)throw new Error(`A job named '${J}' has already been scheduled`);X=!0;let V=XK(K);return Q.onTick=async(H,F)=>{return r7(J,async()=>{try{await W(H,F)}catch(z){throw q1(z),z}},{schedule:{type:"crontab",value:V},timezone:G||void 0})},Y.from(Q)};else return Y[$]}})}function j31(Z){return new Proxy(Z,{get(J,X){if(X==="schedule"&&J.schedule)return new Proxy(J.schedule,{apply(Y,$,Q){let[K,W,G]=Q,V=G?.name,H=G?.timezone;if(!V)throw new Error('Missing "name" for scheduled job. A name is required for Sentry check-in monitoring.');let F=async()=>{return r7(V,async()=>{try{return await W()}catch(z){throw q1(z),z}},{schedule:{type:"crontab",value:XK(K)},timezone:H})};return Y.apply($,[K,F,G])}});else return J[X]}})}function D31(Z){return new Proxy(Z,{get(J,X){if(X==="scheduleJob")return new Proxy(J.scheduleJob,{apply(Y,$,Q){let[K,W,G]=Q;if(typeof K!=="string"||typeof W!=="string"||typeof G!=="function")throw new Error("Automatic instrumentation of 'node-schedule' requires the first parameter of 'scheduleJob' to be a job name string and the second parameter to be a crontab string");let V=K,H=W;async function F(){return r7(V,async()=>{await G?.()},{schedule:{type:"crontab",value:XK(H)}})}return Y.apply($,[V,H,F])}});return J[X]}})}var P31={instrumentCron:N31,instrumentNodeCron:j31,instrumentNodeSchedule:D31};var YK;((L)=>{L.BUILD_PACKETS="build_packets";L.ENTITIES_EMIT_UPDATES="entities_emit_updates";L.ENTITIES_TICK="entities_tick";L.NETWORK_SYNCHRONIZE="network_synchronize";L.NETWORK_SYNCHRONIZE_CLEANUP="network_synchronize_cleanup";L.PHYSICS_CLEANUP="physics_cleanup";L.PHYSICS_STEP="physics_step";L.RELEASE_TICK_ALLOCATION="release_tick_allocation";L.SEND_ALL_PACKETS="send_all_packets";L.SEND_PACKETS="send_packets";L.SERIALIZE_FREE_BUFFERS="serialize_free_buffers";L.SERIALIZE_PACKETS="serialize_packets";L.SERIALIZE_PACKETS_ENCODE="serialize_packets_encode";L.SIMULATION_STEP="simulation_step";L.TICKER_TICK="ticker_tick";L.WORLD_TICK="world_tick"})(YK||={});class t1{static getProcessStats(Z=!1){let J=process.memoryUsage(),X={jsHeapSizeMb:{value:J.heapUsed/1024/1024,unit:"megabyte"},jsHeapCapacityMb:{value:J.heapTotal/1024/1024,unit:"megabyte"},jsHeapUsagePercent:{value:J.heapUsed/J.heapTotal,unit:"percent"},processHeapSizeMb:{value:J.heapUsed/1024/1024,unit:"megabyte"},rssSizeMb:{value:J.rss/1024/1024,unit:"megabyte"}};if(Z)return X;return Object.fromEntries(Object.entries(X).map(([Y,$])=>[Y,$.value]))}static initializeSentry(Z,J=50){KD({dsn:Z,release:nS,environment:process.env.NODE_ENV||"development",tracesSampleRate:1,initialScope:{tags:{gameId:process.env.HYTOPIA_GAME_ID??"unknown",gameSlug:process.env.HYTOPIA_GAME_SLUG??"unknown",lobbyId:process.env.HYTOPIA_LOBBY_ID??"unknown",region:process.env.REGION??"unknown"}},beforeSend:(X)=>{return X.extra=t1.getProcessStats(),X},beforeSendTransaction:(X)=>{if(X.contexts?.trace?.op==="ticker_tick"){let $=X?.start_timestamp,Q=X?.timestamp;if(!$||!Q)return null;if((Q-$)*1000>J)return X.measurements=t1.getProcessStats(!0),X}return null}})}static startSpan(Z,J){if(SF())return Z4({attributes:Z.attributes,name:Z.operation,op:Z.operation},J);else return J()}static sentry(){return Bm}}var C31=new f$,iQ6=5000;class n4 extends M0{static _cachedPacketsSerializedBuffer=new Map;_closeTimeout=null;_wrtcDirectTransport=null;_wrtcClientServerTransport=null;_wrtcClientServerDataProducers=[];_wrtcClientServerDataConsumers=[];_wrtcServerClientTransport=null;_wrtcServerClientReliableDataProducer=null;_wrtcServerClientUnreliableDataProducer=null;_wrtcServerClientDataConsumers=[];_ws;id;constructor(Z,J){super();this.id=U40(),this.onPacket(Y0.PacketId.CONNECTION,this._onConnectionPacket),this.onPacket(Y0.PacketId.HEARTBEAT,this._onHeartbeatPacket),this.bindWs(Z),M0.globalInstance.emit("CONNECTION.OPENED",{connection:this,req:J})}static clearCachedPacketsSerializedBuffers(){if(n4._cachedPacketsSerializedBuffer.size>0)n4._cachedPacketsSerializedBuffer.clear()}static serializePackets(Z){for(let X of Z)if(!Y0.isValidPacket(X))return c.error(`Connection.serializePackets(): Invalid packet payload: ${JSON.stringify(X)}`);let J=n4._cachedPacketsSerializedBuffer.get(Z);if(J)return J;return t1.startSpan({operation:"serialize_packets",attributes:{packets:Z.length,packetIds:Z.map((X)=>X[0]).join(",")}},(X)=>{let Y=t1.startSpan({operation:"serialize_packets_encode"},()=>C31.pack(Z));return X?.setAttribute("serializedBytes",Y.byteLength),n4._cachedPacketsSerializedBuffer.set(Z,Y),Y})}bindWs(Z){let J=!!this._ws;if(J&&this._closeTimeout)clearTimeout(this._closeTimeout),this._closeTimeout=null;if(this._ws)this._ws.onmessage=()=>{},this._ws.onclose=()=>{},this._ws.onerror=()=>{},this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{k:!0})]);if(this._ws=Z,this._ws.binaryType="nodebuffer",this._ws.onmessage=(X)=>this._onMessage(X.data),this._ws.onclose=this._onWsClose,this._ws.onerror=this._onWsError,this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{i:this.id})],!0,!0),J)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this});if(s7.instance.isWrtcEnabled)this._upgradeToWRTC()}closeWrtc(){this._closeWrtcClientServerTransport(),this._closeWrtcServerClientTransport()}disconnect(){try{this._ws.close()}catch(Z){c.error(`Connection.disconnect(): Connection disconnect failed. Error: ${Z}`)}}onPacket(Z,J){this.on("CONNECTION.PACKET_RECEIVED",({packet:X})=>{if(X[0]===Z)J(X)})}send(Z,J=!0,X=!1){if(this._closeTimeout)return;if(this._ws.readyState!==q_.default.OPEN)return;t1.startSpan({operation:"send_packets",attributes:{forceWs:X?"true":"false",wrtcConnected:this._wrtcServerClientTransport?.iceState==="completed"?"true":"false"}},()=>{try{let Y=n4.serializePackets(Z);if(!Y)return;if(this._wrtcServerClientTransport?.iceState==="completed"&&Y.length<(this._wrtcServerClientTransport?.sctpParameters?.maxMessageSize??0)&&!X)try{(J?this._wrtcServerClientReliableDataProducer:this._wrtcServerClientUnreliableDataProducer).send(Y)}catch{this._ws.send(Y)}else this._ws.send(Y);this.emitWithGlobal("CONNECTION.PACKETS_SENT",{connection:this,packets:Z})}catch(Y){c.error(`Connection.send(): Packet send failed. Error: ${Y}`)}})}_closeWrtcClientServerTransport(){this._wrtcDirectTransport?.close(),this._wrtcDirectTransport=null,this._wrtcClientServerTransport?.close(),this._wrtcClientServerTransport=null,this._wrtcClientServerDataProducers.forEach((Z)=>Z.close()),this._wrtcClientServerDataProducers=[],this._wrtcClientServerDataConsumers.forEach((Z)=>Z.close()),this._wrtcClientServerDataConsumers=[]}_closeWrtcServerClientTransport(){this._wrtcServerClientTransport?.close(),this._wrtcServerClientTransport=null,this._wrtcServerClientDataConsumers.forEach((Z)=>Z.close()),this._wrtcServerClientDataConsumers=[],this._wrtcServerClientReliableDataProducer?.close(),this._wrtcServerClientReliableDataProducer=null,this._wrtcServerClientUnreliableDataProducer?.close(),this._wrtcServerClientUnreliableDataProducer=null}_onConnectionPacket=async(Z)=>{let J=Z[1],X=J.c,Y=J.d;if(X){let{i:$,d:Q}=X,K=!1;if($==this._wrtcClientServerTransport?.id)await this._wrtcClientServerTransport.connect({dtlsParameters:Q}),K=!0;if($==this._wrtcServerClientTransport?.id)await this._wrtcServerClientTransport.connect({dtlsParameters:Q}),K=!0;if(K)this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{ca:{i:$}})])}if(Y)for(let $ of Y){let{s:Q,l:K}=$,W=await this._wrtcClientServerTransport.produceData({label:K,sctpStreamParameters:Q}),G=await this._wrtcDirectTransport.consumeData({dataProducerId:W.id});this._wrtcClientServerDataProducers.push(W),this._wrtcClientServerDataConsumers.push(G),G.on("message",(V)=>this._onMessage(V)),this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{pa:{i:W.id,l:K}})])}};_onHeartbeatPacket=()=>{this.send([Y0.createPacket(Y0.bidirectionalPackets.heartbeatPacketDefinition,null)],!0,!0)};_onMessage=(Z)=>{try{let J=this._deserialize(Z);if(!J)return;this.emitWithGlobal("CONNECTION.PACKET_RECEIVED",{connection:this,packet:J})}catch(J){c.error(`Connection._ws.onmessage(): Error: ${J}`)}};_onWrtcIceStateChange=(Z,J)=>{if(["disconnected","closed"].includes(J)){if(Z==this._wrtcClientServerTransport)this._closeWrtcClientServerTransport();else if(Z==this._wrtcServerClientTransport)this._closeWrtcServerClientTransport()}};_onWsClose=()=>{this.closeWrtc(),this.emitWithGlobal("CONNECTION.DISCONNECTED",{connection:this}),this._closeTimeout=setTimeout(()=>{this.emitWithGlobal("CONNECTION.CLOSED",{connection:this}),this.offAll()},iQ6)};_onWsError=(Z)=>{this.emitWithGlobal("CONNECTION.ERROR",{connection:this,error:Z})};_upgradeToWRTC=async()=>{let Z=await s7.instance.createWrtcTransports();if(!Z)return!1;let{directTransport:J,clientServerTransport:X,serverClientTransport:Y}=Z;this._wrtcDirectTransport=J,this._wrtcClientServerTransport=X,this._wrtcClientServerTransport.on("icestatechange",(K)=>{this._onWrtcIceStateChange(this._wrtcClientServerTransport,K)}),this._wrtcServerClientTransport=Y,this._wrtcServerClientTransport.on("icestatechange",(K)=>{this._onWrtcIceStateChange(this._wrtcServerClientTransport,K)}),this._wrtcServerClientReliableDataProducer=await this._wrtcServerClientTransport.produceData({label:"scr",sctpStreamParameters:{streamId:0,ordered:!0}}),this._wrtcServerClientUnreliableDataProducer=await this._wrtcServerClientTransport.produceData({label:"scu",sctpStreamParameters:{streamId:1,ordered:!1,maxPacketLifeTime:35}});let $=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientReliableDataProducer.id}),Q=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientUnreliableDataProducer.id});return this._wrtcServerClientDataConsumers.push($,Q),this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{d:[{i:$.id,pi:$.dataProducerId,l:"scr",s:$.sctpStreamParameters},{i:Q.id,pi:Q.dataProducerId,l:"scu",s:Q.sctpStreamParameters}],t:[{i:this._wrtcClientServerTransport.id,f:"cs",d:this._wrtcClientServerTransport.dtlsParameters,ic:this._wrtcClientServerTransport.iceCandidates,ip:this._wrtcClientServerTransport.iceParameters,s:this._wrtcClientServerTransport.sctpParameters},{i:this._wrtcServerClientTransport.id,f:"sc",d:this._wrtcServerClientTransport.dtlsParameters,ic:this._wrtcServerClientTransport.iceCandidates,ip:this._wrtcServerClientTransport.iceParameters,s:this._wrtcServerClientTransport.sctpParameters}]})]),!0};_deserialize(Z){let J=C31.unpack(Z);if(!J||typeof J!=="object"||typeof J[0]!=="number")return c.error(`Connection._deserialize(): Invalid packet format. Packet: ${JSON.stringify(J)}`);if(!Y0.isValidPacket(J))return c.error(`Connection._deserialize(): Invalid packet payload. Packet: ${JSON.stringify(J)}`);return J}}class GU{_lights=new Map;_nextLightId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}despawnEntityAttachedLights(Z){this.getAllEntityAttachedLights(Z).forEach((J)=>{J.despawn()})}getAllLights(Z=!1){return Z?this._world.tickAllocator.getArray(this._lights.values()):Array.from(this._lights.values())}getAllEntityAttachedLights(Z){return this.getAllLights().filter((J)=>J.attachedToEntity===Z)}registerLight(Z){if(Z.id!==void 0)return Z.id;let J=this._nextLightId;return this._lights.set(J,Z),this._nextLightId++,J}unregisterLight(Z){if(Z.id===void 0)return;this._lights.delete(Z.id)}}class F6{_map=new Map;_values=[];_isDirty=!1;get size(){return this._map.size}get valuesArray(){if(this._isDirty)this._syncArray();return this._values}get(Z){return this._map.get(Z)}set(Z,J){let X=this._map.has(Z);if(this._map.set(Z,J),!X)this._values.push(J);else this._isDirty=!0;return this}has(Z){return this._map.has(Z)}delete(Z){let J=this._map.delete(Z);if(J)this._isDirty=!0;return J}clear(){this._map.clear(),this._values.length=0,this._isDirty=!1}forEach(Z,J){this._map.forEach((X,Y)=>{Z.call(J,X,Y,this)})}keys(){return this._map.keys()}values(){return this._map.values()}entries(){return this._map.entries()}[Symbol.iterator](){return this._map[Symbol.iterator]()}_syncArray(){this._values.length=0;for(let Z of this._map.values())this._values.push(Z);this._isDirty=!1}}var T31;((X)=>{X[X.POINTLIGHT=0]="POINTLIGHT";X[X.SPOTLIGHT=1]="SPOTLIGHT"})(T31||={});var wm;((z)=>{z.DESPAWN="LIGHT.DESPAWN";z.SET_ANGLE="LIGHT.SET_ANGLE";z.SET_ATTACHED_TO_ENTITY="LIGHT.SET_ATTACHED_TO_ENTITY";z.SET_COLOR="LIGHT.SET_COLOR";z.SET_DISTANCE="LIGHT.SET_DISTANCE";z.SET_INTENSITY="LIGHT.SET_INTENSITY";z.SET_OFFSET="LIGHT.SET_OFFSET";z.SET_PENUMBRA="LIGHT.SET_PENUMBRA";z.SET_POSITION="LIGHT.SET_POSITION";z.SET_TRACKED_ENTITY="LIGHT.SET_TRACKED_ENTITY";z.SET_TRACKED_POSITION="LIGHT.SET_TRACKED_POSITION";z.SPAWN="LIGHT.SPAWN"})(wm||={});class Om extends M0{_id;_angle;_attachedToEntity;_color;_distance;_intensity;_offset;_penumbra;_position;_trackedEntity;_trackedPosition;_type;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)c.fatalError("Either attachedToEntity or position must be set, but not both.");super();c.warning("WARNING: Lights are poorly optimized at this time. Using more than a few lights in your game can cause extremely bad performance (FPS) issues. Use lights sparingly!"),this._angle=Z.angle,this._attachedToEntity=Z.attachedToEntity,this._color=Z.color??{r:255,g:255,b:255},this._distance=Z.distance,this._intensity=Z.intensity??1,this._offset=Z.offset,this._penumbra=Z.penumbra,this._position=Z.position,this._trackedEntity=Z.trackedEntity,this._trackedPosition=Z.trackedPosition,this._type=Z.type??0}get id(){return this._id}get angle(){return this._angle}get attachedToEntity(){return this._attachedToEntity}get color(){return this._color}get distance(){return this._distance}get intensity(){return this._intensity}get isSpawned(){return this._id!==void 0}get offset(){return this._offset}get penumbra(){return this._penumbra}get position(){return this._position}get trackedEntity(){return this._trackedEntity}get trackedPosition(){return this._trackedPosition}get type(){return this._type}get world(){return this._world}setAngle(Z){if(this._angle===Z)return;if(this._angle=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ANGLE",{light:this,angle:Z})}setAttachedToEntity(Z){if(!Z.isSpawned)return c.error(`Light.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ATTACHED_TO_ENTITY",{light:this,entity:Z})}setColor(Z){if(this._color.r===Z.r&&this._color.g===Z.g&&this._color.b===Z.b)return;if(this._color=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_COLOR",{light:this,color:Z})}setDistance(Z){if(this._distance===Z)return;if(this._distance=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_DISTANCE",{light:this,distance:Z})}setIntensity(Z){if(this._intensity===Z)return;if(this._intensity=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_INTENSITY",{light:this,intensity:Z})}setOffset(Z){if(this._offset&&this._offset.x===Z.x&&this._offset.y===Z.y&&this._offset.z===Z.z)return;if(this._offset=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_OFFSET",{light:this,offset:Z})}setPenumbra(Z){if(this._penumbra===Z)return;if(this._penumbra=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_PENUMBRA",{light:this,penumbra:Z})}setPosition(Z){if(this._position&&this._position.x===Z.x&&this._position.y===Z.y&&this._position.z===Z.z)return;if(this._position=Z,this._attachedToEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_POSITION",{light:this,position:Z})}setTrackedEntity(Z){if(!Z.isSpawned)return c.error(`Light.setTrackedEntity(): Entity ${Z.id} is not spawned!`);if(this._trackedEntity===Z)return;if(this._trackedEntity=Z,this._trackedPosition=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_ENTITY",{light:this,entity:Z})}setTrackedPosition(Z){if(this._trackedPosition===Z)return;if(this._trackedPosition=Z,this._trackedEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_POSITION",{light:this,position:Z})}despawn(){if(!this.isSpawned||!this._world)return;this._world.lightManager.unregisterLight(this),this.emitWithWorld(this._world,"LIGHT.DESPAWN",{light:this}),this._id=void 0,this._world=void 0}spawn(Z){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return c.error(`Light.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning Light!`);this._id=Z.lightManager.registerLight(this),this._world=Z,this.emitWithWorld(Z,"LIGHT.SPAWN",{light:this})}serialize(){if(!this._world)c.fatalError("Light.serialize(): Light is not in a world and cannot be serialized!");return D0.serializeLight(this,this._world.tickAllocator)}}var Mm;((u)=>{u.BURST="PARTICLE_EMITTER.BURST";u.DESPAWN="PARTICLE_EMITTER.DESPAWN";u.SET_ALPHA_TEST="PARTICLE_EMITTER.SET_ALPHA_TEST";u.SET_ATTACHED_TO_ENTITY="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY";u.SET_ATTACHED_TO_ENTITY_NODE_NAME="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME";u.SET_COLOR_END="PARTICLE_EMITTER.SET_COLOR_END";u.SET_COLOR_END_VARIANCE="PARTICLE_EMITTER.SET_COLOR_END_VARIANCE";u.SET_COLOR_START="PARTICLE_EMITTER.SET_COLOR_START";u.SET_COLOR_START_VARIANCE="PARTICLE_EMITTER.SET_COLOR_START_VARIANCE";u.SET_GRAVITY="PARTICLE_EMITTER.SET_GRAVITY";u.SET_LIFETIME="PARTICLE_EMITTER.SET_LIFETIME";u.SET_LIFETIME_VARIANCE="PARTICLE_EMITTER.SET_LIFETIME_VARIANCE";u.SET_MAX_PARTICLES="PARTICLE_EMITTER.SET_MAX_PARTICLES";u.SET_OFFSET="PARTICLE_EMITTER.SET_OFFSET";u.SET_OPACITY_END="PARTICLE_EMITTER.SET_OPACITY_END";u.SET_OPACITY_END_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE";u.SET_OPACITY_START="PARTICLE_EMITTER.SET_OPACITY_START";u.SET_OPACITY_START_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE";u.SET_PAUSED="PARTICLE_EMITTER.SET_PAUSED";u.SET_POSITION="PARTICLE_EMITTER.SET_POSITION";u.SET_POSITION_VARIANCE="PARTICLE_EMITTER.SET_POSITION_VARIANCE";u.SET_RATE="PARTICLE_EMITTER.SET_RATE";u.SET_RATE_VARIANCE="PARTICLE_EMITTER.SET_RATE_VARIANCE";u.SET_SIZE_END="PARTICLE_EMITTER.SET_SIZE_END";u.SET_SIZE_END_VARIANCE="PARTICLE_EMITTER.SET_SIZE_END_VARIANCE";u.SET_SIZE_START="PARTICLE_EMITTER.SET_SIZE_START";u.SET_SIZE_START_VARIANCE="PARTICLE_EMITTER.SET_SIZE_START_VARIANCE";u.SET_TEXTURE_URI="PARTICLE_EMITTER.SET_TEXTURE_URI";u.SET_TRANSPARENT="PARTICLE_EMITTER.SET_TRANSPARENT";u.SET_VELOCITY="PARTICLE_EMITTER.SET_VELOCITY";u.SET_VELOCITY_VARIANCE="PARTICLE_EMITTER.SET_VELOCITY_VARIANCE";u.SPAWN="PARTICLE_EMITTER.SPAWN"})(Mm||={});class Rm extends M0{_id;_alphaTest;_attachedToEntity;_attachedToEntityNodeName;_colorEnd;_colorEndVariance;_colorStart;_colorStartVariance;_gravity;_lifetime;_lifetimeVariance;_maxParticles;_offset;_opacityEnd;_opacityEndVariance;_opacityStart;_opacityStartVariance;_paused;_position;_positionVariance;_rate;_rateVariance;_sizeEnd;_sizeEndVariance;_sizeStart;_sizeStartVariance;_sizeVariance;_textureUri;_transparent;_velocity;_velocityVariance;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)c.fatalError("Either attachedToEntity or position must be set, but not both.");if(!Z.textureUri)c.fatalError("ParticleEmitter.constructor(): textureUri must be provided.");super();this._alphaTest=Z.alphaTest??0.5,this._attachedToEntity=Z.attachedToEntity,this._attachedToEntityNodeName=Z.attachedToEntityNodeName,this._colorEnd=Z.colorEnd,this._colorEndVariance=Z.colorEndVariance,this._colorStart=Z.colorStart,this._colorStartVariance=Z.colorStartVariance,this._gravity=Z.gravity,this._lifetime=Z.lifetime,this._lifetimeVariance=Z.lifetimeVariance,this._maxParticles=Z.maxParticles,this._offset=Z.offset,this._opacityEnd=Z.opacityEnd,this._opacityEndVariance=Z.opacityEndVariance,this._opacityStart=Z.opacityStart,this._opacityStartVariance=Z.opacityStartVariance,this._paused=!1,this._position=Z.position,this._positionVariance=Z.positionVariance,this._rate=Z.rate,this._rateVariance=Z.rateVariance,this._sizeEnd=Z.sizeEnd,this._sizeEndVariance=Z.sizeEndVariance,this._sizeStart=Z.sizeStart,this._sizeStartVariance=Z.sizeStartVariance,this._textureUri=Z.textureUri,this._transparent=Z.transparent,this._velocity=Z.velocity,this._velocityVariance=Z.velocityVariance}get id(){return this._id}get alphaTest(){return this._alphaTest}get attachedToEntity(){return this._attachedToEntity}get attachedToEntityNodeName(){return this._attachedToEntityNodeName}get colorEnd(){return this._colorEnd}get colorEndVariance(){return this._colorEndVariance}get colorStart(){return this._colorStart}get colorStartVariance(){return this._colorStartVariance}get gravity(){return this._gravity}get isSpawned(){return this._id!==void 0}get lifetime(){return this._lifetime}get lifetimeVariance(){return this._lifetimeVariance}get maxParticles(){return this._maxParticles}get offset(){return this._offset}get opacityEnd(){return this._opacityEnd}get opacityEndVariance(){return this._opacityEndVariance}get opacityStart(){return this._opacityStart}get opacityStartVariance(){return this._opacityStartVariance}get paused(){return this._paused}get position(){return this._position}get positionVariance(){return this._positionVariance}get rate(){return this._rate}get rateVariance(){return this._rateVariance}get sizeEnd(){return this._sizeEnd}get sizeEndVariance(){return this._sizeEndVariance}get sizeStart(){return this._sizeStart}get sizeStartVariance(){return this._sizeStartVariance}get sizeVariance(){return this._sizeVariance}get textureUri(){return this._textureUri}get transparent(){return this._transparent}get velocity(){return this._velocity}get velocityVariance(){return this._velocityVariance}get world(){return this._world}setAlphaTest(Z){if(this._alphaTest===Z)return;if(this._alphaTest=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ALPHA_TEST",{particleEmitter:this,alphaTest:Z})}setAttachedToEntity(Z){if(!Z.isSpawned)return c.error(`ParticleEmitter.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",{particleEmitter:this,entity:Z})}setAttachedToEntityNodeName(Z){if(this._attachedToEntityNodeName===Z)return;if(this._attachedToEntityNodeName=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",{particleEmitter:this,attachedToEntityNodeName:Z})}setColorEnd(Z){if(this._colorEnd&&this._colorEnd.r===Z.r&&this._colorEnd.g===Z.g&&this._colorEnd.b===Z.b)return;if(this._colorEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END",{particleEmitter:this,colorEnd:Z})}setColorEndVariance(Z){if(this._colorEndVariance&&this._colorEndVariance.r===Z.r&&this._colorEndVariance.g===Z.g&&this._colorEndVariance.b===Z.b)return;if(this._colorEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",{particleEmitter:this,colorEndVariance:Z})}setColorStart(Z){if(this._colorStart&&this._colorStart.r===Z.r&&this._colorStart.g===Z.g&&this._colorStart.b===Z.b)return;if(this._colorStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START",{particleEmitter:this,colorStart:Z})}setColorStartVariance(Z){if(this._colorStartVariance&&this._colorStartVariance.r===Z.r&&this._colorStartVariance.g===Z.g&&this._colorStartVariance.b===Z.b)return;if(this._colorStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",{particleEmitter:this,colorStartVariance:Z})}setGravity(Z){if(this._gravity&&this._gravity.x===Z.x&&this._gravity.y===Z.y&&this._gravity.z===Z.z)return;if(this._gravity=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_GRAVITY",{particleEmitter:this,gravity:Z})}setLifetime(Z){if(this._lifetime===Z)return;if(this._lifetime=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME",{particleEmitter:this,lifetime:Z})}setLifetimeVariance(Z){if(this._lifetimeVariance===Z)return;if(this._lifetimeVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",{particleEmitter:this,lifetimeVariance:Z})}setMaxParticles(Z){if(this._maxParticles===Z)return;if(this._maxParticles=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_MAX_PARTICLES",{particleEmitter:this,maxParticles:Z})}setOffset(Z){if(this._offset&&this._offset.x===Z.x&&this._offset.y===Z.y&&this._offset.z===Z.z)return;if(this._offset=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OFFSET",{particleEmitter:this,offset:Z})}setOpacityEnd(Z){if(this._opacityEnd===Z)return;if(this._opacityEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END",{particleEmitter:this,opacityEnd:Z})}setOpacityEndVariance(Z){if(this._opacityEndVariance===Z)return;if(this._opacityEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",{particleEmitter:this,opacityEndVariance:Z})}setOpacityStart(Z){if(this._opacityStart===Z)return;if(this._opacityStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START",{particleEmitter:this,opacityStart:Z})}setOpacityStartVariance(Z){if(this._opacityStartVariance===Z)return;if(this._opacityStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",{particleEmitter:this,opacityStartVariance:Z})}setPosition(Z){if(this._position&&this._position.x===Z.x&&this._position.y===Z.y&&this._position.z===Z.z)return;if(this._position=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION",{particleEmitter:this,position:Z})}setPositionVariance(Z){if(this._positionVariance&&this._positionVariance.x===Z.x&&this._positionVariance.y===Z.y&&this._positionVariance.z===Z.z)return;if(this._positionVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION_VARIANCE",{particleEmitter:this,positionVariance:Z})}setRate(Z){if(this._rate===Z)return;if(this._rate=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE",{particleEmitter:this,rate:Z})}setRateVariance(Z){if(this._rateVariance===Z)return;if(this._rateVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE_VARIANCE",{particleEmitter:this,rateVariance:Z})}setSizeEnd(Z){if(this._sizeEnd===Z)return;if(this._sizeEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END",{particleEmitter:this,sizeEnd:Z})}setSizeEndVariance(Z){if(this._sizeEndVariance===Z)return;if(this._sizeEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",{particleEmitter:this,sizeEndVariance:Z})}setSizeStart(Z){if(this._sizeStart===Z)return;if(this._sizeStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START",{particleEmitter:this,sizeStart:Z})}setSizeStartVariance(Z){if(this._sizeStartVariance===Z)return;if(this._sizeStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",{particleEmitter:this,sizeStartVariance:Z})}setTextureUri(Z){if(this._textureUri===Z)return;if(this._textureUri=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TEXTURE_URI",{particleEmitter:this,textureUri:Z})}setTransparent(Z){if(this._transparent===Z)return;if(this._transparent=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TRANSPARENT",{particleEmitter:this,transparent:Z})}setVelocity(Z){if(this._velocity&&this._velocity.x===Z.x&&this._velocity.y===Z.y&&this._velocity.z===Z.z)return;if(this._velocity=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY",{particleEmitter:this,velocity:Z})}setVelocityVariance(Z){if(this._velocityVariance&&this._velocityVariance.x===Z.x&&this._velocityVariance.y===Z.y&&this._velocityVariance.z===Z.z)return;if(this._velocityVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",{particleEmitter:this,velocityVariance:Z})}burst(Z){if(this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.BURST",{particleEmitter:this,count:Z})}despawn(){if(!this.isSpawned||!this._world)return;this._world.particleEmitterManager.unregisterParticleEmitter(this),this.emitWithWorld(this._world,"PARTICLE_EMITTER.DESPAWN",{particleEmitter:this}),this._id=void 0,this._world=void 0}restart(){if(!this._paused)return;if(this._paused=!1,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}stop(){if(this._paused)return;if(this._paused=!0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}spawn(Z){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return c.error(`ParticleEmitter.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning ParticleEmitter!`);this._id=Z.particleEmitterManager.registerParticleEmitter(this),this._world=Z,this.emitWithWorld(Z,"PARTICLE_EMITTER.SPAWN",{particleEmitter:this})}serialize(){if(!this._world)c.fatalError("ParticleEmitter.serialize(): ParticleEmitter is not in a world and cannot be serialized!");return D0.serializeParticleEmitter(this,this._world.tickAllocator)}}var VU=r(KV(),1);var nQ6={x:0,y:-32,z:0},Nm=60,jm;(($)=>{$.STEP_START="SIMULATION.STEP_START";$.STEP_END="SIMULATION.STEP_END";$.DEBUG_RAYCAST="SIMULATION.DEBUG_RAYCAST";$.DEBUG_RENDER="SIMULATION.DEBUG_RENDER"})(jm||={});class HU extends M0{_colliderMap=new oH;_debugRaycastingEnabled=!1;_debugRenderingEnabled=!1;_debugRenderingFilterFlags;_rapierEventQueue;_rapierSimulation;_world;constructor(Z,J=Nm,X=nQ6){super();this._rapierEventQueue=new VU.default.EventQueue(!0),this._rapierSimulation=new VU.default.World(X),this._rapierSimulation.timestep=Math.fround(1/J),this._world=Z}get colliderMap(){return this._colliderMap}get isDebugRaycastingEnabled(){return this._debugRaycastingEnabled}get isDebugRenderingEnabled(){return this._debugRenderingEnabled}get gravity(){return this._rapierSimulation.gravity}get timestepS(){return this._rapierSimulation.timestep}get world(){return this._world}createRawCollider(Z,J){return this._rapierSimulation.createCollider(Z,J)}createRawRigidBody(Z){return this._rapierSimulation.createRigidBody(Z)}enableDebugRaycasting(Z){this._debugRaycastingEnabled=Z}enableDebugRendering(Z,J=VU.default.QueryFilterFlags.EXCLUDE_FIXED){this._debugRenderingEnabled=Z,this._debugRenderingFilterFlags=J}getContactManifolds(Z,J){let X=[];return this._rapierSimulation.narrowPhase.contactPair(Z,J,(Y,$)=>{if(Y.numContacts()===0)return;let Q=Y.normal(),K=[];for(let W=0;W<Y.numSolverContacts();W++)K.push(Y.solverContactPoint(W));X.push({contactPoints:K,localNormalA:!$?Y.localNormal1():Y.localNormal2(),localNormalB:!$?Y.localNormal2():Y.localNormal1(),normal:!$?Q:{x:-Q.x,y:-Q.y,z:-Q.z}})}),X}intersectionsWithRawShape(Z,J,X,Y={}){let $=new Set,Q=[];return this._rapierSimulation.intersectionsWithShape(J,X,Z,(K)=>{let W=this._colliderMap.getColliderHandleBlockType(K.handle);if(W&&!$.has(W))return $.add(W),Q.push({intersectedBlockType:W}),!0;let G=this._colliderMap.getColliderHandleEntity(K.handle);if(G&&!$.has(G))return $.add(G),Q.push({intersectedEntity:G}),!0;return!0},Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate),Q}raycast(Z,J,X,Y={}){let $=new VU.default.Ray(Z,J),Q=this._rapierSimulation.castRay($,X,Y.solidMode??!0,Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate);if(this._debugRaycastingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RAYCAST",{simulation:this,origin:Z,direction:J,length:X,hit:!!Q});if(!Q)return null;let K=$.pointAt(Q.timeOfImpact),W=Q.timeOfImpact,G=Q.collider,V=this._colliderMap.getColliderHandleBlockType(G.handle);if(V)return{hitBlock:FK.fromGlobalCoordinate({x:Math.floor(K.x-($.dir.x<0?0.0001:-0.0001)),y:Math.floor(K.y-($.dir.y<0?0.0001:-0.0001)),z:Math.floor(K.z-($.dir.z<0?0.0001:-0.0001))},V),hitPoint:K,hitDistance:W};let H=this._colliderMap.getColliderHandleEntity(G.handle);if(H)return{hitEntity:H,hitPoint:K,hitDistance:W};return null}removeRawCollider(Z){this._colliderMap.queueColliderHandleForCleanup(Z.handle),this._rapierSimulation.removeCollider(Z,!1)}removeRawRigidBody(Z){this._rapierSimulation.removeRigidBody(Z)}setGravity(Z){this._rapierSimulation.gravity=Z}step=(Z)=>{this.emitWithWorld(this._world,"SIMULATION.STEP_START",{simulation:this,tickDeltaMs:Z});let J=performance.now();if(t1.startSpan({operation:"physics_step"},()=>{this._rapierSimulation.step(this._rapierEventQueue)}),t1.startSpan({operation:"physics_cleanup"},()=>{this._rapierEventQueue.drainContactForceEvents(this._onContactForceEvent),this._rapierEventQueue.drainCollisionEvents(this._onCollisionEvent),this._colliderMap.cleanup()}),this.emitWithWorld(this._world,"SIMULATION.STEP_END",{simulation:this,stepDurationMs:performance.now()-J}),this._debugRenderingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RENDER",{simulation:this,...this._rapierSimulation.debugRender(this._debugRenderingFilterFlags)})};_onCollisionEvent=(Z,J,X)=>{let[Y,$]=this._getCollisionObjects(Z,J);if(!Y||!$)return;let Q=(K,W)=>{if(K instanceof W9&&W instanceof n8&&K.hasListeners("BLOCK_TYPE.ENTITY_COLLISION"))K.emit("BLOCK_TYPE.ENTITY_COLLISION",{blockType:K,entity:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof n8&&W instanceof W9&&K.hasListeners("ENTITY.BLOCK_COLLISION"))K.emit("ENTITY.BLOCK_COLLISION",{entity:K,blockType:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof n8&&W instanceof n8&&K.hasListeners("ENTITY.ENTITY_COLLISION"))K.emit("ENTITY.ENTITY_COLLISION",{entity:K,otherEntity:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(typeof K==="function"&&(W instanceof n8||W instanceof W9))K(W,X,Z,J)};Q(Y,$),Q($,Y)};_onContactForceEvent=(Z)=>{let[J,X]=this._getCollisionObjects(Z.collider1(),Z.collider2());if(!J||typeof J==="function"||!X||typeof X==="function")return;let Y={totalForce:Z.totalForce(),totalForceMagnitude:Z.totalForceMagnitude(),maxForceDirection:Z.maxForceDirection(),maxForceMagnitude:Z.maxForceMagnitude()},$=(Q,K)=>{if(Q instanceof W9&&K instanceof n8&&Q.hasListeners("BLOCK_TYPE.ENTITY_CONTACT_FORCE"))Q.emit("BLOCK_TYPE.ENTITY_CONTACT_FORCE",{blockType:Q,entity:K,contactForceData:Y});else if(Q instanceof n8&&K instanceof W9&&Q.hasListeners("ENTITY.BLOCK_CONTACT_FORCE"))Q.emit("ENTITY.BLOCK_CONTACT_FORCE",{entity:Q,blockType:K,contactForceData:Y});else if(Q instanceof n8&&K instanceof n8&&Q.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))Q.emit("ENTITY.ENTITY_CONTACT_FORCE",{entity:Q,otherEntity:K,contactForceData:Y})};$(J,X),$(X,J)};_getCollisionObjects(Z,J){let X=this._colliderMap.getColliderHandleBlockType(Z)??this._colliderMap.getColliderHandleCollisionCallback(Z)??this._colliderMap.getColliderHandleEntity(Z),Y=this._colliderMap.getColliderHandleBlockType(J)??this._colliderMap.getColliderHandleCollisionCallback(J)??this._colliderMap.getColliderHandleEntity(J);return[X,Y]}}class WD{_synchronizedPlayerReliablePackets=new F6;_queuedBroadcasts=[];_queuedAudioSynchronizations=new F6;_queuedBlockSynchronizations=new F6;_queuedBlockTypeSynchronizations=new F6;_queuedChunkSynchronizations=new F6;_queuedDebugRaycastSynchronizations=[];_queuedEntitySynchronizations=new F6;_queuedLightSynchronizations=new F6;_queuedParticleEmitterSynchronizations=new F6;_queuedPerPlayerSynchronizations=new F6;_queuedPerPlayerCameraSynchronizations=new F6;_queuedPerPlayerUISynchronizations=new F6;_queuedPerPlayerUIDatasSynchronizations=new F6;_queuedPlayerSynchronizations=new F6;_queuedSceneUISynchronizations=new F6;_queuedWorldSynchronization;_loadedSceneUIs=new Set;_spawnedChunks=new Set;_spawnedEntities=new Set;_world;constructor(Z){this._world=Z,this._subscribeToAudioEvents(),this._subscribeToBlockTypeRegistryEvents(),this._subscribeToChatEvents(),this._subscribeToChunkLatticeEvents(),this._subscribeToEntityEvents(),this._subscribeToLightEvents(),this._subscribeToParticleEmitterEvents(),this._subscribeToPlayerEvents(),this._subscribeToPlayerCameraEvents(),this._subscribeToPlayerUIEvents(),this._subscribeToSceneUIEvents(),this._subscribeToSimulationEvents(),this._subscribeToWorldEvents()}synchronize(){let Z=this._world.tickAllocator,J=this._world.tickAllocator.getArray(),X=this._world.tickAllocator.getArray(),Y=this._world.loop.currentTick;if(this._queuedPerPlayerSynchronizations.size>0)for(let[$,Q]of this._queuedPerPlayerSynchronizations)this._createOrGetSynchronizedPlayerReliablePackets($,J).push(...Q);if(this._queuedEntitySynchronizations.size>0){let $=this._world.tickAllocator.getArray(),Q=this._world.tickAllocator.getArray();for(let K of this._queuedEntitySynchronizations.valuesArray){let W=!1;for(let G in K)if(G!=="i"&&G!=="p"&&G!=="r"){W=!0;break}if(W)$.push(K);else Q.push(K)}if(Q.length>0){let K=Y0.createPacket(Y0.outboundPackets.entitiesPacketDefinition,Q,Y,Z.getArray());X.push(K)}if($.length>0){let K=Y0.createPacket(Y0.outboundPackets.entitiesPacketDefinition,$,Y,Z.getArray());J.push(K);for(let W of this._synchronizedPlayerReliablePackets.valuesArray)W.push(K)}}if(this._queuedAudioSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.audiosPacketDefinition,this._queuedAudioSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedBlockTypeSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.blockTypesPacketDefinition,this._queuedBlockTypeSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedChunkSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.chunksPacketDefinition,this._queuedChunkSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedBlockSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.blocksPacketDefinition,this._queuedBlockSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedLightSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.lightsPacketDefinition,this._queuedLightSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedParticleEmitterSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.particleEmittersPacketDefinition,this._queuedParticleEmitterSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedPerPlayerUISynchronizations.size>0)for(let[$,Q]of this._queuedPerPlayerUISynchronizations){let K=Y0.createPacket(Y0.outboundPackets.uiPacketDefinition,Q,Y,Z.getArray());this._createOrGetSynchronizedPlayerReliablePackets($,J).push(K)}if(this._queuedPerPlayerUIDatasSynchronizations.size>0)for(let[$,Q]of this._queuedPerPlayerUIDatasSynchronizations){let K=Y0.createPacket(Y0.outboundPackets.uiDatasPacketDefinition,Q,Y,Z.getArray());this._createOrGetSynchronizedPlayerReliablePackets($,J).push(K)}if(this._queuedSceneUISynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.sceneUIsPacketDefinition,this._queuedSceneUISynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedWorldSynchronization){let $=Y0.createPacket(Y0.outboundPackets.worldPacketDefinition,this._queuedWorldSynchronization,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedPerPlayerCameraSynchronizations.size>0)for(let[$,Q]of this._queuedPerPlayerCameraSynchronizations){let K=Y0.createPacket(Y0.outboundPackets.cameraPacketDefinition,Q,Y,Z.getArray());this._createOrGetSynchronizedPlayerReliablePackets($,J).push(K)}if(this._queuedPlayerSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.playersPacketDefinition,this._queuedPlayerSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedBroadcasts.length>0)for(let $ of this._queuedBroadcasts){J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedDebugRaycastSynchronizations.length>0){let $=Y0.createPacket(Y0.outboundPackets.physicsDebugRaycastsPacketDefinition,this._queuedDebugRaycastSynchronizations,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}t1.startSpan({operation:"send_all_packets"},()=>{for(let $ of U9.instance.getConnectedPlayersByWorld(this._world)){let Q=this._synchronizedPlayerReliablePackets.get($)??J;if(Q.length>0)$.connection.send(Q);if(X.length>0)$.connection.send(X,!1)}}),t1.startSpan({operation:"network_synchronize_cleanup"},()=>{if(this._queuedBroadcasts.length>0)this._queuedBroadcasts.length=0;if(this._queuedAudioSynchronizations.size>0)this._queuedAudioSynchronizations.clear();if(this._queuedBlockSynchronizations.size>0)this._queuedBlockSynchronizations.clear();if(this._queuedBlockTypeSynchronizations.size>0)this._queuedBlockTypeSynchronizations.clear();if(this._queuedChunkSynchronizations.size>0)this._queuedChunkSynchronizations.clear();if(this._queuedDebugRaycastSynchronizations.length>0)this._queuedDebugRaycastSynchronizations.length=0;if(this._queuedEntitySynchronizations.size>0)this._queuedEntitySynchronizations.clear();if(this._queuedLightSynchronizations.size>0)this._queuedLightSynchronizations.clear();if(this._queuedParticleEmitterSynchronizations.size>0)this._queuedParticleEmitterSynchronizations.clear();if(this._queuedPerPlayerSynchronizations.size>0)this._queuedPerPlayerSynchronizations.clear();if(this._queuedPerPlayerCameraSynchronizations.size>0)this._queuedPerPlayerCameraSynchronizations.clear();if(this._queuedPerPlayerUISynchronizations.size>0)this._queuedPerPlayerUISynchronizations.clear();if(this._queuedPerPlayerUIDatasSynchronizations.size>0)this._queuedPerPlayerUIDatasSynchronizations.clear();if(this._queuedPlayerSynchronizations.size>0)this._queuedPlayerSynchronizations.clear();if(this._queuedSceneUISynchronizations.size>0)this._queuedSceneUISynchronizations.clear();if(this._queuedWorldSynchronization)this._queuedWorldSynchronization=void 0;if(this._loadedSceneUIs.size>0)this._loadedSceneUIs.clear();if(this._spawnedChunks.size>0)this._spawnedChunks.clear();if(this._spawnedEntities.size>0)this._spawnedEntities.clear();if(this._synchronizedPlayerReliablePackets.size>0)this._synchronizedPlayerReliablePackets.clear();n4.clearCachedPacketsSerializedBuffers()})}_subscribeToAudioEvents(){this._world.final("AUDIO.PAUSE",this._onAudioPause),this._world.final("AUDIO.PLAY",this._onAudioPlay),this._world.final("AUDIO.PLAY_RESTART",this._onAudioPlayRestart),this._world.final("AUDIO.SET_ATTACHED_TO_ENTITY",this._onAudioSetAttachedToEntity),this._world.final("AUDIO.SET_CUTOFF_DISTANCE",this._onAudioSetCutoffDistance),this._world.final("AUDIO.SET_DETUNE",this._onAudioSetDetune),this._world.final("AUDIO.SET_DISTORTION",this._onAudioSetDistortion),this._world.final("AUDIO.SET_POSITION",this._onAudioSetPosition),this._world.final("AUDIO.SET_PLAYBACK_RATE",this._onAudioSetPlaybackRate),this._world.final("AUDIO.SET_REFERENCE_DISTANCE",this._onAudioSetReferenceDistance),this._world.final("AUDIO.SET_VOLUME",this._onAudioSetVolume)}_subscribeToBlockTypeRegistryEvents(){this._world.final("BLOCK_TYPE_REGISTRY.REGISTER_BLOCK_TYPE",this._onBlockTypeRegistryRegisterBlockType)}_subscribeToChatEvents(){this._world.final("CHAT.BROADCAST_MESSAGE",this._onChatSendBroadcastMessage),this._world.final("CHAT.PLAYER_MESSAGE",this._onChatSendPlayerMessage)}_subscribeToChunkLatticeEvents(){this._world.final("CHUNK_LATTICE.ADD_CHUNK",this._onChunkLatticeAddChunk),this._world.final("CHUNK_LATTICE.REMOVE_CHUNK",this._onChunkLatticeRemoveChunk),this._world.final("CHUNK_LATTICE.SET_BLOCK",this._onChunkLatticeSetBlock)}_subscribeToEntityEvents(){this._world.final("ENTITY.SPAWN",this._onEntitySpawn),this._world.final("ENTITY.DESPAWN",this._onEntityDespawn),this._world.final("ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE",this._onEntitySetModelAnimationsPlaybackRate),this._world.final("ENTITY.SET_MODEL_HIDDEN_NODES",this._onEntitySetModelHiddenNodes),this._world.final("ENTITY.SET_MODEL_SCALE",this._onEntitySetModelScale),this._world.final("ENTITY.SET_MODEL_SHOWN_NODES",this._onEntitySetModelShownNodes),this._world.final("ENTITY.SET_MODEL_TEXTURE_URI",this._onEntitySetModelTextureUri),this._world.final("ENTITY.SET_OPACITY",this._onEntitySetOpacity),this._world.final("ENTITY.SET_PARENT",this._onEntitySetParent),this._world.final("ENTITY.SET_TINT_COLOR",this._onEntitySetTintColor),this._world.final("ENTITY.START_MODEL_LOOPED_ANIMATIONS",this._onEntityStartModelLoopedAnimations),this._world.final("ENTITY.START_MODEL_ONESHOT_ANIMATIONS",this._onEntityStartModelOneshotAnimations),this._world.final("ENTITY.STOP_MODEL_ANIMATIONS",this._onEntityStopModelAnimations),this._world.final("ENTITY.UPDATE_POSITION",this._onEntityUpdatePosition),this._world.final("ENTITY.UPDATE_ROTATION",this._onEntityUpdateRotation)}_subscribeToLightEvents(){this._world.final("LIGHT.DESPAWN",this._onLightDespawn),this._world.final("LIGHT.SET_ANGLE",this._onLightSetAngle),this._world.final("LIGHT.SET_ATTACHED_TO_ENTITY",this._onLightSetAttachedToEntity),this._world.final("LIGHT.SET_COLOR",this._onLightSetColor),this._world.final("LIGHT.SET_DISTANCE",this._onLightSetDistance),this._world.final("LIGHT.SET_INTENSITY",this._onLightSetIntensity),this._world.final("LIGHT.SET_OFFSET",this._onLightSetOffset),this._world.final("LIGHT.SET_PENUMBRA",this._onLightSetPenumbra),this._world.final("LIGHT.SET_POSITION",this._onLightSetPosition),this._world.final("LIGHT.SET_TRACKED_ENTITY",this._onLightSetTrackedEntity),this._world.final("LIGHT.SET_TRACKED_POSITION",this._onLightSetTrackedPosition),this._world.final("LIGHT.SPAWN",this._onLightSpawn)}_subscribeToParticleEmitterEvents(){this._world.final("PARTICLE_EMITTER.DESPAWN",this._onParticleEmitterDespawn),this._world.final("PARTICLE_EMITTER.BURST",this._onParticleEmitterBurst),this._world.final("PARTICLE_EMITTER.SET_ALPHA_TEST",this._onParticleEmitterSetAlphaTest),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",this._onParticleEmitterSetAttachedToEntity),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",this._onParticleEmitterSetAttachedToEntityNodeName),this._world.final("PARTICLE_EMITTER.SET_COLOR_END",this._onParticleEmitterSetColorEnd),this._world.final("PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",this._onParticleEmitterSetColorEndVariance),this._world.final("PARTICLE_EMITTER.SET_COLOR_START",this._onParticleEmitterSetColorStart),this._world.final("PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",this._onParticleEmitterSetColorStartVariance),this._world.final("PARTICLE_EMITTER.SET_GRAVITY",this._onParticleEmitterSetGravity),this._world.final("PARTICLE_EMITTER.SET_LIFETIME",this._onParticleEmitterSetLifetime),this._world.final("PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",this._onParticleEmitterSetLifetimeVariance),this._world.final("PARTICLE_EMITTER.SET_MAX_PARTICLES",this._onParticleEmitterSetMaxParticles),this._world.final("PARTICLE_EMITTER.SET_OFFSET",this._onParticleEmitterSetOffset),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END",this._onParticleEmitterSetOpacityEnd),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",this._onParticleEmitterSetOpacityEndVariance),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START",this._onParticleEmitterSetOpacityStart),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",this._onParticleEmitterSetOpacityStartVariance),this._world.final("PARTICLE_EMITTER.SET_PAUSED",this._onParticleEmitterSetPaused),this._world.final("PARTICLE_EMITTER.SET_POSITION",this._onParticleEmitterSetPosition),this._world.final("PARTICLE_EMITTER.SET_POSITION_VARIANCE",this._onParticleEmitterSetPositionVariance),this._world.final("PARTICLE_EMITTER.SET_RATE",this._onParticleEmitterSetRate),this._world.final("PARTICLE_EMITTER.SET_RATE_VARIANCE",this._onParticleEmitterSetRateVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_END",this._onParticleEmitterSetSizeEnd),this._world.final("PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",this._onParticleEmitterSetSizeEndVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_START",this._onParticleEmitterSetSizeStart),this._world.final("PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",this._onParticleEmitterSetSizeStartVariance),this._world.final("PARTICLE_EMITTER.SET_TEXTURE_URI",this._onParticleEmitterSetTextureUri),this._world.final("PARTICLE_EMITTER.SET_TRANSPARENT",this._onParticleEmitterSetTransparent),this._world.final("PARTICLE_EMITTER.SET_VELOCITY",this._onParticleEmitterSetVelocity),this._world.final("PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",this._onParticleEmitterSetVelocityVariance),this._world.final("PARTICLE_EMITTER.SPAWN",this._onParticleEmitterSpawn)}_subscribeToPlayerEvents(){this._world.final("PLAYER.JOINED_WORLD",this._onPlayerJoinedWorld),this._world.final("PLAYER.LEFT_WORLD",this._onPlayerLeftWorld),this._world.final("PLAYER.RECONNECTED_WORLD",this._onPlayerReconnectedWorld),this._world.final("PLAYER.REQUEST_SYNC",this._onPlayerRequestSync)}_subscribeToPlayerCameraEvents(){this._world.final("PLAYER_CAMERA.LOOK_AT_ENTITY",this._onPlayerCameraLookAtEntity),this._world.final("PLAYER_CAMERA.LOOK_AT_POSITION",this._onPlayerCameraLookAtPosition),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY",this._onPlayerCameraSetAttachedToEntity),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",this._onPlayerCameraSetAttachedToPosition),this._world.final("PLAYER_CAMERA.SET_FILM_OFFSET",this._onPlayerCameraSetFilmOffset),this._world.final("PLAYER_CAMERA.SET_FORWARD_OFFSET",this._onPlayerCameraSetForwardOffset),this._world.final("PLAYER_CAMERA.SET_FOV",this._onPlayerCameraSetFov),this._world.final("PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES",this._onPlayerCameraSetModelHiddenNodes),this._world.final("PLAYER_CAMERA.SET_MODEL_SHOWN_NODES",this._onPlayerCameraSetModelShownNodes),this._world.final("PLAYER_CAMERA.SET_MODE",this._onPlayerCameraSetMode),this._world.final("PLAYER_CAMERA.SET_OFFSET",this._onPlayerCameraSetOffset),this._world.final("PLAYER_CAMERA.SET_SHOULDER_ANGLE",this._onPlayerCameraSetShoulderAngle),this._world.final("PLAYER_CAMERA.SET_TRACKED_ENTITY",this._onPlayerCameraSetTrackedEntity),this._world.final("PLAYER_CAMERA.SET_TRACKED_POSITION",this._onPlayerCameraSetTrackedPosition),this._world.final("PLAYER_CAMERA.SET_ZOOM",this._onPlayerCameraSetZoom)}_subscribeToPlayerUIEvents(){this._world.final("PLAYER_UI.LOAD",this._onPlayerUILoad),this._world.final("PLAYER_UI.LOCK_POINTER",this._onPlayerUILockPointer),this._world.final("PLAYER_UI.SEND_DATA",this._onPlayerUISendData)}_subscribeToSceneUIEvents(){this._world.final("SCENE_UI.LOAD",this._onSceneUILoad),this._world.final("SCENE_UI.SET_ATTACHED_TO_ENTITY",this._onSceneUISetAttachedToEntity),this._world.final("SCENE_UI.SET_OFFSET",this._onSceneUISetOffset),this._world.final("SCENE_UI.SET_POSITION",this._onSceneUISetPosition),this._world.final("SCENE_UI.SET_STATE",this._onSceneUISetState),this._world.final("SCENE_UI.SET_VIEW_DISTANCE",this._onSceneUISetViewDistance),this._world.final("SCENE_UI.UNLOAD",this._onSceneUIUnload)}_subscribeToSimulationEvents(){this._world.final("SIMULATION.DEBUG_RAYCAST",this._onSimulationDebugRaycast),this._world.final("SIMULATION.DEBUG_RENDER",this._onSimulationDebugRender)}_subscribeToWorldEvents(){this._world.final("WORLD.SET_AMBIENT_LIGHT_COLOR",this._onWorldSetAmbientLightColor),this._world.final("WORLD.SET_AMBIENT_LIGHT_INTENSITY",this._onWorldSetAmbientLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",this._onWorldSetDirectionalLightColor),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",this._onWorldSetDirectionalLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",this._onWorldSetDirectionalLightPosition),this._world.final("WORLD.SET_FOG_COLOR",this._onWorldSetFogColor),this._world.final("WORLD.SET_FOG_FAR",this._onWorldSetFogFar),this._world.final("WORLD.SET_FOG_NEAR",this._onWorldSetFogNear),this._world.final("WORLD.SET_SKYBOX_INTENSITY",this._onWorldSetSkyboxIntensity)}_onAudioPause=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.pa=!0,delete J.pl,delete J.r};_onAudioPlay=(Z)=>{let J=Z.audio.serialize();J.pl=!0,delete J.pa,delete J.r,this._queuedAudioSynchronizations.set(J.i,J)};_onAudioPlayRestart=(Z)=>{let J=Z.audio.serialize();J.r=!0,delete J.pa,delete J.pl,this._queuedAudioSynchronizations.set(J.i,J)};_onAudioSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onAudioSetCutoffDistance=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.cd=Z.cutoffDistance};_onAudioSetDetune=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.de=Z.detune};_onAudioSetDistortion=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.di=Z.distortion};_onAudioSetPosition=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.e=Z.position?void 0:J.e,J.p=Z.position?D0.serializeVector(Z.position,this._world.tickAllocator):void 0};_onAudioSetPlaybackRate=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.pr=Z.playbackRate};_onAudioSetReferenceDistance=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.rd=Z.referenceDistance};_onAudioSetVolume=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.v=Z.volume};_onBlockTypeRegistryRegisterBlockType=(Z)=>{let J=Z.blockType.serialize();this._queuedBlockTypeSynchronizations.set(Z.blockType.id,J)};_onChatSendBroadcastMessage=(Z)=>{let J=this._world.tickAllocator,{player:X,message:Y,color:$}=Z,Q=J.getObject();Q.m=Y,Q.c=$,Q.p=X?.id;let K=J.getArray();K.push(Q),this._queuedBroadcasts.push(Y0.createPacket(Y0.outboundPackets.chatMessagesPacketDefinition,K,this._world.loop.currentTick,J.getArray()))};_onChatSendPlayerMessage=(Z)=>{let J=this._world.tickAllocator,{player:X,message:Y,color:$}=Z,Q=this._queuedPerPlayerSynchronizations.get(X)??[],K=J.getObject();K.m=Y,K.c=$;let W=J.getArray();W.push(K),Q.push(Y0.createPacket(Y0.outboundPackets.chatMessagesPacketDefinition,W,this._world.loop.currentTick,this._world.tickAllocator.getArray())),this._queuedPerPlayerSynchronizations.set(X,Q)};_onChunkLatticeAddChunk=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk);J.b=this._world.tickAllocator.getArray(Z.chunk.blocks),J.rm=void 0,this._spawnedChunks.add(J.c.join(","))};_onChunkLatticeRemoveChunk=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk),X=J.c.join(",");if(this._spawnedChunks.has(X))this._queuedChunkSynchronizations.delete(X),this._spawnedChunks.delete(X);else J.rm=!0};_onChunkLatticeSetBlock=(Z)=>{let J=this._createOrGetQueuedBlockSync(Z.globalCoordinate);J.i=Z.blockTypeId};_onEntitySetModelAnimationsPlaybackRate=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.ap=Z.playbackRate};_onEntitySpawn=(Z)=>{let J=Z.entity.serialize();this._queuedEntitySynchronizations.set(J.i,J),this._spawnedEntities.add(J.i)};_onEntityDespawn=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(this._spawnedEntities.has(J.i))this._queuedEntitySynchronizations.delete(J.i),this._spawnedEntities.delete(J.i);else J.rm=!0};_onEntitySetModelHiddenNodes=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.h=this._world.tickAllocator.getArray(Z.modelHiddenNodes)};_onEntitySetModelScale=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.s=Z.modelScale};_onEntitySetModelShownNodes=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.sn=this._world.tickAllocator.getArray(Z.modelShownNodes)};_onEntitySetModelTextureUri=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.mt=Z.modelTextureUri};_onEntitySetOpacity=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.o=Z.opacity};_onEntitySetParent=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.pe=Z.parent?Z.parent.id:void 0,J.pn=Z.parentNodeName};_onEntitySetTintColor=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.t=Z.tintColor?D0.serializeRgbColor(Z.tintColor,this._world.tickAllocator):void 0};_onEntityStartModelLoopedAnimations=(Z)=>{let J=this._world.tickAllocator,X=this._createOrGetQueuedEntitySync(Z.entity),Y=J.getSet(X.al,Z.animations);if(X.al=J.getArray(Y),X.as){let $=J.getArray();for(let Q of X.as)!Y.has(Q)&&$.push(Q);X.as=$}};_onEntityStartModelOneshotAnimations=(Z)=>{let J=this._world.tickAllocator,X=this._createOrGetQueuedEntitySync(Z.entity),Y=J.getSet(X.ao,Z.animations);if(X.ao=J.getArray(Y),X.as){let $=J.getArray();for(let Q of X.as)!Y.has(Q)&&$.push(Q);X.as=$}};_onEntityStopModelAnimations=(Z)=>{let J=this._world.tickAllocator,X=this._createOrGetQueuedEntitySync(Z.entity);if(X.al){let Y=J.getSet(X.al);for(let $ of Z.animations)Y.delete($);X.al=J.getArray(Y)}if(X.ao){let Y=J.getSet(X.ao);for(let $ of Z.animations)Y.delete($);X.ao=J.getArray(Y)}X.as=J.getArray(J.getSet(X.as,Z.animations))};_onEntityUpdateRotation=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.r=D0.serializeQuaternion(Z.rotation,this._world.tickAllocator)};_onEntityUpdatePosition=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.p=D0.serializeVector(Z.position,this._world.tickAllocator)};_onLightDespawn=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.rm=!0};_onLightSetAngle=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.a=Z.angle};_onLightSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onLightSetColor=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.c=D0.serializeRgbColor(Z.color,this._world.tickAllocator)};_onLightSetDistance=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.d=Z.distance};_onLightSetIntensity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.n=Z.intensity};_onLightSetOffset=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.o=Z.offset?D0.serializeVector(Z.offset,this._world.tickAllocator):void 0};_onLightSetPenumbra=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.pe=Z.penumbra};_onLightSetPosition=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.p=Z.position?D0.serializeVector(Z.position,this._world.tickAllocator):void 0,J.e=Z.position?void 0:J.e};_onLightSetTrackedEntity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.te=Z.entity?Z.entity.id:void 0,J.tp=Z.entity?void 0:J.tp};_onLightSetTrackedPosition=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.tp=Z.position?D0.serializeVector(Z.position,this._world.tickAllocator):void 0,J.te=Z.position?void 0:J.te};_onLightSpawn=(Z)=>{let J=Z.light.serialize();this._queuedLightSynchronizations.set(J.i,J)};_onParticleEmitterBurst=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.b=Z.count};_onParticleEmitterDespawn=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.rm=!0};_onParticleEmitterSetAlphaTest=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.at=Z.alphaTest};_onParticleEmitterSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onParticleEmitterSetAttachedToEntityNodeName=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.en=Z.attachedToEntityNodeName};_onParticleEmitterSetColorEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ce=Z.colorEnd?D0.serializeRgbColor(Z.colorEnd,this._world.tickAllocator):void 0};_onParticleEmitterSetColorEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.cev=Z.colorEndVariance?D0.serializeRgbColor(Z.colorEndVariance,this._world.tickAllocator):void 0};_onParticleEmitterSetColorStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.cs=Z.colorStart?D0.serializeRgbColor(Z.colorStart,this._world.tickAllocator):void 0};_onParticleEmitterSetColorStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.csv=Z.colorStartVariance?D0.serializeRgbColor(Z.colorStartVariance,this._world.tickAllocator):void 0};_onParticleEmitterSetGravity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.g=Z.gravity?D0.serializeVector(Z.gravity,this._world.tickAllocator):void 0};_onParticleEmitterSetLifetime=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.l=Z.lifetime};_onParticleEmitterSetLifetimeVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.lv=Z.lifetimeVariance};_onParticleEmitterSetMaxParticles=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.mp=Z.maxParticles};_onParticleEmitterSetOffset=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.o=Z.offset?D0.serializeVector(Z.offset,this._world.tickAllocator):void 0};_onParticleEmitterSetOpacityEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.oe=Z.opacityEnd};_onParticleEmitterSetOpacityEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.oev=Z.opacityEndVariance};_onParticleEmitterSetOpacityStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.os=Z.opacityStart};_onParticleEmitterSetOpacityStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.osv=Z.opacityStartVariance};_onParticleEmitterSetPaused=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.pa=Z.paused};_onParticleEmitterSetPosition=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.p=Z.position?D0.serializeVector(Z.position,this._world.tickAllocator):void 0,J.e=Z.position?void 0:J.e,J.en=Z.position?void 0:J.en};_onParticleEmitterSetPositionVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.pv=Z.positionVariance?D0.serializeVector(Z.positionVariance,this._world.tickAllocator):void 0};_onParticleEmitterSetRate=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.r=Z.rate};_onParticleEmitterSetRateVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.rv=Z.rateVariance};_onParticleEmitterSetSizeEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.se=Z.sizeEnd};_onParticleEmitterSetSizeEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.sev=Z.sizeEndVariance};_onParticleEmitterSetSizeStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ss=Z.sizeStart};_onParticleEmitterSetSizeStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ssv=Z.sizeStartVariance};_onParticleEmitterSetTextureUri=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.tu=Z.textureUri};_onParticleEmitterSetTransparent=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.t=Z.transparent};_onParticleEmitterSetVelocity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.v=Z.velocity?D0.serializeVector(Z.velocity,this._world.tickAllocator):void 0};_onParticleEmitterSetVelocityVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.vv=Z.velocityVariance?D0.serializeVector(Z.velocityVariance,this._world.tickAllocator):void 0};_onParticleEmitterSpawn=(Z)=>{let J=Z.particleEmitter.serialize();this._queuedParticleEmitterSynchronizations.set(J.i,J)};_onPlayerCameraLookAtEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=D0.serializeVector(Z.entity.position,this._world.tickAllocator),delete J.et,delete J.pt};_onPlayerCameraLookAtPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=Z.position?D0.serializeVector(Z.position,this._world.tickAllocator):void 0,delete J.et,delete J.pt};_onPlayerCameraSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.e=Z.entity.id,delete J.p};_onPlayerCameraSetAttachedToPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.p=Z.position?D0.serializeVector(Z.position,this._world.tickAllocator):void 0,delete J.e};_onPlayerCameraSetFilmOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.fo=Z.filmOffset};_onPlayerCameraSetForwardOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.ffo=Z.forwardOffset};_onPlayerCameraSetFov=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.fv=Z.fov};_onPlayerCameraSetModelHiddenNodes=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.h=this._world.tickAllocator.getArray(Z.modelHiddenNodes)};_onPlayerCameraSetModelShownNodes=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.s=this._world.tickAllocator.getArray(Z.modelShownNodes)};_onPlayerCameraSetMode=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.m=Z.mode};_onPlayerCameraSetOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.o=Z.offset?D0.serializeVector(Z.offset,this._world.tickAllocator):void 0};_onPlayerCameraSetShoulderAngle=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.sa=Z.shoulderAngle};_onPlayerCameraSetTrackedEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.et=Z.entity?Z.entity.id:void 0,delete J.pl,delete J.pt};_onPlayerCameraSetTrackedPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pt=Z.position?D0.serializeVector(Z.position,this._world.tickAllocator):void 0,delete J.et,delete J.pl};_onPlayerCameraSetZoom=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.z=Z.zoom};_onPlayerJoinedWorld=(Z)=>{let J=this._world.tickAllocator,{player:X}=Z,Y=this._queuedPerPlayerSynchronizations.get(X)??J.getArray();Y.push(Y0.createPacket(Y0.outboundPackets.worldPacketDefinition,this._world.serialize(),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.blockTypesPacketDefinition,this._world.blockTypeRegistry.serialize(),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.chunksPacketDefinition,J.map(this._world.chunkLattice.getAllChunks(!0),(Q)=>Q.serialize()),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.entitiesPacketDefinition,J.map(this._world.entityManager.getAllEntities(!0),(Q)=>{if(X.camera.attachedToEntity===void 0&&Q instanceof b7&&Q.player===X)X.camera.setAttachedToEntity(Q);return Q.serialize()}),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.audiosPacketDefinition,J.map(this._world.audioManager.getAllLoopedAudios(!0),(Q)=>Q.serialize()),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.lightsPacketDefinition,J.map(this._world.lightManager.getAllLights(!0),(Q)=>Q.serialize()),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.particleEmittersPacketDefinition,J.map(this._world.particleEmitterManager.getAllParticleEmitters(!0),(Q)=>Q.serialize()),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.sceneUIsPacketDefinition,J.map(this._world.sceneUIManager.getAllSceneUIs(!0),(Q)=>Q.serialize()),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.playersPacketDefinition,J.map(U9.instance.getConnectedPlayers(),(Q)=>Q.serialize()),this._world.loop.currentTick,J.getArray()));let $=this._createOrGetQueuedPlayerCameraSync(X.camera);this._queuedPerPlayerCameraSynchronizations.set(X,J.getObject(X.camera.serialize(),$)),this._queuedPerPlayerSynchronizations.set(X,Y),this._queuedPlayerSynchronizations.set(X.id,X.serialize())};_onPlayerLeftWorld=(Z)=>{let J=this._createOrGetQueuedPlayerSync(Z.player);J.rm=!0};_onPlayerReconnectedWorld=(Z)=>{this._onPlayerJoinedWorld(Z)};_onPlayerRequestSync=(Z)=>{let J=this._world.tickAllocator,X=J.getObject();X.r=Z.receivedAt,X.s=Date.now(),X.p=performance.now()-Z.receivedAtMs,X.n=this._world.loop.nextTickMs,Z.player.connection.send([Y0.createPacket(Y0.outboundPackets.syncResponsePacketDefinition,X,this._world.loop.currentTick,J.getArray())])};_onPlayerUILoad=(Z)=>{let J=this._createOrGetQueuedPlayerUISync(Z.playerUI);J.u=Z.htmlUri};_onPlayerUILockPointer=(Z)=>{let J=this._createOrGetQueuedPlayerUISync(Z.playerUI);J.p=Z.lock};_onPlayerUISendData=(Z)=>{this._createOrGetQueuedPlayerUIDatasSync(Z.playerUI).push(Z.data)};_onSceneUILoad=(Z)=>{let J=Z.sceneUI.serialize();this._queuedSceneUISynchronizations.set(J.i,J),this._loadedSceneUIs.add(J.i)};_onSceneUISetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onSceneUISetOffset=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.o=Z.offset?D0.serializeVector(Z.offset,this._world.tickAllocator):void 0};_onSceneUISetPosition=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.p=Z.position?D0.serializeVector(Z.position,this._world.tickAllocator):void 0,J.e=Z.position?void 0:J.e};_onSceneUISetState=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.s=Z.state};_onSceneUISetViewDistance=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.v=Z.viewDistance};_onSceneUIUnload=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);if(this._loadedSceneUIs.has(J.i))this._queuedSceneUISynchronizations.delete(J.i),this._loadedSceneUIs.delete(J.i);else J.rm=!0};_onSimulationDebugRaycast=(Z)=>{this._queuedDebugRaycastSynchronizations.push(D0.serializePhysicsDebugRaycast(Z,this._world.tickAllocator))};_onSimulationDebugRender=(Z)=>{this._queuedBroadcasts.push(Y0.createPacket(Y0.outboundPackets.physicsDebugRenderPacketDefinition,{v:Array.from(Z.vertices),c:Array.from(Z.colors)},this._world.loop.currentTick,this._world.tickAllocator.getArray()))};_onWorldSetAmbientLightColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ac=D0.serializeRgbColor(Z.color,this._world.tickAllocator)};_onWorldSetAmbientLightIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ai=Z.intensity};_onWorldSetDirectionalLightColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.dc=D0.serializeRgbColor(Z.color,this._world.tickAllocator)};_onWorldSetDirectionalLightIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.di=Z.intensity};_onWorldSetDirectionalLightPosition=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.dp=D0.serializeVector(Z.position,this._world.tickAllocator)};_onWorldSetFogColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.fc=D0.serializeRgbColor(Z.color,this._world.tickAllocator)};_onWorldSetFogFar=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ff=Z.far};_onWorldSetFogNear=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.fn=Z.near};_onWorldSetSkyboxIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.si=Z.intensity};_createOrGetQueuedAudioSync(Z){if(Z.id===void 0)c.fatalError("NetworkSynchronizer._createOrGetQueuedAudioSync(): Audio has no id!");let J=this._queuedAudioSynchronizations.get(Z.id);if(!J)J=this._world.tickAllocator.getObject(),J.i=Z.id,this._queuedAudioSynchronizations.set(Z.id,J);return J}_createOrGetQueuedBlockSync(Z){let{x:J,y:X,z:Y}=Z,$=`${J},${X},${Y}`,Q=this._queuedBlockSynchronizations.get($);if(!Q)Q=this._world.tickAllocator.getObject(),Q.i=0,Q.c=[J,X,Y],this._queuedBlockSynchronizations.set($,Q);return Q}_createOrGetQueuedChunkSync(Z){if(!Z.originCoordinate)c.fatalError("NetworkSynchronizer._createOrGetQueuedChunkSync(): Chunk has no origin coordinate!");let{x:J,y:X,z:Y}=Z.originCoordinate,$=`${J},${X},${Y}`,Q=this._queuedChunkSynchronizations.get($);if(!Q)Q=this._world.tickAllocator.getObject(),Q.c=[J,X,Y],this._queuedChunkSynchronizations.set($,Q);return Q}_createOrGetQueuedEntitySync(Z){if(Z.id===void 0)c.fatalError("NetworkSynchronizer._createOrGetQueuedEntitySync(): Entity has no id!");let J=this._queuedEntitySynchronizations.get(Z.id);if(!J)J=this._world.tickAllocator.getObject(),J.i=Z.id,this._queuedEntitySynchronizations.set(Z.id,J);return J}_createOrGetQueuedLightSync(Z){if(Z.id===void 0)c.fatalError("NetworkSynchronizer._createOrGetQueuedLightSync(): Light has no id!");let J=this._queuedLightSynchronizations.get(Z.id);if(!J)J=this._world.tickAllocator.getObject(),J.i=Z.id,this._queuedLightSynchronizations.set(Z.id,J);return J}_createOrGetQueuedParticleEmitterSync(Z){if(Z.id===void 0)c.fatalError("NetworkSynchronizer._createOrGetQueuedParticleEmitterSync(): ParticleEmitter has no id!");let J=this._queuedParticleEmitterSynchronizations.get(Z.id);if(!J)J=this._world.tickAllocator.getObject(),J.i=Z.id,this._queuedParticleEmitterSynchronizations.set(Z.id,J);return J}_createOrGetQueuedPlayerSync(Z){if(Z.id===void 0)c.fatalError("NetworkSynchronizer._createOrGetQueuedPlayerSync(): Player has no id!");let J=this._queuedPlayerSynchronizations.get(Z.id);if(!J)J=this._world.tickAllocator.getObject(),J.i=Z.id,this._queuedPlayerSynchronizations.set(Z.id,J);return J}_createOrGetQueuedPlayerCameraSync(Z){let J=this._queuedPerPlayerCameraSynchronizations.get(Z.player);if(!J)J=this._world.tickAllocator.getObject(),this._queuedPerPlayerCameraSynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUISync(Z){let J=this._queuedPerPlayerUISynchronizations.get(Z.player);if(!J)J=this._world.tickAllocator.getObject(),this._queuedPerPlayerUISynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUIDatasSync(Z){let J=this._queuedPerPlayerUIDatasSynchronizations.get(Z.player);if(!J)J=this._world.tickAllocator.getArray(),this._queuedPerPlayerUIDatasSynchronizations.set(Z.player,J);return J}_createOrGetQueuedSceneUISync(Z){if(Z.id===void 0)c.fatalError("NetworkSynchronizer._createOrGetQueuedSceneUISync(): SceneUI has no id!");let J=this._queuedSceneUISynchronizations.get(Z.id);if(!J)J=this._world.tickAllocator.getObject(),J.i=Z.id,this._queuedSceneUISynchronizations.set(Z.id,J);return J}_createOrGetQueuedWorldSync(Z){if(Z.id!==this._world.id)c.fatalError("NetworkSynchronizer._createOrGetQueuedWorldSync(): World does not match this network synchronizer world!");return this._queuedWorldSynchronization??=this._world.tickAllocator.getObject(),this._queuedWorldSynchronization.i=Z.id,this._queuedWorldSynchronization}_createOrGetSynchronizedPlayerReliablePackets(Z,J){let X=this._synchronizedPlayerReliablePackets.get(Z);if(!X)X=this._world.tickAllocator.getArray(J),this._synchronizedPlayerReliablePackets.set(Z,X);return X}}class zU{_particleEmitters=new Map;_nextParticleEmitterId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}despawnEntityAttachedParticleEmitters(Z){this.getAllEntityAttachedParticleEmitters(Z).forEach((J)=>{J.despawn()})}getAllParticleEmitters(Z=!1){return Z?this._world.tickAllocator.getArray(this._particleEmitters.values()):Array.from(this._particleEmitters.values())}getAllEntityAttachedParticleEmitters(Z){return this.getAllParticleEmitters().filter((J)=>J.attachedToEntity===Z)}registerParticleEmitter(Z){if(Z.id!==void 0)return Z.id;let J=this._nextParticleEmitterId;return this._particleEmitters.set(J,Z),this._nextParticleEmitterId++,J}unregisterParticleEmitter(Z){if(Z.id===void 0)return;this._particleEmitters.delete(Z.id)}}class FU{_sceneUIs=new Map;_nextSceneUIId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}getAllSceneUIs(Z=!1){return Z?this._world.tickAllocator.getArray(this._sceneUIs.values()):Array.from(this._sceneUIs.values())}getAllEntityAttachedSceneUIs(Z){return this.getAllSceneUIs().filter((J)=>J.attachedToEntity===Z)}getSceneUIById(Z){return this._sceneUIs.get(Z)}registerSceneUI(Z){if(Z.id!==void 0)return Z.id;let J=this._nextSceneUIId;return this._sceneUIs.set(J,Z),this._nextSceneUIId++,J}unloadEntityAttachedSceneUIs(Z){this.getAllEntityAttachedSceneUIs(Z).forEach((J)=>{J.unload()})}unregisterSceneUI(Z){if(Z.id===void 0)return;this._sceneUIs.delete(Z.id)}}class qU{_allocatedArrays=[];_allocatedArray3Numbers=[];_allocatedArray4Numbers=[];_allocatedObjects=[];_allocatedSets=[];_arrayPool=[];_array3NumberPool=[];_array4NumberPool=[];_objectPool=[];_setPool=[];filter(Z,J){let X=this.getArray();for(let Y=0;Y<Z.length;Y++)if(J(Z[Y],Y,Z))X.push(Z[Y]);return X}getArray(Z,J){let X=this._arrayPool.pop()??[];X.length=0;let Y=0;if(Z)for(let $ of Z)X[Y++]=$;if(J)for(let $ of J)X[Y++]=$;return this._allocatedArrays.push(X),X}getArray3Number(Z){let J=this._array3NumberPool.pop()??[0,0,0];if(J[0]=J[1]=J[2]=0,Z){let X=0;for(let Y of Z){if(X>=3)break;J[X++]=Y}}return this._allocatedArray3Numbers.push(J),J}getArray4Number(Z){let J=this._array4NumberPool.pop()??[0,0,0,0];if(J[0]=J[1]=J[2]=J[3]=0,Z){let X=0;for(let Y of Z){if(X>=4)break;J[X++]=Y}}return this._allocatedArray4Numbers.push(J),J}getObject(Z,J){let X=this._objectPool.pop()??Object.create(null);for(let Y in X)delete X[Y];if(Z)Object.assign(X,Z);if(J)Object.assign(X,J);return this._allocatedObjects.push(X),X}getSet(Z,J){let X=this._setPool.pop()??new Set;if(X.clear(),Z)for(let Y of Z)X.add(Y);if(J)for(let Y of J)X.add(Y);return this._allocatedSets.push(X),X}map(Z,J){let X=this.getArray();X.length=Z.length;for(let Y=0;Y<Z.length;Y++)X[Y]=J(Z[Y],Y,Z);return X}reset(){for(let Z=0;Z<this._allocatedArrays.length;Z++)if(this._arrayPool.length<4096)this._arrayPool.push(this._allocatedArrays[Z]);for(let Z=0;Z<this._allocatedArray3Numbers.length;Z++)if(this._array3NumberPool.length<4096)this._array3NumberPool.push(this._allocatedArray3Numbers[Z]);for(let Z=0;Z<this._allocatedArray4Numbers.length;Z++)if(this._array4NumberPool.length<4096)this._array4NumberPool.push(this._allocatedArray4Numbers[Z]);for(let Z=0;Z<this._allocatedObjects.length;Z++)if(this._objectPool.length<4096)this._objectPool.push(this._allocatedObjects[Z]);for(let Z=0;Z<this._allocatedSets.length;Z++)if(this._setPool.length<1024)this._setPool.push(this._allocatedSets[Z]);this._allocatedArrays.length=0,this._allocatedArray3Numbers.length=0,this._allocatedArray4Numbers.length=0,this._allocatedObjects.length=0,this._allocatedSets.length=0}}var aQ6=2,sQ6=3;class UU{_accumulatorMs=0;_targetTicksPerSecond;_fixedTimestepMs;_fixedTimestepS;_maxAccumulatorMs;_nextTickMs=0;_lastLoopTimeMs=0;_tickFunction;_tickErrorCallback;_tickHandle=null;constructor(Z,J,X){this._targetTicksPerSecond=Z,this._fixedTimestepS=Math.fround(1/Z),this._fixedTimestepMs=Math.fround(this._fixedTimestepS*1000),this._maxAccumulatorMs=this._fixedTimestepMs*sQ6,this._tickFunction=J,this._tickErrorCallback=X}get targetTicksPerSecond(){return this._targetTicksPerSecond}get fixedTimestepMs(){return this._fixedTimestepMs}get fixedTimestepS(){return this._fixedTimestepS}get isStarted(){return!!this._tickHandle}get nextTickMs(){return this._nextTickMs}start(){if(this._tickHandle)return;this._lastLoopTimeMs=performance.now();let Z=()=>{let J=performance.now(),X=J-this._lastLoopTimeMs;if(this._lastLoopTimeMs=J,this._accumulatorMs+=X,this._accumulatorMs>this._maxAccumulatorMs)this._accumulatorMs=this._maxAccumulatorMs;if(this._accumulatorMs>=this._fixedTimestepMs)t1.startSpan({operation:"ticker_tick"},()=>{let Y=0;while(this._accumulatorMs>=this._fixedTimestepMs&&Y<aQ6)this._tick(this._fixedTimestepMs),this._accumulatorMs-=this._fixedTimestepMs,Y++;this._nextTickMs=Math.max(0,this._fixedTimestepMs-this._accumulatorMs)});this._tickHandle=setTimeout(Z,this._nextTickMs)};Z()}stop(){if(!this._tickHandle)return;clearTimeout(this._tickHandle),this._tickHandle=null}_tick(Z){try{this._tickFunction(Z)}catch(J){if(J instanceof Error&&this._tickErrorCallback)this._tickErrorCallback(J);else c.warning(`Ticker._tick(): tick callback threw an error, but it was not an instance of Error. Error: ${J}`)}}}var E31;((Q)=>{Q.START="WORLD_LOOP.START";Q.STOP="WORLD_LOOP.STOP";Q.TICK_START="WORLD_LOOP.TICK_START";Q.TICK_END="WORLD_LOOP.TICK_END";Q.TICK_ERROR="WORLD_LOOP.TICK_ERROR"})(E31||={});class LU extends M0{_currentTick=0;_ticker;_world;constructor(Z,J=Nm){super();this._ticker=new UU(J,this._tick,this._onTickError),this._world=Z}get currentTick(){return this._currentTick}get isStarted(){return this._ticker.isStarted}get nextTickMs(){return this._ticker.nextTickMs}get timestepS(){return this._ticker.fixedTimestepS}get world(){return this._world}start(){this._ticker.start(),this.emitWithWorld(this._world,"WORLD_LOOP.START",{worldLoop:this})}stop(){this._ticker.stop(),this.emitWithWorld(this._world,"WORLD_LOOP.STOP",{worldLoop:this})}_tick=(Z)=>{this.emitWithWorld(this._world,"WORLD_LOOP.TICK_START",{worldLoop:this,tickDeltaMs:Z});let J=performance.now();t1.startSpan({operation:"world_tick",attributes:{serverPlayerCount:U9.instance.playerCount,targetTickRate:this._ticker.targetTicksPerSecond,targetTickRateMs:this._ticker.fixedTimestepMs,worldId:this._world.id,worldName:this._world.name,worldChunkCount:this._world.chunkLattice.chunkCount,worldEntityCount:this._world.entityManager.entityCount,worldLoopTick:this._currentTick}},()=>{t1.startSpan({operation:"entities_tick"},()=>this._world.entityManager.tickEntities(Z)),t1.startSpan({operation:"simulation_step"},()=>this._world.simulation.step(Z)),t1.startSpan({operation:"entities_emit_updates"},()=>this._world.entityManager.checkAndEmitUpdates()),t1.startSpan({operation:"network_synchronize"},()=>this._world.networkSynchronizer.synchronize()),t1.startSpan({operation:"release_tick_allocation"},()=>this._world.tickAllocator.reset())}),this._currentTick++,this.emitWithWorld(this._world,"WORLD_LOOP.TICK_END",{worldLoop:this,tickDurationMs:performance.now()-J})};_onTickError=(Z)=>{c.error(`WorldLoop._onTickError(): Error: ${Z}`),this.emitWithWorld(this._world,"WORLD_LOOP.TICK_ERROR",{worldLoop:this,error:Z})}}var Dm;((F)=>{F.SET_AMBIENT_LIGHT_COLOR="WORLD.SET_AMBIENT_LIGHT_COLOR";F.SET_AMBIENT_LIGHT_INTENSITY="WORLD.SET_AMBIENT_LIGHT_INTENSITY";F.SET_DIRECTIONAL_LIGHT_COLOR="WORLD.SET_DIRECTIONAL_LIGHT_COLOR";F.SET_DIRECTIONAL_LIGHT_INTENSITY="WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY";F.SET_DIRECTIONAL_LIGHT_POSITION="WORLD.SET_DIRECTIONAL_LIGHT_POSITION";F.SET_FOG_COLOR="WORLD.SET_FOG_COLOR";F.SET_FOG_FAR="WORLD.SET_FOG_FAR";F.SET_FOG_NEAR="WORLD.SET_FOG_NEAR";F.SET_SKYBOX_INTENSITY="WORLD.SET_SKYBOX_INTENSITY";F.START="WORLD.START";F.STOP="WORLD.STOP"})(Dm||={});class BU extends M0{_id;_ambientLightColor;_ambientLightIntensity;_audioManager;_blockTypeRegistry;_chatManager;_chunkLattice;_directionalLightColor;_directionalLightIntensity;_directionalLightPosition;_entityManager;_fogColor;_fogFar;_fogNear;_lightManager;_loop;_name;_networkSynchronizer;_particleEmitterManager;_sceneUIManager;_simulation;_skyboxIntensity;_skyboxUri;_tag;_tickAllocator;constructor(Z){super();if(this._id=Z.id,this._ambientLightColor=Z.ambientLightColor??{r:255,g:255,b:255},this._ambientLightIntensity=Z.ambientLightIntensity??1,this._directionalLightColor=Z.directionalLightColor??{r:255,g:255,b:255},this._directionalLightIntensity=Z.directionalLightIntensity??3,this._directionalLightPosition=Z.directionalLightPosition??{x:100,y:150,z:100},this._fogColor=Z.fogColor,this._fogFar=Z.fogFar??550,this._fogNear=Z.fogNear??500,this._name=Z.name,this._skyboxIntensity=Z.skyboxIntensity??1,this._skyboxUri=Z.skyboxUri,this._tag=Z.tag,this._audioManager=new P3(this),this._blockTypeRegistry=new OH(this),this._chatManager=new aH(this),this._chunkLattice=new sH(this),this._entityManager=new eH(this),this._lightManager=new GU(this),this._loop=new LU(this,Z.tickRate),this._networkSynchronizer=new WD(this),this._particleEmitterManager=new zU(this),this._sceneUIManager=new FU(this),this._simulation=new HU(this,Z.tickRate,Z.gravity),this._tickAllocator=new qU,Z.map)this.loadMap(Z.map)}get id(){return this._id}get ambientLightColor(){return this._ambientLightColor}get ambientLightIntensity(){return this._ambientLightIntensity}get blockTypeRegistry(){return this._blockTypeRegistry}get chatManager(){return this._chatManager}get chunkLattice(){return this._chunkLattice}get directionalLightColor(){return this._directionalLightColor}get directionalLightIntensity(){return this._directionalLightIntensity}get directionalLightPosition(){return this._directionalLightPosition}get entityManager(){return this._entityManager}get fogColor(){return this._fogColor}get fogFar(){return this._fogFar}get fogNear(){return this._fogNear}get lightManager(){return this._lightManager}get loop(){return this._loop}get name(){return this._name}get networkSynchronizer(){return this._networkSynchronizer}get particleEmitterManager(){return this._particleEmitterManager}get sceneUIManager(){return this._sceneUIManager}get simulation(){return this._simulation}get skyboxIntensity(){return this._skyboxIntensity}get skyboxUri(){return this._skyboxUri}get audioManager(){return this._audioManager}get tag(){return this._tag}get tickAllocator(){return this._tickAllocator}loadMap(Z){if(this.chunkLattice.clear(),Z.blockTypes)for(let J of Z.blockTypes)this.blockTypeRegistry.registerGenericBlockType({id:J.id,isLiquid:J.isLiquid,name:J.name,textureUri:J.textureUri});if(Z.blocks)for(let[J,X]of Object.entries(Z.blocks)){let[Y,$,Q]=J.split(",").map(Number);this.chunkLattice.setBlock({x:Y,y:$,z:Q},X)}if(Z.entities)for(let[J,X]of Object.entries(Z.entities)){let[Y,$,Q]=J.split(",").map(Number);new n8({isEnvironmental:!0,...X}).spawn(this,{x:Y,y:$,z:Q})}}setAmbientLightColor(Z){this._ambientLightColor=Z,this.emit("WORLD.SET_AMBIENT_LIGHT_COLOR",{world:this,color:Z})}setAmbientLightIntensity(Z){this._ambientLightIntensity=Z,this.emit("WORLD.SET_AMBIENT_LIGHT_INTENSITY",{world:this,intensity:Z})}setDirectionalLightColor(Z){this._directionalLightColor=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",{world:this,color:Z})}setDirectionalLightIntensity(Z){this._directionalLightIntensity=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",{world:this,intensity:Z})}setDirectionalLightPosition(Z){this._directionalLightPosition=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",{world:this,position:Z})}setFogColor(Z){this._fogColor=Z,this.emit("WORLD.SET_FOG_COLOR",{world:this,color:Z})}setFogFar(Z){this._fogFar=Z,this.emit("WORLD.SET_FOG_FAR",{world:this,far:Z})}setFogNear(Z){this._fogNear=Z,this.emit("WORLD.SET_FOG_NEAR",{world:this,near:Z})}setSkyboxIntensity(Z){this._skyboxIntensity=Z,this.emit("WORLD.SET_SKYBOX_INTENSITY",{world:this,intensity:Z})}start(){if(this._loop.isStarted)return;this._loop.start(),this.emit("WORLD.START",{world:this,startedAtMs:Date.now()})}stop(){if(!this._loop.isStarted)return;this._loop.stop(),this.emit("WORLD.STOP",{world:this,stoppedAtMs:Date.now()})}serialize(){return D0.serializeWorld(this,this._tickAllocator)}}var I31;((J)=>J.WORLD_CREATED="WORLD_MANAGER.WORLD_CREATED")(I31||={});class IY{static instance=new IY;_defaultWorld;_nextWorldId=1;_worlds=new Map;createWorld(Z){let J=new BU({...Z,id:this._nextWorldId++});return J.start(),this._worlds.set(J.id,J),M0.globalInstance.emit("WORLD_MANAGER.WORLD_CREATED",{world:J}),J}getAllWorlds(){return Array.from(this._worlds.values())}getDefaultWorld(){return this._defaultWorld??=this.createWorld({name:"Default World",skyboxUri:"skyboxes/partly-cloudy"}),this._defaultWorld}getWorldsByTag(Z){let J=[];return this._worlds.forEach((X)=>{if(X.tag===Z)J.push(X)}),J}getWorld(Z){return this._worlds.get(Z)}setDefaultWorld(Z){this._defaultWorld=Z}}var k31;((Y)=>{Y.PLAYER_CONNECTED="PLAYER_MANAGER.PLAYER_CONNECTED";Y.PLAYER_DISCONNECTED="PLAYER_MANAGER.PLAYER_DISCONNECTED";Y.PLAYER_RECONNECTED="PLAYER_MANAGER.PLAYER_RECONNECTED"})(k31||={});class U9{static instance=new U9;worldSelectionHandler;_connectionPlayers=new Map;constructor(){M0.globalInstance.on("CONNECTION.OPENED",({connection:Z,req:J})=>{this._onConnectionOpened(Z,J.session)}),M0.globalInstance.on("CONNECTION.DISCONNECTED",({connection:Z})=>{this._onConnectionDisconnected(Z)}),M0.globalInstance.on("CONNECTION.RECONNECTED",({connection:Z})=>{this._onConnectionReconnected(Z)}),M0.globalInstance.on("CONNECTION.CLOSED",({connection:Z})=>{this._onConnectionClosed(Z)})}get playerCount(){return this._connectionPlayers.size}getConnectedPlayers(){return Array.from(this._connectionPlayers.values())}getConnectedPlayersByWorld(Z){return this.getConnectedPlayers().filter((J)=>J.world===Z)}getConnectedPlayerByUsername(Z){return Array.from(this._connectionPlayers.values()).find((J)=>{return J.username.toLowerCase()===Z.toLowerCase()})}async _onConnectionOpened(Z,J){let X=new CW(Z,J);await X.loadInitialPersistedData(),this._connectionPlayers.set(Z,X),M0.globalInstance.emit("PLAYER_MANAGER.PLAYER_CONNECTED",{player:X});let Y=await this.worldSelectionHandler?.(X);X.joinWorld(Y??IY.instance.getDefaultWorld())}_onConnectionDisconnected(Z){let J=this._connectionPlayers.get(Z);if(J)J.resetInputs(),J.camera.reset()}_onConnectionReconnected(Z){let J=this._connectionPlayers.get(Z);if(J)J.reconnected(),M0.globalInstance.emit("PLAYER_MANAGER.PLAYER_RECONNECTED",{player:J});else c.warning(`PlayerManager._onConnectionReconnected(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}_onConnectionClosed(Z){let J=this._connectionPlayers.get(Z);if(J)J.disconnect(),this._connectionPlayers.delete(Z),M0.globalInstance.emit("PLAYER_MANAGER.PLAYER_DISCONNECTED",{player:J});else c.warning(`PlayerManager._onConnectionClosed(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}}Buffer.poolSize=134217728;var v31;((X)=>{X.START="GAMESERVER.START";X.STOP="GAMESERVER.STOP"})(v31||={});function oQ6(Z){_31.default.init().then(()=>{return $K.instance.modelRegistry.preloadModels()}).then(()=>{if(Z.length>0)Z($K.instance.worldManager.getDefaultWorld());else Z();$K.instance.start()}).catch((J)=>{c.fatalError(`Failed to initialize the game engine, exiting. Error: ${J}`)})}class $K{static _instance;_modelRegistry=S5.instance;_playerManager=U9.instance;_socket=s7.instance;_worldManager=IY.instance;_webServer=FG.instance;constructor(){}static get instance(){if(!this._instance)this._instance=new $K;return this._instance}get modelRegistry(){return this._modelRegistry}get playerManager(){return this._playerManager}get socket(){return this._socket}get webServer(){return this._webServer}get worldManager(){return this._worldManager}start(){M0.globalInstance.emit("GAMESERVER.START",{startedAtMs:performance.now()}),this._webServer.start()}}var q6=r(WK(),1);class GK extends Float32Array{constructor(Z,J,X,Y){super([Z,J,X,Y])}get determinant(){return q6.mat2.determinant(this)}get frobeniusNorm(){return q6.mat2.frob(this)}static create(){let Z=new GK(0,0,0,0);return q6.mat2.identity(Z),Z}static fromRotation(Z){let J=GK.create();return q6.mat2.fromRotation(J,Z),J}static fromScaling(Z){let J=GK.create();return q6.mat2.fromScaling(J,Z),J}add(Z){return q6.mat2.add(this,this,Z),this}adjoint(){return q6.mat2.adjoint(this,this),this}clone(){return new GK(this[0],this[1],this[2],this[3])}copy(Z){return q6.mat2.copy(this,Z),this}equals(Z){return q6.mat2.equals(this,Z)}exactEquals(Z){return q6.mat2.exactEquals(this,Z)}identity(){return q6.mat2.identity(this),this}invert(){return q6.mat2.invert(this,this),this}multiply(Z){return q6.mat2.mul(this,this,Z),this}multiplyScalar(Z){return q6.mat2.multiplyScalar(this,this,Z),this}rotate(Z){return q6.mat2.rotate(this,this,Z),this}subtract(Z){return q6.mat2.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]}][${this[2]},${this[3]}]`}transpose(){return q6.mat2.transpose(this,this),this}}var j8=r(WK(),1);class LZ extends Float32Array{constructor(Z,J,X,Y,$,Q,K,W,G){super([Z,J,X,Y,$,Q,K,W,G])}get determinant(){return j8.mat3.determinant(this)}get frobeniusNorm(){return j8.mat3.frob(this)}static create(){let Z=new LZ(0,0,0,0,0,0,0,0,0);return j8.mat3.identity(Z),Z}static fromMatrix4(Z){let J=LZ.create();return j8.mat3.fromMat4(J,Z),J}static fromQuaternion(Z){let J=LZ.create();return j8.mat3.fromQuat(J,Z),J}static fromRotation(Z){let J=LZ.create();return j8.mat3.fromRotation(J,Z),J}static fromScaling(Z){let J=LZ.create();return j8.mat3.fromScaling(J,Z),J}static fromTranslation(Z){let J=LZ.create();return j8.mat3.fromTranslation(J,Z),J}add(Z){return j8.mat3.add(this,this,Z),this}adjoint(){return j8.mat3.adjoint(this,this),this}clone(){return new LZ(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8])}copy(Z){return j8.mat3.copy(this,Z),this}equals(Z){return j8.mat3.equals(this,Z)}exactEquals(Z){return j8.mat3.exactEquals(this,Z)}identity(){return j8.mat3.identity(this),this}invert(){return j8.mat3.invert(this,this),this}multiply(Z){return j8.mat3.mul(this,this,Z),this}multiplyScalar(Z){return j8.mat3.multiplyScalar(this,this,Z),this}transformVector(Z){return Z.transformMatrix3(this)}projection(Z,J){return j8.mat3.projection(this,Z,J),this}rotate(Z){return j8.mat3.rotate(this,this,Z),this}subtract(Z){return j8.mat3.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]},${this[2]}][${this[3]},${this[4]},${this[5]}][${this[6]},${this[7]},${this[8]}]`}transpose(){return j8.mat3.transpose(this,this),this}}var Y1=r(WK(),1);class P5 extends Float32Array{constructor(Z,J,X,Y,$,Q,K,W,G,V,H,F,z,q,U,B){super([Z,J,X,Y,$,Q,K,W,G,V,H,F,z,q,U,B])}get determinant(){return Y1.mat4.determinant(this)}get frobeniusNorm(){return Y1.mat4.frob(this)}static create(){let Z=new P5(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return Y1.mat4.identity(Z),Z}static fromQuaternion(Z){let J=P5.create();return Y1.mat4.fromQuat(J,Z),J}static fromRotation(Z,J){let X=P5.create();return Y1.mat4.fromRotation(X,Z,J),X}static fromRotationTranslation(Z,J){let X=P5.create();return Y1.mat4.fromRotationTranslation(X,Z,J),X}static fromRotationTranslationScale(Z,J,X){let Y=P5.create();return Y1.mat4.fromRotationTranslationScale(Y,Z,J,X),Y}static fromRotationTranslationScaleOrigin(Z,J,X,Y){let $=P5.create();return Y1.mat4.fromRotationTranslationScaleOrigin($,Z,J,X,Y),$}static fromScaling(Z){let J=P5.create();return Y1.mat4.fromScaling(J,Z),J}static fromTranslation(Z){let J=P5.create();return Y1.mat4.fromTranslation(J,Z),J}static fromXRotation(Z){let J=P5.create();return Y1.mat4.fromXRotation(J,Z),J}static fromYRotation(Z){let J=P5.create();return Y1.mat4.fromYRotation(J,Z),J}static fromZRotation(Z){let J=P5.create();return Y1.mat4.fromZRotation(J,Z),J}add(Z){return Y1.mat4.add(this,this,Z),this}adjoint(){return Y1.mat4.adjoint(this,this),this}clone(){return new P5(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8],this[9],this[10],this[11],this[12],this[13],this[14],this[15])}copy(Z){return Y1.mat4.copy(this,Z),this}equals(Z){return Y1.mat4.equals(this,Z)}exactEquals(Z){return Y1.mat4.exactEquals(this,Z)}frustrum(Z,J,X,Y,$,Q){return Y1.mat4.frustum(this,Z,J,X,Y,$,Q),this}identity(){return Y1.mat4.identity(this),this}invert(){return Y1.mat4.invert(this,this),this}lookAt(Z,J,X){return Y1.mat4.lookAt(this,Z,J,X),this}multiply(Z){return Y1.mat4.mul(this,this,Z),this}multiplyScalar(Z){return Y1.mat4.multiplyScalar(this,this,Z),this}orthographic(Z,J,X,Y,$,Q){return Y1.mat4.ortho(this,Z,J,X,Y,$,Q),this}perspective(Z,J,X,Y){return Y1.mat4.perspective(this,Z,J,X,Y),this}rotate(Z,J){return Y1.mat4.rotate(this,this,Z,J),this}rotateX(Z){return Y1.mat4.rotateX(this,this,Z),this}rotateY(Z){return Y1.mat4.rotateY(this,this,Z),this}rotateZ(Z){return Y1.mat4.rotateZ(this,this,Z),this}scale(Z){return Y1.mat4.scale(this,this,Z),this}subtract(Z){return Y1.mat4.sub(this,this,Z),this}targetTo(Z,J,X){return Y1.mat4.targetTo(this,Z,J,X),this}toString(){return`[${this[0]},${this[1]},${this[2]},${this[3]}][${this[4]},${this[5]},${this[6]},${this[7]}][${this[8]},${this[9]},${this[10]},${this[11]}][${this[12]},${this[13]},${this[14]},${this[15]}]`}translate(Z){return Y1.mat4.translate(this,this,Z),this}transpose(){return Y1.mat4.transpose(this,this),this}}var y1=r(WK(),1);class R3 extends Float32Array{constructor(Z,J,X,Y){super([Z,J,X,Y])}get length(){return y1.quat.length(this)}get squaredLength(){return y1.quat.squaredLength(this)}get magnitude(){return y1.quat.length(this)}get squaredMagnitude(){return y1.quat.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}get z(){return this[2]}set z(Z){this[2]=Z}get w(){return this[3]}set w(Z){this[3]=Z}static fromEuler(Z,J,X){let Y=y1.quat.fromEuler(new Float32Array(4),Z,J,X);return new R3(Y[0],Y[1],Y[2],Y[3])}static fromQuaternionLike(Z){return new R3(Z.x,Z.y,Z.z,Z.w)}clone(){return new R3(this.x,this.y,this.z,this.w)}conjugate(){return y1.quat.conjugate(this,this),this}copy(Z){return y1.quat.copy(this,Z),this}dot(Z){return y1.quat.dot(this,Z)}exponential(){return y1.quat.exp(this,this),this}equals(Z){return y1.quat.equals(this,Z)}exactEquals(Z){return y1.quat.exactEquals(this,Z)}getAngle(Z){return y1.quat.getAngle(this,Z)}identity(){return y1.quat.identity(this),this}invert(){return y1.quat.invert(this,this),this}lerp(Z,J){return y1.quat.lerp(this,this,Z,J),this}logarithm(){return y1.quat.ln(this,this),this}multiply(Z){return y1.quat.multiply(this,this,Z),this}transformVector(Z){return Z.transformQuaternion(this)}normalize(){return y1.quat.normalize(this,this),this}power(Z){return y1.quat.pow(this,this,Z),this}randomize(){return y1.quat.random(this),this}rotateX(Z){return y1.quat.rotateX(this,this,Z),this}rotateY(Z){return y1.quat.rotateY(this,this,Z),this}rotateZ(Z){return y1.quat.rotateZ(this,this,Z),this}scale(Z){return y1.quat.scale(this,this,Z),this}setAxisAngle(Z,J){return y1.quat.setAxisAngle(this,Z,J),this}slerp(Z,J){return y1.quat.slerp(this,this,Z,J),this}toString(){return`${this.x},${this.y},${this.z},${this.w}`}}var U1=r(WK(),1);class wU extends Float32Array{constructor(Z,J){super([Z,J])}get length(){return U1.vec2.length(this)}get squaredLength(){return U1.vec2.squaredLength(this)}get magnitude(){return U1.vec2.length(this)}get squaredMagnitude(){return U1.vec2.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}static create(){return new wU(0,0)}add(Z){return U1.vec2.add(this,this,Z),this}angle(Z){return U1.vec2.angle(this,Z)}ceil(){return U1.vec2.ceil(this,this),this}clone(){return new wU(this.x,this.y)}copy(Z){return U1.vec2.copy(this,Z),this}distance(Z){return U1.vec2.distance(this,Z)}divide(Z){return U1.vec2.divide(this,this,Z),this}dot(Z){return U1.vec2.dot(this,Z)}equals(Z){return U1.vec2.equals(this,Z)}exactEquals(Z){return U1.vec2.exactEquals(this,Z)}floor(){return U1.vec2.floor(this,this),this}invert(){return U1.vec2.inverse(this,this),this}lerp(Z,J){return U1.vec2.lerp(this,this,Z,J),this}max(Z){return U1.vec2.max(this,this,Z),this}min(Z){return U1.vec2.min(this,this,Z),this}multiply(Z){return U1.vec2.mul(this,this,Z),this}negate(){return U1.vec2.negate(this,this),this}normalize(){return U1.vec2.normalize(this,this),this}randomize(Z){return U1.vec2.random(this,Z),this}rotate(Z,J){return U1.vec2.rotate(this,this,Z,J),this}round(){return U1.vec2.round(this,this),this}scale(Z){return U1.vec2.scale(this,this,Z),this}scaleAndAdd(Z,J){return U1.vec2.scaleAndAdd(this,this,Z,J),this}subtract(Z){return U1.vec2.sub(this,this,Z),this}toString(){return`${this.x},${this.y}`}transformMatrix2(Z){return U1.vec2.transformMat2(this,this,Z),this}transformMatrix3(Z){return U1.vec2.transformMat3(this,this,Z),this}transformMatrix4(Z){return U1.vec2.transformMat4(this,this,Z),this}zero(){return U1.vec2.zero(this),this}}var z1=r(WK(),1);class N3 extends Float32Array{constructor(Z,J,X){super([Z,J,X])}get length(){return z1.vec3.length(this)}get squaredLength(){return z1.vec3.squaredLength(this)}get magnitude(){return z1.vec3.length(this)}get squaredMagnitude(){return z1.vec3.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}get z(){return this[2]}set z(Z){this[2]=Z}static create(){return new N3(0,0,0)}static fromVector3Like(Z){return new N3(Z.x,Z.y,Z.z)}add(Z){return z1.vec3.add(this,this,Z),this}ceil(){return z1.vec3.ceil(this,this),this}clone(){return new N3(this.x,this.y,this.z)}copy(Z){return z1.vec3.copy(this,Z),this}cross(Z){return z1.vec3.cross(this,this,Z),this}distance(Z){return z1.vec3.distance(this,Z)}divide(Z){return z1.vec3.div(this,this,Z),this}dot(Z){return z1.vec3.dot(this,Z)}equals(Z){return z1.vec3.equals(this,Z)}exactEquals(Z){return z1.vec3.exactEquals(this,Z)}floor(){return z1.vec3.floor(this,this),this}invert(){return z1.vec3.inverse(this,this),this}lerp(Z,J){return z1.vec3.lerp(this,this,Z,J),this}max(Z){return z1.vec3.max(this,this,Z),this}min(Z){return z1.vec3.min(this,this,Z),this}multiply(Z){return z1.vec3.mul(this,this,Z),this}negate(){return z1.vec3.negate(this,this),this}normalize(){return z1.vec3.normalize(this,this),this}randomize(Z){return z1.vec3.random(this,Z),this}rotateX(Z,J){return z1.vec3.rotateX(this,this,Z,J),this}rotateY(Z,J){return z1.vec3.rotateY(this,this,Z,J),this}rotateZ(Z,J){return z1.vec3.rotateZ(this,this,Z,J),this}round(){return z1.vec3.round(this,this),this}scale(Z){return z1.vec3.scale(this,this,Z),this}scaleAndAdd(Z,J){return z1.vec3.scaleAndAdd(this,this,Z,J),this}subtract(Z){return z1.vec3.sub(this,this,Z),this}toString(){return`${this.x},${this.y},${this.z}`}transformMatrix3(Z){return z1.vec3.transformMat3(this,this,Z),this}transformMatrix4(Z){return z1.vec3.transformMat4(this,this,Z),this}transformQuaternion(Z){return z1.vec3.transformQuat(this,this,Z),this}zero(){return z1.vec3.zero(this),this}}var MH1=r(wH1(),1);var OH1=0.099856;class OU extends vY{faceSpeed=0;idleLoopedAnimations=[];idleLoopedAnimationsSpeed;jumpOneshotAnimations=[];moveLoopedAnimations=[];moveLoopedAnimationsSpeed;moveSpeed=0;_faceTarget;_jumpHeight=0;_moveCompletesWhenStuck=!1;_moveIgnoreAxes={};_moveStartMoveAnimations=!1;_moveStartIdleAnimationsOnCompletion=!0;_moveStoppingDistanceSquared=OH1;_moveStuckAccumulatorMs=0;_moveStuckLastPosition;_moveTarget;_onFace;_onFaceComplete;_onMove;_onMoveComplete;_stopFaceRequested=!1;_stopMoveRequested=!1;constructor(Z={}){super();this.idleLoopedAnimations=Z.idleLoopedAnimations??this.idleLoopedAnimations,this.idleLoopedAnimationsSpeed=Z.idleLoopedAnimationsSpeed??this.idleLoopedAnimationsSpeed,this.jumpOneshotAnimations=Z.jumpOneshotAnimations??this.jumpOneshotAnimations,this.moveLoopedAnimations=Z.moveLoopedAnimations??this.moveLoopedAnimations,this.moveLoopedAnimationsSpeed=Z.moveLoopedAnimationsSpeed??this.moveLoopedAnimationsSpeed}spawn(Z){super.spawn(Z),this._startIdleAnimations(Z)}face(Z,J,X){this._faceTarget=Z,this.faceSpeed=J,this._onFace=X?.faceCallback,this._onFaceComplete=X?.faceCompleteCallback}jump(Z){this._jumpHeight=Z}move(Z,J,X){this.moveSpeed=J,this._moveCompletesWhenStuck=X?.moveCompletesWhenStuck??!1,this._moveIgnoreAxes=X?.moveIgnoreAxes??{},this._moveStartIdleAnimationsOnCompletion=X?.moveStartIdleAnimationsOnCompletion??!0,this._moveStartMoveAnimations=!0,this._moveStoppingDistanceSquared=X?.moveStoppingDistance?X.moveStoppingDistance**2:OH1,this._moveTarget=Z,this._onMove=X?.moveCallback,this._onMoveComplete=X?.moveCompleteCallback,this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0}stopFace(){this._stopFaceRequested=!0}stopMove(){this._stopMoveRequested=!0}tick(Z,J){if(super.tick(Z,J),!this._moveTarget&&!this._faceTarget&&!this._jumpHeight)return;if(this._moveStartMoveAnimations)this._startMoveAnimations(Z),this._moveStartMoveAnimations=!1;let X=J/1000,Y=Z.position;if(Z.isDynamic&&this._jumpHeight>0){let $=Math.abs(Z.world.simulation.gravity.y),Q=Math.sqrt(2*$*this._jumpHeight);Z.applyImpulse({x:0,y:Q*Z.mass,z:0}),this._jumpHeight=0,this._startJumpAnimations(Z)}if(this._moveTarget){let $={x:this._moveIgnoreAxes.x?0:this._moveTarget.x-Y.x,y:this._moveIgnoreAxes.y?0:this._moveTarget.y-Y.y,z:this._moveIgnoreAxes.z?0:this._moveTarget.z-Y.z},Q=$.x*$.x+$.y*$.y+$.z*$.z,K=!1;if(this._moveCompletesWhenStuck){if(this._moveStuckAccumulatorMs+=J,this._moveStuckAccumulatorMs>=500){if(this._moveStuckLastPosition){let W=Y.x-this._moveStuckLastPosition.x,G=Y.y-this._moveStuckLastPosition.y,V=Y.z-this._moveStuckLastPosition.z;K=Math.sqrt(W*W+G*G+V*V)<this.moveSpeed*0.1}this._moveStuckLastPosition=Y,this._moveStuckAccumulatorMs=0}}if(Q>this._moveStoppingDistanceSquared&&!this._stopMoveRequested&&!K){let W=Math.sqrt(Q),G=this.moveSpeed*X,H=Math.min(W,G)/W,F={x:Y.x+$.x*H,y:Y.y+$.y*H,z:Y.z+$.z*H};if(Z.setPosition(F),this._onMove)this._onMove(F,this._moveTarget)}else{if(this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0,this._moveTarget=void 0,this._stopMoveRequested=!1,this._moveStartIdleAnimationsOnCompletion)this._startIdleAnimations(Z);if(this._onMoveComplete){let W=this._onMoveComplete;this._onMove=void 0,this._onMoveComplete=void 0,W(Y)}}}if(this._faceTarget){let $={x:this._faceTarget.x-Y.x,z:this._faceTarget.z-Y.z},Q=Math.atan2(-$.x,-$.z),K=Z.rotation,W=Math.atan2(2*(K.w*K.y),1-2*(K.y*K.y)),G=Q-W;while(G>Math.PI)G-=2*Math.PI;while(G<-Math.PI)G+=2*Math.PI;if(Math.abs(G)>0.01&&!this._stopFaceRequested){let V=this.faceSpeed*X,H=Math.abs(G)<V?G:Math.sign(G)*V,z=(W+H)/2,q={x:0,y:Math.fround(Math.sin(z)),z:0,w:Math.fround(Math.cos(z))};if(Z.setRotation(q),this._onFace)this._onFace(K,q)}else if(this._faceTarget=void 0,this._stopFaceRequested=!1,this._onFaceComplete){let V=this._onFaceComplete;this._onFace=void 0,this._onFaceComplete=void 0,V(Z.rotation)}}}_startIdleAnimations(Z){if(this.idleLoopedAnimationsSpeed)Z.setModelAnimationsPlaybackRate(this.idleLoopedAnimationsSpeed);Z.stopModelAnimations(this.moveLoopedAnimations),Z.stopModelAnimations(this.jumpOneshotAnimations),Z.startModelLoopedAnimations(this.idleLoopedAnimations)}_startJumpAnimations(Z){Z.stopModelAnimations(this.moveLoopedAnimations),Z.stopModelAnimations(this.idleLoopedAnimations),Z.startModelOneshotAnimations(this.jumpOneshotAnimations)}_startMoveAnimations(Z){if(this.moveLoopedAnimationsSpeed)Z.setModelAnimationsPlaybackRate(this.moveLoopedAnimationsSpeed);Z.stopModelAnimations(this.jumpOneshotAnimations),Z.stopModelAnimations(this.idleLoopedAnimations),Z.startModelLoopedAnimations(this.moveLoopedAnimations)}}class Sm extends OU{_debug=!1;_entity;_maxFall=0;_maxJump=0;_maxOpenSetIterations=200;_onPathfindAbort;_onPathfindComplete;_onWaypointMoveComplete;_onWaypointMoveSkipped;_speed=0;_target;_verticalPenalty=0;_waypoints=[];_waypointNextIndex=0;_waypointStoppingDistance;_waypointTimeoutMs=2000;constructor(Z={}){super(Z)}get debug(){return this._debug}get maxFall(){return this._maxFall}get maxJump(){return this._maxJump}get maxOpenSetIterations(){return this._maxOpenSetIterations}get speed(){return this._speed}get target(){return this._target}get verticalPenalty(){return this._verticalPenalty}get waypoints(){return this._waypoints}get waypointNextIndex(){return this._waypointNextIndex}get waypointTimeoutMs(){return this._waypointTimeoutMs}pathfind(Z,J,X){if(this._target=Z,this._speed=J,this._debug=X?.debug??!1,this._maxFall=X?.maxFall?-Math.abs(X.maxFall):0,this._maxJump=X?.maxJump?Math.abs(X.maxJump):0,this._maxOpenSetIterations=X?.maxOpenSetIterations??200,this._onPathfindAbort=X?.pathfindAbortCallback,this._onPathfindComplete=X?.pathfindCompleteCallback,this._onWaypointMoveComplete=X?.waypointMoveCompleteCallback,this._onWaypointMoveSkipped=X?.waypointMoveSkippedCallback,this._verticalPenalty=X?.verticalPenalty??0,this._waypoints=[],this._waypointNextIndex=0,this._waypointStoppingDistance=X?.waypointStoppingDistance,this._waypointTimeoutMs=X?.waypointTimeoutMs??2000/J,!this._calculatePath())return!1;return this._moveToNextWaypoint(),!0}attach(Z){super.attach(Z),this._entity=Z}detach(Z){super.detach(Z),this._entity=void 0}_calculatePath(){if(!this._target||!this._entity?.world)return c.error("PathfindingEntityController._calculatePath: No target or world"),!1;let Z=this._entity.height,J=this._findGroundedStart();if(!J){if(this._debug)c.warning(`PathfindingEntityController._calculatePath: No valid grounded start found within maxFall distance, path search aborted. Start: ${this._coordinateToKey(this._target)}, Target: ${this._coordinateToKey(this._target)}`);return!1}let X={x:Math.floor(this._target.x),y:Math.floor(this._target.y),z:Math.floor(this._target.z)},Y=Math.abs(X.x-J.x),$=Math.abs(X.y-J.y),Q=Math.abs(X.z-J.z);if(Y<=2&&$<=2&&Q<=2&&!this._isNeighborCoordinateBlocked(J,X,this._entity.height))return this._waypoints=[{x:J.x+0.5,y:J.y+Z/2,z:J.z+0.5},{x:X.x+0.5,y:X.y+Z/2,z:X.z+0.5}],!0;if(J.x===X.x&&J.y===X.y&&J.z===X.z)return this._waypoints=[{x:J.x+0.5,y:J.y+Z/2,z:J.z+0.5}],!0;let W=this._coordinateToKey(J),G=new Map,V=new Map([[W,0]]),H=new Map([[W,this._pathfindingHeuristic(J,X)]]),F=new Set,z=new MH1.Heap((R,N)=>{let P=H.get(R[0])??1/0,D=H.get(N[0])??1/0;return P-D});z.push([W,J]);let q=[{x:0,y:0,z:1},{x:1,y:0,z:0},{x:0,y:0,z:-1},{x:-1,y:0,z:0},{x:1,y:0,z:1},{x:1,y:0,z:-1},{x:-1,y:0,z:1},{x:-1,y:0,z:-1}],U=[];for(let R=this._maxJump;R>=this._maxFall;R--){if(R===0)continue;let N=Math.abs(J.y+R-X.y);U.push({y:R,distanceToTargetY:N})}U.sort((R,N)=>R.distanceToTargetY-N.distanceToTargetY);let B=[...q,...U.flatMap(({y:R})=>q.map((N)=>({...N,y:R})))],L=0,w=Math.abs(X.x-J.x)+Math.abs(X.y-J.y)+Math.abs(X.z-J.z),M=Math.min(this._maxOpenSetIterations,w*20);while(!z.isEmpty()&&L<M){L++;let[R,N]=z.pop();if(N.x===X.x&&N.y===X.y&&N.z===X.z){let C=this._reconstructPath(G,N);if(this._waypoints=C.map((T)=>({x:T.x+0.5,y:T.y+Z/2,z:T.z+0.5})),this._debug)console.log(`PathfindingEntityController._calculatePath: Path found after ${L} open set iterations. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`);return!0}F.add(R);let P=V.get(R),D=new Map;for(let C of B){let T=`${C.x},${C.z}`,E=C.y<0;if(E&&D.has(T))continue;let A={x:N.x+C.x,y:N.y+C.y,z:N.z+C.z};if(Math.abs(X.x-A.x)+Math.abs(X.y-A.y)+Math.abs(X.z-A.z)>w*1.5)continue;let x=this._coordinateToKey(A);if(F.has(x))continue;let k=this._isNeighborCoordinateBlocked(N,A,this._entity.height);if(E&&k){D.set(T,!0);continue}if(k)continue;let _=Math.abs(C.x),y=Math.abs(C.y),u=Math.abs(C.z),n=y===0?0:this._verticalPenalty,o=(Math.max(_,y,u)===1&&_+y+u>1?1.4:1)+n,Q0=P+o,W0=V.get(x)??1/0;if(Q0>=W0)continue;G.set(x,N),V.set(x,Q0);let v0=Q0+this._pathfindingHeuristic(A,X);H.set(x,v0),z.push([x,A])}}if(L>=M){if(this._onPathfindAbort?.(),this._debug)c.warning(`PathfindingEntityController._calculatePath: Maximum open set iterations reached (${M}), path search aborted. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`)}else if(this._debug)c.warning(`PathfindingEntityController._calculatePath: No valid path found. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`);return this._target=void 0,this._waypoints=[],!1}_reconstructPath(Z,J){let X=[J],Y=J;while(Z.has(this._coordinateToKey(Y)))Y=Z.get(this._coordinateToKey(Y)),X.unshift(Y);return X}_coordinateToKey(Z){return`${Z.x},${Z.y},${Z.z}`}_moveToNextWaypoint(){let Z=this._waypointNextIndex>0?this._waypoints[this._waypointNextIndex-1]:void 0,J=this._waypoints[this._waypointNextIndex];if(!J||!this._entity)return;let X=0;if(this._entity.isDynamic&&Z&&J.y>Z.y){let Y=J.y-Z.y,$=Math.min(Y,this._maxJump)+0.75;this.jump($);let Q=Math.abs(this._entity.world.simulation.gravity.y),K=Math.sqrt(2*Q*$),W=Z.x+0.5,G=Z.z+0.5,V=J.x+0.5,H=J.z+0.5,F=V-W,z=H-G,q=Math.sqrt(F*F+z*z),U=K/Q,B=q/this._speed;X=Math.min(U*0.8,B)*1000}setTimeout(()=>{if(!this._entity)return;let Y=Date.now();this.face(J,this._speed),this.move(J,this._speed,{moveCompletesWhenStuck:!0,moveIgnoreAxes:{y:this._entity.isDynamic},moveStartIdleAnimationsOnCompletion:this._waypointNextIndex===this._waypoints.length-1,moveStoppingDistance:this._waypointStoppingDistance,moveCallback:()=>{if(Date.now()-Y>this._waypointTimeoutMs&&this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveSkipped?.(J,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint()},moveCompleteCallback:()=>{if(this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveComplete?.(J,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint();else this._onPathfindComplete?.()}})},X)}_pathfindingHeuristic(Z,J){return Math.abs(Z.x-J.x)+Math.abs(Z.y-J.y)+Math.abs(Z.z-J.z)}_isNeighborCoordinateBlocked(Z,J,X){if(!this._entity?.world)return!1;let Y=this._entity.world,$=Math.floor(J.x),Q=Math.floor(J.y),K=Math.floor(J.z),W=Math.floor(Z.x),G=Math.floor(Z.z);if(!Y.chunkLattice.hasBlock({x:$,y:Q-1,z:K}))return!0;for(let V=0;V<X;V++)if(Y.chunkLattice.hasBlock({x:$,y:Q+V,z:K}))return!0;if($!==W&&K!==G)for(let V=0;V<X;V++){let H=Y.chunkLattice.hasBlock({x:$,y:Q+V,z:G}),F=Y.chunkLattice.hasBlock({x:W,y:Q+V,z:K});if(H||F)return!0}return!1}_findGroundedStart(){if(!this._entity?.world)return;let{x:Z,y:J,z:X}=this._entity.position,Y={x:Math.floor(Z),y:Math.floor(J),z:Math.floor(X)};for(let $=0;$<=Math.abs(this._maxFall);$++)if(this._entity.world.chunkLattice.hasBlock({...Y,y:Y.y-$-1}))return{...Y,y:Y.y-$};return}}export{oQ6 as startServer,I31 as WorldManagerEvent,IY as WorldManager,E31 as WorldLoopEvent,LU as WorldLoop,Dm as WorldEvent,BU as World,aS as WebServerEvent,FG as WebServer,N3 as Vector3,wU as Vector2,UU as Ticker,qU as TickAllocator,YK as TelemetrySpanOperation,t1 as Telemetry,jm as SimulationEvent,HU as Simulation,OU as SimpleEntityController,FU as SceneUIManager,rk as SceneUIEvent,tH as SceneUI,X50 as SUPPORTED_INPUT_KEYS,BH as RigidBodyType,M$ as RigidBody,R3 as Quaternion,cw as PlayerUIEvent,iH as PlayerUI,k31 as PlayerManagerEvent,U9 as PlayerManager,nH as PlayerEvent,b7 as PlayerEntity,J50 as PlayerCameraMode,nk as PlayerCameraEvent,pH as PlayerCamera,CW as Player,E$ as PersistenceManager,Sm as PathfindingEntityController,zU as ParticleEmitterManager,Mm as ParticleEmitterEvent,Rm as ParticleEmitter,iS as PORT,W50 as PLAYER_ROTATION_UPDATE_THRESHOLD,K50 as PLAYER_POSITION_UPDATE_THRESHOLD_SQ,S5 as ModelRegistry,P5 as Matrix4,LZ as Matrix3,GK as Matrix2,T31 as LightType,GU as LightManager,wm as LightEvent,Om as Light,F6 as IterationMap,v31 as GameServerEvent,$K as GameServer,M0 as EventRouter,c as ErrorHandler,eH as EntityManager,rH as EntityEvent,n8 as Entity,Q50 as ENTITY_ROTATION_UPDATE_THRESHOLD,$50 as ENTITY_POSITION_UPDATE_THRESHOLD_SQ,g1 as DefaultPlayerEntityController,tk as DefaultPlayerEntity,Y50 as DEFAULT_ENTITY_RIGID_BODY_OPTIONS,E4 as CollisionGroupsBuilder,yY as CollisionGroup,wH as ColliderShape,oH as ColliderMap,K9 as Collider,FI as CoefficientCombineRule,ok as ChunkLatticeEvent,sH as ChunkLattice,V9 as Chunk,aH as ChatManager,ak as ChatEvent,UI as BlockTypeRegistryEvent,OH as BlockTypeRegistry,qI as BlockTypeEvent,W9 as BlockType,FK as Block,gm as BaseEntityControllerEvent,vY as BaseEntityController,P3 as AudioManager,PD as AudioEvent,D3 as Audio};
|
|
493
|
+
`);let{connect:G,buffered:V}=await W;if(Z.emit("proxyConnect",G),this.emit("proxyConnect",G,Z),G.statusCode===200){if(Z.once("socket",RQ6),J.secureEndpoint){KU("Upgrading socket connection to TLS");let F=J.servername||J.host;return Hm.connect({...G31(J,"host","path","port"),socket:Y,servername:_J.isIP(F)?void 0:F})}return Y}Y.destroy();let H=new _J.Socket({writable:!1});return H.readable=!0,Z.once("socket",(F)=>{KU("Replaying proxy buffer for failed request"),F.push(V),F.push(null)}),H}}ej.__initStatic();function RQ6(Z){Z.resume()}function G31(Z,...J){let X={},Y;for(Y in Z)if(!J.includes(Y))X[Y]=Z[Y];return X}var CQ6=32768;function TQ6(Z){return new DQ6({read(){this.push(Z),this.push(null)}})}function ZD(Z){let J;try{J=new URL(Z.url)}catch(G){return Q8(()=>{console.warn("[@sentry/node]: Invalid dsn or tunnel option, will not send any events. The tunnel option must be a full URL when used.")}),EG(Z,()=>Promise.resolve({}))}let X=J.protocol==="https:",Y=EQ6(J,Z.proxy||(X?process.env.https_proxy:void 0)||process.env.http_proxy),$=X?jQ6:NQ6,Q=Z.keepAlive===void 0?!1:Z.keepAlive,K=Y?new ej(Y):new $.Agent({keepAlive:Q,maxSockets:30,timeout:2000}),W=IQ6(Z,Z.httpModule??$,K);return EG(Z,W)}function EQ6(Z,J){let{no_proxy:X}=process.env;if(X?.split(",").some(($)=>Z.host.endsWith($)||Z.hostname.endsWith($)))return;else return J}function IQ6(Z,J,X){let{hostname:Y,pathname:$,port:Q,protocol:K,search:W}=new URL(Z.url);return function G(V){return new Promise((H,F)=>{EF(()=>{let z=TQ6(V.body),q={...Z.headers};if(V.body.length>CQ6)q["content-encoding"]="gzip",z=z.pipe(PQ6());let U=J.request({method:"POST",agent:X,headers:q,hostname:Y,path:`${$}${W}`,port:Q,protocol:K,ca:Z.caCerts},(B)=>{B.on("data",()=>{}),B.on("end",()=>{}),B.setEncoding("utf8");let L=B.headers["retry-after"]??null,w=B.headers["x-sentry-rate-limits"]??null;H({statusCode:B.statusCode,headers:{"retry-after":L,"x-sentry-rate-limits":Array.isArray(w)?w[0]||null:w}})});U.on("error",F),z.pipe(U)})})}}var kQ6=new Set(["false","f","n","no","off","0"]),_Q6=new Set(["true","t","y","yes","on","1"]);function JD(Z,J){let X=String(Z).toLowerCase();if(kQ6.has(X))return!1;if(_Q6.has(X))return!0;return J?.strict?null:Boolean(Z)}import{posix as vQ6,sep as SQ6}from"node:path";function V31(Z){return Z.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}function XD(Z=process.argv[1]?Fx(process.argv[1]):process.cwd(),J=SQ6==="\\"){let X=J?V31(Z):Z;return(Y)=>{if(!Y)return;let $=J?V31(Y):Y,{dir:Q,base:K,ext:W}=vQ6.parse($);if(W===".js"||W===".mjs"||W===".cjs")K=K.slice(0,W.length*-1);let G=decodeURIComponent(K);if(!Q)Q=".";let V=Q.lastIndexOf("/node_modules");if(V>-1)return`${Q.slice(V+14).replace(/\//g,".")}:${G}`;if(Q.startsWith(X)){let H=Q.slice(X.length+1).replace(/\//g,".");return H?`${H}:${G}`:G}return G}}function YD(Z){if(process.env.SENTRY_RELEASE)return process.env.SENTRY_RELEASE;if(O0.SENTRY_RELEASE?.id)return O0.SENTRY_RELEASE.id;let J=process.env.GITHUB_SHA||process.env.CI_MERGE_REQUEST_SOURCE_BRANCH_SHA||process.env.CI_BUILD_REF||process.env.CI_COMMIT_SHA||process.env.BITBUCKET_COMMIT,X=process.env.APPVEYOR_PULL_REQUEST_HEAD_COMMIT||process.env.APPVEYOR_REPO_COMMIT||process.env.CODEBUILD_RESOLVED_SOURCE_VERSION||process.env.AWS_COMMIT_ID||process.env.BUILD_SOURCEVERSION||process.env.GIT_CLONE_COMMIT_HASH||process.env.BUDDY_EXECUTION_REVISION||process.env.BUILDKITE_COMMIT||process.env.CIRCLE_SHA1||process.env.CIRRUS_CHANGE_IN_REPO||process.env.CF_REVISION||process.env.CM_COMMIT||process.env.CF_PAGES_COMMIT_SHA||process.env.DRONE_COMMIT_SHA||process.env.FC_GIT_COMMIT_SHA||process.env.HEROKU_TEST_RUN_COMMIT_VERSION||process.env.HEROKU_SLUG_COMMIT||process.env.RAILWAY_GIT_COMMIT_SHA||process.env.RENDER_GIT_COMMIT||process.env.SEMAPHORE_GIT_SHA||process.env.TRAVIS_PULL_REQUEST_SHA||process.env.VERCEL_GIT_COMMIT_SHA||process.env.VERCEL_GITHUB_COMMIT_SHA||process.env.VERCEL_GITLAB_COMMIT_SHA||process.env.VERCEL_BITBUCKET_COMMIT_SHA||process.env.ZEIT_GITHUB_COMMIT_SHA||process.env.ZEIT_GITLAB_COMMIT_SHA||process.env.ZEIT_BITBUCKET_COMMIT_SHA,Y=process.env.CI_COMMIT_ID||process.env.SOURCE_COMMIT||process.env.SOURCE_VERSION||process.env.GIT_COMMIT||process.env.COMMIT_REF||process.env.BUILD_VCS_NUMBER||process.env.CI_COMMIT_SHA;return J||X||Y||Z}var $D=SM(Px(XD()));var z31=r(X0(),1),F31=r(W1(),1);import*as H31 from"node:os";import{threadId as AQ6,isMainThread as xQ6}from"worker_threads";var hQ6=60000;class WU extends nM{constructor(Z){let J=Z.serverName||global.process.env.SENTRY_NAME||H31.hostname(),X={...Z,platform:"node",runtime:{name:"node",version:global.process.version},serverName:J};if(Z.openTelemetryInstrumentations)F31.registerInstrumentations({instrumentations:Z.openTelemetryInstrumentations});Yx(X,"node"),g.log(`Initializing Sentry: process: ${process.pid}, thread: ${xQ6?"main":`worker-${AQ6}`}.`);super(X);if(this.getOptions()._experiments?.enableLogs){if(this._logOnExitFlushListener=()=>{bX(this)},J)this.on("beforeCaptureLog",(Y)=>{Y.attributes={...Y.attributes,"server.address":J}});process.on("beforeExit",this._logOnExitFlushListener)}}get tracer(){if(this._tracer)return this._tracer;let Z="@sentry/node",J=B8,X=z31.trace.getTracer(Z,J);return this._tracer=X,X}async flush(Z){let X=this.traceProvider?.activeSpanProcessor;if(X)await X.forceFlush();if(this.getOptions().sendClientReports)this._flushOutcomes();return super.flush(Z)}close(Z){if(this._clientReportInterval)clearInterval(this._clientReportInterval);if(this._clientReportOnExitFlushListener)process.off("beforeExit",this._clientReportOnExitFlushListener);if(this._logOnExitFlushListener)process.off("beforeExit",this._logOnExitFlushListener);return super.close(Z)}startClientReportTracking(){let Z=this.getOptions();if(Z.sendClientReports)this._clientReportOnExitFlushListener=()=>{this._flushOutcomes()},this._clientReportInterval=setInterval(()=>{m0&&g.log("Flushing client reports based on interval."),this._flushOutcomes()},Z.clientReportFlushInterval??hQ6).unref(),process.on("beforeExit",this._clientReportOnExitFlushListener)}_getTraceInfoFromScope(Z){if(!Z)return[void 0,void 0];return S41(this,Z)}}var q7=r(X0(),1),q31=r(py(),1),U31=r(ay(),1),M3=r(D1(),1);var L31=r(Yy(),1);import fQ6 from"module";var zm=1e6;function QD(Z,J={}){if(Z.getOptions().debug)w31();let X=bQ6(Z,J);Z.traceProvider=X}function Fm(){let[Z=0,J=0]=process.versions.node.split(".").map(Number);if(Z>=21||Z===20&&J>=6||Z===18&&J>=19){if(!O0._sentryEsmLoaderHookRegistered)try{let{addHookMessagePort:X}=L31.createAddHookMessageChannel();fQ6.register("import-in-the-middle/hook.mjs",import.meta.url,{data:{addHookMessagePort:X,include:[]},transferList:[X]})}catch(X){g.warn("Failed to register ESM hook",X)}}else Q8(()=>{console.warn(`[Sentry] You are using Node.js v${process.versions.node} in ESM mode ("import syntax"). The Sentry Node.js SDK is not compatible with ESM in Node.js versions before 18.19.0 or before 20.6.0. Please either build your application with CommonJS ("require() syntax"), or upgrade your Node.js version.`)})}function B31(Z={}){let{debug:J}=Z;if(J)g.enable(),w31();if(!L4())Fm();yQ6(Z.integrations).forEach((X)=>{if(X(),J)g.log(`[Sentry] Preloaded ${X.id} instrumentation`)})}function yQ6(Z){let J=K31();if(!Z)return J;return J.filter((X)=>Z.includes(X.id))}function bQ6(Z,J={}){let X=new U31.BasicTracerProvider({sampler:new Ub(Z),resource:new q31.Resource({[M3.ATTR_SERVICE_NAME]:"node",[M3.SEMRESATTRS_SERVICE_NAMESPACE]:"sentry",[M3.ATTR_SERVICE_VERSION]:B8}),forceFlushTimeoutMillis:500,spanProcessors:[new qb({timeout:gQ6(Z.getOptions().maxSpanWaitDuration)}),...J.spanProcessors||[]]});return q7.trace.setGlobalTracerProvider(X),q7.propagation.setGlobalPropagator(new Gb),q7.context.setGlobalContextManager(new oj),X}function gQ6(Z){if(Z==null)return;if(Z>zm)return m0&&g.warn(`\`maxSpanWaitDuration\` is too high, using the maximum value of ${zm}`),zm;else if(Z<=0||Number.isNaN(Z)){m0&&g.warn("`maxSpanWaitDuration` must be a positive number, using default value instead.");return}return Z}function w31(){let Z=new Proxy(g,{get(J,X,Y){return Reflect.get(J,X==="verbose"?"debug":X,Y)}});q7.diag.disable(),q7.diag.setLogger(Z,q7.DiagLogLevel.DEBUG)}function mQ6(){return L4()?[dN()]:[]}function qm(){return[fF(),hF(),yF(),bF(),gF(),_N(),xN(),cN(),lN(),bN(),uN(),yN(),aj(),Q31(),...mQ6()]}function Um(Z){return[...qm(),...F5(Z)?rj():[]]}function KD(Z={}){return M31(Z,Um)}function O31(Z={}){return M31(Z,()=>[])}function M31(Z={},J){let X=uQ6(Z,J);if(X.debug===!0)if(m0)g.enable();else Q8(()=>{console.warn("[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.")});if(!L4()&&X.registerEsmLoaderHooks!==!1)Fm();if(TN(),l0().update(X.initialScope),X.spotlight&&!X.integrations.some(({name:Q})=>Q===sg))X.integrations.push(fj({sidecarUrl:typeof X.spotlight==="string"?X.spotlight:void 0}));let $=new WU(X);if(l0().setClient($),$.init(),g.log(`Running in ${L4()?"CommonJS":"ESM"} mode.`),$.startClientReportTracking(),lQ6(),!X.skipOpenTelemetrySetup)QD($,{spanProcessors:X.openTelemetrySpanProcessors}),Lm();return D41($),A41($),$}function Lm(){if(!m0)return;let Z=E41(),J=["SentryContextManager","SentryPropagator"];if(F5())J.push("SentrySpanProcessor");for(let X of J)if(!Z.includes(X))g.error(`You have to set up the ${X}. Without this, the OpenTelemetry & Sentry integration will not work properly.`);if(!Z.includes("SentrySampler"))g.warn("You have to set up the SentrySampler. Without this, the OpenTelemetry & Sentry integration may still work, but sample rates set for the Sentry SDK will not be respected. If you use a custom sampler, make sure to use `wrapSamplingDecision`.")}function uQ6(Z,J){let X=dQ6(Z.release),Y=Z.spotlight??JD(process.env.SENTRY_SPOTLIGHT,{strict:!0})??process.env.SENTRY_SPOTLIGHT,$=cQ6(Z.tracesSampleRate),Q={...Z,dsn:Z.dsn??process.env.SENTRY_DSN,environment:Z.environment??process.env.SENTRY_ENVIRONMENT,sendClientReports:Z.sendClientReports??!0,transport:Z.transport??ZD,stackParser:qA(Z.stackParser||$D),release:X,tracesSampleRate:$,spotlight:Y,debug:JD(Z.debug??process.env.SENTRY_DEBUG)},K=Z.integrations,W=Z.defaultIntegrations??J(Q);return{...Q,integrations:iA({defaultIntegrations:W,integrations:K})}}function dQ6(Z){if(Z!==void 0)return Z;let J=YD();if(J!==void 0)return J;return}function cQ6(Z){if(Z!==void 0)return Z;let J=process.env.SENTRY_TRACES_SAMPLE_RATE;if(!J)return;let X=parseFloat(J);return isFinite(X)?X:void 0}function lQ6(){if(JD(process.env.SENTRY_USE_ENVIRONMENT)!==!1){let Z=process.env.SENTRY_TRACE,J=process.env.SENTRY_BAGGAGE,X=QQ(Z,J);l0().setPropagationContext(X)}}var pQ6=[["january","1"],["february","2"],["march","3"],["april","4"],["may","5"],["june","6"],["july","7"],["august","8"],["september","9"],["october","10"],["november","11"],["december","12"],["jan","1"],["feb","2"],["mar","3"],["apr","4"],["may","5"],["jun","6"],["jul","7"],["aug","8"],["sep","9"],["oct","10"],["nov","11"],["dec","12"],["sunday","0"],["monday","1"],["tuesday","2"],["wednesday","3"],["thursday","4"],["friday","5"],["saturday","6"],["sun","0"],["mon","1"],["tue","2"],["wed","3"],["thu","4"],["fri","5"],["sat","6"]];function XK(Z){return pQ6.reduce((J,[X,Y])=>J.replace(new RegExp(X,"gi"),Y),Z)}var R31="Automatic instrumentation of CronJob only supports crontab string";function N31(Z,J){let X=!1;return new Proxy(Z,{construct(Y,$){let[Q,K,W,G,V,...H]=$;if(typeof Q!=="string")throw new Error(R31);if(X)throw new Error(`A job named '${J}' has already been scheduled`);X=!0;let F=XK(Q);async function z(q,U){return r7(J,async()=>{try{await K(q,U)}catch(B){throw q1(B),B}},{schedule:{type:"crontab",value:F},timezone:V||void 0})}return new Y(Q,z,W,G,V,...H)},get(Y,$){if($==="from")return(Q)=>{let{cronTime:K,onTick:W,timeZone:G}=Q;if(typeof K!=="string")throw new Error(R31);if(X)throw new Error(`A job named '${J}' has already been scheduled`);X=!0;let V=XK(K);return Q.onTick=async(H,F)=>{return r7(J,async()=>{try{await W(H,F)}catch(z){throw q1(z),z}},{schedule:{type:"crontab",value:V},timezone:G||void 0})},Y.from(Q)};else return Y[$]}})}function j31(Z){return new Proxy(Z,{get(J,X){if(X==="schedule"&&J.schedule)return new Proxy(J.schedule,{apply(Y,$,Q){let[K,W,G]=Q,V=G?.name,H=G?.timezone;if(!V)throw new Error('Missing "name" for scheduled job. A name is required for Sentry check-in monitoring.');let F=async()=>{return r7(V,async()=>{try{return await W()}catch(z){throw q1(z),z}},{schedule:{type:"crontab",value:XK(K)},timezone:H})};return Y.apply($,[K,F,G])}});else return J[X]}})}function D31(Z){return new Proxy(Z,{get(J,X){if(X==="scheduleJob")return new Proxy(J.scheduleJob,{apply(Y,$,Q){let[K,W,G]=Q;if(typeof K!=="string"||typeof W!=="string"||typeof G!=="function")throw new Error("Automatic instrumentation of 'node-schedule' requires the first parameter of 'scheduleJob' to be a job name string and the second parameter to be a crontab string");let V=K,H=W;async function F(){return r7(V,async()=>{await G?.()},{schedule:{type:"crontab",value:XK(H)}})}return Y.apply($,[V,H,F])}});return J[X]}})}var P31={instrumentCron:N31,instrumentNodeCron:j31,instrumentNodeSchedule:D31};var YK;((L)=>{L.BUILD_PACKETS="build_packets";L.ENTITIES_EMIT_UPDATES="entities_emit_updates";L.ENTITIES_TICK="entities_tick";L.NETWORK_SYNCHRONIZE="network_synchronize";L.NETWORK_SYNCHRONIZE_CLEANUP="network_synchronize_cleanup";L.PHYSICS_CLEANUP="physics_cleanup";L.PHYSICS_STEP="physics_step";L.RELEASE_TICK_ALLOCATION="release_tick_allocation";L.SEND_ALL_PACKETS="send_all_packets";L.SEND_PACKETS="send_packets";L.SERIALIZE_FREE_BUFFERS="serialize_free_buffers";L.SERIALIZE_PACKETS="serialize_packets";L.SERIALIZE_PACKETS_ENCODE="serialize_packets_encode";L.SIMULATION_STEP="simulation_step";L.TICKER_TICK="ticker_tick";L.WORLD_TICK="world_tick"})(YK||={});class t1{static getProcessStats(Z=!1){let J=process.memoryUsage(),X={jsHeapSizeMb:{value:J.heapUsed/1024/1024,unit:"megabyte"},jsHeapCapacityMb:{value:J.heapTotal/1024/1024,unit:"megabyte"},jsHeapUsagePercent:{value:J.heapUsed/J.heapTotal,unit:"percent"},processHeapSizeMb:{value:J.heapUsed/1024/1024,unit:"megabyte"},rssSizeMb:{value:J.rss/1024/1024,unit:"megabyte"}};if(Z)return X;return Object.fromEntries(Object.entries(X).map(([Y,$])=>[Y,$.value]))}static initializeSentry(Z,J=50){KD({dsn:Z,release:nS,environment:process.env.NODE_ENV||"development",tracesSampleRate:1,initialScope:{tags:{gameId:process.env.HYTOPIA_GAME_ID??"unknown",gameSlug:process.env.HYTOPIA_GAME_SLUG??"unknown",lobbyId:process.env.HYTOPIA_LOBBY_ID??"unknown",region:process.env.REGION??"unknown"}},beforeSend:(X)=>{return X.extra=t1.getProcessStats(),X},beforeSendTransaction:(X)=>{if(X.contexts?.trace?.op==="ticker_tick"){let $=X?.start_timestamp,Q=X?.timestamp;if(!$||!Q)return null;if((Q-$)*1000>J)return X.measurements=t1.getProcessStats(!0),X}return null}})}static startSpan(Z,J){if(SF())return Z4({attributes:Z.attributes,name:Z.operation,op:Z.operation},J);else return J()}static sentry(){return Bm}}var C31=new f$,iQ6=5000;class n4 extends M0{static _cachedPacketsSerializedBuffer=new Map;_closeTimeout=null;_wrtcDirectTransport=null;_wrtcClientServerTransport=null;_wrtcClientServerDataProducers=[];_wrtcClientServerDataConsumers=[];_wrtcServerClientTransport=null;_wrtcServerClientReliableDataProducer=null;_wrtcServerClientUnreliableDataProducer=null;_wrtcServerClientDataConsumers=[];_ws;id;constructor(Z,J){super();this.id=U40(),this.onPacket(Y0.PacketId.CONNECTION,this._onConnectionPacket),this.onPacket(Y0.PacketId.HEARTBEAT,this._onHeartbeatPacket),this.bindWs(Z),M0.globalInstance.emit("CONNECTION.OPENED",{connection:this,req:J})}static clearCachedPacketsSerializedBuffers(){if(n4._cachedPacketsSerializedBuffer.size>0)n4._cachedPacketsSerializedBuffer.clear()}static serializePackets(Z){for(let X of Z)if(!Y0.isValidPacket(X))return c.error(`Connection.serializePackets(): Invalid packet payload: ${JSON.stringify(X)}`);let J=n4._cachedPacketsSerializedBuffer.get(Z);if(J)return J;return t1.startSpan({operation:"serialize_packets",attributes:{packets:Z.length,packetIds:Z.map((X)=>X[0]).join(",")}},(X)=>{let Y=t1.startSpan({operation:"serialize_packets_encode"},()=>C31.pack(Z));return X?.setAttribute("serializedBytes",Y.byteLength),n4._cachedPacketsSerializedBuffer.set(Z,Y),Y})}bindWs(Z){let J=!!this._ws;if(J&&this._closeTimeout)clearTimeout(this._closeTimeout),this._closeTimeout=null;if(this._ws)this._ws.onmessage=()=>{},this._ws.onclose=()=>{},this._ws.onerror=()=>{},this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{k:!0})]);if(this._ws=Z,this._ws.binaryType="nodebuffer",this._ws.onmessage=(X)=>this._onMessage(X.data),this._ws.onclose=this._onWsClose,this._ws.onerror=this._onWsError,this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{i:this.id})],!0,!0),J)this.emitWithGlobal("CONNECTION.RECONNECTED",{connection:this});if(s7.instance.isWrtcEnabled)this._upgradeToWRTC()}closeWrtc(){this._closeWrtcClientServerTransport(),this._closeWrtcServerClientTransport()}disconnect(){try{this._ws.close()}catch(Z){c.error(`Connection.disconnect(): Connection disconnect failed. Error: ${Z}`)}}onPacket(Z,J){this.on("CONNECTION.PACKET_RECEIVED",({packet:X})=>{if(X[0]===Z)J(X)})}send(Z,J=!0,X=!1){if(this._closeTimeout)return;if(this._ws.readyState!==q_.default.OPEN)return;t1.startSpan({operation:"send_packets",attributes:{forceWs:X?"true":"false",wrtcConnected:this._wrtcServerClientTransport?.iceState==="completed"?"true":"false"}},()=>{try{let Y=n4.serializePackets(Z);if(!Y)return;if(this._wrtcServerClientTransport?.iceState==="completed"&&Y.length<(this._wrtcServerClientTransport?.sctpParameters?.maxMessageSize??0)&&!X)try{(J?this._wrtcServerClientReliableDataProducer:this._wrtcServerClientUnreliableDataProducer).send(Y)}catch{this._ws.send(Y)}else this._ws.send(Y);this.emitWithGlobal("CONNECTION.PACKETS_SENT",{connection:this,packets:Z})}catch(Y){c.error(`Connection.send(): Packet send failed. Error: ${Y}`)}})}_closeWrtcClientServerTransport(){this._wrtcDirectTransport?.close(),this._wrtcDirectTransport=null,this._wrtcClientServerTransport?.close(),this._wrtcClientServerTransport=null,this._wrtcClientServerDataProducers.forEach((Z)=>Z.close()),this._wrtcClientServerDataProducers=[],this._wrtcClientServerDataConsumers.forEach((Z)=>Z.close()),this._wrtcClientServerDataConsumers=[]}_closeWrtcServerClientTransport(){this._wrtcServerClientTransport?.close(),this._wrtcServerClientTransport=null,this._wrtcServerClientDataConsumers.forEach((Z)=>Z.close()),this._wrtcServerClientDataConsumers=[],this._wrtcServerClientReliableDataProducer?.close(),this._wrtcServerClientReliableDataProducer=null,this._wrtcServerClientUnreliableDataProducer?.close(),this._wrtcServerClientUnreliableDataProducer=null}_onConnectionPacket=async(Z)=>{let J=Z[1],X=J.c,Y=J.d;if(X){let{i:$,d:Q}=X,K=!1;if($==this._wrtcClientServerTransport?.id)await this._wrtcClientServerTransport.connect({dtlsParameters:Q}),K=!0;if($==this._wrtcServerClientTransport?.id)await this._wrtcServerClientTransport.connect({dtlsParameters:Q}),K=!0;if(K)this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{ca:{i:$}})])}if(Y)for(let $ of Y){let{s:Q,l:K}=$,W=await this._wrtcClientServerTransport.produceData({label:K,sctpStreamParameters:Q}),G=await this._wrtcDirectTransport.consumeData({dataProducerId:W.id});this._wrtcClientServerDataProducers.push(W),this._wrtcClientServerDataConsumers.push(G),G.on("message",(V)=>this._onMessage(V)),this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{pa:{i:W.id,l:K}})])}};_onHeartbeatPacket=()=>{this.send([Y0.createPacket(Y0.bidirectionalPackets.heartbeatPacketDefinition,null)],!0,!0)};_onMessage=(Z)=>{try{let J=this._deserialize(Z);if(!J)return;this.emitWithGlobal("CONNECTION.PACKET_RECEIVED",{connection:this,packet:J})}catch(J){c.error(`Connection._ws.onmessage(): Error: ${J}`)}};_onWrtcIceStateChange=(Z,J)=>{if(["disconnected","closed"].includes(J)){if(Z==this._wrtcClientServerTransport)this._closeWrtcClientServerTransport();else if(Z==this._wrtcServerClientTransport)this._closeWrtcServerClientTransport()}};_onWsClose=()=>{this.closeWrtc(),this.emitWithGlobal("CONNECTION.DISCONNECTED",{connection:this}),this._closeTimeout=setTimeout(()=>{this.emitWithGlobal("CONNECTION.CLOSED",{connection:this}),this.offAll()},iQ6)};_onWsError=(Z)=>{this.emitWithGlobal("CONNECTION.ERROR",{connection:this,error:Z})};_upgradeToWRTC=async()=>{let Z=await s7.instance.createWrtcTransports();if(!Z)return!1;let{directTransport:J,clientServerTransport:X,serverClientTransport:Y}=Z;this._wrtcDirectTransport=J,this._wrtcClientServerTransport=X,this._wrtcClientServerTransport.on("icestatechange",(K)=>{this._onWrtcIceStateChange(this._wrtcClientServerTransport,K)}),this._wrtcServerClientTransport=Y,this._wrtcServerClientTransport.on("icestatechange",(K)=>{this._onWrtcIceStateChange(this._wrtcServerClientTransport,K)}),this._wrtcServerClientReliableDataProducer=await this._wrtcServerClientTransport.produceData({label:"scr",sctpStreamParameters:{streamId:0,ordered:!0}}),this._wrtcServerClientUnreliableDataProducer=await this._wrtcServerClientTransport.produceData({label:"scu",sctpStreamParameters:{streamId:1,ordered:!1,maxPacketLifeTime:35}});let $=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientReliableDataProducer.id}),Q=await this._wrtcServerClientTransport.consumeData({dataProducerId:this._wrtcServerClientUnreliableDataProducer.id});return this._wrtcServerClientDataConsumers.push($,Q),this.send([Y0.createPacket(Y0.bidirectionalPackets.connectionPacketDefinition,{d:[{i:$.id,pi:$.dataProducerId,l:"scr",s:$.sctpStreamParameters},{i:Q.id,pi:Q.dataProducerId,l:"scu",s:Q.sctpStreamParameters}],t:[{i:this._wrtcClientServerTransport.id,f:"cs",d:this._wrtcClientServerTransport.dtlsParameters,ic:this._wrtcClientServerTransport.iceCandidates,ip:this._wrtcClientServerTransport.iceParameters,s:this._wrtcClientServerTransport.sctpParameters},{i:this._wrtcServerClientTransport.id,f:"sc",d:this._wrtcServerClientTransport.dtlsParameters,ic:this._wrtcServerClientTransport.iceCandidates,ip:this._wrtcServerClientTransport.iceParameters,s:this._wrtcServerClientTransport.sctpParameters}]})]),!0};_deserialize(Z){let J=C31.unpack(Z);if(!J||typeof J!=="object"||typeof J[0]!=="number")return c.error(`Connection._deserialize(): Invalid packet format. Packet: ${JSON.stringify(J)}`);if(!Y0.isValidPacket(J))return c.error(`Connection._deserialize(): Invalid packet payload. Packet: ${JSON.stringify(J)}`);return J}}class GU{_lights=new Map;_nextLightId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}despawnEntityAttachedLights(Z){this.getAllEntityAttachedLights(Z).forEach((J)=>{J.despawn()})}getAllLights(Z=!1){return Z?this._world.tickAllocator.getArray(this._lights.values()):Array.from(this._lights.values())}getAllEntityAttachedLights(Z){return this.getAllLights().filter((J)=>J.attachedToEntity===Z)}registerLight(Z){if(Z.id!==void 0)return Z.id;let J=this._nextLightId;return this._lights.set(J,Z),this._nextLightId++,J}unregisterLight(Z){if(Z.id===void 0)return;this._lights.delete(Z.id)}}class F6{_map=new Map;_values=[];_isDirty=!1;get size(){return this._map.size}get valuesArray(){if(this._isDirty)this._syncArray();return this._values}get(Z){return this._map.get(Z)}set(Z,J){let X=this._map.has(Z);if(this._map.set(Z,J),!X)this._values.push(J);else this._isDirty=!0;return this}has(Z){return this._map.has(Z)}delete(Z){let J=this._map.delete(Z);if(J)this._isDirty=!0;return J}clear(){this._map.clear(),this._values.length=0,this._isDirty=!1}forEach(Z,J){this._map.forEach((X,Y)=>{Z.call(J,X,Y,this)})}keys(){return this._map.keys()}values(){return this._map.values()}entries(){return this._map.entries()}[Symbol.iterator](){return this._map[Symbol.iterator]()}_syncArray(){this._values.length=0;for(let Z of this._map.values())this._values.push(Z);this._isDirty=!1}}var T31;((X)=>{X[X.POINTLIGHT=0]="POINTLIGHT";X[X.SPOTLIGHT=1]="SPOTLIGHT"})(T31||={});var wm;((z)=>{z.DESPAWN="LIGHT.DESPAWN";z.SET_ANGLE="LIGHT.SET_ANGLE";z.SET_ATTACHED_TO_ENTITY="LIGHT.SET_ATTACHED_TO_ENTITY";z.SET_COLOR="LIGHT.SET_COLOR";z.SET_DISTANCE="LIGHT.SET_DISTANCE";z.SET_INTENSITY="LIGHT.SET_INTENSITY";z.SET_OFFSET="LIGHT.SET_OFFSET";z.SET_PENUMBRA="LIGHT.SET_PENUMBRA";z.SET_POSITION="LIGHT.SET_POSITION";z.SET_TRACKED_ENTITY="LIGHT.SET_TRACKED_ENTITY";z.SET_TRACKED_POSITION="LIGHT.SET_TRACKED_POSITION";z.SPAWN="LIGHT.SPAWN"})(wm||={});class Om extends M0{_id;_angle;_attachedToEntity;_color;_distance;_intensity;_offset;_penumbra;_position;_trackedEntity;_trackedPosition;_type;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)c.fatalError("Either attachedToEntity or position must be set, but not both.");super();c.warning("WARNING: Lights are poorly optimized at this time. Using more than a few lights in your game can cause extremely bad performance (FPS) issues. Use lights sparingly!"),this._angle=Z.angle,this._attachedToEntity=Z.attachedToEntity,this._color=Z.color??{r:255,g:255,b:255},this._distance=Z.distance,this._intensity=Z.intensity??1,this._offset=Z.offset,this._penumbra=Z.penumbra,this._position=Z.position,this._trackedEntity=Z.trackedEntity,this._trackedPosition=Z.trackedPosition,this._type=Z.type??0}get id(){return this._id}get angle(){return this._angle}get attachedToEntity(){return this._attachedToEntity}get color(){return this._color}get distance(){return this._distance}get intensity(){return this._intensity}get isSpawned(){return this._id!==void 0}get offset(){return this._offset}get penumbra(){return this._penumbra}get position(){return this._position}get trackedEntity(){return this._trackedEntity}get trackedPosition(){return this._trackedPosition}get type(){return this._type}get world(){return this._world}setAngle(Z){if(this._angle===Z)return;if(this._angle=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ANGLE",{light:this,angle:Z})}setAttachedToEntity(Z){if(!Z.isSpawned)return c.error(`Light.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_ATTACHED_TO_ENTITY",{light:this,entity:Z})}setColor(Z){if(this._color.r===Z.r&&this._color.g===Z.g&&this._color.b===Z.b)return;if(this._color=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_COLOR",{light:this,color:Z})}setDistance(Z){if(this._distance===Z)return;if(this._distance=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_DISTANCE",{light:this,distance:Z})}setIntensity(Z){if(this._intensity===Z)return;if(this._intensity=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_INTENSITY",{light:this,intensity:Z})}setOffset(Z){if(this._offset&&this._offset.x===Z.x&&this._offset.y===Z.y&&this._offset.z===Z.z)return;if(this._offset=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_OFFSET",{light:this,offset:Z})}setPenumbra(Z){if(this._penumbra===Z)return;if(this._penumbra=Z,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_PENUMBRA",{light:this,penumbra:Z})}setPosition(Z){if(this._position&&this._position.x===Z.x&&this._position.y===Z.y&&this._position.z===Z.z)return;if(this._position=Z,this._attachedToEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_POSITION",{light:this,position:Z})}setTrackedEntity(Z){if(!Z.isSpawned)return c.error(`Light.setTrackedEntity(): Entity ${Z.id} is not spawned!`);if(this._trackedEntity===Z)return;if(this._trackedEntity=Z,this._trackedPosition=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_ENTITY",{light:this,entity:Z})}setTrackedPosition(Z){if(this._trackedPosition===Z)return;if(this._trackedPosition=Z,this._trackedEntity=void 0,this.isSpawned)this.emitWithWorld(this._world,"LIGHT.SET_TRACKED_POSITION",{light:this,position:Z})}despawn(){if(!this.isSpawned||!this._world)return;this._world.lightManager.unregisterLight(this),this.emitWithWorld(this._world,"LIGHT.DESPAWN",{light:this}),this._id=void 0,this._world=void 0}spawn(Z){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return c.error(`Light.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning Light!`);this._id=Z.lightManager.registerLight(this),this._world=Z,this.emitWithWorld(Z,"LIGHT.SPAWN",{light:this})}serialize(){if(!this._world)c.fatalError("Light.serialize(): Light is not in a world and cannot be serialized!");return D0.serializeLight(this,this._world.tickAllocator)}}var Mm;((u)=>{u.BURST="PARTICLE_EMITTER.BURST";u.DESPAWN="PARTICLE_EMITTER.DESPAWN";u.SET_ALPHA_TEST="PARTICLE_EMITTER.SET_ALPHA_TEST";u.SET_ATTACHED_TO_ENTITY="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY";u.SET_ATTACHED_TO_ENTITY_NODE_NAME="PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME";u.SET_COLOR_END="PARTICLE_EMITTER.SET_COLOR_END";u.SET_COLOR_END_VARIANCE="PARTICLE_EMITTER.SET_COLOR_END_VARIANCE";u.SET_COLOR_START="PARTICLE_EMITTER.SET_COLOR_START";u.SET_COLOR_START_VARIANCE="PARTICLE_EMITTER.SET_COLOR_START_VARIANCE";u.SET_GRAVITY="PARTICLE_EMITTER.SET_GRAVITY";u.SET_LIFETIME="PARTICLE_EMITTER.SET_LIFETIME";u.SET_LIFETIME_VARIANCE="PARTICLE_EMITTER.SET_LIFETIME_VARIANCE";u.SET_MAX_PARTICLES="PARTICLE_EMITTER.SET_MAX_PARTICLES";u.SET_OFFSET="PARTICLE_EMITTER.SET_OFFSET";u.SET_OPACITY_END="PARTICLE_EMITTER.SET_OPACITY_END";u.SET_OPACITY_END_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE";u.SET_OPACITY_START="PARTICLE_EMITTER.SET_OPACITY_START";u.SET_OPACITY_START_VARIANCE="PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE";u.SET_PAUSED="PARTICLE_EMITTER.SET_PAUSED";u.SET_POSITION="PARTICLE_EMITTER.SET_POSITION";u.SET_POSITION_VARIANCE="PARTICLE_EMITTER.SET_POSITION_VARIANCE";u.SET_RATE="PARTICLE_EMITTER.SET_RATE";u.SET_RATE_VARIANCE="PARTICLE_EMITTER.SET_RATE_VARIANCE";u.SET_SIZE_END="PARTICLE_EMITTER.SET_SIZE_END";u.SET_SIZE_END_VARIANCE="PARTICLE_EMITTER.SET_SIZE_END_VARIANCE";u.SET_SIZE_START="PARTICLE_EMITTER.SET_SIZE_START";u.SET_SIZE_START_VARIANCE="PARTICLE_EMITTER.SET_SIZE_START_VARIANCE";u.SET_TEXTURE_URI="PARTICLE_EMITTER.SET_TEXTURE_URI";u.SET_TRANSPARENT="PARTICLE_EMITTER.SET_TRANSPARENT";u.SET_VELOCITY="PARTICLE_EMITTER.SET_VELOCITY";u.SET_VELOCITY_VARIANCE="PARTICLE_EMITTER.SET_VELOCITY_VARIANCE";u.SPAWN="PARTICLE_EMITTER.SPAWN"})(Mm||={});class Rm extends M0{_id;_alphaTest;_attachedToEntity;_attachedToEntityNodeName;_colorEnd;_colorEndVariance;_colorStart;_colorStartVariance;_gravity;_lifetime;_lifetimeVariance;_maxParticles;_offset;_opacityEnd;_opacityEndVariance;_opacityStart;_opacityStartVariance;_paused;_position;_positionVariance;_rate;_rateVariance;_sizeEnd;_sizeEndVariance;_sizeStart;_sizeStartVariance;_sizeVariance;_textureUri;_transparent;_velocity;_velocityVariance;_world;constructor(Z){if(!!Z.attachedToEntity===!!Z.position)c.fatalError("Either attachedToEntity or position must be set, but not both.");if(!Z.textureUri)c.fatalError("ParticleEmitter.constructor(): textureUri must be provided.");super();this._alphaTest=Z.alphaTest??0.5,this._attachedToEntity=Z.attachedToEntity,this._attachedToEntityNodeName=Z.attachedToEntityNodeName,this._colorEnd=Z.colorEnd,this._colorEndVariance=Z.colorEndVariance,this._colorStart=Z.colorStart,this._colorStartVariance=Z.colorStartVariance,this._gravity=Z.gravity,this._lifetime=Z.lifetime,this._lifetimeVariance=Z.lifetimeVariance,this._maxParticles=Z.maxParticles,this._offset=Z.offset,this._opacityEnd=Z.opacityEnd,this._opacityEndVariance=Z.opacityEndVariance,this._opacityStart=Z.opacityStart,this._opacityStartVariance=Z.opacityStartVariance,this._paused=!1,this._position=Z.position,this._positionVariance=Z.positionVariance,this._rate=Z.rate,this._rateVariance=Z.rateVariance,this._sizeEnd=Z.sizeEnd,this._sizeEndVariance=Z.sizeEndVariance,this._sizeStart=Z.sizeStart,this._sizeStartVariance=Z.sizeStartVariance,this._textureUri=Z.textureUri,this._transparent=Z.transparent,this._velocity=Z.velocity,this._velocityVariance=Z.velocityVariance}get id(){return this._id}get alphaTest(){return this._alphaTest}get attachedToEntity(){return this._attachedToEntity}get attachedToEntityNodeName(){return this._attachedToEntityNodeName}get colorEnd(){return this._colorEnd}get colorEndVariance(){return this._colorEndVariance}get colorStart(){return this._colorStart}get colorStartVariance(){return this._colorStartVariance}get gravity(){return this._gravity}get isSpawned(){return this._id!==void 0}get lifetime(){return this._lifetime}get lifetimeVariance(){return this._lifetimeVariance}get maxParticles(){return this._maxParticles}get offset(){return this._offset}get opacityEnd(){return this._opacityEnd}get opacityEndVariance(){return this._opacityEndVariance}get opacityStart(){return this._opacityStart}get opacityStartVariance(){return this._opacityStartVariance}get paused(){return this._paused}get position(){return this._position}get positionVariance(){return this._positionVariance}get rate(){return this._rate}get rateVariance(){return this._rateVariance}get sizeEnd(){return this._sizeEnd}get sizeEndVariance(){return this._sizeEndVariance}get sizeStart(){return this._sizeStart}get sizeStartVariance(){return this._sizeStartVariance}get sizeVariance(){return this._sizeVariance}get textureUri(){return this._textureUri}get transparent(){return this._transparent}get velocity(){return this._velocity}get velocityVariance(){return this._velocityVariance}get world(){return this._world}setAlphaTest(Z){if(this._alphaTest===Z)return;if(this._alphaTest=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ALPHA_TEST",{particleEmitter:this,alphaTest:Z})}setAttachedToEntity(Z){if(!Z.isSpawned)return c.error(`ParticleEmitter.setAttachedToEntity(): Entity ${Z.id} is not spawned!`);if(this._attachedToEntity===Z)return;if(this._attachedToEntity=Z,this._position=void 0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",{particleEmitter:this,entity:Z})}setAttachedToEntityNodeName(Z){if(this._attachedToEntityNodeName===Z)return;if(this._attachedToEntityNodeName=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",{particleEmitter:this,attachedToEntityNodeName:Z})}setColorEnd(Z){if(this._colorEnd&&this._colorEnd.r===Z.r&&this._colorEnd.g===Z.g&&this._colorEnd.b===Z.b)return;if(this._colorEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END",{particleEmitter:this,colorEnd:Z})}setColorEndVariance(Z){if(this._colorEndVariance&&this._colorEndVariance.r===Z.r&&this._colorEndVariance.g===Z.g&&this._colorEndVariance.b===Z.b)return;if(this._colorEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",{particleEmitter:this,colorEndVariance:Z})}setColorStart(Z){if(this._colorStart&&this._colorStart.r===Z.r&&this._colorStart.g===Z.g&&this._colorStart.b===Z.b)return;if(this._colorStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START",{particleEmitter:this,colorStart:Z})}setColorStartVariance(Z){if(this._colorStartVariance&&this._colorStartVariance.r===Z.r&&this._colorStartVariance.g===Z.g&&this._colorStartVariance.b===Z.b)return;if(this._colorStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",{particleEmitter:this,colorStartVariance:Z})}setGravity(Z){if(this._gravity&&this._gravity.x===Z.x&&this._gravity.y===Z.y&&this._gravity.z===Z.z)return;if(this._gravity=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_GRAVITY",{particleEmitter:this,gravity:Z})}setLifetime(Z){if(this._lifetime===Z)return;if(this._lifetime=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME",{particleEmitter:this,lifetime:Z})}setLifetimeVariance(Z){if(this._lifetimeVariance===Z)return;if(this._lifetimeVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",{particleEmitter:this,lifetimeVariance:Z})}setMaxParticles(Z){if(this._maxParticles===Z)return;if(this._maxParticles=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_MAX_PARTICLES",{particleEmitter:this,maxParticles:Z})}setOffset(Z){if(this._offset&&this._offset.x===Z.x&&this._offset.y===Z.y&&this._offset.z===Z.z)return;if(this._offset=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OFFSET",{particleEmitter:this,offset:Z})}setOpacityEnd(Z){if(this._opacityEnd===Z)return;if(this._opacityEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END",{particleEmitter:this,opacityEnd:Z})}setOpacityEndVariance(Z){if(this._opacityEndVariance===Z)return;if(this._opacityEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",{particleEmitter:this,opacityEndVariance:Z})}setOpacityStart(Z){if(this._opacityStart===Z)return;if(this._opacityStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START",{particleEmitter:this,opacityStart:Z})}setOpacityStartVariance(Z){if(this._opacityStartVariance===Z)return;if(this._opacityStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",{particleEmitter:this,opacityStartVariance:Z})}setPosition(Z){if(this._position&&this._position.x===Z.x&&this._position.y===Z.y&&this._position.z===Z.z)return;if(this._position=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION",{particleEmitter:this,position:Z})}setPositionVariance(Z){if(this._positionVariance&&this._positionVariance.x===Z.x&&this._positionVariance.y===Z.y&&this._positionVariance.z===Z.z)return;if(this._positionVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_POSITION_VARIANCE",{particleEmitter:this,positionVariance:Z})}setRate(Z){if(this._rate===Z)return;if(this._rate=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE",{particleEmitter:this,rate:Z})}setRateVariance(Z){if(this._rateVariance===Z)return;if(this._rateVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_RATE_VARIANCE",{particleEmitter:this,rateVariance:Z})}setSizeEnd(Z){if(this._sizeEnd===Z)return;if(this._sizeEnd=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END",{particleEmitter:this,sizeEnd:Z})}setSizeEndVariance(Z){if(this._sizeEndVariance===Z)return;if(this._sizeEndVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",{particleEmitter:this,sizeEndVariance:Z})}setSizeStart(Z){if(this._sizeStart===Z)return;if(this._sizeStart=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START",{particleEmitter:this,sizeStart:Z})}setSizeStartVariance(Z){if(this._sizeStartVariance===Z)return;if(this._sizeStartVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",{particleEmitter:this,sizeStartVariance:Z})}setTextureUri(Z){if(this._textureUri===Z)return;if(this._textureUri=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TEXTURE_URI",{particleEmitter:this,textureUri:Z})}setTransparent(Z){if(this._transparent===Z)return;if(this._transparent=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_TRANSPARENT",{particleEmitter:this,transparent:Z})}setVelocity(Z){if(this._velocity&&this._velocity.x===Z.x&&this._velocity.y===Z.y&&this._velocity.z===Z.z)return;if(this._velocity=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY",{particleEmitter:this,velocity:Z})}setVelocityVariance(Z){if(this._velocityVariance&&this._velocityVariance.x===Z.x&&this._velocityVariance.y===Z.y&&this._velocityVariance.z===Z.z)return;if(this._velocityVariance=Z,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",{particleEmitter:this,velocityVariance:Z})}burst(Z){if(this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.BURST",{particleEmitter:this,count:Z})}despawn(){if(!this.isSpawned||!this._world)return;this._world.particleEmitterManager.unregisterParticleEmitter(this),this.emitWithWorld(this._world,"PARTICLE_EMITTER.DESPAWN",{particleEmitter:this}),this._id=void 0,this._world=void 0}restart(){if(!this._paused)return;if(this._paused=!1,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}stop(){if(this._paused)return;if(this._paused=!0,this.isSpawned)this.emitWithWorld(this._world,"PARTICLE_EMITTER.SET_PAUSED",{particleEmitter:this,paused:this._paused})}spawn(Z){if(this.isSpawned)return;if(this._attachedToEntity&&!this._attachedToEntity.isSpawned)return c.error(`ParticleEmitter.spawn(): Attached entity ${this._attachedToEntity.id} must be spawned before spawning ParticleEmitter!`);this._id=Z.particleEmitterManager.registerParticleEmitter(this),this._world=Z,this.emitWithWorld(Z,"PARTICLE_EMITTER.SPAWN",{particleEmitter:this})}serialize(){if(!this._world)c.fatalError("ParticleEmitter.serialize(): ParticleEmitter is not in a world and cannot be serialized!");return D0.serializeParticleEmitter(this,this._world.tickAllocator)}}var VU=r(KV(),1);var nQ6={x:0,y:-32,z:0},Nm=60,jm;(($)=>{$.STEP_START="SIMULATION.STEP_START";$.STEP_END="SIMULATION.STEP_END";$.DEBUG_RAYCAST="SIMULATION.DEBUG_RAYCAST";$.DEBUG_RENDER="SIMULATION.DEBUG_RENDER"})(jm||={});class HU extends M0{_colliderMap=new oH;_debugRaycastingEnabled=!1;_debugRenderingEnabled=!1;_debugRenderingFilterFlags;_rapierEventQueue;_rapierSimulation;_world;constructor(Z,J=Nm,X=nQ6){super();this._rapierEventQueue=new VU.default.EventQueue(!0),this._rapierSimulation=new VU.default.World(X),this._rapierSimulation.timestep=Math.fround(1/J),this._world=Z}get colliderMap(){return this._colliderMap}get isDebugRaycastingEnabled(){return this._debugRaycastingEnabled}get isDebugRenderingEnabled(){return this._debugRenderingEnabled}get gravity(){return this._rapierSimulation.gravity}get timestepS(){return this._rapierSimulation.timestep}get world(){return this._world}createRawCollider(Z,J){return this._rapierSimulation.createCollider(Z,J)}createRawRigidBody(Z){return this._rapierSimulation.createRigidBody(Z)}enableDebugRaycasting(Z){this._debugRaycastingEnabled=Z}enableDebugRendering(Z,J=VU.default.QueryFilterFlags.EXCLUDE_FIXED){this._debugRenderingEnabled=Z,this._debugRenderingFilterFlags=J}getContactManifolds(Z,J){let X=[];return this._rapierSimulation.narrowPhase.contactPair(Z,J,(Y,$)=>{if(Y.numContacts()===0)return;let Q=Y.normal(),K=[];for(let W=0;W<Y.numSolverContacts();W++)K.push(Y.solverContactPoint(W));X.push({contactPoints:K,localNormalA:!$?Y.localNormal1():Y.localNormal2(),localNormalB:!$?Y.localNormal2():Y.localNormal1(),normal:!$?Q:{x:-Q.x,y:-Q.y,z:-Q.z}})}),X}intersectionsWithRawShape(Z,J,X,Y={}){let $=new Set,Q=[];return this._rapierSimulation.intersectionsWithShape(J,X,Z,(K)=>{let W=this._colliderMap.getColliderHandleBlockType(K.handle);if(W&&!$.has(W))return $.add(W),Q.push({intersectedBlockType:W}),!0;let G=this._colliderMap.getColliderHandleEntity(K.handle);if(G&&!$.has(G))return $.add(G),Q.push({intersectedEntity:G}),!0;return!0},Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate),Q}raycast(Z,J,X,Y={}){let $=new VU.default.Ray(Z,J),Q=this._rapierSimulation.castRay($,X,Y.solidMode??!0,Y.filterFlags,Y.filterGroups,Y.filterExcludeCollider,Y.filterExcludeRigidBody,Y.filterPredicate);if(this._debugRaycastingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RAYCAST",{simulation:this,origin:Z,direction:J,length:X,hit:!!Q});if(!Q)return null;let K=$.pointAt(Q.timeOfImpact),W=Q.timeOfImpact,G=Q.collider,V=this._colliderMap.getColliderHandleBlockType(G.handle);if(V)return{hitBlock:FK.fromGlobalCoordinate({x:Math.floor(K.x-($.dir.x<0?0.0001:-0.0001)),y:Math.floor(K.y-($.dir.y<0?0.0001:-0.0001)),z:Math.floor(K.z-($.dir.z<0?0.0001:-0.0001))},V),hitPoint:K,hitDistance:W};let H=this._colliderMap.getColliderHandleEntity(G.handle);if(H)return{hitEntity:H,hitPoint:K,hitDistance:W};return null}removeRawCollider(Z){this._colliderMap.queueColliderHandleForCleanup(Z.handle),this._rapierSimulation.removeCollider(Z,!1)}removeRawRigidBody(Z){this._rapierSimulation.removeRigidBody(Z)}setGravity(Z){this._rapierSimulation.gravity=Z}step=(Z)=>{this.emitWithWorld(this._world,"SIMULATION.STEP_START",{simulation:this,tickDeltaMs:Z});let J=performance.now();if(t1.startSpan({operation:"physics_step"},()=>{this._rapierSimulation.step(this._rapierEventQueue)}),t1.startSpan({operation:"physics_cleanup"},()=>{this._rapierEventQueue.drainContactForceEvents(this._onContactForceEvent),this._rapierEventQueue.drainCollisionEvents(this._onCollisionEvent),this._colliderMap.cleanup()}),this.emitWithWorld(this._world,"SIMULATION.STEP_END",{simulation:this,stepDurationMs:performance.now()-J}),this._debugRenderingEnabled)this.emitWithWorld(this._world,"SIMULATION.DEBUG_RENDER",{simulation:this,...this._rapierSimulation.debugRender(this._debugRenderingFilterFlags)})};_onCollisionEvent=(Z,J,X)=>{let[Y,$]=this._getCollisionObjects(Z,J);if(!Y||!$)return;let Q=(K,W)=>{if(K instanceof W9&&W instanceof n8&&K.hasListeners("BLOCK_TYPE.ENTITY_COLLISION"))K.emit("BLOCK_TYPE.ENTITY_COLLISION",{blockType:K,entity:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof n8&&W instanceof W9&&K.hasListeners("ENTITY.BLOCK_COLLISION"))K.emit("ENTITY.BLOCK_COLLISION",{entity:K,blockType:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(K instanceof n8&&W instanceof n8&&K.hasListeners("ENTITY.ENTITY_COLLISION"))K.emit("ENTITY.ENTITY_COLLISION",{entity:K,otherEntity:W,started:X,colliderHandleA:Z,colliderHandleB:J});else if(typeof K==="function"&&(W instanceof n8||W instanceof W9))K(W,X,Z,J)};Q(Y,$),Q($,Y)};_onContactForceEvent=(Z)=>{let[J,X]=this._getCollisionObjects(Z.collider1(),Z.collider2());if(!J||typeof J==="function"||!X||typeof X==="function")return;let Y={totalForce:Z.totalForce(),totalForceMagnitude:Z.totalForceMagnitude(),maxForceDirection:Z.maxForceDirection(),maxForceMagnitude:Z.maxForceMagnitude()},$=(Q,K)=>{if(Q instanceof W9&&K instanceof n8&&Q.hasListeners("BLOCK_TYPE.ENTITY_CONTACT_FORCE"))Q.emit("BLOCK_TYPE.ENTITY_CONTACT_FORCE",{blockType:Q,entity:K,contactForceData:Y});else if(Q instanceof n8&&K instanceof W9&&Q.hasListeners("ENTITY.BLOCK_CONTACT_FORCE"))Q.emit("ENTITY.BLOCK_CONTACT_FORCE",{entity:Q,blockType:K,contactForceData:Y});else if(Q instanceof n8&&K instanceof n8&&Q.hasListeners("ENTITY.ENTITY_CONTACT_FORCE"))Q.emit("ENTITY.ENTITY_CONTACT_FORCE",{entity:Q,otherEntity:K,contactForceData:Y})};$(J,X),$(X,J)};_getCollisionObjects(Z,J){let X=this._colliderMap.getColliderHandleBlockType(Z)??this._colliderMap.getColliderHandleCollisionCallback(Z)??this._colliderMap.getColliderHandleEntity(Z),Y=this._colliderMap.getColliderHandleBlockType(J)??this._colliderMap.getColliderHandleCollisionCallback(J)??this._colliderMap.getColliderHandleEntity(J);return[X,Y]}}class WD{_synchronizedPlayerReliablePackets=new F6;_queuedBroadcasts=[];_queuedAudioSynchronizations=new F6;_queuedBlockSynchronizations=new F6;_queuedBlockTypeSynchronizations=new F6;_queuedChunkSynchronizations=new F6;_queuedDebugRaycastSynchronizations=[];_queuedEntitySynchronizations=new F6;_queuedLightSynchronizations=new F6;_queuedParticleEmitterSynchronizations=new F6;_queuedPerPlayerSynchronizations=new F6;_queuedPerPlayerCameraSynchronizations=new F6;_queuedPerPlayerUISynchronizations=new F6;_queuedPerPlayerUIDatasSynchronizations=new F6;_queuedPlayerSynchronizations=new F6;_queuedSceneUISynchronizations=new F6;_queuedWorldSynchronization;_loadedSceneUIs=new Set;_spawnedChunks=new Set;_spawnedEntities=new Set;_world;constructor(Z){this._world=Z,this._subscribeToAudioEvents(),this._subscribeToBlockTypeRegistryEvents(),this._subscribeToChatEvents(),this._subscribeToChunkLatticeEvents(),this._subscribeToEntityEvents(),this._subscribeToLightEvents(),this._subscribeToParticleEmitterEvents(),this._subscribeToPlayerEvents(),this._subscribeToPlayerCameraEvents(),this._subscribeToPlayerUIEvents(),this._subscribeToSceneUIEvents(),this._subscribeToSimulationEvents(),this._subscribeToWorldEvents()}synchronize(){let Z=this._world.tickAllocator,J=this._world.tickAllocator.getArray(),X=this._world.tickAllocator.getArray(),Y=this._world.loop.currentTick;if(this._queuedPerPlayerSynchronizations.size>0)for(let[$,Q]of this._queuedPerPlayerSynchronizations)this._createOrGetSynchronizedPlayerReliablePackets($,J).push(...Q);if(this._queuedEntitySynchronizations.size>0){let $=this._world.tickAllocator.getArray(),Q=this._world.tickAllocator.getArray();for(let K of this._queuedEntitySynchronizations.valuesArray){let W=!1;for(let G in K)if(G!=="i"&&G!=="p"&&G!=="r"){W=!0;break}if(W)$.push(K);else Q.push(K)}if(Q.length>0){let K=Y0.createPacket(Y0.outboundPackets.entitiesPacketDefinition,Q,Y,Z.getArray());X.push(K)}if($.length>0){let K=Y0.createPacket(Y0.outboundPackets.entitiesPacketDefinition,$,Y,Z.getArray());J.push(K);for(let W of this._synchronizedPlayerReliablePackets.valuesArray)W.push(K)}}if(this._queuedAudioSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.audiosPacketDefinition,this._queuedAudioSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedBlockTypeSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.blockTypesPacketDefinition,this._queuedBlockTypeSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedChunkSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.chunksPacketDefinition,this._queuedChunkSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedBlockSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.blocksPacketDefinition,this._queuedBlockSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedLightSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.lightsPacketDefinition,this._queuedLightSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedParticleEmitterSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.particleEmittersPacketDefinition,this._queuedParticleEmitterSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedPerPlayerUISynchronizations.size>0)for(let[$,Q]of this._queuedPerPlayerUISynchronizations){let K=Y0.createPacket(Y0.outboundPackets.uiPacketDefinition,Q,Y,Z.getArray());this._createOrGetSynchronizedPlayerReliablePackets($,J).push(K)}if(this._queuedPerPlayerUIDatasSynchronizations.size>0)for(let[$,Q]of this._queuedPerPlayerUIDatasSynchronizations){let K=Y0.createPacket(Y0.outboundPackets.uiDatasPacketDefinition,Q,Y,Z.getArray());this._createOrGetSynchronizedPlayerReliablePackets($,J).push(K)}if(this._queuedSceneUISynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.sceneUIsPacketDefinition,this._queuedSceneUISynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedWorldSynchronization){let $=Y0.createPacket(Y0.outboundPackets.worldPacketDefinition,this._queuedWorldSynchronization,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedPerPlayerCameraSynchronizations.size>0)for(let[$,Q]of this._queuedPerPlayerCameraSynchronizations){let K=Y0.createPacket(Y0.outboundPackets.cameraPacketDefinition,Q,Y,Z.getArray());this._createOrGetSynchronizedPlayerReliablePackets($,J).push(K)}if(this._queuedPlayerSynchronizations.size>0){let $=Y0.createPacket(Y0.outboundPackets.playersPacketDefinition,this._queuedPlayerSynchronizations.valuesArray,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedBroadcasts.length>0)for(let $ of this._queuedBroadcasts){J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}if(this._queuedDebugRaycastSynchronizations.length>0){let $=Y0.createPacket(Y0.outboundPackets.physicsDebugRaycastsPacketDefinition,this._queuedDebugRaycastSynchronizations,Y,Z.getArray());J.push($);for(let Q of this._synchronizedPlayerReliablePackets.valuesArray)Q.push($)}t1.startSpan({operation:"send_all_packets"},()=>{for(let $ of U9.instance.getConnectedPlayersByWorld(this._world)){let Q=this._synchronizedPlayerReliablePackets.get($)??J;if(Q.length>0)$.connection.send(Q);if(X.length>0)$.connection.send(X,!1)}}),t1.startSpan({operation:"network_synchronize_cleanup"},()=>{if(this._queuedBroadcasts.length>0)this._queuedBroadcasts.length=0;if(this._queuedAudioSynchronizations.size>0)this._queuedAudioSynchronizations.clear();if(this._queuedBlockSynchronizations.size>0)this._queuedBlockSynchronizations.clear();if(this._queuedBlockTypeSynchronizations.size>0)this._queuedBlockTypeSynchronizations.clear();if(this._queuedChunkSynchronizations.size>0)this._queuedChunkSynchronizations.clear();if(this._queuedDebugRaycastSynchronizations.length>0)this._queuedDebugRaycastSynchronizations.length=0;if(this._queuedEntitySynchronizations.size>0)this._queuedEntitySynchronizations.clear();if(this._queuedLightSynchronizations.size>0)this._queuedLightSynchronizations.clear();if(this._queuedParticleEmitterSynchronizations.size>0)this._queuedParticleEmitterSynchronizations.clear();if(this._queuedPerPlayerSynchronizations.size>0)this._queuedPerPlayerSynchronizations.clear();if(this._queuedPerPlayerCameraSynchronizations.size>0)this._queuedPerPlayerCameraSynchronizations.clear();if(this._queuedPerPlayerUISynchronizations.size>0)this._queuedPerPlayerUISynchronizations.clear();if(this._queuedPerPlayerUIDatasSynchronizations.size>0)this._queuedPerPlayerUIDatasSynchronizations.clear();if(this._queuedPlayerSynchronizations.size>0)this._queuedPlayerSynchronizations.clear();if(this._queuedSceneUISynchronizations.size>0)this._queuedSceneUISynchronizations.clear();if(this._queuedWorldSynchronization)this._queuedWorldSynchronization=void 0;if(this._loadedSceneUIs.size>0)this._loadedSceneUIs.clear();if(this._spawnedChunks.size>0)this._spawnedChunks.clear();if(this._spawnedEntities.size>0)this._spawnedEntities.clear();if(this._synchronizedPlayerReliablePackets.size>0)this._synchronizedPlayerReliablePackets.clear();n4.clearCachedPacketsSerializedBuffers()})}_subscribeToAudioEvents(){this._world.final("AUDIO.PAUSE",this._onAudioPause),this._world.final("AUDIO.PLAY",this._onAudioPlay),this._world.final("AUDIO.PLAY_RESTART",this._onAudioPlayRestart),this._world.final("AUDIO.SET_ATTACHED_TO_ENTITY",this._onAudioSetAttachedToEntity),this._world.final("AUDIO.SET_CUTOFF_DISTANCE",this._onAudioSetCutoffDistance),this._world.final("AUDIO.SET_DETUNE",this._onAudioSetDetune),this._world.final("AUDIO.SET_DISTORTION",this._onAudioSetDistortion),this._world.final("AUDIO.SET_POSITION",this._onAudioSetPosition),this._world.final("AUDIO.SET_PLAYBACK_RATE",this._onAudioSetPlaybackRate),this._world.final("AUDIO.SET_REFERENCE_DISTANCE",this._onAudioSetReferenceDistance),this._world.final("AUDIO.SET_VOLUME",this._onAudioSetVolume)}_subscribeToBlockTypeRegistryEvents(){this._world.final("BLOCK_TYPE_REGISTRY.REGISTER_BLOCK_TYPE",this._onBlockTypeRegistryRegisterBlockType)}_subscribeToChatEvents(){this._world.final("CHAT.BROADCAST_MESSAGE",this._onChatSendBroadcastMessage),this._world.final("CHAT.PLAYER_MESSAGE",this._onChatSendPlayerMessage)}_subscribeToChunkLatticeEvents(){this._world.final("CHUNK_LATTICE.ADD_CHUNK",this._onChunkLatticeAddChunk),this._world.final("CHUNK_LATTICE.REMOVE_CHUNK",this._onChunkLatticeRemoveChunk),this._world.final("CHUNK_LATTICE.SET_BLOCK",this._onChunkLatticeSetBlock)}_subscribeToEntityEvents(){this._world.final("ENTITY.SPAWN",this._onEntitySpawn),this._world.final("ENTITY.DESPAWN",this._onEntityDespawn),this._world.final("ENTITY.SET_MODEL_ANIMATIONS_PLAYBACK_RATE",this._onEntitySetModelAnimationsPlaybackRate),this._world.final("ENTITY.SET_MODEL_HIDDEN_NODES",this._onEntitySetModelHiddenNodes),this._world.final("ENTITY.SET_MODEL_SCALE",this._onEntitySetModelScale),this._world.final("ENTITY.SET_MODEL_SHOWN_NODES",this._onEntitySetModelShownNodes),this._world.final("ENTITY.SET_MODEL_TEXTURE_URI",this._onEntitySetModelTextureUri),this._world.final("ENTITY.SET_OPACITY",this._onEntitySetOpacity),this._world.final("ENTITY.SET_PARENT",this._onEntitySetParent),this._world.final("ENTITY.SET_TINT_COLOR",this._onEntitySetTintColor),this._world.final("ENTITY.START_MODEL_LOOPED_ANIMATIONS",this._onEntityStartModelLoopedAnimations),this._world.final("ENTITY.START_MODEL_ONESHOT_ANIMATIONS",this._onEntityStartModelOneshotAnimations),this._world.final("ENTITY.STOP_MODEL_ANIMATIONS",this._onEntityStopModelAnimations),this._world.final("ENTITY.UPDATE_POSITION",this._onEntityUpdatePosition),this._world.final("ENTITY.UPDATE_ROTATION",this._onEntityUpdateRotation)}_subscribeToLightEvents(){this._world.final("LIGHT.DESPAWN",this._onLightDespawn),this._world.final("LIGHT.SET_ANGLE",this._onLightSetAngle),this._world.final("LIGHT.SET_ATTACHED_TO_ENTITY",this._onLightSetAttachedToEntity),this._world.final("LIGHT.SET_COLOR",this._onLightSetColor),this._world.final("LIGHT.SET_DISTANCE",this._onLightSetDistance),this._world.final("LIGHT.SET_INTENSITY",this._onLightSetIntensity),this._world.final("LIGHT.SET_OFFSET",this._onLightSetOffset),this._world.final("LIGHT.SET_PENUMBRA",this._onLightSetPenumbra),this._world.final("LIGHT.SET_POSITION",this._onLightSetPosition),this._world.final("LIGHT.SET_TRACKED_ENTITY",this._onLightSetTrackedEntity),this._world.final("LIGHT.SET_TRACKED_POSITION",this._onLightSetTrackedPosition),this._world.final("LIGHT.SPAWN",this._onLightSpawn)}_subscribeToParticleEmitterEvents(){this._world.final("PARTICLE_EMITTER.DESPAWN",this._onParticleEmitterDespawn),this._world.final("PARTICLE_EMITTER.BURST",this._onParticleEmitterBurst),this._world.final("PARTICLE_EMITTER.SET_ALPHA_TEST",this._onParticleEmitterSetAlphaTest),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY",this._onParticleEmitterSetAttachedToEntity),this._world.final("PARTICLE_EMITTER.SET_ATTACHED_TO_ENTITY_NODE_NAME",this._onParticleEmitterSetAttachedToEntityNodeName),this._world.final("PARTICLE_EMITTER.SET_COLOR_END",this._onParticleEmitterSetColorEnd),this._world.final("PARTICLE_EMITTER.SET_COLOR_END_VARIANCE",this._onParticleEmitterSetColorEndVariance),this._world.final("PARTICLE_EMITTER.SET_COLOR_START",this._onParticleEmitterSetColorStart),this._world.final("PARTICLE_EMITTER.SET_COLOR_START_VARIANCE",this._onParticleEmitterSetColorStartVariance),this._world.final("PARTICLE_EMITTER.SET_GRAVITY",this._onParticleEmitterSetGravity),this._world.final("PARTICLE_EMITTER.SET_LIFETIME",this._onParticleEmitterSetLifetime),this._world.final("PARTICLE_EMITTER.SET_LIFETIME_VARIANCE",this._onParticleEmitterSetLifetimeVariance),this._world.final("PARTICLE_EMITTER.SET_MAX_PARTICLES",this._onParticleEmitterSetMaxParticles),this._world.final("PARTICLE_EMITTER.SET_OFFSET",this._onParticleEmitterSetOffset),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END",this._onParticleEmitterSetOpacityEnd),this._world.final("PARTICLE_EMITTER.SET_OPACITY_END_VARIANCE",this._onParticleEmitterSetOpacityEndVariance),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START",this._onParticleEmitterSetOpacityStart),this._world.final("PARTICLE_EMITTER.SET_OPACITY_START_VARIANCE",this._onParticleEmitterSetOpacityStartVariance),this._world.final("PARTICLE_EMITTER.SET_PAUSED",this._onParticleEmitterSetPaused),this._world.final("PARTICLE_EMITTER.SET_POSITION",this._onParticleEmitterSetPosition),this._world.final("PARTICLE_EMITTER.SET_POSITION_VARIANCE",this._onParticleEmitterSetPositionVariance),this._world.final("PARTICLE_EMITTER.SET_RATE",this._onParticleEmitterSetRate),this._world.final("PARTICLE_EMITTER.SET_RATE_VARIANCE",this._onParticleEmitterSetRateVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_END",this._onParticleEmitterSetSizeEnd),this._world.final("PARTICLE_EMITTER.SET_SIZE_END_VARIANCE",this._onParticleEmitterSetSizeEndVariance),this._world.final("PARTICLE_EMITTER.SET_SIZE_START",this._onParticleEmitterSetSizeStart),this._world.final("PARTICLE_EMITTER.SET_SIZE_START_VARIANCE",this._onParticleEmitterSetSizeStartVariance),this._world.final("PARTICLE_EMITTER.SET_TEXTURE_URI",this._onParticleEmitterSetTextureUri),this._world.final("PARTICLE_EMITTER.SET_TRANSPARENT",this._onParticleEmitterSetTransparent),this._world.final("PARTICLE_EMITTER.SET_VELOCITY",this._onParticleEmitterSetVelocity),this._world.final("PARTICLE_EMITTER.SET_VELOCITY_VARIANCE",this._onParticleEmitterSetVelocityVariance),this._world.final("PARTICLE_EMITTER.SPAWN",this._onParticleEmitterSpawn)}_subscribeToPlayerEvents(){this._world.final("PLAYER.JOINED_WORLD",this._onPlayerJoinedWorld),this._world.final("PLAYER.LEFT_WORLD",this._onPlayerLeftWorld),this._world.final("PLAYER.RECONNECTED_WORLD",this._onPlayerReconnectedWorld),this._world.final("PLAYER.REQUEST_SYNC",this._onPlayerRequestSync)}_subscribeToPlayerCameraEvents(){this._world.final("PLAYER_CAMERA.LOOK_AT_ENTITY",this._onPlayerCameraLookAtEntity),this._world.final("PLAYER_CAMERA.LOOK_AT_POSITION",this._onPlayerCameraLookAtPosition),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_ENTITY",this._onPlayerCameraSetAttachedToEntity),this._world.final("PLAYER_CAMERA.SET_ATTACHED_TO_POSITION",this._onPlayerCameraSetAttachedToPosition),this._world.final("PLAYER_CAMERA.SET_FILM_OFFSET",this._onPlayerCameraSetFilmOffset),this._world.final("PLAYER_CAMERA.SET_FORWARD_OFFSET",this._onPlayerCameraSetForwardOffset),this._world.final("PLAYER_CAMERA.SET_FOV",this._onPlayerCameraSetFov),this._world.final("PLAYER_CAMERA.SET_MODEL_HIDDEN_NODES",this._onPlayerCameraSetModelHiddenNodes),this._world.final("PLAYER_CAMERA.SET_MODEL_SHOWN_NODES",this._onPlayerCameraSetModelShownNodes),this._world.final("PLAYER_CAMERA.SET_MODE",this._onPlayerCameraSetMode),this._world.final("PLAYER_CAMERA.SET_OFFSET",this._onPlayerCameraSetOffset),this._world.final("PLAYER_CAMERA.SET_SHOULDER_ANGLE",this._onPlayerCameraSetShoulderAngle),this._world.final("PLAYER_CAMERA.SET_TRACKED_ENTITY",this._onPlayerCameraSetTrackedEntity),this._world.final("PLAYER_CAMERA.SET_TRACKED_POSITION",this._onPlayerCameraSetTrackedPosition),this._world.final("PLAYER_CAMERA.SET_ZOOM",this._onPlayerCameraSetZoom)}_subscribeToPlayerUIEvents(){this._world.final("PLAYER_UI.LOAD",this._onPlayerUILoad),this._world.final("PLAYER_UI.LOCK_POINTER",this._onPlayerUILockPointer),this._world.final("PLAYER_UI.SEND_DATA",this._onPlayerUISendData)}_subscribeToSceneUIEvents(){this._world.final("SCENE_UI.LOAD",this._onSceneUILoad),this._world.final("SCENE_UI.SET_ATTACHED_TO_ENTITY",this._onSceneUISetAttachedToEntity),this._world.final("SCENE_UI.SET_OFFSET",this._onSceneUISetOffset),this._world.final("SCENE_UI.SET_POSITION",this._onSceneUISetPosition),this._world.final("SCENE_UI.SET_STATE",this._onSceneUISetState),this._world.final("SCENE_UI.SET_VIEW_DISTANCE",this._onSceneUISetViewDistance),this._world.final("SCENE_UI.UNLOAD",this._onSceneUIUnload)}_subscribeToSimulationEvents(){this._world.final("SIMULATION.DEBUG_RAYCAST",this._onSimulationDebugRaycast),this._world.final("SIMULATION.DEBUG_RENDER",this._onSimulationDebugRender)}_subscribeToWorldEvents(){this._world.final("WORLD.SET_AMBIENT_LIGHT_COLOR",this._onWorldSetAmbientLightColor),this._world.final("WORLD.SET_AMBIENT_LIGHT_INTENSITY",this._onWorldSetAmbientLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",this._onWorldSetDirectionalLightColor),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",this._onWorldSetDirectionalLightIntensity),this._world.final("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",this._onWorldSetDirectionalLightPosition),this._world.final("WORLD.SET_FOG_COLOR",this._onWorldSetFogColor),this._world.final("WORLD.SET_FOG_FAR",this._onWorldSetFogFar),this._world.final("WORLD.SET_FOG_NEAR",this._onWorldSetFogNear),this._world.final("WORLD.SET_SKYBOX_INTENSITY",this._onWorldSetSkyboxIntensity)}_onAudioPause=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.pa=!0,delete J.pl,delete J.r};_onAudioPlay=(Z)=>{let J=Z.audio.serialize();J.pl=!0,delete J.pa,delete J.r,this._queuedAudioSynchronizations.set(J.i,J)};_onAudioPlayRestart=(Z)=>{let J=Z.audio.serialize();J.r=!0,delete J.pa,delete J.pl,this._queuedAudioSynchronizations.set(J.i,J)};_onAudioSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onAudioSetCutoffDistance=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.cd=Z.cutoffDistance};_onAudioSetDetune=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.de=Z.detune};_onAudioSetDistortion=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.di=Z.distortion};_onAudioSetPosition=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.e=Z.position?void 0:J.e,J.p=Z.position?D0.serializeVector(Z.position,this._world.tickAllocator):void 0};_onAudioSetPlaybackRate=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.pr=Z.playbackRate};_onAudioSetReferenceDistance=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.rd=Z.referenceDistance};_onAudioSetVolume=(Z)=>{let J=this._createOrGetQueuedAudioSync(Z.audio);J.v=Z.volume};_onBlockTypeRegistryRegisterBlockType=(Z)=>{let J=Z.blockType.serialize();this._queuedBlockTypeSynchronizations.set(Z.blockType.id,J)};_onChatSendBroadcastMessage=(Z)=>{let J=this._world.tickAllocator,{player:X,message:Y,color:$}=Z,Q=J.getObject();Q.m=Y,Q.c=$,Q.p=X?.id;let K=J.getArray();K.push(Q),this._queuedBroadcasts.push(Y0.createPacket(Y0.outboundPackets.chatMessagesPacketDefinition,K,this._world.loop.currentTick,J.getArray()))};_onChatSendPlayerMessage=(Z)=>{let J=this._world.tickAllocator,{player:X,message:Y,color:$}=Z,Q=this._queuedPerPlayerSynchronizations.get(X)??[],K=J.getObject();K.m=Y,K.c=$;let W=J.getArray();W.push(K),Q.push(Y0.createPacket(Y0.outboundPackets.chatMessagesPacketDefinition,W,this._world.loop.currentTick,this._world.tickAllocator.getArray())),this._queuedPerPlayerSynchronizations.set(X,Q)};_onChunkLatticeAddChunk=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk);J.b=this._world.tickAllocator.getArray(Z.chunk.blocks),J.rm=void 0,this._spawnedChunks.add(J.c.join(","))};_onChunkLatticeRemoveChunk=(Z)=>{let J=this._createOrGetQueuedChunkSync(Z.chunk),X=J.c.join(",");if(this._spawnedChunks.has(X))this._queuedChunkSynchronizations.delete(X),this._spawnedChunks.delete(X);else J.rm=!0};_onChunkLatticeSetBlock=(Z)=>{let J=this._createOrGetQueuedBlockSync(Z.globalCoordinate);J.i=Z.blockTypeId};_onEntitySetModelAnimationsPlaybackRate=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.ap=Z.playbackRate};_onEntitySpawn=(Z)=>{let J=Z.entity.serialize();this._queuedEntitySynchronizations.set(J.i,J),this._spawnedEntities.add(J.i)};_onEntityDespawn=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);if(this._spawnedEntities.has(J.i))this._queuedEntitySynchronizations.delete(J.i),this._spawnedEntities.delete(J.i);else J.rm=!0};_onEntitySetModelHiddenNodes=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.h=this._world.tickAllocator.getArray(Z.modelHiddenNodes)};_onEntitySetModelScale=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.s=Z.modelScale};_onEntitySetModelShownNodes=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.sn=this._world.tickAllocator.getArray(Z.modelShownNodes)};_onEntitySetModelTextureUri=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.mt=Z.modelTextureUri};_onEntitySetOpacity=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.o=Z.opacity};_onEntitySetParent=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.pe=Z.parent?Z.parent.id:void 0,J.pn=Z.parentNodeName};_onEntitySetTintColor=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.t=Z.tintColor?D0.serializeRgbColor(Z.tintColor,this._world.tickAllocator):void 0};_onEntityStartModelLoopedAnimations=(Z)=>{let J=this._world.tickAllocator,X=this._createOrGetQueuedEntitySync(Z.entity),Y=J.getSet(X.al,Z.animations);if(X.al=J.getArray(Y),X.as){let $=J.getArray();for(let Q of X.as)!Y.has(Q)&&$.push(Q);X.as=$}};_onEntityStartModelOneshotAnimations=(Z)=>{let J=this._world.tickAllocator,X=this._createOrGetQueuedEntitySync(Z.entity),Y=J.getSet(X.ao,Z.animations);if(X.ao=J.getArray(Y),X.as){let $=J.getArray();for(let Q of X.as)!Y.has(Q)&&$.push(Q);X.as=$}};_onEntityStopModelAnimations=(Z)=>{let J=this._world.tickAllocator,X=this._createOrGetQueuedEntitySync(Z.entity);if(X.al){let Y=J.getSet(X.al);for(let $ of Z.animations)Y.delete($);X.al=J.getArray(Y)}if(X.ao){let Y=J.getSet(X.ao);for(let $ of Z.animations)Y.delete($);X.ao=J.getArray(Y)}X.as=J.getArray(J.getSet(X.as,Z.animations))};_onEntityUpdateRotation=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.r=D0.serializeQuaternion(Z.rotation,this._world.tickAllocator)};_onEntityUpdatePosition=(Z)=>{let J=this._createOrGetQueuedEntitySync(Z.entity);J.p=D0.serializeVector(Z.position,this._world.tickAllocator)};_onLightDespawn=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.rm=!0};_onLightSetAngle=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.a=Z.angle};_onLightSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onLightSetColor=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.c=D0.serializeRgbColor(Z.color,this._world.tickAllocator)};_onLightSetDistance=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.d=Z.distance};_onLightSetIntensity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.n=Z.intensity};_onLightSetOffset=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.o=Z.offset?D0.serializeVector(Z.offset,this._world.tickAllocator):void 0};_onLightSetPenumbra=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.pe=Z.penumbra};_onLightSetPosition=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.p=Z.position?D0.serializeVector(Z.position,this._world.tickAllocator):void 0,J.e=Z.position?void 0:J.e};_onLightSetTrackedEntity=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.te=Z.entity?Z.entity.id:void 0,J.tp=Z.entity?void 0:J.tp};_onLightSetTrackedPosition=(Z)=>{let J=this._createOrGetQueuedLightSync(Z.light);J.tp=Z.position?D0.serializeVector(Z.position,this._world.tickAllocator):void 0,J.te=Z.position?void 0:J.te};_onLightSpawn=(Z)=>{let J=Z.light.serialize();this._queuedLightSynchronizations.set(J.i,J)};_onParticleEmitterBurst=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.b=Z.count};_onParticleEmitterDespawn=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.rm=!0};_onParticleEmitterSetAlphaTest=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.at=Z.alphaTest};_onParticleEmitterSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onParticleEmitterSetAttachedToEntityNodeName=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.en=Z.attachedToEntityNodeName};_onParticleEmitterSetColorEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ce=Z.colorEnd?D0.serializeRgbColor(Z.colorEnd,this._world.tickAllocator):void 0};_onParticleEmitterSetColorEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.cev=Z.colorEndVariance?D0.serializeRgbColor(Z.colorEndVariance,this._world.tickAllocator):void 0};_onParticleEmitterSetColorStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.cs=Z.colorStart?D0.serializeRgbColor(Z.colorStart,this._world.tickAllocator):void 0};_onParticleEmitterSetColorStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.csv=Z.colorStartVariance?D0.serializeRgbColor(Z.colorStartVariance,this._world.tickAllocator):void 0};_onParticleEmitterSetGravity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.g=Z.gravity?D0.serializeVector(Z.gravity,this._world.tickAllocator):void 0};_onParticleEmitterSetLifetime=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.l=Z.lifetime};_onParticleEmitterSetLifetimeVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.lv=Z.lifetimeVariance};_onParticleEmitterSetMaxParticles=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.mp=Z.maxParticles};_onParticleEmitterSetOffset=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.o=Z.offset?D0.serializeVector(Z.offset,this._world.tickAllocator):void 0};_onParticleEmitterSetOpacityEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.oe=Z.opacityEnd};_onParticleEmitterSetOpacityEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.oev=Z.opacityEndVariance};_onParticleEmitterSetOpacityStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.os=Z.opacityStart};_onParticleEmitterSetOpacityStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.osv=Z.opacityStartVariance};_onParticleEmitterSetPaused=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.pa=Z.paused};_onParticleEmitterSetPosition=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.p=Z.position?D0.serializeVector(Z.position,this._world.tickAllocator):void 0,J.e=Z.position?void 0:J.e,J.en=Z.position?void 0:J.en};_onParticleEmitterSetPositionVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.pv=Z.positionVariance?D0.serializeVector(Z.positionVariance,this._world.tickAllocator):void 0};_onParticleEmitterSetRate=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.r=Z.rate};_onParticleEmitterSetRateVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.rv=Z.rateVariance};_onParticleEmitterSetSizeEnd=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.se=Z.sizeEnd};_onParticleEmitterSetSizeEndVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.sev=Z.sizeEndVariance};_onParticleEmitterSetSizeStart=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ss=Z.sizeStart};_onParticleEmitterSetSizeStartVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.ssv=Z.sizeStartVariance};_onParticleEmitterSetTextureUri=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.tu=Z.textureUri};_onParticleEmitterSetTransparent=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.t=Z.transparent};_onParticleEmitterSetVelocity=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.v=Z.velocity?D0.serializeVector(Z.velocity,this._world.tickAllocator):void 0};_onParticleEmitterSetVelocityVariance=(Z)=>{let J=this._createOrGetQueuedParticleEmitterSync(Z.particleEmitter);J.vv=Z.velocityVariance?D0.serializeVector(Z.velocityVariance,this._world.tickAllocator):void 0};_onParticleEmitterSpawn=(Z)=>{let J=Z.particleEmitter.serialize();this._queuedParticleEmitterSynchronizations.set(J.i,J)};_onPlayerCameraLookAtEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=D0.serializeVector(Z.entity.position,this._world.tickAllocator),delete J.et,delete J.pt};_onPlayerCameraLookAtPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pl=Z.position?D0.serializeVector(Z.position,this._world.tickAllocator):void 0,delete J.et,delete J.pt};_onPlayerCameraSetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.e=Z.entity.id,delete J.p};_onPlayerCameraSetAttachedToPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.p=Z.position?D0.serializeVector(Z.position,this._world.tickAllocator):void 0,delete J.e};_onPlayerCameraSetFilmOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.fo=Z.filmOffset};_onPlayerCameraSetForwardOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.ffo=Z.forwardOffset};_onPlayerCameraSetFov=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.fv=Z.fov};_onPlayerCameraSetModelHiddenNodes=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.h=this._world.tickAllocator.getArray(Z.modelHiddenNodes)};_onPlayerCameraSetModelShownNodes=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.s=this._world.tickAllocator.getArray(Z.modelShownNodes)};_onPlayerCameraSetMode=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.m=Z.mode};_onPlayerCameraSetOffset=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.o=Z.offset?D0.serializeVector(Z.offset,this._world.tickAllocator):void 0};_onPlayerCameraSetShoulderAngle=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.sa=Z.shoulderAngle};_onPlayerCameraSetTrackedEntity=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.et=Z.entity?Z.entity.id:void 0,delete J.pl,delete J.pt};_onPlayerCameraSetTrackedPosition=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.pt=Z.position?D0.serializeVector(Z.position,this._world.tickAllocator):void 0,delete J.et,delete J.pl};_onPlayerCameraSetZoom=(Z)=>{let J=this._createOrGetQueuedPlayerCameraSync(Z.playerCamera);J.z=Z.zoom};_onPlayerJoinedWorld=(Z)=>{let J=this._world.tickAllocator,{player:X}=Z,Y=this._queuedPerPlayerSynchronizations.get(X)??J.getArray();Y.push(Y0.createPacket(Y0.outboundPackets.worldPacketDefinition,this._world.serialize(),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.blockTypesPacketDefinition,this._world.blockTypeRegistry.serialize(),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.chunksPacketDefinition,J.map(this._world.chunkLattice.getAllChunks(!0),(Q)=>Q.serialize()),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.entitiesPacketDefinition,J.map(this._world.entityManager.getAllEntities(!0),(Q)=>{if(X.camera.attachedToEntity===void 0&&Q instanceof b7&&Q.player===X)X.camera.setAttachedToEntity(Q);return Q.serialize()}),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.audiosPacketDefinition,J.map(this._world.audioManager.getAllLoopedAudios(!0),(Q)=>Q.serialize()),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.lightsPacketDefinition,J.map(this._world.lightManager.getAllLights(!0),(Q)=>Q.serialize()),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.particleEmittersPacketDefinition,J.map(this._world.particleEmitterManager.getAllParticleEmitters(!0),(Q)=>Q.serialize()),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.sceneUIsPacketDefinition,J.map(this._world.sceneUIManager.getAllSceneUIs(!0),(Q)=>Q.serialize()),this._world.loop.currentTick,J.getArray())),Y.push(Y0.createPacket(Y0.outboundPackets.playersPacketDefinition,J.map(U9.instance.getConnectedPlayers(),(Q)=>Q.serialize()),this._world.loop.currentTick,J.getArray()));let $=this._createOrGetQueuedPlayerCameraSync(X.camera);this._queuedPerPlayerCameraSynchronizations.set(X,J.getObject(X.camera.serialize(),$)),this._queuedPerPlayerSynchronizations.set(X,Y),this._queuedPlayerSynchronizations.set(X.id,X.serialize())};_onPlayerLeftWorld=(Z)=>{let J=this._createOrGetQueuedPlayerSync(Z.player);J.rm=!0};_onPlayerReconnectedWorld=(Z)=>{this._onPlayerJoinedWorld(Z)};_onPlayerRequestSync=(Z)=>{let J=this._world.tickAllocator,X=J.getObject();X.r=Z.receivedAt,X.s=Date.now(),X.p=performance.now()-Z.receivedAtMs,X.n=this._world.loop.nextTickMs,Z.player.connection.send([Y0.createPacket(Y0.outboundPackets.syncResponsePacketDefinition,X,this._world.loop.currentTick,J.getArray())])};_onPlayerUILoad=(Z)=>{let J=this._createOrGetQueuedPlayerUISync(Z.playerUI);J.u=Z.htmlUri};_onPlayerUILockPointer=(Z)=>{let J=this._createOrGetQueuedPlayerUISync(Z.playerUI);J.p=Z.lock};_onPlayerUISendData=(Z)=>{this._createOrGetQueuedPlayerUIDatasSync(Z.playerUI).push(Z.data)};_onSceneUILoad=(Z)=>{let J=Z.sceneUI.serialize();this._queuedSceneUISynchronizations.set(J.i,J),this._loadedSceneUIs.add(J.i)};_onSceneUISetAttachedToEntity=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.e=Z.entity?Z.entity.id:void 0,J.p=Z.entity?void 0:J.p};_onSceneUISetOffset=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.o=Z.offset?D0.serializeVector(Z.offset,this._world.tickAllocator):void 0};_onSceneUISetPosition=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.p=Z.position?D0.serializeVector(Z.position,this._world.tickAllocator):void 0,J.e=Z.position?void 0:J.e};_onSceneUISetState=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.s=Z.state};_onSceneUISetViewDistance=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);J.v=Z.viewDistance};_onSceneUIUnload=(Z)=>{let J=this._createOrGetQueuedSceneUISync(Z.sceneUI);if(this._loadedSceneUIs.has(J.i))this._queuedSceneUISynchronizations.delete(J.i),this._loadedSceneUIs.delete(J.i);else J.rm=!0};_onSimulationDebugRaycast=(Z)=>{this._queuedDebugRaycastSynchronizations.push(D0.serializePhysicsDebugRaycast(Z,this._world.tickAllocator))};_onSimulationDebugRender=(Z)=>{this._queuedBroadcasts.push(Y0.createPacket(Y0.outboundPackets.physicsDebugRenderPacketDefinition,{v:Array.from(Z.vertices),c:Array.from(Z.colors)},this._world.loop.currentTick,this._world.tickAllocator.getArray()))};_onWorldSetAmbientLightColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ac=D0.serializeRgbColor(Z.color,this._world.tickAllocator)};_onWorldSetAmbientLightIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ai=Z.intensity};_onWorldSetDirectionalLightColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.dc=D0.serializeRgbColor(Z.color,this._world.tickAllocator)};_onWorldSetDirectionalLightIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.di=Z.intensity};_onWorldSetDirectionalLightPosition=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.dp=D0.serializeVector(Z.position,this._world.tickAllocator)};_onWorldSetFogColor=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.fc=D0.serializeRgbColor(Z.color,this._world.tickAllocator)};_onWorldSetFogFar=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.ff=Z.far};_onWorldSetFogNear=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.fn=Z.near};_onWorldSetSkyboxIntensity=(Z)=>{let J=this._createOrGetQueuedWorldSync(Z.world);J.si=Z.intensity};_createOrGetQueuedAudioSync(Z){if(Z.id===void 0)c.fatalError("NetworkSynchronizer._createOrGetQueuedAudioSync(): Audio has no id!");let J=this._queuedAudioSynchronizations.get(Z.id);if(!J)J=this._world.tickAllocator.getObject(),J.i=Z.id,this._queuedAudioSynchronizations.set(Z.id,J);return J}_createOrGetQueuedBlockSync(Z){let{x:J,y:X,z:Y}=Z,$=`${J},${X},${Y}`,Q=this._queuedBlockSynchronizations.get($);if(!Q)Q=this._world.tickAllocator.getObject(),Q.i=0,Q.c=[J,X,Y],this._queuedBlockSynchronizations.set($,Q);return Q}_createOrGetQueuedChunkSync(Z){if(!Z.originCoordinate)c.fatalError("NetworkSynchronizer._createOrGetQueuedChunkSync(): Chunk has no origin coordinate!");let{x:J,y:X,z:Y}=Z.originCoordinate,$=`${J},${X},${Y}`,Q=this._queuedChunkSynchronizations.get($);if(!Q)Q=this._world.tickAllocator.getObject(),Q.c=[J,X,Y],this._queuedChunkSynchronizations.set($,Q);return Q}_createOrGetQueuedEntitySync(Z){if(Z.id===void 0)c.fatalError("NetworkSynchronizer._createOrGetQueuedEntitySync(): Entity has no id!");let J=this._queuedEntitySynchronizations.get(Z.id);if(!J)J=this._world.tickAllocator.getObject(),J.i=Z.id,this._queuedEntitySynchronizations.set(Z.id,J);return J}_createOrGetQueuedLightSync(Z){if(Z.id===void 0)c.fatalError("NetworkSynchronizer._createOrGetQueuedLightSync(): Light has no id!");let J=this._queuedLightSynchronizations.get(Z.id);if(!J)J=this._world.tickAllocator.getObject(),J.i=Z.id,this._queuedLightSynchronizations.set(Z.id,J);return J}_createOrGetQueuedParticleEmitterSync(Z){if(Z.id===void 0)c.fatalError("NetworkSynchronizer._createOrGetQueuedParticleEmitterSync(): ParticleEmitter has no id!");let J=this._queuedParticleEmitterSynchronizations.get(Z.id);if(!J)J=this._world.tickAllocator.getObject(),J.i=Z.id,this._queuedParticleEmitterSynchronizations.set(Z.id,J);return J}_createOrGetQueuedPlayerSync(Z){if(Z.id===void 0)c.fatalError("NetworkSynchronizer._createOrGetQueuedPlayerSync(): Player has no id!");let J=this._queuedPlayerSynchronizations.get(Z.id);if(!J)J=this._world.tickAllocator.getObject(),J.i=Z.id,this._queuedPlayerSynchronizations.set(Z.id,J);return J}_createOrGetQueuedPlayerCameraSync(Z){let J=this._queuedPerPlayerCameraSynchronizations.get(Z.player);if(!J)J=this._world.tickAllocator.getObject(),this._queuedPerPlayerCameraSynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUISync(Z){let J=this._queuedPerPlayerUISynchronizations.get(Z.player);if(!J)J=this._world.tickAllocator.getObject(),this._queuedPerPlayerUISynchronizations.set(Z.player,J);return J}_createOrGetQueuedPlayerUIDatasSync(Z){let J=this._queuedPerPlayerUIDatasSynchronizations.get(Z.player);if(!J)J=this._world.tickAllocator.getArray(),this._queuedPerPlayerUIDatasSynchronizations.set(Z.player,J);return J}_createOrGetQueuedSceneUISync(Z){if(Z.id===void 0)c.fatalError("NetworkSynchronizer._createOrGetQueuedSceneUISync(): SceneUI has no id!");let J=this._queuedSceneUISynchronizations.get(Z.id);if(!J)J=this._world.tickAllocator.getObject(),J.i=Z.id,this._queuedSceneUISynchronizations.set(Z.id,J);return J}_createOrGetQueuedWorldSync(Z){if(Z.id!==this._world.id)c.fatalError("NetworkSynchronizer._createOrGetQueuedWorldSync(): World does not match this network synchronizer world!");return this._queuedWorldSynchronization??=this._world.tickAllocator.getObject(),this._queuedWorldSynchronization.i=Z.id,this._queuedWorldSynchronization}_createOrGetSynchronizedPlayerReliablePackets(Z,J){let X=this._synchronizedPlayerReliablePackets.get(Z);if(!X)X=this._world.tickAllocator.getArray(J),this._synchronizedPlayerReliablePackets.set(Z,X);return X}}class zU{_particleEmitters=new Map;_nextParticleEmitterId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}despawnEntityAttachedParticleEmitters(Z){this.getAllEntityAttachedParticleEmitters(Z).forEach((J)=>{J.despawn()})}getAllParticleEmitters(Z=!1){return Z?this._world.tickAllocator.getArray(this._particleEmitters.values()):Array.from(this._particleEmitters.values())}getAllEntityAttachedParticleEmitters(Z){return this.getAllParticleEmitters().filter((J)=>J.attachedToEntity===Z)}registerParticleEmitter(Z){if(Z.id!==void 0)return Z.id;let J=this._nextParticleEmitterId;return this._particleEmitters.set(J,Z),this._nextParticleEmitterId++,J}unregisterParticleEmitter(Z){if(Z.id===void 0)return;this._particleEmitters.delete(Z.id)}}class FU{_sceneUIs=new Map;_nextSceneUIId=1;_world;constructor(Z){this._world=Z}get world(){return this._world}getAllSceneUIs(Z=!1){return Z?this._world.tickAllocator.getArray(this._sceneUIs.values()):Array.from(this._sceneUIs.values())}getAllEntityAttachedSceneUIs(Z){return this.getAllSceneUIs().filter((J)=>J.attachedToEntity===Z)}getSceneUIById(Z){return this._sceneUIs.get(Z)}registerSceneUI(Z){if(Z.id!==void 0)return Z.id;let J=this._nextSceneUIId;return this._sceneUIs.set(J,Z),this._nextSceneUIId++,J}unloadEntityAttachedSceneUIs(Z){this.getAllEntityAttachedSceneUIs(Z).forEach((J)=>{J.unload()})}unregisterSceneUI(Z){if(Z.id===void 0)return;this._sceneUIs.delete(Z.id)}}class qU{_allocatedArrays=[];_allocatedArray3Numbers=[];_allocatedArray4Numbers=[];_allocatedObjects=[];_allocatedSets=[];_arrayPool=[];_array3NumberPool=[];_array4NumberPool=[];_objectPool=[];_setPool=[];filter(Z,J){let X=this.getArray();for(let Y=0;Y<Z.length;Y++)if(J(Z[Y],Y,Z))X.push(Z[Y]);return X}getArray(Z,J){let X=this._arrayPool.pop()??[];X.length=0;let Y=0;if(Z)for(let $ of Z)X[Y++]=$;if(J)for(let $ of J)X[Y++]=$;return this._allocatedArrays.push(X),X}getArray3Number(Z){let J=this._array3NumberPool.pop()??[0,0,0];if(J[0]=J[1]=J[2]=0,Z){let X=0;for(let Y of Z){if(X>=3)break;J[X++]=Y}}return this._allocatedArray3Numbers.push(J),J}getArray4Number(Z){let J=this._array4NumberPool.pop()??[0,0,0,0];if(J[0]=J[1]=J[2]=J[3]=0,Z){let X=0;for(let Y of Z){if(X>=4)break;J[X++]=Y}}return this._allocatedArray4Numbers.push(J),J}getObject(Z,J){let X=this._objectPool.pop()??Object.create(null);for(let Y in X)delete X[Y];if(Z)Object.assign(X,Z);if(J)Object.assign(X,J);return this._allocatedObjects.push(X),X}getSet(Z,J){let X=this._setPool.pop()??new Set;if(X.clear(),Z)for(let Y of Z)X.add(Y);if(J)for(let Y of J)X.add(Y);return this._allocatedSets.push(X),X}map(Z,J){let X=this.getArray();X.length=Z.length;for(let Y=0;Y<Z.length;Y++)X[Y]=J(Z[Y],Y,Z);return X}reset(){for(let Z=0;Z<this._allocatedArrays.length;Z++)if(this._arrayPool.length<4096)this._arrayPool.push(this._allocatedArrays[Z]);for(let Z=0;Z<this._allocatedArray3Numbers.length;Z++)if(this._array3NumberPool.length<4096)this._array3NumberPool.push(this._allocatedArray3Numbers[Z]);for(let Z=0;Z<this._allocatedArray4Numbers.length;Z++)if(this._array4NumberPool.length<4096)this._array4NumberPool.push(this._allocatedArray4Numbers[Z]);for(let Z=0;Z<this._allocatedObjects.length;Z++)if(this._objectPool.length<4096)this._objectPool.push(this._allocatedObjects[Z]);for(let Z=0;Z<this._allocatedSets.length;Z++)if(this._setPool.length<1024)this._setPool.push(this._allocatedSets[Z]);this._allocatedArrays.length=0,this._allocatedArray3Numbers.length=0,this._allocatedArray4Numbers.length=0,this._allocatedObjects.length=0,this._allocatedSets.length=0}}var aQ6=2,sQ6=3;class UU{_accumulatorMs=0;_targetTicksPerSecond;_fixedTimestepMs;_fixedTimestepS;_maxAccumulatorMs;_nextTickMs=0;_lastLoopTimeMs=0;_tickFunction;_tickErrorCallback;_tickHandle=null;constructor(Z,J,X){this._targetTicksPerSecond=Z,this._fixedTimestepS=Math.fround(1/Z),this._fixedTimestepMs=Math.fround(this._fixedTimestepS*1000),this._maxAccumulatorMs=this._fixedTimestepMs*sQ6,this._tickFunction=J,this._tickErrorCallback=X}get targetTicksPerSecond(){return this._targetTicksPerSecond}get fixedTimestepMs(){return this._fixedTimestepMs}get fixedTimestepS(){return this._fixedTimestepS}get isStarted(){return!!this._tickHandle}get nextTickMs(){return this._nextTickMs}start(){if(this._tickHandle)return;this._lastLoopTimeMs=performance.now();let Z=()=>{let J=performance.now(),X=J-this._lastLoopTimeMs;if(this._lastLoopTimeMs=J,this._accumulatorMs+=X,this._accumulatorMs>this._maxAccumulatorMs)this._accumulatorMs=this._maxAccumulatorMs;if(this._accumulatorMs>=this._fixedTimestepMs)t1.startSpan({operation:"ticker_tick"},()=>{let Y=0;while(this._accumulatorMs>=this._fixedTimestepMs&&Y<aQ6)this._tick(this._fixedTimestepMs),this._accumulatorMs-=this._fixedTimestepMs,Y++});this._nextTickMs=Math.max(0,this._fixedTimestepMs-this._accumulatorMs),this._tickHandle=setTimeout(Z,this._nextTickMs)};Z()}stop(){if(!this._tickHandle)return;clearTimeout(this._tickHandle),this._tickHandle=null}_tick(Z){try{this._tickFunction(Z)}catch(J){if(J instanceof Error&&this._tickErrorCallback)this._tickErrorCallback(J);else c.warning(`Ticker._tick(): tick callback threw an error, but it was not an instance of Error. Error: ${J}`)}}}var E31;((Q)=>{Q.START="WORLD_LOOP.START";Q.STOP="WORLD_LOOP.STOP";Q.TICK_START="WORLD_LOOP.TICK_START";Q.TICK_END="WORLD_LOOP.TICK_END";Q.TICK_ERROR="WORLD_LOOP.TICK_ERROR"})(E31||={});class LU extends M0{_currentTick=0;_ticker;_world;constructor(Z,J=Nm){super();this._ticker=new UU(J,this._tick,this._onTickError),this._world=Z}get currentTick(){return this._currentTick}get isStarted(){return this._ticker.isStarted}get nextTickMs(){return this._ticker.nextTickMs}get timestepS(){return this._ticker.fixedTimestepS}get world(){return this._world}start(){this._ticker.start(),this.emitWithWorld(this._world,"WORLD_LOOP.START",{worldLoop:this})}stop(){this._ticker.stop(),this.emitWithWorld(this._world,"WORLD_LOOP.STOP",{worldLoop:this})}_tick=(Z)=>{this.emitWithWorld(this._world,"WORLD_LOOP.TICK_START",{worldLoop:this,tickDeltaMs:Z});let J=performance.now();t1.startSpan({operation:"world_tick",attributes:{serverPlayerCount:U9.instance.playerCount,targetTickRate:this._ticker.targetTicksPerSecond,targetTickRateMs:this._ticker.fixedTimestepMs,worldId:this._world.id,worldName:this._world.name,worldChunkCount:this._world.chunkLattice.chunkCount,worldEntityCount:this._world.entityManager.entityCount,worldLoopTick:this._currentTick}},()=>{t1.startSpan({operation:"entities_tick"},()=>this._world.entityManager.tickEntities(Z)),t1.startSpan({operation:"simulation_step"},()=>this._world.simulation.step(Z)),t1.startSpan({operation:"entities_emit_updates"},()=>this._world.entityManager.checkAndEmitUpdates()),t1.startSpan({operation:"network_synchronize"},()=>this._world.networkSynchronizer.synchronize()),t1.startSpan({operation:"release_tick_allocation"},()=>this._world.tickAllocator.reset())}),this._currentTick++,this.emitWithWorld(this._world,"WORLD_LOOP.TICK_END",{worldLoop:this,tickDurationMs:performance.now()-J})};_onTickError=(Z)=>{c.error(`WorldLoop._onTickError(): Error: ${Z}`),this.emitWithWorld(this._world,"WORLD_LOOP.TICK_ERROR",{worldLoop:this,error:Z})}}var Dm;((F)=>{F.SET_AMBIENT_LIGHT_COLOR="WORLD.SET_AMBIENT_LIGHT_COLOR";F.SET_AMBIENT_LIGHT_INTENSITY="WORLD.SET_AMBIENT_LIGHT_INTENSITY";F.SET_DIRECTIONAL_LIGHT_COLOR="WORLD.SET_DIRECTIONAL_LIGHT_COLOR";F.SET_DIRECTIONAL_LIGHT_INTENSITY="WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY";F.SET_DIRECTIONAL_LIGHT_POSITION="WORLD.SET_DIRECTIONAL_LIGHT_POSITION";F.SET_FOG_COLOR="WORLD.SET_FOG_COLOR";F.SET_FOG_FAR="WORLD.SET_FOG_FAR";F.SET_FOG_NEAR="WORLD.SET_FOG_NEAR";F.SET_SKYBOX_INTENSITY="WORLD.SET_SKYBOX_INTENSITY";F.START="WORLD.START";F.STOP="WORLD.STOP"})(Dm||={});class BU extends M0{_id;_ambientLightColor;_ambientLightIntensity;_audioManager;_blockTypeRegistry;_chatManager;_chunkLattice;_directionalLightColor;_directionalLightIntensity;_directionalLightPosition;_entityManager;_fogColor;_fogFar;_fogNear;_lightManager;_loop;_name;_networkSynchronizer;_particleEmitterManager;_sceneUIManager;_simulation;_skyboxIntensity;_skyboxUri;_tag;_tickAllocator;constructor(Z){super();if(this._id=Z.id,this._ambientLightColor=Z.ambientLightColor??{r:255,g:255,b:255},this._ambientLightIntensity=Z.ambientLightIntensity??1,this._directionalLightColor=Z.directionalLightColor??{r:255,g:255,b:255},this._directionalLightIntensity=Z.directionalLightIntensity??3,this._directionalLightPosition=Z.directionalLightPosition??{x:100,y:150,z:100},this._fogColor=Z.fogColor,this._fogFar=Z.fogFar??550,this._fogNear=Z.fogNear??500,this._name=Z.name,this._skyboxIntensity=Z.skyboxIntensity??1,this._skyboxUri=Z.skyboxUri,this._tag=Z.tag,this._audioManager=new P3(this),this._blockTypeRegistry=new OH(this),this._chatManager=new aH(this),this._chunkLattice=new sH(this),this._entityManager=new eH(this),this._lightManager=new GU(this),this._loop=new LU(this,Z.tickRate),this._networkSynchronizer=new WD(this),this._particleEmitterManager=new zU(this),this._sceneUIManager=new FU(this),this._simulation=new HU(this,Z.tickRate,Z.gravity),this._tickAllocator=new qU,Z.map)this.loadMap(Z.map)}get id(){return this._id}get ambientLightColor(){return this._ambientLightColor}get ambientLightIntensity(){return this._ambientLightIntensity}get blockTypeRegistry(){return this._blockTypeRegistry}get chatManager(){return this._chatManager}get chunkLattice(){return this._chunkLattice}get directionalLightColor(){return this._directionalLightColor}get directionalLightIntensity(){return this._directionalLightIntensity}get directionalLightPosition(){return this._directionalLightPosition}get entityManager(){return this._entityManager}get fogColor(){return this._fogColor}get fogFar(){return this._fogFar}get fogNear(){return this._fogNear}get lightManager(){return this._lightManager}get loop(){return this._loop}get name(){return this._name}get networkSynchronizer(){return this._networkSynchronizer}get particleEmitterManager(){return this._particleEmitterManager}get sceneUIManager(){return this._sceneUIManager}get simulation(){return this._simulation}get skyboxIntensity(){return this._skyboxIntensity}get skyboxUri(){return this._skyboxUri}get audioManager(){return this._audioManager}get tag(){return this._tag}get tickAllocator(){return this._tickAllocator}loadMap(Z){if(this.chunkLattice.clear(),Z.blockTypes)for(let J of Z.blockTypes)this.blockTypeRegistry.registerGenericBlockType({id:J.id,isLiquid:J.isLiquid,name:J.name,textureUri:J.textureUri});if(Z.blocks)for(let[J,X]of Object.entries(Z.blocks)){let[Y,$,Q]=J.split(",").map(Number);this.chunkLattice.setBlock({x:Y,y:$,z:Q},X)}if(Z.entities)for(let[J,X]of Object.entries(Z.entities)){let[Y,$,Q]=J.split(",").map(Number);new n8({isEnvironmental:!0,...X}).spawn(this,{x:Y,y:$,z:Q})}}setAmbientLightColor(Z){this._ambientLightColor=Z,this.emit("WORLD.SET_AMBIENT_LIGHT_COLOR",{world:this,color:Z})}setAmbientLightIntensity(Z){this._ambientLightIntensity=Z,this.emit("WORLD.SET_AMBIENT_LIGHT_INTENSITY",{world:this,intensity:Z})}setDirectionalLightColor(Z){this._directionalLightColor=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_COLOR",{world:this,color:Z})}setDirectionalLightIntensity(Z){this._directionalLightIntensity=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_INTENSITY",{world:this,intensity:Z})}setDirectionalLightPosition(Z){this._directionalLightPosition=Z,this.emit("WORLD.SET_DIRECTIONAL_LIGHT_POSITION",{world:this,position:Z})}setFogColor(Z){this._fogColor=Z,this.emit("WORLD.SET_FOG_COLOR",{world:this,color:Z})}setFogFar(Z){this._fogFar=Z,this.emit("WORLD.SET_FOG_FAR",{world:this,far:Z})}setFogNear(Z){this._fogNear=Z,this.emit("WORLD.SET_FOG_NEAR",{world:this,near:Z})}setSkyboxIntensity(Z){this._skyboxIntensity=Z,this.emit("WORLD.SET_SKYBOX_INTENSITY",{world:this,intensity:Z})}start(){if(this._loop.isStarted)return;this._loop.start(),this.emit("WORLD.START",{world:this,startedAtMs:Date.now()})}stop(){if(!this._loop.isStarted)return;this._loop.stop(),this.emit("WORLD.STOP",{world:this,stoppedAtMs:Date.now()})}serialize(){return D0.serializeWorld(this,this._tickAllocator)}}var I31;((J)=>J.WORLD_CREATED="WORLD_MANAGER.WORLD_CREATED")(I31||={});class IY{static instance=new IY;_defaultWorld;_nextWorldId=1;_worlds=new Map;createWorld(Z){let J=new BU({...Z,id:this._nextWorldId++});return J.start(),this._worlds.set(J.id,J),M0.globalInstance.emit("WORLD_MANAGER.WORLD_CREATED",{world:J}),J}getAllWorlds(){return Array.from(this._worlds.values())}getDefaultWorld(){return this._defaultWorld??=this.createWorld({name:"Default World",skyboxUri:"skyboxes/partly-cloudy"}),this._defaultWorld}getWorldsByTag(Z){let J=[];return this._worlds.forEach((X)=>{if(X.tag===Z)J.push(X)}),J}getWorld(Z){return this._worlds.get(Z)}setDefaultWorld(Z){this._defaultWorld=Z}}var k31;((Y)=>{Y.PLAYER_CONNECTED="PLAYER_MANAGER.PLAYER_CONNECTED";Y.PLAYER_DISCONNECTED="PLAYER_MANAGER.PLAYER_DISCONNECTED";Y.PLAYER_RECONNECTED="PLAYER_MANAGER.PLAYER_RECONNECTED"})(k31||={});class U9{static instance=new U9;worldSelectionHandler;_connectionPlayers=new Map;constructor(){M0.globalInstance.on("CONNECTION.OPENED",({connection:Z,req:J})=>{this._onConnectionOpened(Z,J.session)}),M0.globalInstance.on("CONNECTION.DISCONNECTED",({connection:Z})=>{this._onConnectionDisconnected(Z)}),M0.globalInstance.on("CONNECTION.RECONNECTED",({connection:Z})=>{this._onConnectionReconnected(Z)}),M0.globalInstance.on("CONNECTION.CLOSED",({connection:Z})=>{this._onConnectionClosed(Z)})}get playerCount(){return this._connectionPlayers.size}getConnectedPlayers(){return Array.from(this._connectionPlayers.values())}getConnectedPlayersByWorld(Z){return this.getConnectedPlayers().filter((J)=>J.world===Z)}getConnectedPlayerByUsername(Z){return Array.from(this._connectionPlayers.values()).find((J)=>{return J.username.toLowerCase()===Z.toLowerCase()})}async _onConnectionOpened(Z,J){let X=new CW(Z,J);await X.loadInitialPersistedData(),this._connectionPlayers.set(Z,X),M0.globalInstance.emit("PLAYER_MANAGER.PLAYER_CONNECTED",{player:X});let Y=await this.worldSelectionHandler?.(X);X.joinWorld(Y??IY.instance.getDefaultWorld())}_onConnectionDisconnected(Z){let J=this._connectionPlayers.get(Z);if(J)J.resetInputs(),J.camera.reset()}_onConnectionReconnected(Z){let J=this._connectionPlayers.get(Z);if(J)J.reconnected(),M0.globalInstance.emit("PLAYER_MANAGER.PLAYER_RECONNECTED",{player:J});else c.warning(`PlayerManager._onConnectionReconnected(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}_onConnectionClosed(Z){let J=this._connectionPlayers.get(Z);if(J)J.disconnect(),this._connectionPlayers.delete(Z),M0.globalInstance.emit("PLAYER_MANAGER.PLAYER_DISCONNECTED",{player:J});else c.warning(`PlayerManager._onConnectionClosed(): Connection ${Z.id} not in the PlayerManager._connectionPlayers map.`)}}Buffer.poolSize=134217728;var v31;((X)=>{X.START="GAMESERVER.START";X.STOP="GAMESERVER.STOP"})(v31||={});function oQ6(Z){_31.default.init().then(()=>{return $K.instance.modelRegistry.preloadModels()}).then(()=>{if(Z.length>0)Z($K.instance.worldManager.getDefaultWorld());else Z();$K.instance.start()}).catch((J)=>{c.fatalError(`Failed to initialize the game engine, exiting. Error: ${J}`)})}class $K{static _instance;_modelRegistry=S5.instance;_playerManager=U9.instance;_socket=s7.instance;_worldManager=IY.instance;_webServer=FG.instance;constructor(){}static get instance(){if(!this._instance)this._instance=new $K;return this._instance}get modelRegistry(){return this._modelRegistry}get playerManager(){return this._playerManager}get socket(){return this._socket}get webServer(){return this._webServer}get worldManager(){return this._worldManager}start(){M0.globalInstance.emit("GAMESERVER.START",{startedAtMs:performance.now()}),this._webServer.start()}}var q6=r(WK(),1);class GK extends Float32Array{constructor(Z,J,X,Y){super([Z,J,X,Y])}get determinant(){return q6.mat2.determinant(this)}get frobeniusNorm(){return q6.mat2.frob(this)}static create(){let Z=new GK(0,0,0,0);return q6.mat2.identity(Z),Z}static fromRotation(Z){let J=GK.create();return q6.mat2.fromRotation(J,Z),J}static fromScaling(Z){let J=GK.create();return q6.mat2.fromScaling(J,Z),J}add(Z){return q6.mat2.add(this,this,Z),this}adjoint(){return q6.mat2.adjoint(this,this),this}clone(){return new GK(this[0],this[1],this[2],this[3])}copy(Z){return q6.mat2.copy(this,Z),this}equals(Z){return q6.mat2.equals(this,Z)}exactEquals(Z){return q6.mat2.exactEquals(this,Z)}identity(){return q6.mat2.identity(this),this}invert(){return q6.mat2.invert(this,this),this}multiply(Z){return q6.mat2.mul(this,this,Z),this}multiplyScalar(Z){return q6.mat2.multiplyScalar(this,this,Z),this}rotate(Z){return q6.mat2.rotate(this,this,Z),this}subtract(Z){return q6.mat2.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]}][${this[2]},${this[3]}]`}transpose(){return q6.mat2.transpose(this,this),this}}var j8=r(WK(),1);class LZ extends Float32Array{constructor(Z,J,X,Y,$,Q,K,W,G){super([Z,J,X,Y,$,Q,K,W,G])}get determinant(){return j8.mat3.determinant(this)}get frobeniusNorm(){return j8.mat3.frob(this)}static create(){let Z=new LZ(0,0,0,0,0,0,0,0,0);return j8.mat3.identity(Z),Z}static fromMatrix4(Z){let J=LZ.create();return j8.mat3.fromMat4(J,Z),J}static fromQuaternion(Z){let J=LZ.create();return j8.mat3.fromQuat(J,Z),J}static fromRotation(Z){let J=LZ.create();return j8.mat3.fromRotation(J,Z),J}static fromScaling(Z){let J=LZ.create();return j8.mat3.fromScaling(J,Z),J}static fromTranslation(Z){let J=LZ.create();return j8.mat3.fromTranslation(J,Z),J}add(Z){return j8.mat3.add(this,this,Z),this}adjoint(){return j8.mat3.adjoint(this,this),this}clone(){return new LZ(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8])}copy(Z){return j8.mat3.copy(this,Z),this}equals(Z){return j8.mat3.equals(this,Z)}exactEquals(Z){return j8.mat3.exactEquals(this,Z)}identity(){return j8.mat3.identity(this),this}invert(){return j8.mat3.invert(this,this),this}multiply(Z){return j8.mat3.mul(this,this,Z),this}multiplyScalar(Z){return j8.mat3.multiplyScalar(this,this,Z),this}transformVector(Z){return Z.transformMatrix3(this)}projection(Z,J){return j8.mat3.projection(this,Z,J),this}rotate(Z){return j8.mat3.rotate(this,this,Z),this}subtract(Z){return j8.mat3.sub(this,this,Z),this}toString(){return`[${this[0]},${this[1]},${this[2]}][${this[3]},${this[4]},${this[5]}][${this[6]},${this[7]},${this[8]}]`}transpose(){return j8.mat3.transpose(this,this),this}}var Y1=r(WK(),1);class P5 extends Float32Array{constructor(Z,J,X,Y,$,Q,K,W,G,V,H,F,z,q,U,B){super([Z,J,X,Y,$,Q,K,W,G,V,H,F,z,q,U,B])}get determinant(){return Y1.mat4.determinant(this)}get frobeniusNorm(){return Y1.mat4.frob(this)}static create(){let Z=new P5(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);return Y1.mat4.identity(Z),Z}static fromQuaternion(Z){let J=P5.create();return Y1.mat4.fromQuat(J,Z),J}static fromRotation(Z,J){let X=P5.create();return Y1.mat4.fromRotation(X,Z,J),X}static fromRotationTranslation(Z,J){let X=P5.create();return Y1.mat4.fromRotationTranslation(X,Z,J),X}static fromRotationTranslationScale(Z,J,X){let Y=P5.create();return Y1.mat4.fromRotationTranslationScale(Y,Z,J,X),Y}static fromRotationTranslationScaleOrigin(Z,J,X,Y){let $=P5.create();return Y1.mat4.fromRotationTranslationScaleOrigin($,Z,J,X,Y),$}static fromScaling(Z){let J=P5.create();return Y1.mat4.fromScaling(J,Z),J}static fromTranslation(Z){let J=P5.create();return Y1.mat4.fromTranslation(J,Z),J}static fromXRotation(Z){let J=P5.create();return Y1.mat4.fromXRotation(J,Z),J}static fromYRotation(Z){let J=P5.create();return Y1.mat4.fromYRotation(J,Z),J}static fromZRotation(Z){let J=P5.create();return Y1.mat4.fromZRotation(J,Z),J}add(Z){return Y1.mat4.add(this,this,Z),this}adjoint(){return Y1.mat4.adjoint(this,this),this}clone(){return new P5(this[0],this[1],this[2],this[3],this[4],this[5],this[6],this[7],this[8],this[9],this[10],this[11],this[12],this[13],this[14],this[15])}copy(Z){return Y1.mat4.copy(this,Z),this}equals(Z){return Y1.mat4.equals(this,Z)}exactEquals(Z){return Y1.mat4.exactEquals(this,Z)}frustrum(Z,J,X,Y,$,Q){return Y1.mat4.frustum(this,Z,J,X,Y,$,Q),this}identity(){return Y1.mat4.identity(this),this}invert(){return Y1.mat4.invert(this,this),this}lookAt(Z,J,X){return Y1.mat4.lookAt(this,Z,J,X),this}multiply(Z){return Y1.mat4.mul(this,this,Z),this}multiplyScalar(Z){return Y1.mat4.multiplyScalar(this,this,Z),this}orthographic(Z,J,X,Y,$,Q){return Y1.mat4.ortho(this,Z,J,X,Y,$,Q),this}perspective(Z,J,X,Y){return Y1.mat4.perspective(this,Z,J,X,Y),this}rotate(Z,J){return Y1.mat4.rotate(this,this,Z,J),this}rotateX(Z){return Y1.mat4.rotateX(this,this,Z),this}rotateY(Z){return Y1.mat4.rotateY(this,this,Z),this}rotateZ(Z){return Y1.mat4.rotateZ(this,this,Z),this}scale(Z){return Y1.mat4.scale(this,this,Z),this}subtract(Z){return Y1.mat4.sub(this,this,Z),this}targetTo(Z,J,X){return Y1.mat4.targetTo(this,Z,J,X),this}toString(){return`[${this[0]},${this[1]},${this[2]},${this[3]}][${this[4]},${this[5]},${this[6]},${this[7]}][${this[8]},${this[9]},${this[10]},${this[11]}][${this[12]},${this[13]},${this[14]},${this[15]}]`}translate(Z){return Y1.mat4.translate(this,this,Z),this}transpose(){return Y1.mat4.transpose(this,this),this}}var y1=r(WK(),1);class R3 extends Float32Array{constructor(Z,J,X,Y){super([Z,J,X,Y])}get length(){return y1.quat.length(this)}get squaredLength(){return y1.quat.squaredLength(this)}get magnitude(){return y1.quat.length(this)}get squaredMagnitude(){return y1.quat.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}get z(){return this[2]}set z(Z){this[2]=Z}get w(){return this[3]}set w(Z){this[3]=Z}static fromEuler(Z,J,X){let Y=y1.quat.fromEuler(new Float32Array(4),Z,J,X);return new R3(Y[0],Y[1],Y[2],Y[3])}static fromQuaternionLike(Z){return new R3(Z.x,Z.y,Z.z,Z.w)}clone(){return new R3(this.x,this.y,this.z,this.w)}conjugate(){return y1.quat.conjugate(this,this),this}copy(Z){return y1.quat.copy(this,Z),this}dot(Z){return y1.quat.dot(this,Z)}exponential(){return y1.quat.exp(this,this),this}equals(Z){return y1.quat.equals(this,Z)}exactEquals(Z){return y1.quat.exactEquals(this,Z)}getAngle(Z){return y1.quat.getAngle(this,Z)}identity(){return y1.quat.identity(this),this}invert(){return y1.quat.invert(this,this),this}lerp(Z,J){return y1.quat.lerp(this,this,Z,J),this}logarithm(){return y1.quat.ln(this,this),this}multiply(Z){return y1.quat.multiply(this,this,Z),this}transformVector(Z){return Z.transformQuaternion(this)}normalize(){return y1.quat.normalize(this,this),this}power(Z){return y1.quat.pow(this,this,Z),this}randomize(){return y1.quat.random(this),this}rotateX(Z){return y1.quat.rotateX(this,this,Z),this}rotateY(Z){return y1.quat.rotateY(this,this,Z),this}rotateZ(Z){return y1.quat.rotateZ(this,this,Z),this}scale(Z){return y1.quat.scale(this,this,Z),this}setAxisAngle(Z,J){return y1.quat.setAxisAngle(this,Z,J),this}slerp(Z,J){return y1.quat.slerp(this,this,Z,J),this}toString(){return`${this.x},${this.y},${this.z},${this.w}`}}var U1=r(WK(),1);class wU extends Float32Array{constructor(Z,J){super([Z,J])}get length(){return U1.vec2.length(this)}get squaredLength(){return U1.vec2.squaredLength(this)}get magnitude(){return U1.vec2.length(this)}get squaredMagnitude(){return U1.vec2.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}static create(){return new wU(0,0)}add(Z){return U1.vec2.add(this,this,Z),this}angle(Z){return U1.vec2.angle(this,Z)}ceil(){return U1.vec2.ceil(this,this),this}clone(){return new wU(this.x,this.y)}copy(Z){return U1.vec2.copy(this,Z),this}distance(Z){return U1.vec2.distance(this,Z)}divide(Z){return U1.vec2.divide(this,this,Z),this}dot(Z){return U1.vec2.dot(this,Z)}equals(Z){return U1.vec2.equals(this,Z)}exactEquals(Z){return U1.vec2.exactEquals(this,Z)}floor(){return U1.vec2.floor(this,this),this}invert(){return U1.vec2.inverse(this,this),this}lerp(Z,J){return U1.vec2.lerp(this,this,Z,J),this}max(Z){return U1.vec2.max(this,this,Z),this}min(Z){return U1.vec2.min(this,this,Z),this}multiply(Z){return U1.vec2.mul(this,this,Z),this}negate(){return U1.vec2.negate(this,this),this}normalize(){return U1.vec2.normalize(this,this),this}randomize(Z){return U1.vec2.random(this,Z),this}rotate(Z,J){return U1.vec2.rotate(this,this,Z,J),this}round(){return U1.vec2.round(this,this),this}scale(Z){return U1.vec2.scale(this,this,Z),this}scaleAndAdd(Z,J){return U1.vec2.scaleAndAdd(this,this,Z,J),this}subtract(Z){return U1.vec2.sub(this,this,Z),this}toString(){return`${this.x},${this.y}`}transformMatrix2(Z){return U1.vec2.transformMat2(this,this,Z),this}transformMatrix3(Z){return U1.vec2.transformMat3(this,this,Z),this}transformMatrix4(Z){return U1.vec2.transformMat4(this,this,Z),this}zero(){return U1.vec2.zero(this),this}}var z1=r(WK(),1);class N3 extends Float32Array{constructor(Z,J,X){super([Z,J,X])}get length(){return z1.vec3.length(this)}get squaredLength(){return z1.vec3.squaredLength(this)}get magnitude(){return z1.vec3.length(this)}get squaredMagnitude(){return z1.vec3.squaredLength(this)}get x(){return this[0]}set x(Z){this[0]=Z}get y(){return this[1]}set y(Z){this[1]=Z}get z(){return this[2]}set z(Z){this[2]=Z}static create(){return new N3(0,0,0)}static fromVector3Like(Z){return new N3(Z.x,Z.y,Z.z)}add(Z){return z1.vec3.add(this,this,Z),this}ceil(){return z1.vec3.ceil(this,this),this}clone(){return new N3(this.x,this.y,this.z)}copy(Z){return z1.vec3.copy(this,Z),this}cross(Z){return z1.vec3.cross(this,this,Z),this}distance(Z){return z1.vec3.distance(this,Z)}divide(Z){return z1.vec3.div(this,this,Z),this}dot(Z){return z1.vec3.dot(this,Z)}equals(Z){return z1.vec3.equals(this,Z)}exactEquals(Z){return z1.vec3.exactEquals(this,Z)}floor(){return z1.vec3.floor(this,this),this}invert(){return z1.vec3.inverse(this,this),this}lerp(Z,J){return z1.vec3.lerp(this,this,Z,J),this}max(Z){return z1.vec3.max(this,this,Z),this}min(Z){return z1.vec3.min(this,this,Z),this}multiply(Z){return z1.vec3.mul(this,this,Z),this}negate(){return z1.vec3.negate(this,this),this}normalize(){return z1.vec3.normalize(this,this),this}randomize(Z){return z1.vec3.random(this,Z),this}rotateX(Z,J){return z1.vec3.rotateX(this,this,Z,J),this}rotateY(Z,J){return z1.vec3.rotateY(this,this,Z,J),this}rotateZ(Z,J){return z1.vec3.rotateZ(this,this,Z,J),this}round(){return z1.vec3.round(this,this),this}scale(Z){return z1.vec3.scale(this,this,Z),this}scaleAndAdd(Z,J){return z1.vec3.scaleAndAdd(this,this,Z,J),this}subtract(Z){return z1.vec3.sub(this,this,Z),this}toString(){return`${this.x},${this.y},${this.z}`}transformMatrix3(Z){return z1.vec3.transformMat3(this,this,Z),this}transformMatrix4(Z){return z1.vec3.transformMat4(this,this,Z),this}transformQuaternion(Z){return z1.vec3.transformQuat(this,this,Z),this}zero(){return z1.vec3.zero(this),this}}var MH1=r(wH1(),1);var OH1=0.099856;class OU extends vY{faceSpeed=0;idleLoopedAnimations=[];idleLoopedAnimationsSpeed;jumpOneshotAnimations=[];moveLoopedAnimations=[];moveLoopedAnimationsSpeed;moveSpeed=0;_faceTarget;_jumpHeight=0;_moveCompletesWhenStuck=!1;_moveIgnoreAxes={};_moveStartMoveAnimations=!1;_moveStartIdleAnimationsOnCompletion=!0;_moveStoppingDistanceSquared=OH1;_moveStuckAccumulatorMs=0;_moveStuckLastPosition;_moveTarget;_onFace;_onFaceComplete;_onMove;_onMoveComplete;_stopFaceRequested=!1;_stopMoveRequested=!1;constructor(Z={}){super();this.idleLoopedAnimations=Z.idleLoopedAnimations??this.idleLoopedAnimations,this.idleLoopedAnimationsSpeed=Z.idleLoopedAnimationsSpeed??this.idleLoopedAnimationsSpeed,this.jumpOneshotAnimations=Z.jumpOneshotAnimations??this.jumpOneshotAnimations,this.moveLoopedAnimations=Z.moveLoopedAnimations??this.moveLoopedAnimations,this.moveLoopedAnimationsSpeed=Z.moveLoopedAnimationsSpeed??this.moveLoopedAnimationsSpeed}spawn(Z){super.spawn(Z),this._startIdleAnimations(Z)}face(Z,J,X){this._faceTarget=Z,this.faceSpeed=J,this._onFace=X?.faceCallback,this._onFaceComplete=X?.faceCompleteCallback}jump(Z){this._jumpHeight=Z}move(Z,J,X){this.moveSpeed=J,this._moveCompletesWhenStuck=X?.moveCompletesWhenStuck??!1,this._moveIgnoreAxes=X?.moveIgnoreAxes??{},this._moveStartIdleAnimationsOnCompletion=X?.moveStartIdleAnimationsOnCompletion??!0,this._moveStartMoveAnimations=!0,this._moveStoppingDistanceSquared=X?.moveStoppingDistance?X.moveStoppingDistance**2:OH1,this._moveTarget=Z,this._onMove=X?.moveCallback,this._onMoveComplete=X?.moveCompleteCallback,this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0}stopFace(){this._stopFaceRequested=!0}stopMove(){this._stopMoveRequested=!0}tick(Z,J){if(super.tick(Z,J),!this._moveTarget&&!this._faceTarget&&!this._jumpHeight)return;if(this._moveStartMoveAnimations)this._startMoveAnimations(Z),this._moveStartMoveAnimations=!1;let X=J/1000,Y=Z.position;if(Z.isDynamic&&this._jumpHeight>0){let $=Math.abs(Z.world.simulation.gravity.y),Q=Math.sqrt(2*$*this._jumpHeight);Z.applyImpulse({x:0,y:Q*Z.mass,z:0}),this._jumpHeight=0,this._startJumpAnimations(Z)}if(this._moveTarget){let $={x:this._moveIgnoreAxes.x?0:this._moveTarget.x-Y.x,y:this._moveIgnoreAxes.y?0:this._moveTarget.y-Y.y,z:this._moveIgnoreAxes.z?0:this._moveTarget.z-Y.z},Q=$.x*$.x+$.y*$.y+$.z*$.z,K=!1;if(this._moveCompletesWhenStuck){if(this._moveStuckAccumulatorMs+=J,this._moveStuckAccumulatorMs>=500){if(this._moveStuckLastPosition){let W=Y.x-this._moveStuckLastPosition.x,G=Y.y-this._moveStuckLastPosition.y,V=Y.z-this._moveStuckLastPosition.z;K=Math.sqrt(W*W+G*G+V*V)<this.moveSpeed*0.1}this._moveStuckLastPosition=Y,this._moveStuckAccumulatorMs=0}}if(Q>this._moveStoppingDistanceSquared&&!this._stopMoveRequested&&!K){let W=Math.sqrt(Q),G=this.moveSpeed*X,H=Math.min(W,G)/W,F={x:Y.x+$.x*H,y:Y.y+$.y*H,z:Y.z+$.z*H};if(Z.setPosition(F),this._onMove)this._onMove(F,this._moveTarget)}else{if(this._moveStuckAccumulatorMs=0,this._moveStuckLastPosition=void 0,this._moveTarget=void 0,this._stopMoveRequested=!1,this._moveStartIdleAnimationsOnCompletion)this._startIdleAnimations(Z);if(this._onMoveComplete){let W=this._onMoveComplete;this._onMove=void 0,this._onMoveComplete=void 0,W(Y)}}}if(this._faceTarget){let $={x:this._faceTarget.x-Y.x,z:this._faceTarget.z-Y.z},Q=Math.atan2(-$.x,-$.z),K=Z.rotation,W=Math.atan2(2*(K.w*K.y),1-2*(K.y*K.y)),G=Q-W;while(G>Math.PI)G-=2*Math.PI;while(G<-Math.PI)G+=2*Math.PI;if(Math.abs(G)>0.01&&!this._stopFaceRequested){let V=this.faceSpeed*X,H=Math.abs(G)<V?G:Math.sign(G)*V,z=(W+H)/2,q={x:0,y:Math.fround(Math.sin(z)),z:0,w:Math.fround(Math.cos(z))};if(Z.setRotation(q),this._onFace)this._onFace(K,q)}else if(this._faceTarget=void 0,this._stopFaceRequested=!1,this._onFaceComplete){let V=this._onFaceComplete;this._onFace=void 0,this._onFaceComplete=void 0,V(Z.rotation)}}}_startIdleAnimations(Z){if(this.idleLoopedAnimationsSpeed)Z.setModelAnimationsPlaybackRate(this.idleLoopedAnimationsSpeed);Z.stopModelAnimations(this.moveLoopedAnimations),Z.stopModelAnimations(this.jumpOneshotAnimations),Z.startModelLoopedAnimations(this.idleLoopedAnimations)}_startJumpAnimations(Z){Z.stopModelAnimations(this.moveLoopedAnimations),Z.stopModelAnimations(this.idleLoopedAnimations),Z.startModelOneshotAnimations(this.jumpOneshotAnimations)}_startMoveAnimations(Z){if(this.moveLoopedAnimationsSpeed)Z.setModelAnimationsPlaybackRate(this.moveLoopedAnimationsSpeed);Z.stopModelAnimations(this.jumpOneshotAnimations),Z.stopModelAnimations(this.idleLoopedAnimations),Z.startModelLoopedAnimations(this.moveLoopedAnimations)}}class Sm extends OU{_debug=!1;_entity;_maxFall=0;_maxJump=0;_maxOpenSetIterations=200;_onPathfindAbort;_onPathfindComplete;_onWaypointMoveComplete;_onWaypointMoveSkipped;_speed=0;_target;_verticalPenalty=0;_waypoints=[];_waypointNextIndex=0;_waypointStoppingDistance;_waypointTimeoutMs=2000;constructor(Z={}){super(Z)}get debug(){return this._debug}get maxFall(){return this._maxFall}get maxJump(){return this._maxJump}get maxOpenSetIterations(){return this._maxOpenSetIterations}get speed(){return this._speed}get target(){return this._target}get verticalPenalty(){return this._verticalPenalty}get waypoints(){return this._waypoints}get waypointNextIndex(){return this._waypointNextIndex}get waypointTimeoutMs(){return this._waypointTimeoutMs}pathfind(Z,J,X){if(this._target=Z,this._speed=J,this._debug=X?.debug??!1,this._maxFall=X?.maxFall?-Math.abs(X.maxFall):0,this._maxJump=X?.maxJump?Math.abs(X.maxJump):0,this._maxOpenSetIterations=X?.maxOpenSetIterations??200,this._onPathfindAbort=X?.pathfindAbortCallback,this._onPathfindComplete=X?.pathfindCompleteCallback,this._onWaypointMoveComplete=X?.waypointMoveCompleteCallback,this._onWaypointMoveSkipped=X?.waypointMoveSkippedCallback,this._verticalPenalty=X?.verticalPenalty??0,this._waypoints=[],this._waypointNextIndex=0,this._waypointStoppingDistance=X?.waypointStoppingDistance,this._waypointTimeoutMs=X?.waypointTimeoutMs??2000/J,!this._calculatePath())return!1;return this._moveToNextWaypoint(),!0}attach(Z){super.attach(Z),this._entity=Z}detach(Z){super.detach(Z),this._entity=void 0}_calculatePath(){if(!this._target||!this._entity?.world)return c.error("PathfindingEntityController._calculatePath: No target or world"),!1;let Z=this._entity.height,J=this._findGroundedStart();if(!J){if(this._debug)c.warning(`PathfindingEntityController._calculatePath: No valid grounded start found within maxFall distance, path search aborted. Start: ${this._coordinateToKey(this._target)}, Target: ${this._coordinateToKey(this._target)}`);return!1}let X={x:Math.floor(this._target.x),y:Math.floor(this._target.y),z:Math.floor(this._target.z)},Y=Math.abs(X.x-J.x),$=Math.abs(X.y-J.y),Q=Math.abs(X.z-J.z);if(Y<=2&&$<=2&&Q<=2&&!this._isNeighborCoordinateBlocked(J,X,this._entity.height))return this._waypoints=[{x:J.x+0.5,y:J.y+Z/2,z:J.z+0.5},{x:X.x+0.5,y:X.y+Z/2,z:X.z+0.5}],!0;if(J.x===X.x&&J.y===X.y&&J.z===X.z)return this._waypoints=[{x:J.x+0.5,y:J.y+Z/2,z:J.z+0.5}],!0;let W=this._coordinateToKey(J),G=new Map,V=new Map([[W,0]]),H=new Map([[W,this._pathfindingHeuristic(J,X)]]),F=new Set,z=new MH1.Heap((R,N)=>{let P=H.get(R[0])??1/0,D=H.get(N[0])??1/0;return P-D});z.push([W,J]);let q=[{x:0,y:0,z:1},{x:1,y:0,z:0},{x:0,y:0,z:-1},{x:-1,y:0,z:0},{x:1,y:0,z:1},{x:1,y:0,z:-1},{x:-1,y:0,z:1},{x:-1,y:0,z:-1}],U=[];for(let R=this._maxJump;R>=this._maxFall;R--){if(R===0)continue;let N=Math.abs(J.y+R-X.y);U.push({y:R,distanceToTargetY:N})}U.sort((R,N)=>R.distanceToTargetY-N.distanceToTargetY);let B=[...q,...U.flatMap(({y:R})=>q.map((N)=>({...N,y:R})))],L=0,w=Math.abs(X.x-J.x)+Math.abs(X.y-J.y)+Math.abs(X.z-J.z),M=Math.min(this._maxOpenSetIterations,w*20);while(!z.isEmpty()&&L<M){L++;let[R,N]=z.pop();if(N.x===X.x&&N.y===X.y&&N.z===X.z){let C=this._reconstructPath(G,N);if(this._waypoints=C.map((T)=>({x:T.x+0.5,y:T.y+Z/2,z:T.z+0.5})),this._debug)console.log(`PathfindingEntityController._calculatePath: Path found after ${L} open set iterations. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`);return!0}F.add(R);let P=V.get(R),D=new Map;for(let C of B){let T=`${C.x},${C.z}`,E=C.y<0;if(E&&D.has(T))continue;let A={x:N.x+C.x,y:N.y+C.y,z:N.z+C.z};if(Math.abs(X.x-A.x)+Math.abs(X.y-A.y)+Math.abs(X.z-A.z)>w*1.5)continue;let x=this._coordinateToKey(A);if(F.has(x))continue;let k=this._isNeighborCoordinateBlocked(N,A,this._entity.height);if(E&&k){D.set(T,!0);continue}if(k)continue;let _=Math.abs(C.x),y=Math.abs(C.y),u=Math.abs(C.z),n=y===0?0:this._verticalPenalty,o=(Math.max(_,y,u)===1&&_+y+u>1?1.4:1)+n,Q0=P+o,W0=V.get(x)??1/0;if(Q0>=W0)continue;G.set(x,N),V.set(x,Q0);let v0=Q0+this._pathfindingHeuristic(A,X);H.set(x,v0),z.push([x,A])}}if(L>=M){if(this._onPathfindAbort?.(),this._debug)c.warning(`PathfindingEntityController._calculatePath: Maximum open set iterations reached (${M}), path search aborted. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`)}else if(this._debug)c.warning(`PathfindingEntityController._calculatePath: No valid path found. Start: ${this._coordinateToKey(J)}, Target: ${this._coordinateToKey(this._target)}`);return this._target=void 0,this._waypoints=[],!1}_reconstructPath(Z,J){let X=[J],Y=J;while(Z.has(this._coordinateToKey(Y)))Y=Z.get(this._coordinateToKey(Y)),X.unshift(Y);return X}_coordinateToKey(Z){return`${Z.x},${Z.y},${Z.z}`}_moveToNextWaypoint(){let Z=this._waypointNextIndex>0?this._waypoints[this._waypointNextIndex-1]:void 0,J=this._waypoints[this._waypointNextIndex];if(!J||!this._entity)return;let X=0;if(this._entity.isDynamic&&Z&&J.y>Z.y){let Y=J.y-Z.y,$=Math.min(Y,this._maxJump)+0.75;this.jump($);let Q=Math.abs(this._entity.world.simulation.gravity.y),K=Math.sqrt(2*Q*$),W=Z.x+0.5,G=Z.z+0.5,V=J.x+0.5,H=J.z+0.5,F=V-W,z=H-G,q=Math.sqrt(F*F+z*z),U=K/Q,B=q/this._speed;X=Math.min(U*0.8,B)*1000}setTimeout(()=>{if(!this._entity)return;let Y=Date.now();this.face(J,this._speed),this.move(J,this._speed,{moveCompletesWhenStuck:!0,moveIgnoreAxes:{y:this._entity.isDynamic},moveStartIdleAnimationsOnCompletion:this._waypointNextIndex===this._waypoints.length-1,moveStoppingDistance:this._waypointStoppingDistance,moveCallback:()=>{if(Date.now()-Y>this._waypointTimeoutMs&&this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveSkipped?.(J,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint()},moveCompleteCallback:()=>{if(this._waypointNextIndex<this._waypoints.length-1)this._onWaypointMoveComplete?.(J,this._waypointNextIndex),this._waypointNextIndex++,this._moveToNextWaypoint();else this._onPathfindComplete?.()}})},X)}_pathfindingHeuristic(Z,J){return Math.abs(Z.x-J.x)+Math.abs(Z.y-J.y)+Math.abs(Z.z-J.z)}_isNeighborCoordinateBlocked(Z,J,X){if(!this._entity?.world)return!1;let Y=this._entity.world,$=Math.floor(J.x),Q=Math.floor(J.y),K=Math.floor(J.z),W=Math.floor(Z.x),G=Math.floor(Z.z);if(!Y.chunkLattice.hasBlock({x:$,y:Q-1,z:K}))return!0;for(let V=0;V<X;V++)if(Y.chunkLattice.hasBlock({x:$,y:Q+V,z:K}))return!0;if($!==W&&K!==G)for(let V=0;V<X;V++){let H=Y.chunkLattice.hasBlock({x:$,y:Q+V,z:G}),F=Y.chunkLattice.hasBlock({x:W,y:Q+V,z:K});if(H||F)return!0}return!1}_findGroundedStart(){if(!this._entity?.world)return;let{x:Z,y:J,z:X}=this._entity.position,Y={x:Math.floor(Z),y:Math.floor(J),z:Math.floor(X)};for(let $=0;$<=Math.abs(this._maxFall);$++)if(this._entity.world.chunkLattice.hasBlock({...Y,y:Y.y-$-1}))return{...Y,y:Y.y-$};return}}export{oQ6 as startServer,I31 as WorldManagerEvent,IY as WorldManager,E31 as WorldLoopEvent,LU as WorldLoop,Dm as WorldEvent,BU as World,aS as WebServerEvent,FG as WebServer,N3 as Vector3,wU as Vector2,UU as Ticker,qU as TickAllocator,YK as TelemetrySpanOperation,t1 as Telemetry,jm as SimulationEvent,HU as Simulation,OU as SimpleEntityController,FU as SceneUIManager,rk as SceneUIEvent,tH as SceneUI,X50 as SUPPORTED_INPUT_KEYS,BH as RigidBodyType,M$ as RigidBody,R3 as Quaternion,cw as PlayerUIEvent,iH as PlayerUI,k31 as PlayerManagerEvent,U9 as PlayerManager,nH as PlayerEvent,b7 as PlayerEntity,J50 as PlayerCameraMode,nk as PlayerCameraEvent,pH as PlayerCamera,CW as Player,E$ as PersistenceManager,Sm as PathfindingEntityController,zU as ParticleEmitterManager,Mm as ParticleEmitterEvent,Rm as ParticleEmitter,iS as PORT,W50 as PLAYER_ROTATION_UPDATE_THRESHOLD,K50 as PLAYER_POSITION_UPDATE_THRESHOLD_SQ,S5 as ModelRegistry,P5 as Matrix4,LZ as Matrix3,GK as Matrix2,T31 as LightType,GU as LightManager,wm as LightEvent,Om as Light,F6 as IterationMap,v31 as GameServerEvent,$K as GameServer,M0 as EventRouter,c as ErrorHandler,eH as EntityManager,rH as EntityEvent,n8 as Entity,Q50 as ENTITY_ROTATION_UPDATE_THRESHOLD,$50 as ENTITY_POSITION_UPDATE_THRESHOLD_SQ,g1 as DefaultPlayerEntityController,tk as DefaultPlayerEntity,Y50 as DEFAULT_ENTITY_RIGID_BODY_OPTIONS,E4 as CollisionGroupsBuilder,yY as CollisionGroup,wH as ColliderShape,oH as ColliderMap,K9 as Collider,FI as CoefficientCombineRule,ok as ChunkLatticeEvent,sH as ChunkLattice,V9 as Chunk,aH as ChatManager,ak as ChatEvent,UI as BlockTypeRegistryEvent,OH as BlockTypeRegistry,qI as BlockTypeEvent,W9 as BlockType,FK as Block,gm as BaseEntityControllerEvent,vY as BaseEntityController,P3 as AudioManager,PD as AudioEvent,D3 as Audio};
|