@utsp/runtime-client 0.9.0-nightly.20251210150441.b1cbb1e → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +19 -1
- package/dist/index.mjs +1 -1
- package/package.json +7 -7
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var M=Object.defineProperty;var z=Object.getOwnPropertyDescriptor;var W=Object.getOwnPropertyNames;var N=Object.prototype.hasOwnProperty;var q=(p,e,t)=>e in p?M(p,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):p[e]=t;var v=(p,e)=>M(p,"name",{value:e,configurable:!0});var j=(p,e)=>{for(var t in e)M(p,t,{get:e[t],enumerable:!0})},_=(p,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of W(e))!N.call(p,i)&&i!==t&&M(p,i,{get:()=>e[i],enumerable:!(n=z(e,i))||n.enumerable});return p};var X=p=>_(M({},"__esModule",{value:!0}),p);var s=(p,e,t)=>(q(p,typeof e!="symbol"?e+"":e,t),t);var V={};j(V,{AudioManager:()=>G.AudioManager,ClientRuntime:()=>A,RendererType:()=>x,ScalingMode:()=>H.ScalingMode});module.exports=X(V);var b=require("@utsp/core"),C=require("@utsp/render"),O=require("@utsp/types"),T=require("@utsp/input"),U=require("@utsp/network-client"),D=require("@utsp/audio");var Y=require("@utsp/types"),x=(t=>(t.TerminalGL="webgl",t.Terminal2D="terminal2d",t))(x||{});var B=class B{constructor(e=60){s(this,"frameCount",0);s(this,"fps",0);s(this,"fpsUpdateTime",0);s(this,"lastCoreTime",0);s(this,"lastRenderTime",0);s(this,"lastTotalTime",0);s(this,"coreTimeSamples",[]);s(this,"renderTimeSamples",[]);s(this,"totalTimeSamples",[]);s(this,"maxSamples");if(e<=0)throw new Error("maxSamples must be positive");this.maxSamples=e}startTracking(e){this.fpsUpdateTime=e,this.frameCount=0,this.fps=0}updateFPS(e){this.frameCount++,e-this.fpsUpdateTime>=1e3&&(this.fps=Math.round(this.frameCount*1e3/(e-this.fpsUpdateTime)),this.frameCount=0,this.fpsUpdateTime=e)}recordFrameTiming(e,t){let n=e+t;this.lastCoreTime=e,this.lastRenderTime=t,this.lastTotalTime=n,this.coreTimeSamples.push(e),this.renderTimeSamples.push(t),this.totalTimeSamples.push(n),this.coreTimeSamples.length>this.maxSamples&&(this.coreTimeSamples.shift(),this.renderTimeSamples.shift(),this.totalTimeSamples.shift())}getFPS(){return this.fps}getLastFrameTiming(){if(!(this.lastCoreTime===0&&this.lastRenderTime===0))return{coreTime:this.lastCoreTime,renderTime:this.lastRenderTime,totalTime:this.lastTotalTime}}getAverageFrameTiming(){if(this.coreTimeSamples.length!==0)return{coreTime:this.average(this.coreTimeSamples),renderTime:this.average(this.renderTimeSamples),totalTime:this.average(this.totalTimeSamples)}}getStats(){return{fps:this.fps,lastFrame:this.getLastFrameTiming(),avgFrame:this.getAverageFrameTiming(),sampleCount:this.coreTimeSamples.length,maxSamples:this.maxSamples}}reset(){this.frameCount=0,this.fps=0,this.fpsUpdateTime=0,this.lastCoreTime=0,this.lastRenderTime=0,this.lastTotalTime=0,this.coreTimeSamples=[],this.renderTimeSamples=[],this.totalTimeSamples=[]}average(e){return e.length===0?0:e.reduce((t,n)=>t+n,0)/e.length}};v(B,"PerformanceMonitor");var S=B;var L=require("@utsp/core");var F=class F{constructor(e,t={}){s(this,"renderer");s(this,"options");this.renderer=e,this.options={debug:t.debug??!1,useImageDataRendering:t.useImageDataRendering??!1}}async initialize(e){await this.loadDefaultFont(e),await this.waitForReady()}async waitForReady(e=100,t=50){this.log("Waiting for renderer to be ready");let n=0;return new Promise((i,r)=>{let o=v(()=>{if(n++,this.renderer.isReady())this.log(`Renderer ready after ${n*t}ms`),i();else if(n>=e){let c=`Renderer failed to be ready after ${e*t}ms`;this.log(c),r(new Error(c))}else setTimeout(o,t)},"check");o()})}async loadDefaultFont(e){this.log("Loading ASCII 8x8 font");let t=(0,L.createASCII8x8FontLoad)(1);e.hasBitmapFont(t.fontId)||e.loadBitmapFontById(t.fontId,{charWidth:t.width,charHeight:t.height,cellWidth:t.cellWidth,cellHeight:t.cellHeight,glyphs:new Map(t.characters.map(n=>[n.charCode,n.bitmap]))}),"setImageDataRendering"in this.renderer&&this.options.useImageDataRendering&&(this.renderer.setImageDataRendering(!0),this.log("ImageData rendering enabled")),this.log("Font loaded and event triggered")}render(e,t){if(!this.renderer.isReady())return console.warn("[RENDERER MANAGER] Renderer not ready"),!1;let n=e.getRenderState(t);if(!n||n.displays.length===0)return console.warn("[RENDERER MANAGER] No render state or no displays"),!1;let i=n.displays[0];return this.renderer.renderDisplayData(i),!0}getRenderer(){return this.renderer}getCanvas(){return this.renderer.getCanvas()}isReady(){return this.renderer.isReady()}destroy(){this.log("Destroying renderer"),this.renderer.destroy()}log(e){this.options.debug&&console.warn(`[RendererManager] ${e}`)}};v(F,"RendererManager");var I=F;var w=require("@utsp/input");var E=class E{constructor(e,t,n,i,r){s(this,"network");s(this,"core");s(this,"rendererManager");s(this,"performanceMonitor");s(this,"options");s(this,"audioManager",null);s(this,"postProcessCallback",null);s(this,"userId","");s(this,"lastReceivedTick",-1);s(this,"connected",!1);this.network=e,this.core=t,this.rendererManager=n,this.performanceMonitor=i,this.options={serverUrl:r.serverUrl,username:r.username,token:r.token??"",debug:r.debug??!1,autoReconnect:r.autoReconnect??!0,canvasWidth:r.canvasWidth,canvasHeight:r.canvasHeight}}async connect(){this.log(`Connecting to ${this.options.serverUrl}`),await this.network.connect(),this.connected=!0,this.log("Connected to server"),this.setupNetworkHandlers()}async joinGame(e){return new Promise((t,n)=>{this.network.send("join",{username:this.options.username,token:this.options.token}),this.network.on("join_response",i=>{if(i.success){this.userId=i.userId,this.log(`Joined game as ${this.userId}`);let r=this.core.createUser(this.userId,this.options.username);this.audioManager&&r.setAudioProcessor(this.audioManager),e.initUser(this.core,r,{username:this.options.username,token:this.options.token}),t(this.userId)}else n(new Error(i.error||"Failed to join game"))}),setTimeout(()=>n(new Error("Join timeout")),5e3)})}sendInput(e){let t=this.core.getUser(this.userId);if(!t)return;let n=this.rendererManager.getCanvas();if(n){let h=this.rendererManager.getRenderer()?.getOffsets?.(),R={offsetX:h?.offsetX??0,offsetY:h?.offsetY??0},y=w.InputCollector.collectMousePosition(e,n,this.options.canvasWidth,this.options.canvasHeight,R);t.setMousePosition(y.x,y.y,y.over),t.updateMacroMouse(y.x,y.y,y.isLeftDown),w.InputCollector.collectTouchPositions(e,n,this.options.canvasWidth,this.options.canvasHeight,10,R).forEach(k=>{t.setTouchPosition(k.id,k.x,k.y,k.over)})}let i=t.getInputBindingRegistry(),r=i.getAllAxes(),o=i.getAllButtons(),a=w.InputCollector.collectAxisSources(r,e),c=w.InputCollector.collectButtonSources(o,e),d=w.InputCollector.collectTextInputs(e);d.length>0&&t.setTextInputs(d);let u={};r.forEach(g=>{let h=i.evaluateAxis(g.bindingId,a);u[g.name]=h,t.setAxis(g.name,h)});let l={};o.forEach(g=>{let h=i.evaluateButton(g.bindingId,c);l[g.name]=h,t.setButton(g.name,h)});let m=t.getMouseDisplayInfo(),f=m?{x:m.localX,y:m.localY}:null;this.network.send("input",{timestamp:Date.now(),axes:u,buttons:l,mousePosition:f,textInputs:d})}disconnect(){this.connected&&(this.network.send("leave",{}),this.network.disconnect(),this.connected=!1,this.log("Disconnected from server"))}getUserId(){return this.userId}isConnected(){return this.connected}destroy(){this.disconnect(),this.network.destroy(),this.log("NetworkSync destroyed")}setupNetworkHandlers(){this.network.on("update",e=>{try{let t=this.convertToUint8Array(e,"update");if(!t)return;let n=this.core.applyUpdatePacketBuffer(this.userId,t);n?(this.postProcessCallback&&n.postProcessOrders&&n.postProcessOrders.length>0&&this.postProcessCallback(n.postProcessOrders),this.rendererManager.render(this.core,this.userId)):this.log("Failed to apply update packet")}catch(t){this.log(`Error applying update packet: ${t}`)}}),this.network.on("update-static",e=>{this.handleUpdatePacket(e,"update-static")}),this.network.on("update-dynamic",e=>{this.handleUpdatePacket(e,"update-dynamic")}),this.network.on("load",e=>{try{let t=this.convertToUint8Array(e,"load");if(!t)return;this.core.applyLoadPacket(t)?this.log("Load packet applied successfully"):this.log("Failed to apply load packet")}catch(t){this.log(`Error applying load packet: ${t}`)}}),this.network.on("input-bindings",e=>{this.core.applyInputBindingsLoadPacket(this.userId,e)?this.log("Input bindings configured"):this.log("Failed to apply input bindings")}),this.audioManager&&this.setupSoundHandlers(),this.network.on("disconnect",()=>{this.connected=!1,this.log("Disconnected from server")})}handleUpdatePacket(e,t){try{let n=this.convertToUint8Array(e,t);if(!n)return;let i=new DataView(n.buffer,n.byteOffset,n.byteLength),r=Number(i.getBigUint64(0,!1));if(t==="update-dynamic"&&r<this.lastReceivedTick)return;r>this.lastReceivedTick&&(this.lastReceivedTick=r);let o=this.core.applyUpdatePacketBuffer(this.userId,n);if(o){console.warn(`[CLIENT] ${t}: ${n.length}B (tick ${r}) - APPLIED`),this.postProcessCallback&&o.postProcessOrders&&o.postProcessOrders.length>0&&this.postProcessCallback(o.postProcessOrders),this.options.debug&&this.debugRenderState();let a=performance.now();this.rendererManager.render(this.core,this.userId);let c=performance.now()-a;this.performanceMonitor.recordFrameTiming(0,c),this.options.debug&&console.warn(`[CLIENT] render() completed for ${t} (${c.toFixed(2)}ms)`)}else console.warn(`[CLIENT] Failed to apply ${t} packet (tick ${r})`)}catch(n){this.log(`Error applying ${t} update packet: ${n}`),console.error(n)}}convertToUint8Array(e,t){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):Array.isArray(e)?new Uint8Array(e):e.data&&Array.isArray(e.data)?new Uint8Array(e.data):typeof e=="object"&&e.type==="Buffer"?new Uint8Array(e.data):(this.log(`Unknown data type for ${t} packet: ${typeof e}`),null)}debugRenderState(){let e=this.core.getUser(this.userId);if(e){let n=e.getLayers();console.warn(`[CLIENT] User has ${n.length} layers`),n.forEach((i,r)=>{let o=i.getOrders(),a=i.getStatic();(o.length>0||a)&&console.warn(` Layer ${r}: ${o.length} orders, static=${a}, z=${i.getZOrder()}`)})}let t=this.rendererManager.isReady();console.warn(`[CLIENT] Renderer ready: ${t}`)}log(e){this.options.debug&&console.warn(`[NetworkSync] ${e}`)}setAudioManager(e){if(this.audioManager=e,e&&this.userId){let t=this.core.getUser(this.userId);t&&t.setAudioProcessor(e)}this.connected&&e&&this.setupSoundHandlers()}setPostProcessCallback(e){this.postProcessCallback=e}setupSoundHandlers(){this.audioManager&&(this.network.on("sound-load",async e=>{e.mode==="file"?await this.handleSoundLoad(e):e.mode==="external"&&await this.handleSoundExternalLoad(e)}),this.log("Sound handlers registered"))}async handleSoundLoad(e){if(!this.audioManager){this.log("Cannot load sounds: AudioManager not initialized");return}let t=this.audioManager.getSoundBank();if(!t){this.log("Cannot load sounds: SoundBank not initialized");return}for(let n of e.sounds)try{await t.loadFromData(n.soundId,n.name,n.data),this.log(`Loaded sound: ${n.name} (${n.data.length} bytes)`),this.sendAudioAck({type:"sound-loaded",soundId:n.soundId,name:n.name})}catch(i){console.error(`[NetworkSync] Failed to load sound "${n.name}":`,i),this.sendAudioAck({type:"sound-error",soundId:n.soundId,name:n.name,error:String(i)})}}async handleSoundExternalLoad(e){if(!this.audioManager){this.log("Cannot load external sounds: AudioManager not initialized");return}let t=this.audioManager.getSoundBank();if(!t){this.log("Cannot load external sounds: SoundBank not initialized");return}for(let n of e.sounds)try{await t.loadFromUrl(n.soundId,n.name,n.url),this.log(`Loaded external sound: ${n.name} from ${n.url}`),this.sendAudioAck({type:"sound-loaded",soundId:n.soundId,name:n.name})}catch(i){console.error(`[NetworkSync] Failed to load external sound "${n.name}":`,i),this.sendAudioAck({type:"sound-error",soundId:n.soundId,name:n.name,error:String(i)})}}sendAudioAck(e){this.network.send("audio-ack",e),this.log(`Sent audio-ack: ${e.type}`)}sendBridge(e,t){this.network.sendBridge(e,t),this.log(`Bridge sent on channel '${e}'`)}onBridge(e,t){this.network.onBridge(e,t),this.log(`Bridge handler registered for channel '${e}'`)}offBridge(e,t){this.network.offBridge(e,t),this.log(`Bridge handler removed for channel '${e}'`)}removeAllBridgeHandlers(e){this.network.removeAllBridgeHandlers(e),this.log(e?`All bridge handlers removed for '${e}'`:"All bridge handlers removed")}};v(E,"NetworkSync");var P=E;var $=class ${constructor(e){s(this,"core");s(this,"rendererManager");s(this,"rendererType");s(this,"input",null);s(this,"networkSync",null);s(this,"options");s(this,"running",!1);s(this,"startTime",0);s(this,"lastTimestamp",0);s(this,"userId","");s(this,"mode");s(this,"visibilityChangeHandler");s(this,"tickRate",30);s(this,"accumulatedTime",0);s(this,"FRAME_TIME_MIN",1e3/60);s(this,"lastRenderTimestamp",0);s(this,"rafId",0);s(this,"firstTickDone",!1);s(this,"performanceMonitor");s(this,"renderMode","continuous");s(this,"renderRequested",!1);s(this,"autoplayOverlay",null);s(this,"autoplay",!0);s(this,"audioManager",null);s(this,"postProcessOverlay",null);s(this,"postProcessOrderCollector",new b.PostProcessOrderCollector);s(this,"localBridgeHandlers",new Map);s(this,"localBridgeWildcardHandlers",new Set);this.mode=e.mode,e.mode==="local"?(this.options={mode:"local",application:e.application,container:e.container,debug:e.debug??!1,width:e.width??80,height:e.height??25,userId:e.userId??"local",username:e.username??"User",renderer:e.renderer??"webgl",useImageDataRendering:e.useImageDataRendering??!0,mobileInputConfig:e.mobileInputConfig,captureInput:e.captureInput??!1,inputEnabled:e.inputEnabled??!0,autoplay:e.autoplay??!0,autoplayOptions:e.autoplayOptions},this.userId=e.userId??"local",this.autoplay=e.autoplay??!0):(this.options={mode:"connected",application:e.application,container:e.container,serverUrl:e.serverUrl,username:e.username??"Player",debug:e.debug??!1,width:e.width??80,height:e.height??25,autoReconnect:e.autoReconnect??!0,token:e.token,renderer:e.renderer??"webgl",useImageDataRendering:e.useImageDataRendering??!0,mobileInputConfig:e.mobileInputConfig,captureInput:e.captureInput??!1,inputEnabled:e.inputEnabled??!0,autoplay:e.autoplay??!0,autoplayOptions:e.autoplayOptions},this.autoplay=e.autoplay??!0),this.log(`Initializing ClientRuntime (${this.mode} mode)`),this.core=new b.Core({mode:"client",maxUsers:this.mode==="local"?1:100}),this.core.onPaletteChanged(n=>{this.onCorePaletteChanged(n)}),this.core.onBitmapFontChanged(n=>{this.onCoreBitmapFontChanged(n)}),this.visibilityChangeHandler=()=>{!document.hidden&&this.running&&(this.lastTimestamp=performance.now(),this.accumulatedTime=0,this.log("Tab visible: Reset timing"))},document.addEventListener("visibilitychange",this.visibilityChangeHandler);let t=this.createRenderer();if(this.rendererType=this.options.renderer??"webgl",this.rendererManager=new I(t,{debug:this.options.debug,useImageDataRendering:this.options.useImageDataRendering}),this.options.inputEnabled?this.input=new T.UnifiedInputRouter({enableKeyboardMouse:!0,enableGamepad:!0,enableMobile:!0,targetElement:window,mobileTargetElement:void 0,debug:this.options.debug,keyboardConfig:{preventDefault:this.options.captureInput??!1,stopPropagation:this.options.captureInput??!1},mouseConfig:{preventDefault:this.options.captureInput??!1,stopPropagation:this.options.captureInput??!1},mobileConfig:{preventDefault:this.options.mobileInputConfig?.preventDefault??!0,passive:this.options.mobileInputConfig?.passive??!1,maxTouches:this.options.mobileInputConfig?.maxTouches??10}}):this.log("Input disabled (inputEnabled: false)"),this.performanceMonitor=new S(60),this.mode==="connected"){let n=this.options,i=new U.SocketIOClient({url:n.serverUrl,autoReconnect:n.autoReconnect,auth:{username:n.username,token:n.token},debug:this.options.debug});this.networkSync=new P(i,this.core,this.rendererManager,this.performanceMonitor,{serverUrl:n.serverUrl,username:n.username,token:n.token,debug:this.options.debug,autoReconnect:n.autoReconnect,canvasWidth:this.options.width,canvasHeight:this.options.height})}this.tickRate=e.tickRate??30,this.tickRate===0&&!e.renderMode?(this.renderMode="on-demand",this.log("tickRate is 0: automatically enabling on-demand render mode")):this.renderMode=e.renderMode??"continuous",this.log(`Configured: tickRate=${this.tickRate}, renderMode=${this.renderMode}`),this.log("ClientRuntime initialized")}getMode(){return this.mode}getRendererType(){return this.rendererType}isRunning(){return this.running}createRenderer(){if((this.options.renderer??"webgl")==="terminal2d"){this.log("Creating Terminal 2D renderer");let r=new C.Terminal2D(this.options.container,{fixedCols:this.options.width,fixedRows:this.options.height,cellAspectRatio:1});return this.options.useImageDataRendering&&(this.log("Enabling ImageData rendering (pixel-perfect, optimized)"),r.setImageDataRendering(!0)),this.log("Canvas 2D renderer created successfully"),r}this.log("Creating TerminalGL renderer");let n=document.createElement("canvas").getContext("webgl");if(!n)throw new Error("WebGL not supported. TerminalGL requires WebGL 1.0.");if(!n.getExtension("OES_element_index_uint"))throw new Error("OES_element_index_uint extension not supported. TerminalGL requires this extension for large terminals (256x256). Supported on 97% of devices (Android 4.3+, iOS 8+, Desktop).");if(!(this.options.container instanceof HTMLDivElement))throw new Error(`TerminalGL requires container to be an HTMLDivElement. Received: ${this.options.container.tagName}`);let i=new C.TerminalGL(this.options.container,{cols:this.options.width,rows:this.options.height,charWidth:8,charHeight:8,scalingMode:O.ScalingMode.None});return this.log("TerminalGL created successfully"),i}setTickRate(e){if(e<0||e>1e3)throw new Error(`Invalid tick rate: ${e}. Must be between 0 and 1000.`);if(this.mode==="connected"){this.log("setTickRate() has no effect in connected mode");return}this.tickRate=e,e===0&&this.renderMode==="continuous"?(this.renderMode="on-demand",this.log(`Tick rate set to ${e} TPS (update loop disabled, automatically switched to on-demand render mode)`)):this.log(`Tick rate set to ${e} TPS ${e===0?"(update loop disabled)":""}`)}setRenderMode(e){this.renderMode=e,this.log(`Render mode set to ${e}`)}setMaxFPS(e){if(e<=0||e>240)throw new Error(`Invalid FPS: ${e}. Must be between 1 and 240.`);this.FRAME_TIME_MIN=1e3/e,this.log(`Max FPS set to ${e}`)}getTickRate(){return this.tickRate}requestRender(){this.renderMode==="on-demand"?(this.renderRequested=!0,this.log("Render requested")):this.log("requestRender() has no effect in continuous mode")}async start(){if(this.running){this.log("Already running");return}this.log("Starting ClientRuntime"),this.audioManager=new D.AudioManager({debug:this.options.debug}),this.autoplay?(this.log("Autoplay enabled, initializing AudioManager..."),this.audioManager.initialize()):(this.log("Autoplay disabled, showing overlay..."),await new Promise(n=>{this.autoplayOverlay=new C.AutoplayOverlay(this.options.container,{...this.options.autoplayOptions,onStart:()=>{this.log("User clicked start button"),this.audioManager&&(this.audioManager.initialize(),this.audioManager.playStartSound()),n()}})}),this.log("Autoplay overlay dismissed, continuing startup...")),await this.rendererManager.initialize(this.core),this.log("Renderer is ready"),this.postProcessOverlay=new C.PostProcessOverlay(this.options.container),this.log("PostProcessOverlay created"),this.onCorePaletteChanged(this.core.getPalette()),this.log("Initial palette sent to renderer"),this.log("Calling application.init()"),await this.options.application.init(this.core,this);let e=this.rendererManager.getCanvas();e&&this.input&&this.input.setMobileTarget(e),this.mode==="connected"&&this.networkSync?(this.log("Connecting to server"),this.audioManager&&this.networkSync.setAudioManager(this.audioManager),this.networkSync.setPostProcessCallback(n=>{this.applyPostProcessOrders(n)}),await this.networkSync.connect(),this.userId=await this.networkSync.joinGame(this.options.application)):await this.createLocalUser();let t=this.core.getUser(this.userId);if(t){let n=t.getDisplays();if(n.length>0){let r=n[0].getSize(),o=r.x,a=r.y,c=this.rendererManager.getRenderer(),d,u;if(this.rendererType==="webgl"){let m=c.getGridSize();d=m.cols,u=m.rows}else{let l=c;d=l.getCols(),u=l.getRows()}(d!==o||u!==a)&&(this.log(`Adjusting renderer from ${d}\xD7${u} to match display ${o}\xD7${a}`),c.resize(o,a))}}this.input&&this.input.start(),this.running=!0,this.startTime=performance.now(),this.lastTimestamp=this.startTime,this.lastRenderTimestamp=this.startTime,this.accumulatedTime=0,this.firstTickDone=!1,this.performanceMonitor.reset(),this.performanceMonitor.startTracking(this.startTime),this.log("Starting main loop"),this.mainLoop(this.lastTimestamp)}async stop(){if(!this.running)return;this.log("Stopping ClientRuntime"),this.running=!1,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=0),this.audioManager&&this.audioManager.stopAll(),this.input&&this.input.stop(),this.mode==="connected"&&this.networkSync&&this.networkSync.disconnect();let e=this.core.getUser(this.userId);e&&this.options.application.destroyUser&&this.options.application.destroyUser(this.core,e,"Runtime stopped"),this.log("ClientRuntime stopped")}getStats(){let e=this.performanceMonitor.getStats();return{mode:this.mode,running:this.running,userCount:this.core.getUsers().length,fps:e.fps,uptime:this.running?performance.now()-this.startTime:0,totalFrames:0,latency:void 0,lastFrameTiming:e.lastFrame,avgFrameTiming:e.avgFrame}}async destroy(){await this.stop(),this.log("Destroying ClientRuntime"),this.visibilityChangeHandler&&(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeHandler=void 0),this.autoplayOverlay&&(this.autoplayOverlay.destroy(),this.autoplayOverlay=null),this.audioManager&&(this.audioManager.destroy(),this.audioManager=null),this.postProcessOverlay&&(this.postProcessOverlay.destroy(),this.postProcessOverlay=null);let e=this.rendererManager.getRenderer();e&&"clearOnResizeCallback"in e&&e.clearOnResizeCallback(),this.options.application.destroy&&this.options.application.destroy(),this.rendererManager.destroy(),this.input&&this.input.destroy(),this.networkSync&&this.networkSync.destroy(),this.log("ClientRuntime destroyed")}async createLocalUser(){let e=this.options;this.log(`Creating local user: ${this.userId}`);let t=this.core.createUser(this.userId,e.username);if(this.audioManager&&t.setAudioProcessor(this.audioManager),this.log("Calling application.initUser()"),this.options.application.initUser(this.core,t,{username:e.username}),t.hasAudioConfigCommands()&&(this.log("Applying audio config commands from initUser()"),t.applyAudioConfigCommands(t.flushAudioConfigCommands())),t.hasPendingMacroOrders()){this.log("Applying macro orders from initUser()");let n=t.flushMacroOrders();t.applyMacroOrders(n)}if(t.hasPostProcessCommands()){this.log("Applying post-process commands from initUser()");let n=t.flushPostProcessCommands(),i=this.postProcessOrderCollector.convertCommands(n);this.applyPostProcessOrders(i)}t.needsSendSounds()&&(await this.loadSoundsFromRegistry(),t.clearSendSounds()),this.log("Performing initial render"),this.core.endTick(),this.render(),this.log("Initial render complete")}async loadSoundsFromRegistry(){if(!this.audioManager){this.log("Cannot load sounds: AudioManager not initialized");return}let e=this.audioManager.getSoundBank();if(!e){this.log("Cannot load sounds: SoundBank not initialized");return}let n=this.core.getSoundRegistry().getAll();if(n.length===0){this.log("No sounds to load from registry");return}this.log(`Loading ${n.length} sounds from Core registry into AudioManager...`);for(let i of n)try{i.loadType==="file"&&i.data?(await e.loadFromData(i.soundId,i.name,i.data),this.log(`\u{1F50A} Loaded sound: ${i.name} (${i.data.length} bytes)`)):i.loadType==="external"&&i.url&&(await e.loadFromUrl(i.soundId,i.name,i.url),this.log(`\u{1F50A} Loaded external sound: ${i.name} from ${i.url}`))}catch(r){console.error(`[ClientRuntime] Failed to load sound "${i.name}":`,r)}this.log(`\u2713 ${e.size} sounds loaded into AudioManager`)}mainLoop(e){if(!this.running){this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=0);return}if(this.renderMode==="on-demand"){this.renderRequested&&(this.renderRequested=!1,this.performanceMonitor.updateFPS(e),this.render()),this.rafId=requestAnimationFrame(o=>this.mainLoop(o));return}let t=e-this.lastRenderTimestamp;if(this.lastRenderTimestamp>0&&t<this.FRAME_TIME_MIN-1){this.rafId=requestAnimationFrame(o=>this.mainLoop(o));return}this.lastRenderTimestamp=e;let n=(e-this.lastTimestamp)/1e3,i=Math.min(n,.1);this.lastTimestamp=e,this.performanceMonitor.updateFPS(e);let r=this.core.getUser(this.userId);if(!r){this.rafId=requestAnimationFrame(o=>this.mainLoop(o));return}if(this.mode==="local"){if(this.tickRate===0){let d=performance.now();this.render();let u=performance.now()-d;this.performanceMonitor.recordFrameTiming(0,u),this.rafId=requestAnimationFrame(l=>this.mainLoop(l));return}if(!this.firstTickDone){this.firstTickDone=!0,this.lastTimestamp=e,this.accumulatedTime=0,this.rafId=requestAnimationFrame(d=>this.mainLoop(d));return}this.accumulatedTime+=i;let o=1/this.tickRate;this.accumulatedTime>.5&&(this.accumulatedTime=o);let a=0,c=0;for(;this.accumulatedTime>=o&&a<5;){let d=performance.now();if(this.collectAndApplyInput(r),this.options.application.update(this.core,o),this.options.application.updateUser(this.core,r,o),r.clearTextInputs(),r.hasAudioConfigCommands()&&r.applyAudioConfigCommands(r.flushAudioConfigCommands()),r.hasSoundCommands()&&r.applyAudioCommands(r.flushSoundCommands()),r.hasPostProcessCommands()){let l=r.flushPostProcessCommands(),m=this.postProcessOrderCollector.convertCommands(l);this.applyPostProcessOrders(m)}if(r.hasPendingMacroOrders()){let l=r.flushMacroOrders();r.applyMacroOrders(l)}let u=r.updateMacros();if(r.processMacroEvents(u),r.hasBridgeMessages()){let l=r.getBridgeMessages();this.dispatchLocalBridgeMessages(l)}this.core.endTickSplit(),c+=performance.now()-d,this.accumulatedTime-=o,a++}if(a>0){let d=performance.now();this.render();let u=performance.now()-d;this.performanceMonitor.recordFrameTiming(c,u)}}else{let o=r.updateMacros();r.processMacroEvents(o),this.collectAndSendInput()}this.rafId=requestAnimationFrame(o=>this.mainLoop(o))}collectAndApplyInput(e){if(!this.input)return;let t=this.rendererManager.getCanvas();if(t){let a=e.getDisplays(),c=a.length>0?a[0].size.x:this.options.width,d=a.length>0?a[0].size.y:this.options.height,l=this.rendererManager.getRenderer()?.getOffsets?.(),m={offsetX:l?.offsetX??0,offsetY:l?.offsetY??0},f=T.InputCollector.collectMousePosition(this.input,t,c,d,m);e.setMousePosition(f.x,f.y,f.over),e.updateMacroMouse(f.x,f.y,f.isLeftDown);let g=T.InputCollector.collectTouchPositions(this.input,t,c,d,10,m);this.options.debug&&g.length>0&&console.warn("\u{1F4F1} Collected touches:",g),g.forEach(h=>{e.setTouchPosition(h.id,h.x,h.y,h.over)})}let n=T.InputCollector.collectTextInputs(this.input);n.length>0&&e.setTextInputs(n);let i=e.getInputBindingRegistry(),r=i.getAllAxes(),o=i.getAllButtons();if(r.length>0||o.length>0){let a=T.InputCollector.collectAxisSources(r,this.input),c=T.InputCollector.collectButtonSourcesWithTransitions(o,this.input);r.forEach(d=>{let u=i.evaluateAxis(d.bindingId,a);e.setAxis(d.name,u)}),o.forEach(d=>{let u=new Map,l=new Map,m=new Map;for(let[R,y]of c)u.set(R,y.pressed),l.set(R,y.justPressed),m.set(R,y.justReleased);let f=i.evaluateButton(d.bindingId,u),g=i.evaluateButton(d.bindingId,l),h=i.evaluateButton(d.bindingId,m);e.setButton(d.name,f),e.setButton(`${d.name}_justPressed`,g),e.setButton(`${d.name}_justReleased`,h)})}this.input.poll?.()}collectAndSendInput(){!this.networkSync||!this.input||this.networkSync.sendInput(this.input)}render(){let e=this.core.getUser(this.userId);if(e){let t=e.getMacroRenderOrders();for(let[n,i]of t){let r=e.getLayerById(n);r&&i.length>0&&r.addTemporaryOrders(i)}}this.rendererManager.render(this.core,this.userId)}onCorePaletteChanged(e){this.log(`Palette changed, updating renderer (${e.size} colors)`);let t=[];for(let i=0;i<256;i++){let r=e.get(i);r?t.push({r:r.r,g:r.g,b:r.b,a:r.a}):t.push({r:0,g:0,b:0,a:0})}let n=this.rendererManager.getRenderer();if(!n){console.warn("[ClientRuntime] Cannot update palette: renderer is null");return}"setPalette"in n&&typeof n.setPalette=="function"?(n.setPalette(t),this.log("\u2713 Renderer palette updated successfully")):console.warn("[ClientRuntime] Renderer does not have setPalette method")}onCoreBitmapFontChanged(e){this.log(`Bitmap font ${e} changed, updating renderer`);let t=this.core.getBitmapFont(e);if(!t){console.warn(`[ClientRuntime] Font ${e} not found in registry`);return}let n=new Map,i=0;for(let o=0;o<256;o++){let a=t.getGlyph(o);a&&(n.set(o,a),i++)}this.log(`Built bitmap font map with ${i} glyphs, dimensions: ${t.getCharWidth()}x${t.getCharHeight()} (cell: ${t.getCellWidth()}x${t.getCellHeight()})`);let r=this.rendererManager.getRenderer();if(!r){console.warn("[ClientRuntime] Cannot update font: renderer is null");return}"setBitmapFont"in r&&typeof r.setBitmapFont=="function"?(r.setBitmapFont(n,t.getCharWidth(),t.getCharHeight(),t.getCellWidth(),t.getCellHeight()),this.log("\u2713 Renderer bitmap font updated successfully"),this.postProcessOverlay&&"syncWithRenderer"in this.postProcessOverlay&&"getCellWidth"in r&&"getCellHeight"in r&&"getCurrentScale"in r&&"getGridSize"in r&&(this.postProcessOverlay.syncWithRenderer(r),this.log("\u2713 PostProcessOverlay synced with renderer dimensions"))):console.warn("[ClientRuntime] Renderer does not have setBitmapFont method")}getAudioManager(){return this.audioManager}getAudioContext(){return this.audioManager?.getContext()??null}applyAmbientEffectConfig(e){let t=this.rendererManager?.getRenderer();t&&"setAmbientEffect"in t&&(e.enabled?t.setAmbientEffect({blur:e.blur,scale:e.scale}):t.setAmbientEffect(!1),this.log(`Ambient effect ${e.enabled?"enabled":"disabled"}`))}applyPostProcessOrders(e){if(!this.postProcessOverlay){this.log("PostProcessOverlay not initialized, skipping post-process orders");return}for(let t of e)switch(t.type){case b.PostProcessOrderType.SetConfig:{let n={};t.scanlines&&(n.scanlines={enabled:t.scanlines.enabled,opacity:t.scanlines.opacity,pattern:this.patternFromType(t.scanlines.pattern),color:{r:t.scanlines.colorR,g:t.scanlines.colorG,b:t.scanlines.colorB}}),t.ambientEffect&&(n.ambientEffect={enabled:t.ambientEffect.enabled,blur:t.ambientEffect.blur,scale:t.ambientEffect.scale}),this.postProcessOverlay.setConfig(Object.keys(n).length>0?n:null),n.ambientEffect&&this.applyAmbientEffectConfig(n.ambientEffect);break}case b.PostProcessOrderType.SetScanlines:{this.postProcessOverlay.setScanlines({enabled:t.enabled,opacity:t.opacity,pattern:this.patternFromType(t.pattern),color:{r:t.colorR,g:t.colorG,b:t.colorB}});break}case b.PostProcessOrderType.SetAmbientEffect:{this.applyAmbientEffectConfig({enabled:t.enabled,blur:t.blur,scale:t.scale});break}case b.PostProcessOrderType.SetScalingMode:{this.applyScalingMode(t.mode);break}case b.PostProcessOrderType.SetGrid:{this.applyGridConfig(t);break}}}applyScalingMode(e){let t=this.rendererManager.getRenderer();if(t&&"setScalingMode"in t){let n=(0,O.valueToScalingMode)(e);t.setScalingMode(n),this.log(`Scaling mode set to ${n}`)}}applyGridConfig(e){let t=this.rendererManager.getRenderer();if(t&&"setGrid"in t){let n=e.colorA/255;t.setGrid({enabled:e.enabled,color:`rgba(${e.colorR},${e.colorG},${e.colorB},${n})`,lineWidth:e.lineWidth}),this.log(`Grid ${e.enabled?"enabled":"disabled"}`)}}patternFromType(e){switch(e){case 0:return"horizontal";case 1:return"vertical";case 2:return"grid";default:return"horizontal"}}getPostProcessOverlay(){return this.postProcessOverlay}dispatchLocalBridgeMessages(e){for(let t of e){let{channel:n,data:i}=t,r=this.localBridgeHandlers.get(n);if(r)for(let o of r)try{o(i)}catch(a){console.error(`[ClientRuntime] Bridge handler error on '${n}':`,a)}for(let o of this.localBridgeWildcardHandlers)try{o(n,i)}catch(a){console.error("[ClientRuntime] Bridge wildcard handler error:",a)}this.log(`Bridge message dispatched on channel '${n}'`)}}sendBridge(e,t){if(this.mode==="connected"&&this.networkSync)this.networkSync.sendBridge(e,t);else if(this.mode==="local"){let n=this.core.getUser(this.userId);n&&this.options.application.onBridgeMessage&&(this.options.application.onBridgeMessage(this.core,n,e,t),this.log(`Bridge message sent to application on channel '${e}'`))}}onBridge(e,t){this.mode==="connected"&&this.networkSync?this.networkSync.onBridge(e,t):this.mode==="local"&&(e==="*"?this.localBridgeWildcardHandlers.add(t):(this.localBridgeHandlers.has(e)||this.localBridgeHandlers.set(e,new Set),this.localBridgeHandlers.get(e).add(t)),this.log(`Bridge handler registered for channel '${e}'`))}offBridge(e,t){this.mode==="connected"&&this.networkSync?this.networkSync.offBridge(e,t):this.mode==="local"&&(e==="*"?this.localBridgeWildcardHandlers.delete(t):this.localBridgeHandlers.get(e)?.delete(t))}removeAllBridgeHandlers(e){this.mode==="connected"&&this.networkSync?this.networkSync.removeAllBridgeHandlers(e):this.mode==="local"&&(e===void 0?(this.localBridgeHandlers.clear(),this.localBridgeWildcardHandlers.clear()):e==="*"?this.localBridgeWildcardHandlers.clear():this.localBridgeHandlers.delete(e))}log(e){this.options.debug&&console.warn(`[ClientRuntime/${this.mode}] ${e}`)}};v($,"ClientRuntime");var A=$;var H=require("@utsp/render"),G=require("@utsp/audio");
|
|
1
|
+
"use strict";var F=Object.defineProperty;var K=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var V=Object.prototype.hasOwnProperty;var $=(c,e,t)=>e in c?F(c,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):c[e]=t;var f=(c,e)=>F(c,"name",{value:e,configurable:!0});var Y=(c,e)=>{for(var t in e)F(c,t,{get:e[t],enumerable:!0})},j=(c,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of H(e))!V.call(c,r)&&r!==t&&F(c,r,{get:()=>e[r],enumerable:!(i=K(e,r))||i.enumerable});return c};var z=c=>j(F({},"__esModule",{value:!0}),c);var o=(c,e,t)=>($(c,typeof e!="symbol"?e+"":e,t),t);var X={};Y(X,{AudioManager:()=>W.AudioManager,ClientRuntime:()=>A,RendererType:()=>P,ScalingMode:()=>D.ScalingMode});module.exports=z(X);var C=require("@utsp/core"),R=require("@utsp/render"),I=require("@utsp/types"),v=require("@utsp/input"),q=require("@utsp/network-client"),Q=require("@utsp/audio");var N=require("@utsp/types"),P=(t=>(t.TerminalGL="webgl",t.Terminal2D="terminal2d",t))(P||{});var O=class O{constructor(e=60){o(this,"frameCount",0);o(this,"fps",0);o(this,"fpsUpdateTime",0);o(this,"lastCoreTime",0);o(this,"lastRenderTime",0);o(this,"lastTotalTime",0);o(this,"coreTimeSamples",[]);o(this,"renderTimeSamples",[]);o(this,"totalTimeSamples",[]);o(this,"maxSamples");if(e<=0)throw new Error("maxSamples must be positive");this.maxSamples=e}startTracking(e){this.fpsUpdateTime=e,this.frameCount=0,this.fps=0}updateFPS(e){this.frameCount++,e-this.fpsUpdateTime>=1e3&&(this.fps=Math.round(this.frameCount*1e3/(e-this.fpsUpdateTime)),this.frameCount=0,this.fpsUpdateTime=e)}recordFrameTiming(e,t){let i=e+t;this.lastCoreTime=e,this.lastRenderTime=t,this.lastTotalTime=i,this.coreTimeSamples.push(e),this.renderTimeSamples.push(t),this.totalTimeSamples.push(i),this.coreTimeSamples.length>this.maxSamples&&(this.coreTimeSamples.shift(),this.renderTimeSamples.shift(),this.totalTimeSamples.shift())}getFPS(){return this.fps}getLastFrameTiming(){if(!(this.lastCoreTime===0&&this.lastRenderTime===0))return{coreTime:this.lastCoreTime,renderTime:this.lastRenderTime,totalTime:this.lastTotalTime}}getAverageFrameTiming(){if(this.coreTimeSamples.length!==0)return{coreTime:this.average(this.coreTimeSamples),renderTime:this.average(this.renderTimeSamples),totalTime:this.average(this.totalTimeSamples)}}getStats(){return{fps:this.fps,lastFrame:this.getLastFrameTiming(),avgFrame:this.getAverageFrameTiming(),sampleCount:this.coreTimeSamples.length,maxSamples:this.maxSamples}}reset(){this.frameCount=0,this.fps=0,this.fpsUpdateTime=0,this.lastCoreTime=0,this.lastRenderTime=0,this.lastTotalTime=0,this.coreTimeSamples=[],this.renderTimeSamples=[],this.totalTimeSamples=[]}average(e){return e.length===0?0:e.reduce((t,i)=>t+i,0)/e.length}};f(O,"PerformanceMonitor");var k=O;var J="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",M={glyphWidth:8,glyphHeight:8,cellWidth:8,cellHeight:8,atlasBlocks:1,atlasWidth:128,atlasHeight:128};function G(){let c=atob(J),e=new Uint8Array(c.length);for(let t=0;t<c.length;t++)e[t]=c.charCodeAt(t);return e}f(G,"decodeDefaultAtlas");var x=class x{constructor(e,t={}){o(this,"renderer");o(this,"options");this.renderer=e,this.options={debug:t.debug??!1,useImageDataRendering:t.useImageDataRendering??!1}}async initialize(e){if("setImageDataRendering"in this.renderer&&this.options.useImageDataRendering&&(this.renderer.setImageDataRendering(!0),this.log("ImageData rendering enabled")),"setImageFont"in this.renderer&&typeof this.renderer.setImageFont=="function"){this.log("Loading default 8x8 font atlas...");let t=G();await this.renderer.setImageFont(t,M.glyphWidth,M.glyphHeight,M.cellWidth,M.cellHeight,M.atlasBlocks),this.log("Default 8x8 font atlas loaded")}await this.waitForReady(),this.log("Initialized and ready")}async waitForReady(e=100,t=50){this.log("Waiting for renderer to be ready");let i=0;return new Promise((r,n)=>{let s=f(()=>{if(i++,this.renderer.isReady())this.log(`Renderer ready after ${i*t}ms`),r();else if(i>=e){let u=`Renderer failed to be ready after ${e*t}ms`;this.log(u),n(new Error(u))}else setTimeout(s,t)},"check");s()})}async loadDefaultFont(e){console.warn("[RendererManager] loadDefaultFont() is deprecated. Use ImageFont instead.")}render(e,t){if(!this.renderer.isReady())return console.warn("[RENDERER MANAGER] Renderer not ready"),!1;let i=e.getRenderState(t);if(!i||i.displays.length===0)return console.warn("[RENDERER MANAGER] No render state or no displays"),!1;let r=i.displays[0];return this.renderer.renderDisplayData(r),!0}getRenderer(){return this.renderer}getCanvas(){return this.renderer.getCanvas()}isReady(){return this.renderer.isReady()}destroy(){this.log("Destroying renderer"),this.renderer.destroy()}log(e){this.options.debug&&console.warn(`[RendererManager] ${e}`)}};f(x,"RendererManager");var U=x;var S=require("@utsp/input");var B=class B{constructor(e,t,i,r,n){o(this,"network");o(this,"core");o(this,"rendererManager");o(this,"performanceMonitor");o(this,"options");o(this,"audioManager",null);o(this,"postProcessCallback",null);o(this,"userId","");o(this,"lastReceivedTick",-1);o(this,"connected",!1);this.network=e,this.core=t,this.rendererManager=i,this.performanceMonitor=r,this.options={serverUrl:n.serverUrl,username:n.username,token:n.token??"",debug:n.debug??!1,autoReconnect:n.autoReconnect??!0,canvasWidth:n.canvasWidth,canvasHeight:n.canvasHeight}}async connect(){this.log(`Connecting to ${this.options.serverUrl}`),await this.network.connect(),this.connected=!0,this.log("Connected to server"),this.setupNetworkHandlers()}async joinGame(e){return new Promise((t,i)=>{this.network.send("join",{username:this.options.username,token:this.options.token}),this.network.on("join_response",r=>{if(r.success){this.userId=r.userId,this.log(`Joined game as ${this.userId}`);let n=this.core.createUser(this.userId,this.options.username);this.audioManager&&n.setAudioProcessor(this.audioManager),e.initUser(this.core,n,{username:this.options.username,token:this.options.token}),t(this.userId)}else i(new Error(r.error||"Failed to join game"))}),setTimeout(()=>i(new Error("Join timeout")),5e3)})}sendInput(e){let t=this.core.getUser(this.userId);if(!t)return;let i=this.rendererManager.getCanvas();if(i){let p=this.rendererManager.getRenderer()?.getOffsets?.(),T={offsetX:p?.offsetX??0,offsetY:p?.offsetY??0},b=S.InputCollector.collectMousePosition(e,i,this.options.canvasWidth,this.options.canvasHeight,T);t.setMousePosition(b.x,b.y,b.over),t.updateMacroMouse(b.x,b.y,b.isLeftDown),S.InputCollector.collectTouchPositions(e,i,this.options.canvasWidth,this.options.canvasHeight,10,T).forEach(w=>{t.setTouchPosition(w.id,w.x,w.y,w.over)})}let r=t.getInputBindingRegistry(),n=r.getAllAxes(),s=r.getAllButtons(),a=S.InputCollector.collectAxisSources(n,e),u=S.InputCollector.collectButtonSources(s,e),d=S.InputCollector.collectTextInputs(e);d.length>0&&t.setTextInputs(d);let h={};n.forEach(m=>{let p=r.evaluateAxis(m.bindingId,a);h[m.name]=p,t.setAxis(m.name,p)});let l={};s.forEach(m=>{let p=r.evaluateButton(m.bindingId,u);l[m.name]=p,t.setButton(m.name,p)});let g=t.getMouseDisplayInfo(),y=g?{x:g.localX,y:g.localY}:null;this.network.send("input",{timestamp:Date.now(),axes:h,buttons:l,mousePosition:y,textInputs:d})}disconnect(){this.connected&&(this.network.send("leave",{}),this.network.disconnect(),this.connected=!1,this.log("Disconnected from server"))}getUserId(){return this.userId}isConnected(){return this.connected}destroy(){this.disconnect(),this.network.destroy(),this.log("NetworkSync destroyed")}setupNetworkHandlers(){this.network.on("update",e=>{try{let t=this.convertToUint8Array(e,"update");if(!t)return;let i=this.core.applyUpdatePacketBuffer(this.userId,t);i?(this.postProcessCallback&&i.postProcessOrders&&i.postProcessOrders.length>0&&this.postProcessCallback(i.postProcessOrders),this.rendererManager.render(this.core,this.userId)):this.log("Failed to apply update packet")}catch(t){this.log(`Error applying update packet: ${t}`)}}),this.network.on("update-static",e=>{this.handleUpdatePacket(e,"update-static")}),this.network.on("update-dynamic",e=>{this.handleUpdatePacket(e,"update-dynamic")}),this.network.on("load",e=>{try{let t=this.convertToUint8Array(e,"load");if(!t)return;this.core.applyLoadPacket(t)?this.log("Load packet applied successfully"):this.log("Failed to apply load packet")}catch(t){this.log(`Error applying load packet: ${t}`)}}),this.network.on("input-bindings",e=>{this.core.applyInputBindingsLoadPacket(this.userId,e)?this.log("Input bindings configured"):this.log("Failed to apply input bindings")}),this.audioManager&&this.setupSoundHandlers(),this.network.on("disconnect",()=>{this.connected=!1,this.log("Disconnected from server")})}handleUpdatePacket(e,t){try{let i=this.convertToUint8Array(e,t);if(!i)return;let r=new DataView(i.buffer,i.byteOffset,i.byteLength),n=Number(r.getBigUint64(0,!1));if(t==="update-dynamic"&&n<this.lastReceivedTick)return;n>this.lastReceivedTick&&(this.lastReceivedTick=n);let s=this.core.applyUpdatePacketBuffer(this.userId,i);if(s){console.warn(`[CLIENT] ${t}: ${i.length}B (tick ${n}) - APPLIED`),this.postProcessCallback&&s.postProcessOrders&&s.postProcessOrders.length>0&&this.postProcessCallback(s.postProcessOrders),this.options.debug&&this.debugRenderState();let a=performance.now();this.rendererManager.render(this.core,this.userId);let u=performance.now()-a;this.performanceMonitor.recordFrameTiming(0,u),this.options.debug&&console.warn(`[CLIENT] render() completed for ${t} (${u.toFixed(2)}ms)`)}else console.warn(`[CLIENT] Failed to apply ${t} packet (tick ${n})`)}catch(i){this.log(`Error applying ${t} update packet: ${i}`),console.error(i)}}convertToUint8Array(e,t){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):Array.isArray(e)?new Uint8Array(e):e.data&&Array.isArray(e.data)?new Uint8Array(e.data):typeof e=="object"&&e.type==="Buffer"?new Uint8Array(e.data):(this.log(`Unknown data type for ${t} packet: ${typeof e}`),null)}debugRenderState(){let e=this.core.getUser(this.userId);if(e){let i=e.getLayers();console.warn(`[CLIENT] User has ${i.length} layers`),i.forEach((r,n)=>{let s=r.getOrders(),a=r.getStatic();(s.length>0||a)&&console.warn(` Layer ${n}: ${s.length} orders, static=${a}, z=${r.getZOrder()}`)})}let t=this.rendererManager.isReady();console.warn(`[CLIENT] Renderer ready: ${t}`)}log(e){this.options.debug&&console.warn(`[NetworkSync] ${e}`)}setAudioManager(e){if(this.audioManager=e,e&&this.userId){let t=this.core.getUser(this.userId);t&&t.setAudioProcessor(e)}this.connected&&e&&this.setupSoundHandlers()}setPostProcessCallback(e){this.postProcessCallback=e}setupSoundHandlers(){this.audioManager&&(this.network.on("sound-load",async e=>{e.mode==="file"?await this.handleSoundLoad(e):e.mode==="external"&&await this.handleSoundExternalLoad(e)}),this.log("Sound handlers registered"))}async handleSoundLoad(e){if(!this.audioManager){this.log("Cannot load sounds: AudioManager not initialized");return}let t=this.audioManager.getSoundBank();if(!t){this.log("Cannot load sounds: SoundBank not initialized");return}for(let i of e.sounds)try{await t.loadFromData(i.soundId,i.name,i.data),this.log(`Loaded sound: ${i.name} (${i.data.length} bytes)`),this.sendAudioAck({type:"sound-loaded",soundId:i.soundId,name:i.name})}catch(r){console.error(`[NetworkSync] Failed to load sound "${i.name}":`,r),this.sendAudioAck({type:"sound-error",soundId:i.soundId,name:i.name,error:String(r)})}}async handleSoundExternalLoad(e){if(!this.audioManager){this.log("Cannot load external sounds: AudioManager not initialized");return}let t=this.audioManager.getSoundBank();if(!t){this.log("Cannot load external sounds: SoundBank not initialized");return}for(let i of e.sounds)try{await t.loadFromUrl(i.soundId,i.name,i.url),this.log(`Loaded external sound: ${i.name} from ${i.url}`),this.sendAudioAck({type:"sound-loaded",soundId:i.soundId,name:i.name})}catch(r){console.error(`[NetworkSync] Failed to load external sound "${i.name}":`,r),this.sendAudioAck({type:"sound-error",soundId:i.soundId,name:i.name,error:String(r)})}}sendAudioAck(e){this.network.send("audio-ack",e),this.log(`Sent audio-ack: ${e.type}`)}sendBridge(e,t){this.network.sendBridge(e,t),this.log(`Bridge sent on channel '${e}'`)}onBridge(e,t){this.network.onBridge(e,t),this.log(`Bridge handler registered for channel '${e}'`)}offBridge(e,t){this.network.offBridge(e,t),this.log(`Bridge handler removed for channel '${e}'`)}removeAllBridgeHandlers(e){this.network.removeAllBridgeHandlers(e),this.log(e?`All bridge handlers removed for '${e}'`:"All bridge handlers removed")}};f(B,"NetworkSync");var E=B;var L=class L{constructor(e){o(this,"core");o(this,"rendererManager");o(this,"rendererType");o(this,"input",null);o(this,"networkSync",null);o(this,"options");o(this,"running",!1);o(this,"startTime",0);o(this,"lastTimestamp",0);o(this,"userId","");o(this,"mode");o(this,"visibilityChangeHandler");o(this,"tickRate",30);o(this,"accumulatedTime",0);o(this,"FRAME_TIME_MIN",1e3/60);o(this,"lastRenderTimestamp",0);o(this,"rafId",0);o(this,"firstTickDone",!1);o(this,"performanceMonitor");o(this,"renderMode","continuous");o(this,"renderRequested",!1);o(this,"autoplayOverlay",null);o(this,"autoplay",!0);o(this,"audioManager",null);o(this,"postProcessOverlay",null);o(this,"postProcessOrderCollector",new C.PostProcessOrderCollector);o(this,"localBridgeHandlers",new Map);o(this,"localBridgeWildcardHandlers",new Set);this.mode=e.mode,e.mode==="local"?(this.options={mode:"local",application:e.application,container:e.container,debug:e.debug??!1,width:e.width??80,height:e.height??25,userId:e.userId??"local",username:e.username??"User",renderer:e.renderer??"webgl",useImageDataRendering:e.useImageDataRendering??!0,mobileInputConfig:e.mobileInputConfig,captureInput:e.captureInput??!1,inputEnabled:e.inputEnabled??!0,autoplay:e.autoplay??!0,autoplayOptions:e.autoplayOptions,scalingMode:e.scalingMode??I.ScalingMode.None},this.userId=e.userId??"local",this.autoplay=e.autoplay??!0):(this.options={mode:"connected",application:e.application,container:e.container,serverUrl:e.serverUrl,username:e.username??"Player",debug:e.debug??!1,width:e.width??80,height:e.height??25,autoReconnect:e.autoReconnect??!0,token:e.token,renderer:e.renderer??"webgl",useImageDataRendering:e.useImageDataRendering??!0,mobileInputConfig:e.mobileInputConfig,captureInput:e.captureInput??!1,inputEnabled:e.inputEnabled??!0,autoplay:e.autoplay??!0,autoplayOptions:e.autoplayOptions,scalingMode:e.scalingMode??I.ScalingMode.None},this.autoplay=e.autoplay??!0),this.log(`Initializing ClientRuntime (${this.mode} mode)`),this.core=new C.Core({mode:"client",maxUsers:this.mode==="local"?1:100}),this.core.onPaletteChanged(i=>{this.onCorePaletteChanged(i)}),this.core.onBitmapFontChanged(i=>{this.onCoreBitmapFontChanged(i)}),this.core.onImageFontChanged(i=>{this.onCoreImageFontChanged(i)}),this.visibilityChangeHandler=()=>{!document.hidden&&this.running&&(this.lastTimestamp=performance.now(),this.accumulatedTime=0,this.log("Tab visible: Reset timing"))},document.addEventListener("visibilitychange",this.visibilityChangeHandler);let t=this.createRenderer();if(this.rendererType=this.options.renderer??"webgl",this.rendererManager=new U(t,{debug:this.options.debug,useImageDataRendering:this.options.useImageDataRendering}),this.options.inputEnabled?this.input=new v.UnifiedInputRouter({enableKeyboardMouse:!0,enableGamepad:!0,enableMobile:!0,targetElement:window,mobileTargetElement:void 0,debug:this.options.debug,keyboardConfig:{preventDefault:this.options.captureInput??!1,stopPropagation:this.options.captureInput??!1},mouseConfig:{preventDefault:this.options.captureInput??!1,stopPropagation:this.options.captureInput??!1},mobileConfig:{preventDefault:this.options.mobileInputConfig?.preventDefault??!0,passive:this.options.mobileInputConfig?.passive??!1,maxTouches:this.options.mobileInputConfig?.maxTouches??10}}):this.log("Input disabled (inputEnabled: false)"),this.performanceMonitor=new k(60),this.mode==="connected"){let i=this.options,r=new q.SocketIOClient({url:i.serverUrl,autoReconnect:i.autoReconnect,auth:{username:i.username,token:i.token},debug:this.options.debug});this.networkSync=new E(r,this.core,this.rendererManager,this.performanceMonitor,{serverUrl:i.serverUrl,username:i.username,token:i.token,debug:this.options.debug,autoReconnect:i.autoReconnect,canvasWidth:this.options.width,canvasHeight:this.options.height})}this.tickRate=e.tickRate??30,this.tickRate===0&&!e.renderMode?(this.renderMode="on-demand",this.log("tickRate is 0: automatically enabling on-demand render mode")):this.renderMode=e.renderMode??"continuous",this.log(`Configured: tickRate=${this.tickRate}, renderMode=${this.renderMode}`),this.log("ClientRuntime initialized")}getMode(){return this.mode}getRendererType(){return this.rendererType}isRunning(){return this.running}createRenderer(){if((this.options.renderer??"webgl")==="terminal2d"){this.log("Creating Terminal 2D renderer");let n=new R.Terminal2D(this.options.container,{fixedCols:this.options.width,fixedRows:this.options.height,cellAspectRatio:1,scalingMode:this.options.scalingMode??I.ScalingMode.None});return this.options.useImageDataRendering&&(this.log("Enabling ImageData rendering (pixel-perfect, optimized)"),n.setImageDataRendering(!0)),this.log("Canvas 2D renderer created successfully"),n}this.log("Creating TerminalGL renderer");let i=document.createElement("canvas").getContext("webgl");if(!i)throw new Error("WebGL not supported. TerminalGL requires WebGL 1.0.");if(!i.getExtension("OES_element_index_uint"))throw new Error("OES_element_index_uint extension not supported. TerminalGL requires this extension for large terminals (256x256). Supported on 97% of devices (Android 4.3+, iOS 8+, Desktop).");if(!(this.options.container instanceof HTMLDivElement))throw new Error(`TerminalGL requires container to be an HTMLDivElement. Received: ${this.options.container.tagName}`);let r=new R.TerminalGL(this.options.container,{cols:this.options.width,rows:this.options.height,charWidth:8,charHeight:8,scalingMode:this.options.scalingMode??I.ScalingMode.None});return this.log("TerminalGL created successfully"),r}setTickRate(e){if(e<0||e>1e3)throw new Error(`Invalid tick rate: ${e}. Must be between 0 and 1000.`);if(this.mode==="connected"){this.log("setTickRate() has no effect in connected mode");return}this.tickRate=e,e===0&&this.renderMode==="continuous"?(this.renderMode="on-demand",this.log(`Tick rate set to ${e} TPS (update loop disabled, automatically switched to on-demand render mode)`)):this.log(`Tick rate set to ${e} TPS ${e===0?"(update loop disabled)":""}`)}setRenderMode(e){this.renderMode=e,this.log(`Render mode set to ${e}`)}setMaxFPS(e){if(e<=0||e>240)throw new Error(`Invalid FPS: ${e}. Must be between 1 and 240.`);this.FRAME_TIME_MIN=1e3/e,this.log(`Max FPS set to ${e}`)}getTickRate(){return this.tickRate}requestRender(){this.renderMode==="on-demand"?(this.renderRequested=!0,this.log("Render requested")):this.log("requestRender() has no effect in continuous mode")}async start(){if(this.running){this.log("Already running");return}this.log("Starting ClientRuntime"),this.audioManager=new Q.AudioManager({debug:this.options.debug}),this.autoplay?(this.log("Autoplay enabled, initializing AudioManager..."),this.audioManager.initialize()):(this.log("Autoplay disabled, showing overlay..."),await new Promise(i=>{this.autoplayOverlay=new R.AutoplayOverlay(this.options.container,{...this.options.autoplayOptions,onStart:()=>{this.log("User clicked start button"),this.audioManager&&(this.audioManager.initialize(),this.audioManager.playStartSound()),i()}})}),this.log("Autoplay overlay dismissed, continuing startup...")),await this.rendererManager.initialize(this.core),this.log("Renderer is ready"),this.postProcessOverlay=new R.PostProcessOverlay(this.options.container),this.log("PostProcessOverlay created"),this.onCorePaletteChanged(this.core.getPalette()),this.log("Initial palette sent to renderer"),this.log("Calling application.init()"),await this.options.application.init(this.core,this);let e=this.rendererManager.getCanvas();e&&this.input&&this.input.setMobileTarget(e),this.mode==="connected"&&this.networkSync?(this.log("Connecting to server"),this.audioManager&&this.networkSync.setAudioManager(this.audioManager),this.networkSync.setPostProcessCallback(i=>{this.applyPostProcessOrders(i)}),await this.networkSync.connect(),this.userId=await this.networkSync.joinGame(this.options.application)):await this.createLocalUser();let t=this.core.getUser(this.userId);if(t){let i=t.getDisplays();if(i.length>0){let n=i[0].getSize(),s=n.x,a=n.y,u=this.rendererManager.getRenderer(),d,h;if(this.rendererType==="webgl"){let g=u.getGridSize();d=g.cols,h=g.rows}else{let l=u;d=l.getCols(),h=l.getRows()}(d!==s||h!==a)&&(this.log(`Adjusting renderer from ${d}\xD7${h} to match display ${s}\xD7${a}`),u.resize(s,a))}}this.input&&this.input.start(),this.running=!0,this.startTime=performance.now(),this.lastTimestamp=this.startTime,this.lastRenderTimestamp=this.startTime,this.accumulatedTime=0,this.firstTickDone=!1,this.performanceMonitor.reset(),this.performanceMonitor.startTracking(this.startTime),this.log("Starting main loop"),this.mainLoop(this.lastTimestamp)}async stop(){if(!this.running)return;this.log("Stopping ClientRuntime"),this.running=!1,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=0),this.audioManager&&this.audioManager.stopAll(),this.input&&this.input.stop(),this.mode==="connected"&&this.networkSync&&this.networkSync.disconnect();let e=this.core.getUser(this.userId);e&&this.options.application.destroyUser&&this.options.application.destroyUser(this.core,e,"Runtime stopped"),this.log("ClientRuntime stopped")}getStats(){let e=this.performanceMonitor.getStats();return{mode:this.mode,running:this.running,userCount:this.core.getUsers().length,fps:e.fps,uptime:this.running?performance.now()-this.startTime:0,totalFrames:0,latency:void 0,lastFrameTiming:e.lastFrame,avgFrameTiming:e.avgFrame}}async destroy(){await this.stop(),this.log("Destroying ClientRuntime"),this.visibilityChangeHandler&&(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeHandler=void 0),this.autoplayOverlay&&(this.autoplayOverlay.destroy(),this.autoplayOverlay=null),this.audioManager&&(this.audioManager.destroy(),this.audioManager=null),this.postProcessOverlay&&(this.postProcessOverlay.destroy(),this.postProcessOverlay=null);let e=this.rendererManager.getRenderer();e&&"clearOnResizeCallback"in e&&e.clearOnResizeCallback(),this.options.application.destroy&&this.options.application.destroy(),this.rendererManager.destroy(),this.input&&this.input.destroy(),this.networkSync&&this.networkSync.destroy(),this.log("ClientRuntime destroyed")}async createLocalUser(){let e=this.options;this.log(`Creating local user: ${this.userId}`);let t=this.core.createUser(this.userId,e.username);if(this.audioManager&&t.setAudioProcessor(this.audioManager),this.log("Calling application.initUser()"),this.options.application.initUser(this.core,t,{username:e.username}),t.hasAudioConfigCommands()&&(this.log("Applying audio config commands from initUser()"),t.applyAudioConfigCommands(t.flushAudioConfigCommands())),t.hasPendingMacroOrders()){this.log("Applying macro orders from initUser()");let i=t.flushMacroOrders();t.applyMacroOrders(i)}if(t.hasPostProcessCommands()){this.log("Applying post-process commands from initUser()");let i=t.flushPostProcessCommands(),r=this.postProcessOrderCollector.convertCommands(i);this.applyPostProcessOrders(r)}t.needsSendSounds()&&(await this.loadSoundsFromRegistry(),t.clearSendSounds()),this.log("Performing initial render"),this.core.endTick(),this.render(),this.log("Initial render complete")}async loadSoundsFromRegistry(){if(!this.audioManager){this.log("Cannot load sounds: AudioManager not initialized");return}let e=this.audioManager.getSoundBank();if(!e){this.log("Cannot load sounds: SoundBank not initialized");return}let i=this.core.getSoundRegistry().getAll();if(i.length===0){this.log("No sounds to load from registry");return}this.log(`Loading ${i.length} sounds from Core registry into AudioManager...`);for(let r of i)try{r.loadType==="file"&&r.data?(await e.loadFromData(r.soundId,r.name,r.data),this.log(`\u{1F50A} Loaded sound: ${r.name} (${r.data.length} bytes)`)):r.loadType==="external"&&r.url&&(await e.loadFromUrl(r.soundId,r.name,r.url),this.log(`\u{1F50A} Loaded external sound: ${r.name} from ${r.url}`))}catch(n){console.error(`[ClientRuntime] Failed to load sound "${r.name}":`,n)}this.log(`\u2713 ${e.size} sounds loaded into AudioManager`)}mainLoop(e){if(!this.running){this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=0);return}if(this.renderMode==="on-demand"){this.renderRequested&&(this.renderRequested=!1,this.performanceMonitor.updateFPS(e),this.render()),this.rafId=requestAnimationFrame(s=>this.mainLoop(s));return}let t=e-this.lastRenderTimestamp;if(this.lastRenderTimestamp>0&&t<this.FRAME_TIME_MIN-1){this.rafId=requestAnimationFrame(s=>this.mainLoop(s));return}this.lastRenderTimestamp=e;let i=(e-this.lastTimestamp)/1e3,r=Math.min(i,.1);this.lastTimestamp=e,this.performanceMonitor.updateFPS(e);let n=this.core.getUser(this.userId);if(!n){this.rafId=requestAnimationFrame(s=>this.mainLoop(s));return}if(this.mode==="local"){if(this.tickRate===0){let d=performance.now();this.render();let h=performance.now()-d;this.performanceMonitor.recordFrameTiming(0,h),this.rafId=requestAnimationFrame(l=>this.mainLoop(l));return}if(!this.firstTickDone){this.firstTickDone=!0,this.lastTimestamp=e,this.accumulatedTime=0,this.rafId=requestAnimationFrame(d=>this.mainLoop(d));return}this.accumulatedTime+=r;let s=1/this.tickRate;this.accumulatedTime>.5&&(this.accumulatedTime=s);let a=0,u=0;for(;this.accumulatedTime>=s&&a<5;){let d=performance.now();if(this.collectAndApplyInput(n),this.options.application.update(this.core,s),this.options.application.updateUser(this.core,n,s),n.clearTextInputs(),n.hasAudioConfigCommands()&&n.applyAudioConfigCommands(n.flushAudioConfigCommands()),n.hasSoundCommands()&&n.applyAudioCommands(n.flushSoundCommands()),n.hasPostProcessCommands()){let l=n.flushPostProcessCommands(),g=this.postProcessOrderCollector.convertCommands(l);this.applyPostProcessOrders(g)}if(n.hasPendingMacroOrders()){let l=n.flushMacroOrders();n.applyMacroOrders(l)}let h=n.updateMacros();if(n.processMacroEvents(h),n.hasBridgeMessages()){let l=n.getBridgeMessages();this.dispatchLocalBridgeMessages(l)}this.core.endTickSplit(),u+=performance.now()-d,this.accumulatedTime-=s,a++}if(a>0){let d=performance.now();this.render();let h=performance.now()-d;this.performanceMonitor.recordFrameTiming(u,h)}}else{let s=n.updateMacros();n.processMacroEvents(s),this.collectAndSendInput()}this.rafId=requestAnimationFrame(s=>this.mainLoop(s))}collectAndApplyInput(e){if(!this.input)return;let t=this.rendererManager.getCanvas();if(t){let a=e.getDisplays(),u=a.length>0?a[0].size.x:this.options.width,d=a.length>0?a[0].size.y:this.options.height,l=this.rendererManager.getRenderer()?.getOffsets?.(),g={offsetX:l?.offsetX??0,offsetY:l?.offsetY??0},y=v.InputCollector.collectMousePosition(this.input,t,u,d,g);e.setMousePosition(y.x,y.y,y.over),e.updateMacroMouse(y.x,y.y,y.isLeftDown);let m=v.InputCollector.collectTouchPositions(this.input,t,u,d,10,g);this.options.debug&&m.length>0&&console.warn("\u{1F4F1} Collected touches:",m),m.forEach(p=>{e.setTouchPosition(p.id,p.x,p.y,p.over)})}let i=v.InputCollector.collectTextInputs(this.input);i.length>0&&e.setTextInputs(i);let r=e.getInputBindingRegistry(),n=r.getAllAxes(),s=r.getAllButtons();if(n.length>0||s.length>0){let a=v.InputCollector.collectAxisSources(n,this.input),u=v.InputCollector.collectButtonSourcesWithTransitions(s,this.input);n.forEach(d=>{let h=r.evaluateAxis(d.bindingId,a);e.setAxis(d.name,h)}),s.forEach(d=>{let h=new Map,l=new Map,g=new Map;for(let[T,b]of u)h.set(T,b.pressed),l.set(T,b.justPressed),g.set(T,b.justReleased);let y=r.evaluateButton(d.bindingId,h),m=r.evaluateButton(d.bindingId,l),p=r.evaluateButton(d.bindingId,g);e.setButton(d.name,y),e.setButton(`${d.name}_justPressed`,m),e.setButton(`${d.name}_justReleased`,p)})}this.input.poll?.()}collectAndSendInput(){!this.networkSync||!this.input||this.networkSync.sendInput(this.input)}render(){let e=this.core.getUser(this.userId);if(e){let t=e.getMacroRenderOrders();for(let[i,r]of t){let n=e.getLayerById(i);n&&r.length>0&&n.addTemporaryOrders(r)}}this.rendererManager.render(this.core,this.userId)}onCorePaletteChanged(e){this.log(`Palette changed, updating renderer (${e.size} colors)`);let t=[];for(let r=0;r<256;r++){let n=e.get(r);n?t.push({r:n.r,g:n.g,b:n.b,a:n.a}):t.push({r:0,g:0,b:0,a:0})}let i=this.rendererManager.getRenderer();if(!i){console.warn("[ClientRuntime] Cannot update palette: renderer is null");return}"setPalette"in i&&typeof i.setPalette=="function"?(i.setPalette(t),this.log("\u2713 Renderer palette updated successfully")):console.warn("[ClientRuntime] Renderer does not have setPalette method")}onCoreBitmapFontChanged(e){this.log(`Bitmap font ${e} changed, updating renderer`);let t=this.core.getBitmapFont(e);if(!t){console.warn(`[ClientRuntime] Font ${e} not found in registry`);return}let i=new Map,r=0;for(let s=0;s<256;s++){let a=t.getGlyph(s);a&&(i.set(s,a),r++)}this.log(`Built bitmap font map with ${r} glyphs, dimensions: ${t.getCharWidth()}x${t.getCharHeight()} (cell: ${t.getCellWidth()}x${t.getCellHeight()})`);let n=this.rendererManager.getRenderer();if(!n){console.warn("[ClientRuntime] Cannot update font: renderer is null");return}"setBitmapFont"in n&&typeof n.setBitmapFont=="function"?(n.setBitmapFont(i,t.getCharWidth(),t.getCharHeight(),t.getCellWidth(),t.getCellHeight()),this.log("\u2713 Renderer bitmap font updated successfully"),this.postProcessOverlay&&"syncWithRenderer"in this.postProcessOverlay&&"getCellWidth"in n&&"getCellHeight"in n&&"getCurrentScale"in n&&"getGridSize"in n&&(this.postProcessOverlay.syncWithRenderer(n),this.log("\u2713 PostProcessOverlay synced with renderer dimensions"))):console.warn("[ClientRuntime] Renderer does not have setBitmapFont method")}onCoreImageFontChanged(e){this.log(`Image font ${e} changed, updating renderer`);let t=this.core.getImageFont(e);if(!t){console.warn(`[ClientRuntime] Image font ${e} not found in registry`);return}this.log(`Loading image font with ${t.getAtlasBlocks()} blocks (${t.getAtlasBlocks()*256} chars), glyph: ${t.getGlyphWidth()}x${t.getGlyphHeight()}, cell: ${t.getCellWidth()}x${t.getCellHeight()}`);let i=this.rendererManager.getRenderer();if(!i){console.warn("[ClientRuntime] Cannot update image font: renderer is null");return}"setImageFont"in i&&typeof i.setImageFont=="function"?(i.setImageFont(t.getImageData(),t.getGlyphWidth(),t.getGlyphHeight(),t.getCellWidth(),t.getCellHeight(),t.getAtlasBlocks()),this.log("\u2713 Renderer image font updated successfully"),this.postProcessOverlay&&"syncWithRenderer"in this.postProcessOverlay&&"getCellWidth"in i&&"getCellHeight"in i&&"getCurrentScale"in i&&"getGridSize"in i&&(this.postProcessOverlay.syncWithRenderer(i),this.log("\u2713 PostProcessOverlay synced with renderer dimensions"))):console.warn("[ClientRuntime] Renderer does not have setImageFont method")}getAudioManager(){return this.audioManager}getAudioContext(){return this.audioManager?.getContext()??null}applyAmbientEffectConfig(e){let t=this.rendererManager?.getRenderer();t&&"setAmbientEffect"in t&&(e.enabled?t.setAmbientEffect({blur:e.blur,scale:e.scale}):t.setAmbientEffect(!1),this.log(`Ambient effect ${e.enabled?"enabled":"disabled"}`))}applyPostProcessOrders(e){if(!this.postProcessOverlay){this.log("PostProcessOverlay not initialized, skipping post-process orders");return}for(let t of e)switch(t.type){case C.PostProcessOrderType.SetConfig:{let i={};t.scanlines&&(i.scanlines={enabled:t.scanlines.enabled,opacity:t.scanlines.opacity,pattern:this.patternFromType(t.scanlines.pattern),color:{r:t.scanlines.colorR,g:t.scanlines.colorG,b:t.scanlines.colorB}}),t.ambientEffect&&(i.ambientEffect={enabled:t.ambientEffect.enabled,blur:t.ambientEffect.blur,scale:t.ambientEffect.scale}),this.postProcessOverlay.setConfig(Object.keys(i).length>0?i:null),i.ambientEffect&&this.applyAmbientEffectConfig(i.ambientEffect);break}case C.PostProcessOrderType.SetScanlines:{this.postProcessOverlay.setScanlines({enabled:t.enabled,opacity:t.opacity,pattern:this.patternFromType(t.pattern),color:{r:t.colorR,g:t.colorG,b:t.colorB}});break}case C.PostProcessOrderType.SetAmbientEffect:{this.applyAmbientEffectConfig({enabled:t.enabled,blur:t.blur,scale:t.scale});break}case C.PostProcessOrderType.SetScalingMode:{this.applyScalingMode(t.mode);break}case C.PostProcessOrderType.SetGrid:{this.applyGridConfig(t);break}}}applyScalingMode(e){let t=this.rendererManager.getRenderer();if(t&&"setScalingMode"in t){let i=(0,I.valueToScalingMode)(e);t.setScalingMode(i),this.log(`Scaling mode set to ${i}`)}}applyGridConfig(e){let t=this.rendererManager.getRenderer();if(t&&"setGrid"in t){let i=e.colorA/255;t.setGrid({enabled:e.enabled,color:`rgba(${e.colorR},${e.colorG},${e.colorB},${i})`,lineWidth:e.lineWidth}),this.log(`Grid ${e.enabled?"enabled":"disabled"}`)}}patternFromType(e){switch(e){case 0:return"horizontal";case 1:return"vertical";case 2:return"grid";default:return"horizontal"}}getPostProcessOverlay(){return this.postProcessOverlay}dispatchLocalBridgeMessages(e){for(let t of e){let{channel:i,data:r}=t,n=this.localBridgeHandlers.get(i);if(n)for(let s of n)try{s(r)}catch(a){console.error(`[ClientRuntime] Bridge handler error on '${i}':`,a)}for(let s of this.localBridgeWildcardHandlers)try{s(i,r)}catch(a){console.error("[ClientRuntime] Bridge wildcard handler error:",a)}this.log(`Bridge message dispatched on channel '${i}'`)}}sendBridge(e,t){if(this.mode==="connected"&&this.networkSync)this.networkSync.sendBridge(e,t);else if(this.mode==="local"){let i=this.core.getUser(this.userId);i&&this.options.application.onBridgeMessage&&(this.options.application.onBridgeMessage(this.core,i,e,t),this.log(`Bridge message sent to application on channel '${e}'`))}}onBridge(e,t){this.mode==="connected"&&this.networkSync?this.networkSync.onBridge(e,t):this.mode==="local"&&(e==="*"?this.localBridgeWildcardHandlers.add(t):(this.localBridgeHandlers.has(e)||this.localBridgeHandlers.set(e,new Set),this.localBridgeHandlers.get(e).add(t)),this.log(`Bridge handler registered for channel '${e}'`))}offBridge(e,t){this.mode==="connected"&&this.networkSync?this.networkSync.offBridge(e,t):this.mode==="local"&&(e==="*"?this.localBridgeWildcardHandlers.delete(t):this.localBridgeHandlers.get(e)?.delete(t))}removeAllBridgeHandlers(e){this.mode==="connected"&&this.networkSync?this.networkSync.removeAllBridgeHandlers(e):this.mode==="local"&&(e===void 0?(this.localBridgeHandlers.clear(),this.localBridgeWildcardHandlers.clear()):e==="*"?this.localBridgeWildcardHandlers.clear():this.localBridgeHandlers.delete(e))}log(e){this.options.debug&&console.warn(`[ClientRuntime/${this.mode}] ${e}`)}};f(L,"ClientRuntime");var A=L;var D=require("@utsp/render"),W=require("@utsp/audio");
|
package/dist/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { AutoplayOverlayOptions, PostProcessOverlay } from '@utsp/render';
|
|
|
2
2
|
export { ScalingMode } from '@utsp/render';
|
|
3
3
|
import { AudioManager } from '@utsp/audio';
|
|
4
4
|
export { AudioManager, AudioManagerOptions, ToneOptions } from '@utsp/audio';
|
|
5
|
-
import { IApplication } from '@utsp/types';
|
|
5
|
+
import { IApplication, ScalingMode } from '@utsp/types';
|
|
6
6
|
export { IApplication } from '@utsp/types';
|
|
7
7
|
|
|
8
8
|
/**
|
|
@@ -61,6 +61,19 @@ interface BaseClientRuntimeOptions {
|
|
|
61
61
|
renderMode?: RenderMode;
|
|
62
62
|
/** Tick rate in ticks per second (default: 30). Set to 0 to disable update loop (only init/initUser, no update/updateUser). When set to 0, automatically enables 'on-demand' render mode. */
|
|
63
63
|
tickRate?: number;
|
|
64
|
+
/**
|
|
65
|
+
* Scaling mode for pixel-perfect rendering (default: ScalingMode.None)
|
|
66
|
+
*
|
|
67
|
+
* Controls how the canvas is scaled to fit the container:
|
|
68
|
+
* - ScalingMode.None: Fills available space, may have sub-pixel artifacts (default)
|
|
69
|
+
* - ScalingMode.Eighth: Snaps to 0.125 increments (1.0, 1.125, 1.25...)
|
|
70
|
+
* - ScalingMode.Quarter: Snaps to 0.25 increments (1.0, 1.25, 1.5...)
|
|
71
|
+
* - ScalingMode.Half: Snaps to 0.5 increments (1.0, 1.5, 2.0...)
|
|
72
|
+
* - ScalingMode.Integer: Integer scaling only (1x, 2x, 3x...), crispest pixels
|
|
73
|
+
*
|
|
74
|
+
* Use ScalingMode.Integer for pixel-art style games that need crisp, artifact-free rendering.
|
|
75
|
+
*/
|
|
76
|
+
scalingMode?: ScalingMode;
|
|
64
77
|
/** Capture input events to prevent default browser behavior (Tab, arrows, etc.). Default: false. When true, preventDefault() and stopPropagation() are called on keyboard and mouse events to keep focus in the terminal. All F keys (F1-F12) and Ctrl/Cmd shortcuts are automatically excluded. */
|
|
65
78
|
captureInput?: boolean;
|
|
66
79
|
/** Enable input handling (keyboard, mouse, touch, gamepad). Default: true. When false, no input listeners are created - useful for display-only clients in documentation pages where you want to scroll freely without the client intercepting events. */
|
|
@@ -254,6 +267,11 @@ declare class ClientRuntime {
|
|
|
254
267
|
* Loads the font from registry and updates renderer
|
|
255
268
|
*/
|
|
256
269
|
private onCoreBitmapFontChanged;
|
|
270
|
+
/**
|
|
271
|
+
* Handle image font change from Core
|
|
272
|
+
* Loads the PNG font atlas from registry and updates renderer
|
|
273
|
+
*/
|
|
274
|
+
private onCoreImageFontChanged;
|
|
257
275
|
/**
|
|
258
276
|
* Get the AudioManager instance
|
|
259
277
|
* Returns null before start() is called
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var B=Object.defineProperty;var E=(b,e,t)=>e in b?B(b,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):b[e]=t;var y=(b,e)=>B(b,"name",{value:e,configurable:!0});var s=(b,e,t)=>(E(b,typeof e!="symbol"?e+"":e,t),t);import{Core as L,PostProcessOrderType as C,PostProcessOrderCollector as U}from"@utsp/core";import{TerminalGL as D,Terminal2D as H,AutoplayOverlay as G,PostProcessOverlay as z}from"@utsp/render";import{ScalingMode as W,valueToScalingMode as N}from"@utsp/types";import{UnifiedInputRouter as q,InputCollector as R}from"@utsp/input";import{SocketIOClient as j}from"@utsp/network-client";import{AudioManager as _}from"@utsp/audio";import{ScalingMode as K}from"@utsp/types";var F=(t=>(t.TerminalGL="webgl",t.Terminal2D="terminal2d",t))(F||{});var I=class I{constructor(e=60){s(this,"frameCount",0);s(this,"fps",0);s(this,"fpsUpdateTime",0);s(this,"lastCoreTime",0);s(this,"lastRenderTime",0);s(this,"lastTotalTime",0);s(this,"coreTimeSamples",[]);s(this,"renderTimeSamples",[]);s(this,"totalTimeSamples",[]);s(this,"maxSamples");if(e<=0)throw new Error("maxSamples must be positive");this.maxSamples=e}startTracking(e){this.fpsUpdateTime=e,this.frameCount=0,this.fps=0}updateFPS(e){this.frameCount++,e-this.fpsUpdateTime>=1e3&&(this.fps=Math.round(this.frameCount*1e3/(e-this.fpsUpdateTime)),this.frameCount=0,this.fpsUpdateTime=e)}recordFrameTiming(e,t){let n=e+t;this.lastCoreTime=e,this.lastRenderTime=t,this.lastTotalTime=n,this.coreTimeSamples.push(e),this.renderTimeSamples.push(t),this.totalTimeSamples.push(n),this.coreTimeSamples.length>this.maxSamples&&(this.coreTimeSamples.shift(),this.renderTimeSamples.shift(),this.totalTimeSamples.shift())}getFPS(){return this.fps}getLastFrameTiming(){if(!(this.lastCoreTime===0&&this.lastRenderTime===0))return{coreTime:this.lastCoreTime,renderTime:this.lastRenderTime,totalTime:this.lastTotalTime}}getAverageFrameTiming(){if(this.coreTimeSamples.length!==0)return{coreTime:this.average(this.coreTimeSamples),renderTime:this.average(this.renderTimeSamples),totalTime:this.average(this.totalTimeSamples)}}getStats(){return{fps:this.fps,lastFrame:this.getLastFrameTiming(),avgFrame:this.getAverageFrameTiming(),sampleCount:this.coreTimeSamples.length,maxSamples:this.maxSamples}}reset(){this.frameCount=0,this.fps=0,this.fpsUpdateTime=0,this.lastCoreTime=0,this.lastRenderTime=0,this.lastTotalTime=0,this.coreTimeSamples=[],this.renderTimeSamples=[],this.totalTimeSamples=[]}average(e){return e.length===0?0:e.reduce((t,n)=>t+n,0)/e.length}};y(I,"PerformanceMonitor");var M=I;import{createASCII8x8FontLoad as $}from"@utsp/core";var P=class P{constructor(e,t={}){s(this,"renderer");s(this,"options");this.renderer=e,this.options={debug:t.debug??!1,useImageDataRendering:t.useImageDataRendering??!1}}async initialize(e){await this.loadDefaultFont(e),await this.waitForReady()}async waitForReady(e=100,t=50){this.log("Waiting for renderer to be ready");let n=0;return new Promise((i,r)=>{let o=y(()=>{if(n++,this.renderer.isReady())this.log(`Renderer ready after ${n*t}ms`),i();else if(n>=e){let c=`Renderer failed to be ready after ${e*t}ms`;this.log(c),r(new Error(c))}else setTimeout(o,t)},"check");o()})}async loadDefaultFont(e){this.log("Loading ASCII 8x8 font");let t=$(1);e.hasBitmapFont(t.fontId)||e.loadBitmapFontById(t.fontId,{charWidth:t.width,charHeight:t.height,cellWidth:t.cellWidth,cellHeight:t.cellHeight,glyphs:new Map(t.characters.map(n=>[n.charCode,n.bitmap]))}),"setImageDataRendering"in this.renderer&&this.options.useImageDataRendering&&(this.renderer.setImageDataRendering(!0),this.log("ImageData rendering enabled")),this.log("Font loaded and event triggered")}render(e,t){if(!this.renderer.isReady())return console.warn("[RENDERER MANAGER] Renderer not ready"),!1;let n=e.getRenderState(t);if(!n||n.displays.length===0)return console.warn("[RENDERER MANAGER] No render state or no displays"),!1;let i=n.displays[0];return this.renderer.renderDisplayData(i),!0}getRenderer(){return this.renderer}getCanvas(){return this.renderer.getCanvas()}isReady(){return this.renderer.isReady()}destroy(){this.log("Destroying renderer"),this.renderer.destroy()}log(e){this.options.debug&&console.warn(`[RendererManager] ${e}`)}};y(P,"RendererManager");var k=P;import{InputCollector as T}from"@utsp/input";var A=class A{constructor(e,t,n,i,r){s(this,"network");s(this,"core");s(this,"rendererManager");s(this,"performanceMonitor");s(this,"options");s(this,"audioManager",null);s(this,"postProcessCallback",null);s(this,"userId","");s(this,"lastReceivedTick",-1);s(this,"connected",!1);this.network=e,this.core=t,this.rendererManager=n,this.performanceMonitor=i,this.options={serverUrl:r.serverUrl,username:r.username,token:r.token??"",debug:r.debug??!1,autoReconnect:r.autoReconnect??!0,canvasWidth:r.canvasWidth,canvasHeight:r.canvasHeight}}async connect(){this.log(`Connecting to ${this.options.serverUrl}`),await this.network.connect(),this.connected=!0,this.log("Connected to server"),this.setupNetworkHandlers()}async joinGame(e){return new Promise((t,n)=>{this.network.send("join",{username:this.options.username,token:this.options.token}),this.network.on("join_response",i=>{if(i.success){this.userId=i.userId,this.log(`Joined game as ${this.userId}`);let r=this.core.createUser(this.userId,this.options.username);this.audioManager&&r.setAudioProcessor(this.audioManager),e.initUser(this.core,r,{username:this.options.username,token:this.options.token}),t(this.userId)}else n(new Error(i.error||"Failed to join game"))}),setTimeout(()=>n(new Error("Join timeout")),5e3)})}sendInput(e){let t=this.core.getUser(this.userId);if(!t)return;let n=this.rendererManager.getCanvas();if(n){let p=this.rendererManager.getRenderer()?.getOffsets?.(),v={offsetX:p?.offsetX??0,offsetY:p?.offsetY??0},f=T.collectMousePosition(e,n,this.options.canvasWidth,this.options.canvasHeight,v);t.setMousePosition(f.x,f.y,f.over),t.updateMacroMouse(f.x,f.y,f.isLeftDown),T.collectTouchPositions(e,n,this.options.canvasWidth,this.options.canvasHeight,10,v).forEach(w=>{t.setTouchPosition(w.id,w.x,w.y,w.over)})}let i=t.getInputBindingRegistry(),r=i.getAllAxes(),o=i.getAllButtons(),a=T.collectAxisSources(r,e),c=T.collectButtonSources(o,e),d=T.collectTextInputs(e);d.length>0&&t.setTextInputs(d);let u={};r.forEach(m=>{let p=i.evaluateAxis(m.bindingId,a);u[m.name]=p,t.setAxis(m.name,p)});let l={};o.forEach(m=>{let p=i.evaluateButton(m.bindingId,c);l[m.name]=p,t.setButton(m.name,p)});let h=t.getMouseDisplayInfo(),g=h?{x:h.localX,y:h.localY}:null;this.network.send("input",{timestamp:Date.now(),axes:u,buttons:l,mousePosition:g,textInputs:d})}disconnect(){this.connected&&(this.network.send("leave",{}),this.network.disconnect(),this.connected=!1,this.log("Disconnected from server"))}getUserId(){return this.userId}isConnected(){return this.connected}destroy(){this.disconnect(),this.network.destroy(),this.log("NetworkSync destroyed")}setupNetworkHandlers(){this.network.on("update",e=>{try{let t=this.convertToUint8Array(e,"update");if(!t)return;let n=this.core.applyUpdatePacketBuffer(this.userId,t);n?(this.postProcessCallback&&n.postProcessOrders&&n.postProcessOrders.length>0&&this.postProcessCallback(n.postProcessOrders),this.rendererManager.render(this.core,this.userId)):this.log("Failed to apply update packet")}catch(t){this.log(`Error applying update packet: ${t}`)}}),this.network.on("update-static",e=>{this.handleUpdatePacket(e,"update-static")}),this.network.on("update-dynamic",e=>{this.handleUpdatePacket(e,"update-dynamic")}),this.network.on("load",e=>{try{let t=this.convertToUint8Array(e,"load");if(!t)return;this.core.applyLoadPacket(t)?this.log("Load packet applied successfully"):this.log("Failed to apply load packet")}catch(t){this.log(`Error applying load packet: ${t}`)}}),this.network.on("input-bindings",e=>{this.core.applyInputBindingsLoadPacket(this.userId,e)?this.log("Input bindings configured"):this.log("Failed to apply input bindings")}),this.audioManager&&this.setupSoundHandlers(),this.network.on("disconnect",()=>{this.connected=!1,this.log("Disconnected from server")})}handleUpdatePacket(e,t){try{let n=this.convertToUint8Array(e,t);if(!n)return;let i=new DataView(n.buffer,n.byteOffset,n.byteLength),r=Number(i.getBigUint64(0,!1));if(t==="update-dynamic"&&r<this.lastReceivedTick)return;r>this.lastReceivedTick&&(this.lastReceivedTick=r);let o=this.core.applyUpdatePacketBuffer(this.userId,n);if(o){console.warn(`[CLIENT] ${t}: ${n.length}B (tick ${r}) - APPLIED`),this.postProcessCallback&&o.postProcessOrders&&o.postProcessOrders.length>0&&this.postProcessCallback(o.postProcessOrders),this.options.debug&&this.debugRenderState();let a=performance.now();this.rendererManager.render(this.core,this.userId);let c=performance.now()-a;this.performanceMonitor.recordFrameTiming(0,c),this.options.debug&&console.warn(`[CLIENT] render() completed for ${t} (${c.toFixed(2)}ms)`)}else console.warn(`[CLIENT] Failed to apply ${t} packet (tick ${r})`)}catch(n){this.log(`Error applying ${t} update packet: ${n}`),console.error(n)}}convertToUint8Array(e,t){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):Array.isArray(e)?new Uint8Array(e):e.data&&Array.isArray(e.data)?new Uint8Array(e.data):typeof e=="object"&&e.type==="Buffer"?new Uint8Array(e.data):(this.log(`Unknown data type for ${t} packet: ${typeof e}`),null)}debugRenderState(){let e=this.core.getUser(this.userId);if(e){let n=e.getLayers();console.warn(`[CLIENT] User has ${n.length} layers`),n.forEach((i,r)=>{let o=i.getOrders(),a=i.getStatic();(o.length>0||a)&&console.warn(` Layer ${r}: ${o.length} orders, static=${a}, z=${i.getZOrder()}`)})}let t=this.rendererManager.isReady();console.warn(`[CLIENT] Renderer ready: ${t}`)}log(e){this.options.debug&&console.warn(`[NetworkSync] ${e}`)}setAudioManager(e){if(this.audioManager=e,e&&this.userId){let t=this.core.getUser(this.userId);t&&t.setAudioProcessor(e)}this.connected&&e&&this.setupSoundHandlers()}setPostProcessCallback(e){this.postProcessCallback=e}setupSoundHandlers(){this.audioManager&&(this.network.on("sound-load",async e=>{e.mode==="file"?await this.handleSoundLoad(e):e.mode==="external"&&await this.handleSoundExternalLoad(e)}),this.log("Sound handlers registered"))}async handleSoundLoad(e){if(!this.audioManager){this.log("Cannot load sounds: AudioManager not initialized");return}let t=this.audioManager.getSoundBank();if(!t){this.log("Cannot load sounds: SoundBank not initialized");return}for(let n of e.sounds)try{await t.loadFromData(n.soundId,n.name,n.data),this.log(`Loaded sound: ${n.name} (${n.data.length} bytes)`),this.sendAudioAck({type:"sound-loaded",soundId:n.soundId,name:n.name})}catch(i){console.error(`[NetworkSync] Failed to load sound "${n.name}":`,i),this.sendAudioAck({type:"sound-error",soundId:n.soundId,name:n.name,error:String(i)})}}async handleSoundExternalLoad(e){if(!this.audioManager){this.log("Cannot load external sounds: AudioManager not initialized");return}let t=this.audioManager.getSoundBank();if(!t){this.log("Cannot load external sounds: SoundBank not initialized");return}for(let n of e.sounds)try{await t.loadFromUrl(n.soundId,n.name,n.url),this.log(`Loaded external sound: ${n.name} from ${n.url}`),this.sendAudioAck({type:"sound-loaded",soundId:n.soundId,name:n.name})}catch(i){console.error(`[NetworkSync] Failed to load external sound "${n.name}":`,i),this.sendAudioAck({type:"sound-error",soundId:n.soundId,name:n.name,error:String(i)})}}sendAudioAck(e){this.network.send("audio-ack",e),this.log(`Sent audio-ack: ${e.type}`)}sendBridge(e,t){this.network.sendBridge(e,t),this.log(`Bridge sent on channel '${e}'`)}onBridge(e,t){this.network.onBridge(e,t),this.log(`Bridge handler registered for channel '${e}'`)}offBridge(e,t){this.network.offBridge(e,t),this.log(`Bridge handler removed for channel '${e}'`)}removeAllBridgeHandlers(e){this.network.removeAllBridgeHandlers(e),this.log(e?`All bridge handlers removed for '${e}'`:"All bridge handlers removed")}};y(A,"NetworkSync");var S=A;var x=class x{constructor(e){s(this,"core");s(this,"rendererManager");s(this,"rendererType");s(this,"input",null);s(this,"networkSync",null);s(this,"options");s(this,"running",!1);s(this,"startTime",0);s(this,"lastTimestamp",0);s(this,"userId","");s(this,"mode");s(this,"visibilityChangeHandler");s(this,"tickRate",30);s(this,"accumulatedTime",0);s(this,"FRAME_TIME_MIN",1e3/60);s(this,"lastRenderTimestamp",0);s(this,"rafId",0);s(this,"firstTickDone",!1);s(this,"performanceMonitor");s(this,"renderMode","continuous");s(this,"renderRequested",!1);s(this,"autoplayOverlay",null);s(this,"autoplay",!0);s(this,"audioManager",null);s(this,"postProcessOverlay",null);s(this,"postProcessOrderCollector",new U);s(this,"localBridgeHandlers",new Map);s(this,"localBridgeWildcardHandlers",new Set);this.mode=e.mode,e.mode==="local"?(this.options={mode:"local",application:e.application,container:e.container,debug:e.debug??!1,width:e.width??80,height:e.height??25,userId:e.userId??"local",username:e.username??"User",renderer:e.renderer??"webgl",useImageDataRendering:e.useImageDataRendering??!0,mobileInputConfig:e.mobileInputConfig,captureInput:e.captureInput??!1,inputEnabled:e.inputEnabled??!0,autoplay:e.autoplay??!0,autoplayOptions:e.autoplayOptions},this.userId=e.userId??"local",this.autoplay=e.autoplay??!0):(this.options={mode:"connected",application:e.application,container:e.container,serverUrl:e.serverUrl,username:e.username??"Player",debug:e.debug??!1,width:e.width??80,height:e.height??25,autoReconnect:e.autoReconnect??!0,token:e.token,renderer:e.renderer??"webgl",useImageDataRendering:e.useImageDataRendering??!0,mobileInputConfig:e.mobileInputConfig,captureInput:e.captureInput??!1,inputEnabled:e.inputEnabled??!0,autoplay:e.autoplay??!0,autoplayOptions:e.autoplayOptions},this.autoplay=e.autoplay??!0),this.log(`Initializing ClientRuntime (${this.mode} mode)`),this.core=new L({mode:"client",maxUsers:this.mode==="local"?1:100}),this.core.onPaletteChanged(n=>{this.onCorePaletteChanged(n)}),this.core.onBitmapFontChanged(n=>{this.onCoreBitmapFontChanged(n)}),this.visibilityChangeHandler=()=>{!document.hidden&&this.running&&(this.lastTimestamp=performance.now(),this.accumulatedTime=0,this.log("Tab visible: Reset timing"))},document.addEventListener("visibilitychange",this.visibilityChangeHandler);let t=this.createRenderer();if(this.rendererType=this.options.renderer??"webgl",this.rendererManager=new k(t,{debug:this.options.debug,useImageDataRendering:this.options.useImageDataRendering}),this.options.inputEnabled?this.input=new q({enableKeyboardMouse:!0,enableGamepad:!0,enableMobile:!0,targetElement:window,mobileTargetElement:void 0,debug:this.options.debug,keyboardConfig:{preventDefault:this.options.captureInput??!1,stopPropagation:this.options.captureInput??!1},mouseConfig:{preventDefault:this.options.captureInput??!1,stopPropagation:this.options.captureInput??!1},mobileConfig:{preventDefault:this.options.mobileInputConfig?.preventDefault??!0,passive:this.options.mobileInputConfig?.passive??!1,maxTouches:this.options.mobileInputConfig?.maxTouches??10}}):this.log("Input disabled (inputEnabled: false)"),this.performanceMonitor=new M(60),this.mode==="connected"){let n=this.options,i=new j({url:n.serverUrl,autoReconnect:n.autoReconnect,auth:{username:n.username,token:n.token},debug:this.options.debug});this.networkSync=new S(i,this.core,this.rendererManager,this.performanceMonitor,{serverUrl:n.serverUrl,username:n.username,token:n.token,debug:this.options.debug,autoReconnect:n.autoReconnect,canvasWidth:this.options.width,canvasHeight:this.options.height})}this.tickRate=e.tickRate??30,this.tickRate===0&&!e.renderMode?(this.renderMode="on-demand",this.log("tickRate is 0: automatically enabling on-demand render mode")):this.renderMode=e.renderMode??"continuous",this.log(`Configured: tickRate=${this.tickRate}, renderMode=${this.renderMode}`),this.log("ClientRuntime initialized")}getMode(){return this.mode}getRendererType(){return this.rendererType}isRunning(){return this.running}createRenderer(){if((this.options.renderer??"webgl")==="terminal2d"){this.log("Creating Terminal 2D renderer");let r=new H(this.options.container,{fixedCols:this.options.width,fixedRows:this.options.height,cellAspectRatio:1});return this.options.useImageDataRendering&&(this.log("Enabling ImageData rendering (pixel-perfect, optimized)"),r.setImageDataRendering(!0)),this.log("Canvas 2D renderer created successfully"),r}this.log("Creating TerminalGL renderer");let n=document.createElement("canvas").getContext("webgl");if(!n)throw new Error("WebGL not supported. TerminalGL requires WebGL 1.0.");if(!n.getExtension("OES_element_index_uint"))throw new Error("OES_element_index_uint extension not supported. TerminalGL requires this extension for large terminals (256x256). Supported on 97% of devices (Android 4.3+, iOS 8+, Desktop).");if(!(this.options.container instanceof HTMLDivElement))throw new Error(`TerminalGL requires container to be an HTMLDivElement. Received: ${this.options.container.tagName}`);let i=new D(this.options.container,{cols:this.options.width,rows:this.options.height,charWidth:8,charHeight:8,scalingMode:W.None});return this.log("TerminalGL created successfully"),i}setTickRate(e){if(e<0||e>1e3)throw new Error(`Invalid tick rate: ${e}. Must be between 0 and 1000.`);if(this.mode==="connected"){this.log("setTickRate() has no effect in connected mode");return}this.tickRate=e,e===0&&this.renderMode==="continuous"?(this.renderMode="on-demand",this.log(`Tick rate set to ${e} TPS (update loop disabled, automatically switched to on-demand render mode)`)):this.log(`Tick rate set to ${e} TPS ${e===0?"(update loop disabled)":""}`)}setRenderMode(e){this.renderMode=e,this.log(`Render mode set to ${e}`)}setMaxFPS(e){if(e<=0||e>240)throw new Error(`Invalid FPS: ${e}. Must be between 1 and 240.`);this.FRAME_TIME_MIN=1e3/e,this.log(`Max FPS set to ${e}`)}getTickRate(){return this.tickRate}requestRender(){this.renderMode==="on-demand"?(this.renderRequested=!0,this.log("Render requested")):this.log("requestRender() has no effect in continuous mode")}async start(){if(this.running){this.log("Already running");return}this.log("Starting ClientRuntime"),this.audioManager=new _({debug:this.options.debug}),this.autoplay?(this.log("Autoplay enabled, initializing AudioManager..."),this.audioManager.initialize()):(this.log("Autoplay disabled, showing overlay..."),await new Promise(n=>{this.autoplayOverlay=new G(this.options.container,{...this.options.autoplayOptions,onStart:()=>{this.log("User clicked start button"),this.audioManager&&(this.audioManager.initialize(),this.audioManager.playStartSound()),n()}})}),this.log("Autoplay overlay dismissed, continuing startup...")),await this.rendererManager.initialize(this.core),this.log("Renderer is ready"),this.postProcessOverlay=new z(this.options.container),this.log("PostProcessOverlay created"),this.onCorePaletteChanged(this.core.getPalette()),this.log("Initial palette sent to renderer"),this.log("Calling application.init()"),await this.options.application.init(this.core,this);let e=this.rendererManager.getCanvas();e&&this.input&&this.input.setMobileTarget(e),this.mode==="connected"&&this.networkSync?(this.log("Connecting to server"),this.audioManager&&this.networkSync.setAudioManager(this.audioManager),this.networkSync.setPostProcessCallback(n=>{this.applyPostProcessOrders(n)}),await this.networkSync.connect(),this.userId=await this.networkSync.joinGame(this.options.application)):await this.createLocalUser();let t=this.core.getUser(this.userId);if(t){let n=t.getDisplays();if(n.length>0){let r=n[0].getSize(),o=r.x,a=r.y,c=this.rendererManager.getRenderer(),d,u;if(this.rendererType==="webgl"){let h=c.getGridSize();d=h.cols,u=h.rows}else{let l=c;d=l.getCols(),u=l.getRows()}(d!==o||u!==a)&&(this.log(`Adjusting renderer from ${d}\xD7${u} to match display ${o}\xD7${a}`),c.resize(o,a))}}this.input&&this.input.start(),this.running=!0,this.startTime=performance.now(),this.lastTimestamp=this.startTime,this.lastRenderTimestamp=this.startTime,this.accumulatedTime=0,this.firstTickDone=!1,this.performanceMonitor.reset(),this.performanceMonitor.startTracking(this.startTime),this.log("Starting main loop"),this.mainLoop(this.lastTimestamp)}async stop(){if(!this.running)return;this.log("Stopping ClientRuntime"),this.running=!1,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=0),this.audioManager&&this.audioManager.stopAll(),this.input&&this.input.stop(),this.mode==="connected"&&this.networkSync&&this.networkSync.disconnect();let e=this.core.getUser(this.userId);e&&this.options.application.destroyUser&&this.options.application.destroyUser(this.core,e,"Runtime stopped"),this.log("ClientRuntime stopped")}getStats(){let e=this.performanceMonitor.getStats();return{mode:this.mode,running:this.running,userCount:this.core.getUsers().length,fps:e.fps,uptime:this.running?performance.now()-this.startTime:0,totalFrames:0,latency:void 0,lastFrameTiming:e.lastFrame,avgFrameTiming:e.avgFrame}}async destroy(){await this.stop(),this.log("Destroying ClientRuntime"),this.visibilityChangeHandler&&(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeHandler=void 0),this.autoplayOverlay&&(this.autoplayOverlay.destroy(),this.autoplayOverlay=null),this.audioManager&&(this.audioManager.destroy(),this.audioManager=null),this.postProcessOverlay&&(this.postProcessOverlay.destroy(),this.postProcessOverlay=null);let e=this.rendererManager.getRenderer();e&&"clearOnResizeCallback"in e&&e.clearOnResizeCallback(),this.options.application.destroy&&this.options.application.destroy(),this.rendererManager.destroy(),this.input&&this.input.destroy(),this.networkSync&&this.networkSync.destroy(),this.log("ClientRuntime destroyed")}async createLocalUser(){let e=this.options;this.log(`Creating local user: ${this.userId}`);let t=this.core.createUser(this.userId,e.username);if(this.audioManager&&t.setAudioProcessor(this.audioManager),this.log("Calling application.initUser()"),this.options.application.initUser(this.core,t,{username:e.username}),t.hasAudioConfigCommands()&&(this.log("Applying audio config commands from initUser()"),t.applyAudioConfigCommands(t.flushAudioConfigCommands())),t.hasPendingMacroOrders()){this.log("Applying macro orders from initUser()");let n=t.flushMacroOrders();t.applyMacroOrders(n)}if(t.hasPostProcessCommands()){this.log("Applying post-process commands from initUser()");let n=t.flushPostProcessCommands(),i=this.postProcessOrderCollector.convertCommands(n);this.applyPostProcessOrders(i)}t.needsSendSounds()&&(await this.loadSoundsFromRegistry(),t.clearSendSounds()),this.log("Performing initial render"),this.core.endTick(),this.render(),this.log("Initial render complete")}async loadSoundsFromRegistry(){if(!this.audioManager){this.log("Cannot load sounds: AudioManager not initialized");return}let e=this.audioManager.getSoundBank();if(!e){this.log("Cannot load sounds: SoundBank not initialized");return}let n=this.core.getSoundRegistry().getAll();if(n.length===0){this.log("No sounds to load from registry");return}this.log(`Loading ${n.length} sounds from Core registry into AudioManager...`);for(let i of n)try{i.loadType==="file"&&i.data?(await e.loadFromData(i.soundId,i.name,i.data),this.log(`\u{1F50A} Loaded sound: ${i.name} (${i.data.length} bytes)`)):i.loadType==="external"&&i.url&&(await e.loadFromUrl(i.soundId,i.name,i.url),this.log(`\u{1F50A} Loaded external sound: ${i.name} from ${i.url}`))}catch(r){console.error(`[ClientRuntime] Failed to load sound "${i.name}":`,r)}this.log(`\u2713 ${e.size} sounds loaded into AudioManager`)}mainLoop(e){if(!this.running){this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=0);return}if(this.renderMode==="on-demand"){this.renderRequested&&(this.renderRequested=!1,this.performanceMonitor.updateFPS(e),this.render()),this.rafId=requestAnimationFrame(o=>this.mainLoop(o));return}let t=e-this.lastRenderTimestamp;if(this.lastRenderTimestamp>0&&t<this.FRAME_TIME_MIN-1){this.rafId=requestAnimationFrame(o=>this.mainLoop(o));return}this.lastRenderTimestamp=e;let n=(e-this.lastTimestamp)/1e3,i=Math.min(n,.1);this.lastTimestamp=e,this.performanceMonitor.updateFPS(e);let r=this.core.getUser(this.userId);if(!r){this.rafId=requestAnimationFrame(o=>this.mainLoop(o));return}if(this.mode==="local"){if(this.tickRate===0){let d=performance.now();this.render();let u=performance.now()-d;this.performanceMonitor.recordFrameTiming(0,u),this.rafId=requestAnimationFrame(l=>this.mainLoop(l));return}if(!this.firstTickDone){this.firstTickDone=!0,this.lastTimestamp=e,this.accumulatedTime=0,this.rafId=requestAnimationFrame(d=>this.mainLoop(d));return}this.accumulatedTime+=i;let o=1/this.tickRate;this.accumulatedTime>.5&&(this.accumulatedTime=o);let a=0,c=0;for(;this.accumulatedTime>=o&&a<5;){let d=performance.now();if(this.collectAndApplyInput(r),this.options.application.update(this.core,o),this.options.application.updateUser(this.core,r,o),r.clearTextInputs(),r.hasAudioConfigCommands()&&r.applyAudioConfigCommands(r.flushAudioConfigCommands()),r.hasSoundCommands()&&r.applyAudioCommands(r.flushSoundCommands()),r.hasPostProcessCommands()){let l=r.flushPostProcessCommands(),h=this.postProcessOrderCollector.convertCommands(l);this.applyPostProcessOrders(h)}if(r.hasPendingMacroOrders()){let l=r.flushMacroOrders();r.applyMacroOrders(l)}let u=r.updateMacros();if(r.processMacroEvents(u),r.hasBridgeMessages()){let l=r.getBridgeMessages();this.dispatchLocalBridgeMessages(l)}this.core.endTickSplit(),c+=performance.now()-d,this.accumulatedTime-=o,a++}if(a>0){let d=performance.now();this.render();let u=performance.now()-d;this.performanceMonitor.recordFrameTiming(c,u)}}else{let o=r.updateMacros();r.processMacroEvents(o),this.collectAndSendInput()}this.rafId=requestAnimationFrame(o=>this.mainLoop(o))}collectAndApplyInput(e){if(!this.input)return;let t=this.rendererManager.getCanvas();if(t){let a=e.getDisplays(),c=a.length>0?a[0].size.x:this.options.width,d=a.length>0?a[0].size.y:this.options.height,l=this.rendererManager.getRenderer()?.getOffsets?.(),h={offsetX:l?.offsetX??0,offsetY:l?.offsetY??0},g=R.collectMousePosition(this.input,t,c,d,h);e.setMousePosition(g.x,g.y,g.over),e.updateMacroMouse(g.x,g.y,g.isLeftDown);let m=R.collectTouchPositions(this.input,t,c,d,10,h);this.options.debug&&m.length>0&&console.warn("\u{1F4F1} Collected touches:",m),m.forEach(p=>{e.setTouchPosition(p.id,p.x,p.y,p.over)})}let n=R.collectTextInputs(this.input);n.length>0&&e.setTextInputs(n);let i=e.getInputBindingRegistry(),r=i.getAllAxes(),o=i.getAllButtons();if(r.length>0||o.length>0){let a=R.collectAxisSources(r,this.input),c=R.collectButtonSourcesWithTransitions(o,this.input);r.forEach(d=>{let u=i.evaluateAxis(d.bindingId,a);e.setAxis(d.name,u)}),o.forEach(d=>{let u=new Map,l=new Map,h=new Map;for(let[v,f]of c)u.set(v,f.pressed),l.set(v,f.justPressed),h.set(v,f.justReleased);let g=i.evaluateButton(d.bindingId,u),m=i.evaluateButton(d.bindingId,l),p=i.evaluateButton(d.bindingId,h);e.setButton(d.name,g),e.setButton(`${d.name}_justPressed`,m),e.setButton(`${d.name}_justReleased`,p)})}this.input.poll?.()}collectAndSendInput(){!this.networkSync||!this.input||this.networkSync.sendInput(this.input)}render(){let e=this.core.getUser(this.userId);if(e){let t=e.getMacroRenderOrders();for(let[n,i]of t){let r=e.getLayerById(n);r&&i.length>0&&r.addTemporaryOrders(i)}}this.rendererManager.render(this.core,this.userId)}onCorePaletteChanged(e){this.log(`Palette changed, updating renderer (${e.size} colors)`);let t=[];for(let i=0;i<256;i++){let r=e.get(i);r?t.push({r:r.r,g:r.g,b:r.b,a:r.a}):t.push({r:0,g:0,b:0,a:0})}let n=this.rendererManager.getRenderer();if(!n){console.warn("[ClientRuntime] Cannot update palette: renderer is null");return}"setPalette"in n&&typeof n.setPalette=="function"?(n.setPalette(t),this.log("\u2713 Renderer palette updated successfully")):console.warn("[ClientRuntime] Renderer does not have setPalette method")}onCoreBitmapFontChanged(e){this.log(`Bitmap font ${e} changed, updating renderer`);let t=this.core.getBitmapFont(e);if(!t){console.warn(`[ClientRuntime] Font ${e} not found in registry`);return}let n=new Map,i=0;for(let o=0;o<256;o++){let a=t.getGlyph(o);a&&(n.set(o,a),i++)}this.log(`Built bitmap font map with ${i} glyphs, dimensions: ${t.getCharWidth()}x${t.getCharHeight()} (cell: ${t.getCellWidth()}x${t.getCellHeight()})`);let r=this.rendererManager.getRenderer();if(!r){console.warn("[ClientRuntime] Cannot update font: renderer is null");return}"setBitmapFont"in r&&typeof r.setBitmapFont=="function"?(r.setBitmapFont(n,t.getCharWidth(),t.getCharHeight(),t.getCellWidth(),t.getCellHeight()),this.log("\u2713 Renderer bitmap font updated successfully"),this.postProcessOverlay&&"syncWithRenderer"in this.postProcessOverlay&&"getCellWidth"in r&&"getCellHeight"in r&&"getCurrentScale"in r&&"getGridSize"in r&&(this.postProcessOverlay.syncWithRenderer(r),this.log("\u2713 PostProcessOverlay synced with renderer dimensions"))):console.warn("[ClientRuntime] Renderer does not have setBitmapFont method")}getAudioManager(){return this.audioManager}getAudioContext(){return this.audioManager?.getContext()??null}applyAmbientEffectConfig(e){let t=this.rendererManager?.getRenderer();t&&"setAmbientEffect"in t&&(e.enabled?t.setAmbientEffect({blur:e.blur,scale:e.scale}):t.setAmbientEffect(!1),this.log(`Ambient effect ${e.enabled?"enabled":"disabled"}`))}applyPostProcessOrders(e){if(!this.postProcessOverlay){this.log("PostProcessOverlay not initialized, skipping post-process orders");return}for(let t of e)switch(t.type){case C.SetConfig:{let n={};t.scanlines&&(n.scanlines={enabled:t.scanlines.enabled,opacity:t.scanlines.opacity,pattern:this.patternFromType(t.scanlines.pattern),color:{r:t.scanlines.colorR,g:t.scanlines.colorG,b:t.scanlines.colorB}}),t.ambientEffect&&(n.ambientEffect={enabled:t.ambientEffect.enabled,blur:t.ambientEffect.blur,scale:t.ambientEffect.scale}),this.postProcessOverlay.setConfig(Object.keys(n).length>0?n:null),n.ambientEffect&&this.applyAmbientEffectConfig(n.ambientEffect);break}case C.SetScanlines:{this.postProcessOverlay.setScanlines({enabled:t.enabled,opacity:t.opacity,pattern:this.patternFromType(t.pattern),color:{r:t.colorR,g:t.colorG,b:t.colorB}});break}case C.SetAmbientEffect:{this.applyAmbientEffectConfig({enabled:t.enabled,blur:t.blur,scale:t.scale});break}case C.SetScalingMode:{this.applyScalingMode(t.mode);break}case C.SetGrid:{this.applyGridConfig(t);break}}}applyScalingMode(e){let t=this.rendererManager.getRenderer();if(t&&"setScalingMode"in t){let n=N(e);t.setScalingMode(n),this.log(`Scaling mode set to ${n}`)}}applyGridConfig(e){let t=this.rendererManager.getRenderer();if(t&&"setGrid"in t){let n=e.colorA/255;t.setGrid({enabled:e.enabled,color:`rgba(${e.colorR},${e.colorG},${e.colorB},${n})`,lineWidth:e.lineWidth}),this.log(`Grid ${e.enabled?"enabled":"disabled"}`)}}patternFromType(e){switch(e){case 0:return"horizontal";case 1:return"vertical";case 2:return"grid";default:return"horizontal"}}getPostProcessOverlay(){return this.postProcessOverlay}dispatchLocalBridgeMessages(e){for(let t of e){let{channel:n,data:i}=t,r=this.localBridgeHandlers.get(n);if(r)for(let o of r)try{o(i)}catch(a){console.error(`[ClientRuntime] Bridge handler error on '${n}':`,a)}for(let o of this.localBridgeWildcardHandlers)try{o(n,i)}catch(a){console.error("[ClientRuntime] Bridge wildcard handler error:",a)}this.log(`Bridge message dispatched on channel '${n}'`)}}sendBridge(e,t){if(this.mode==="connected"&&this.networkSync)this.networkSync.sendBridge(e,t);else if(this.mode==="local"){let n=this.core.getUser(this.userId);n&&this.options.application.onBridgeMessage&&(this.options.application.onBridgeMessage(this.core,n,e,t),this.log(`Bridge message sent to application on channel '${e}'`))}}onBridge(e,t){this.mode==="connected"&&this.networkSync?this.networkSync.onBridge(e,t):this.mode==="local"&&(e==="*"?this.localBridgeWildcardHandlers.add(t):(this.localBridgeHandlers.has(e)||this.localBridgeHandlers.set(e,new Set),this.localBridgeHandlers.get(e).add(t)),this.log(`Bridge handler registered for channel '${e}'`))}offBridge(e,t){this.mode==="connected"&&this.networkSync?this.networkSync.offBridge(e,t):this.mode==="local"&&(e==="*"?this.localBridgeWildcardHandlers.delete(t):this.localBridgeHandlers.get(e)?.delete(t))}removeAllBridgeHandlers(e){this.mode==="connected"&&this.networkSync?this.networkSync.removeAllBridgeHandlers(e):this.mode==="local"&&(e===void 0?(this.localBridgeHandlers.clear(),this.localBridgeWildcardHandlers.clear()):e==="*"?this.localBridgeWildcardHandlers.clear():this.localBridgeHandlers.delete(e))}log(e){this.options.debug&&console.warn(`[ClientRuntime/${this.mode}] ${e}`)}};y(x,"ClientRuntime");var O=x;import{ScalingMode as Re}from"@utsp/render";import{AudioManager as Me}from"@utsp/audio";export{Me as AudioManager,O as ClientRuntime,F as RendererType,Re as ScalingMode};
|
|
1
|
+
var x=Object.defineProperty;var G=(m,e,t)=>e in m?x(m,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):m[e]=t;var f=(m,e)=>x(m,"name",{value:e,configurable:!0});var o=(m,e,t)=>(G(m,typeof e!="symbol"?e+"":e,t),t);import{Core as Q,PostProcessOrderType as I,PostProcessOrderCollector as D}from"@utsp/core";import{TerminalGL as W,Terminal2D as K,AutoplayOverlay as H,PostProcessOverlay as V}from"@utsp/render";import{ScalingMode as k,valueToScalingMode as $}from"@utsp/types";import{UnifiedInputRouter as Y,InputCollector as T}from"@utsp/input";import{SocketIOClient as j}from"@utsp/network-client";import{AudioManager as z}from"@utsp/audio";import{ScalingMode as Z}from"@utsp/types";var B=(t=>(t.TerminalGL="webgl",t.Terminal2D="terminal2d",t))(B||{});var U=class U{constructor(e=60){o(this,"frameCount",0);o(this,"fps",0);o(this,"fpsUpdateTime",0);o(this,"lastCoreTime",0);o(this,"lastRenderTime",0);o(this,"lastTotalTime",0);o(this,"coreTimeSamples",[]);o(this,"renderTimeSamples",[]);o(this,"totalTimeSamples",[]);o(this,"maxSamples");if(e<=0)throw new Error("maxSamples must be positive");this.maxSamples=e}startTracking(e){this.fpsUpdateTime=e,this.frameCount=0,this.fps=0}updateFPS(e){this.frameCount++,e-this.fpsUpdateTime>=1e3&&(this.fps=Math.round(this.frameCount*1e3/(e-this.fpsUpdateTime)),this.frameCount=0,this.fpsUpdateTime=e)}recordFrameTiming(e,t){let i=e+t;this.lastCoreTime=e,this.lastRenderTime=t,this.lastTotalTime=i,this.coreTimeSamples.push(e),this.renderTimeSamples.push(t),this.totalTimeSamples.push(i),this.coreTimeSamples.length>this.maxSamples&&(this.coreTimeSamples.shift(),this.renderTimeSamples.shift(),this.totalTimeSamples.shift())}getFPS(){return this.fps}getLastFrameTiming(){if(!(this.lastCoreTime===0&&this.lastRenderTime===0))return{coreTime:this.lastCoreTime,renderTime:this.lastRenderTime,totalTime:this.lastTotalTime}}getAverageFrameTiming(){if(this.coreTimeSamples.length!==0)return{coreTime:this.average(this.coreTimeSamples),renderTime:this.average(this.renderTimeSamples),totalTime:this.average(this.totalTimeSamples)}}getStats(){return{fps:this.fps,lastFrame:this.getLastFrameTiming(),avgFrame:this.getAverageFrameTiming(),sampleCount:this.coreTimeSamples.length,maxSamples:this.maxSamples}}reset(){this.frameCount=0,this.fps=0,this.fpsUpdateTime=0,this.lastCoreTime=0,this.lastRenderTime=0,this.lastTotalTime=0,this.coreTimeSamples=[],this.renderTimeSamples=[],this.totalTimeSamples=[]}average(e){return e.length===0?0:e.reduce((t,i)=>t+i,0)/e.length}};f(U,"PerformanceMonitor");var S=U;var q="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",v={glyphWidth:8,glyphHeight:8,cellWidth:8,cellHeight:8,atlasBlocks:1,atlasWidth:128,atlasHeight:128};function L(){let m=atob(q),e=new Uint8Array(m.length);for(let t=0;t<m.length;t++)e[t]=m.charCodeAt(t);return e}f(L,"decodeDefaultAtlas");var E=class E{constructor(e,t={}){o(this,"renderer");o(this,"options");this.renderer=e,this.options={debug:t.debug??!1,useImageDataRendering:t.useImageDataRendering??!1}}async initialize(e){if("setImageDataRendering"in this.renderer&&this.options.useImageDataRendering&&(this.renderer.setImageDataRendering(!0),this.log("ImageData rendering enabled")),"setImageFont"in this.renderer&&typeof this.renderer.setImageFont=="function"){this.log("Loading default 8x8 font atlas...");let t=L();await this.renderer.setImageFont(t,v.glyphWidth,v.glyphHeight,v.cellWidth,v.cellHeight,v.atlasBlocks),this.log("Default 8x8 font atlas loaded")}await this.waitForReady(),this.log("Initialized and ready")}async waitForReady(e=100,t=50){this.log("Waiting for renderer to be ready");let i=0;return new Promise((r,n)=>{let s=f(()=>{if(i++,this.renderer.isReady())this.log(`Renderer ready after ${i*t}ms`),r();else if(i>=e){let c=`Renderer failed to be ready after ${e*t}ms`;this.log(c),n(new Error(c))}else setTimeout(s,t)},"check");s()})}async loadDefaultFont(e){console.warn("[RendererManager] loadDefaultFont() is deprecated. Use ImageFont instead.")}render(e,t){if(!this.renderer.isReady())return console.warn("[RENDERER MANAGER] Renderer not ready"),!1;let i=e.getRenderState(t);if(!i||i.displays.length===0)return console.warn("[RENDERER MANAGER] No render state or no displays"),!1;let r=i.displays[0];return this.renderer.renderDisplayData(r),!0}getRenderer(){return this.renderer}getCanvas(){return this.renderer.getCanvas()}isReady(){return this.renderer.isReady()}destroy(){this.log("Destroying renderer"),this.renderer.destroy()}log(e){this.options.debug&&console.warn(`[RendererManager] ${e}`)}};f(E,"RendererManager");var F=E;import{InputCollector as R}from"@utsp/input";var A=class A{constructor(e,t,i,r,n){o(this,"network");o(this,"core");o(this,"rendererManager");o(this,"performanceMonitor");o(this,"options");o(this,"audioManager",null);o(this,"postProcessCallback",null);o(this,"userId","");o(this,"lastReceivedTick",-1);o(this,"connected",!1);this.network=e,this.core=t,this.rendererManager=i,this.performanceMonitor=r,this.options={serverUrl:n.serverUrl,username:n.username,token:n.token??"",debug:n.debug??!1,autoReconnect:n.autoReconnect??!0,canvasWidth:n.canvasWidth,canvasHeight:n.canvasHeight}}async connect(){this.log(`Connecting to ${this.options.serverUrl}`),await this.network.connect(),this.connected=!0,this.log("Connected to server"),this.setupNetworkHandlers()}async joinGame(e){return new Promise((t,i)=>{this.network.send("join",{username:this.options.username,token:this.options.token}),this.network.on("join_response",r=>{if(r.success){this.userId=r.userId,this.log(`Joined game as ${this.userId}`);let n=this.core.createUser(this.userId,this.options.username);this.audioManager&&n.setAudioProcessor(this.audioManager),e.initUser(this.core,n,{username:this.options.username,token:this.options.token}),t(this.userId)}else i(new Error(r.error||"Failed to join game"))}),setTimeout(()=>i(new Error("Join timeout")),5e3)})}sendInput(e){let t=this.core.getUser(this.userId);if(!t)return;let i=this.rendererManager.getCanvas();if(i){let h=this.rendererManager.getRenderer()?.getOffsets?.(),C={offsetX:h?.offsetX??0,offsetY:h?.offsetY??0},b=R.collectMousePosition(e,i,this.options.canvasWidth,this.options.canvasHeight,C);t.setMousePosition(b.x,b.y,b.over),t.updateMacroMouse(b.x,b.y,b.isLeftDown),R.collectTouchPositions(e,i,this.options.canvasWidth,this.options.canvasHeight,10,C).forEach(M=>{t.setTouchPosition(M.id,M.x,M.y,M.over)})}let r=t.getInputBindingRegistry(),n=r.getAllAxes(),s=r.getAllButtons(),a=R.collectAxisSources(n,e),c=R.collectButtonSources(s,e),d=R.collectTextInputs(e);d.length>0&&t.setTextInputs(d);let u={};n.forEach(g=>{let h=r.evaluateAxis(g.bindingId,a);u[g.name]=h,t.setAxis(g.name,h)});let l={};s.forEach(g=>{let h=r.evaluateButton(g.bindingId,c);l[g.name]=h,t.setButton(g.name,h)});let p=t.getMouseDisplayInfo(),y=p?{x:p.localX,y:p.localY}:null;this.network.send("input",{timestamp:Date.now(),axes:u,buttons:l,mousePosition:y,textInputs:d})}disconnect(){this.connected&&(this.network.send("leave",{}),this.network.disconnect(),this.connected=!1,this.log("Disconnected from server"))}getUserId(){return this.userId}isConnected(){return this.connected}destroy(){this.disconnect(),this.network.destroy(),this.log("NetworkSync destroyed")}setupNetworkHandlers(){this.network.on("update",e=>{try{let t=this.convertToUint8Array(e,"update");if(!t)return;let i=this.core.applyUpdatePacketBuffer(this.userId,t);i?(this.postProcessCallback&&i.postProcessOrders&&i.postProcessOrders.length>0&&this.postProcessCallback(i.postProcessOrders),this.rendererManager.render(this.core,this.userId)):this.log("Failed to apply update packet")}catch(t){this.log(`Error applying update packet: ${t}`)}}),this.network.on("update-static",e=>{this.handleUpdatePacket(e,"update-static")}),this.network.on("update-dynamic",e=>{this.handleUpdatePacket(e,"update-dynamic")}),this.network.on("load",e=>{try{let t=this.convertToUint8Array(e,"load");if(!t)return;this.core.applyLoadPacket(t)?this.log("Load packet applied successfully"):this.log("Failed to apply load packet")}catch(t){this.log(`Error applying load packet: ${t}`)}}),this.network.on("input-bindings",e=>{this.core.applyInputBindingsLoadPacket(this.userId,e)?this.log("Input bindings configured"):this.log("Failed to apply input bindings")}),this.audioManager&&this.setupSoundHandlers(),this.network.on("disconnect",()=>{this.connected=!1,this.log("Disconnected from server")})}handleUpdatePacket(e,t){try{let i=this.convertToUint8Array(e,t);if(!i)return;let r=new DataView(i.buffer,i.byteOffset,i.byteLength),n=Number(r.getBigUint64(0,!1));if(t==="update-dynamic"&&n<this.lastReceivedTick)return;n>this.lastReceivedTick&&(this.lastReceivedTick=n);let s=this.core.applyUpdatePacketBuffer(this.userId,i);if(s){console.warn(`[CLIENT] ${t}: ${i.length}B (tick ${n}) - APPLIED`),this.postProcessCallback&&s.postProcessOrders&&s.postProcessOrders.length>0&&this.postProcessCallback(s.postProcessOrders),this.options.debug&&this.debugRenderState();let a=performance.now();this.rendererManager.render(this.core,this.userId);let c=performance.now()-a;this.performanceMonitor.recordFrameTiming(0,c),this.options.debug&&console.warn(`[CLIENT] render() completed for ${t} (${c.toFixed(2)}ms)`)}else console.warn(`[CLIENT] Failed to apply ${t} packet (tick ${n})`)}catch(i){this.log(`Error applying ${t} update packet: ${i}`),console.error(i)}}convertToUint8Array(e,t){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):Array.isArray(e)?new Uint8Array(e):e.data&&Array.isArray(e.data)?new Uint8Array(e.data):typeof e=="object"&&e.type==="Buffer"?new Uint8Array(e.data):(this.log(`Unknown data type for ${t} packet: ${typeof e}`),null)}debugRenderState(){let e=this.core.getUser(this.userId);if(e){let i=e.getLayers();console.warn(`[CLIENT] User has ${i.length} layers`),i.forEach((r,n)=>{let s=r.getOrders(),a=r.getStatic();(s.length>0||a)&&console.warn(` Layer ${n}: ${s.length} orders, static=${a}, z=${r.getZOrder()}`)})}let t=this.rendererManager.isReady();console.warn(`[CLIENT] Renderer ready: ${t}`)}log(e){this.options.debug&&console.warn(`[NetworkSync] ${e}`)}setAudioManager(e){if(this.audioManager=e,e&&this.userId){let t=this.core.getUser(this.userId);t&&t.setAudioProcessor(e)}this.connected&&e&&this.setupSoundHandlers()}setPostProcessCallback(e){this.postProcessCallback=e}setupSoundHandlers(){this.audioManager&&(this.network.on("sound-load",async e=>{e.mode==="file"?await this.handleSoundLoad(e):e.mode==="external"&&await this.handleSoundExternalLoad(e)}),this.log("Sound handlers registered"))}async handleSoundLoad(e){if(!this.audioManager){this.log("Cannot load sounds: AudioManager not initialized");return}let t=this.audioManager.getSoundBank();if(!t){this.log("Cannot load sounds: SoundBank not initialized");return}for(let i of e.sounds)try{await t.loadFromData(i.soundId,i.name,i.data),this.log(`Loaded sound: ${i.name} (${i.data.length} bytes)`),this.sendAudioAck({type:"sound-loaded",soundId:i.soundId,name:i.name})}catch(r){console.error(`[NetworkSync] Failed to load sound "${i.name}":`,r),this.sendAudioAck({type:"sound-error",soundId:i.soundId,name:i.name,error:String(r)})}}async handleSoundExternalLoad(e){if(!this.audioManager){this.log("Cannot load external sounds: AudioManager not initialized");return}let t=this.audioManager.getSoundBank();if(!t){this.log("Cannot load external sounds: SoundBank not initialized");return}for(let i of e.sounds)try{await t.loadFromUrl(i.soundId,i.name,i.url),this.log(`Loaded external sound: ${i.name} from ${i.url}`),this.sendAudioAck({type:"sound-loaded",soundId:i.soundId,name:i.name})}catch(r){console.error(`[NetworkSync] Failed to load external sound "${i.name}":`,r),this.sendAudioAck({type:"sound-error",soundId:i.soundId,name:i.name,error:String(r)})}}sendAudioAck(e){this.network.send("audio-ack",e),this.log(`Sent audio-ack: ${e.type}`)}sendBridge(e,t){this.network.sendBridge(e,t),this.log(`Bridge sent on channel '${e}'`)}onBridge(e,t){this.network.onBridge(e,t),this.log(`Bridge handler registered for channel '${e}'`)}offBridge(e,t){this.network.offBridge(e,t),this.log(`Bridge handler removed for channel '${e}'`)}removeAllBridgeHandlers(e){this.network.removeAllBridgeHandlers(e),this.log(e?`All bridge handlers removed for '${e}'`:"All bridge handlers removed")}};f(A,"NetworkSync");var w=A;var O=class O{constructor(e){o(this,"core");o(this,"rendererManager");o(this,"rendererType");o(this,"input",null);o(this,"networkSync",null);o(this,"options");o(this,"running",!1);o(this,"startTime",0);o(this,"lastTimestamp",0);o(this,"userId","");o(this,"mode");o(this,"visibilityChangeHandler");o(this,"tickRate",30);o(this,"accumulatedTime",0);o(this,"FRAME_TIME_MIN",1e3/60);o(this,"lastRenderTimestamp",0);o(this,"rafId",0);o(this,"firstTickDone",!1);o(this,"performanceMonitor");o(this,"renderMode","continuous");o(this,"renderRequested",!1);o(this,"autoplayOverlay",null);o(this,"autoplay",!0);o(this,"audioManager",null);o(this,"postProcessOverlay",null);o(this,"postProcessOrderCollector",new D);o(this,"localBridgeHandlers",new Map);o(this,"localBridgeWildcardHandlers",new Set);this.mode=e.mode,e.mode==="local"?(this.options={mode:"local",application:e.application,container:e.container,debug:e.debug??!1,width:e.width??80,height:e.height??25,userId:e.userId??"local",username:e.username??"User",renderer:e.renderer??"webgl",useImageDataRendering:e.useImageDataRendering??!0,mobileInputConfig:e.mobileInputConfig,captureInput:e.captureInput??!1,inputEnabled:e.inputEnabled??!0,autoplay:e.autoplay??!0,autoplayOptions:e.autoplayOptions,scalingMode:e.scalingMode??k.None},this.userId=e.userId??"local",this.autoplay=e.autoplay??!0):(this.options={mode:"connected",application:e.application,container:e.container,serverUrl:e.serverUrl,username:e.username??"Player",debug:e.debug??!1,width:e.width??80,height:e.height??25,autoReconnect:e.autoReconnect??!0,token:e.token,renderer:e.renderer??"webgl",useImageDataRendering:e.useImageDataRendering??!0,mobileInputConfig:e.mobileInputConfig,captureInput:e.captureInput??!1,inputEnabled:e.inputEnabled??!0,autoplay:e.autoplay??!0,autoplayOptions:e.autoplayOptions,scalingMode:e.scalingMode??k.None},this.autoplay=e.autoplay??!0),this.log(`Initializing ClientRuntime (${this.mode} mode)`),this.core=new Q({mode:"client",maxUsers:this.mode==="local"?1:100}),this.core.onPaletteChanged(i=>{this.onCorePaletteChanged(i)}),this.core.onBitmapFontChanged(i=>{this.onCoreBitmapFontChanged(i)}),this.core.onImageFontChanged(i=>{this.onCoreImageFontChanged(i)}),this.visibilityChangeHandler=()=>{!document.hidden&&this.running&&(this.lastTimestamp=performance.now(),this.accumulatedTime=0,this.log("Tab visible: Reset timing"))},document.addEventListener("visibilitychange",this.visibilityChangeHandler);let t=this.createRenderer();if(this.rendererType=this.options.renderer??"webgl",this.rendererManager=new F(t,{debug:this.options.debug,useImageDataRendering:this.options.useImageDataRendering}),this.options.inputEnabled?this.input=new Y({enableKeyboardMouse:!0,enableGamepad:!0,enableMobile:!0,targetElement:window,mobileTargetElement:void 0,debug:this.options.debug,keyboardConfig:{preventDefault:this.options.captureInput??!1,stopPropagation:this.options.captureInput??!1},mouseConfig:{preventDefault:this.options.captureInput??!1,stopPropagation:this.options.captureInput??!1},mobileConfig:{preventDefault:this.options.mobileInputConfig?.preventDefault??!0,passive:this.options.mobileInputConfig?.passive??!1,maxTouches:this.options.mobileInputConfig?.maxTouches??10}}):this.log("Input disabled (inputEnabled: false)"),this.performanceMonitor=new S(60),this.mode==="connected"){let i=this.options,r=new j({url:i.serverUrl,autoReconnect:i.autoReconnect,auth:{username:i.username,token:i.token},debug:this.options.debug});this.networkSync=new w(r,this.core,this.rendererManager,this.performanceMonitor,{serverUrl:i.serverUrl,username:i.username,token:i.token,debug:this.options.debug,autoReconnect:i.autoReconnect,canvasWidth:this.options.width,canvasHeight:this.options.height})}this.tickRate=e.tickRate??30,this.tickRate===0&&!e.renderMode?(this.renderMode="on-demand",this.log("tickRate is 0: automatically enabling on-demand render mode")):this.renderMode=e.renderMode??"continuous",this.log(`Configured: tickRate=${this.tickRate}, renderMode=${this.renderMode}`),this.log("ClientRuntime initialized")}getMode(){return this.mode}getRendererType(){return this.rendererType}isRunning(){return this.running}createRenderer(){if((this.options.renderer??"webgl")==="terminal2d"){this.log("Creating Terminal 2D renderer");let n=new K(this.options.container,{fixedCols:this.options.width,fixedRows:this.options.height,cellAspectRatio:1,scalingMode:this.options.scalingMode??k.None});return this.options.useImageDataRendering&&(this.log("Enabling ImageData rendering (pixel-perfect, optimized)"),n.setImageDataRendering(!0)),this.log("Canvas 2D renderer created successfully"),n}this.log("Creating TerminalGL renderer");let i=document.createElement("canvas").getContext("webgl");if(!i)throw new Error("WebGL not supported. TerminalGL requires WebGL 1.0.");if(!i.getExtension("OES_element_index_uint"))throw new Error("OES_element_index_uint extension not supported. TerminalGL requires this extension for large terminals (256x256). Supported on 97% of devices (Android 4.3+, iOS 8+, Desktop).");if(!(this.options.container instanceof HTMLDivElement))throw new Error(`TerminalGL requires container to be an HTMLDivElement. Received: ${this.options.container.tagName}`);let r=new W(this.options.container,{cols:this.options.width,rows:this.options.height,charWidth:8,charHeight:8,scalingMode:this.options.scalingMode??k.None});return this.log("TerminalGL created successfully"),r}setTickRate(e){if(e<0||e>1e3)throw new Error(`Invalid tick rate: ${e}. Must be between 0 and 1000.`);if(this.mode==="connected"){this.log("setTickRate() has no effect in connected mode");return}this.tickRate=e,e===0&&this.renderMode==="continuous"?(this.renderMode="on-demand",this.log(`Tick rate set to ${e} TPS (update loop disabled, automatically switched to on-demand render mode)`)):this.log(`Tick rate set to ${e} TPS ${e===0?"(update loop disabled)":""}`)}setRenderMode(e){this.renderMode=e,this.log(`Render mode set to ${e}`)}setMaxFPS(e){if(e<=0||e>240)throw new Error(`Invalid FPS: ${e}. Must be between 1 and 240.`);this.FRAME_TIME_MIN=1e3/e,this.log(`Max FPS set to ${e}`)}getTickRate(){return this.tickRate}requestRender(){this.renderMode==="on-demand"?(this.renderRequested=!0,this.log("Render requested")):this.log("requestRender() has no effect in continuous mode")}async start(){if(this.running){this.log("Already running");return}this.log("Starting ClientRuntime"),this.audioManager=new z({debug:this.options.debug}),this.autoplay?(this.log("Autoplay enabled, initializing AudioManager..."),this.audioManager.initialize()):(this.log("Autoplay disabled, showing overlay..."),await new Promise(i=>{this.autoplayOverlay=new H(this.options.container,{...this.options.autoplayOptions,onStart:()=>{this.log("User clicked start button"),this.audioManager&&(this.audioManager.initialize(),this.audioManager.playStartSound()),i()}})}),this.log("Autoplay overlay dismissed, continuing startup...")),await this.rendererManager.initialize(this.core),this.log("Renderer is ready"),this.postProcessOverlay=new V(this.options.container),this.log("PostProcessOverlay created"),this.onCorePaletteChanged(this.core.getPalette()),this.log("Initial palette sent to renderer"),this.log("Calling application.init()"),await this.options.application.init(this.core,this);let e=this.rendererManager.getCanvas();e&&this.input&&this.input.setMobileTarget(e),this.mode==="connected"&&this.networkSync?(this.log("Connecting to server"),this.audioManager&&this.networkSync.setAudioManager(this.audioManager),this.networkSync.setPostProcessCallback(i=>{this.applyPostProcessOrders(i)}),await this.networkSync.connect(),this.userId=await this.networkSync.joinGame(this.options.application)):await this.createLocalUser();let t=this.core.getUser(this.userId);if(t){let i=t.getDisplays();if(i.length>0){let n=i[0].getSize(),s=n.x,a=n.y,c=this.rendererManager.getRenderer(),d,u;if(this.rendererType==="webgl"){let p=c.getGridSize();d=p.cols,u=p.rows}else{let l=c;d=l.getCols(),u=l.getRows()}(d!==s||u!==a)&&(this.log(`Adjusting renderer from ${d}\xD7${u} to match display ${s}\xD7${a}`),c.resize(s,a))}}this.input&&this.input.start(),this.running=!0,this.startTime=performance.now(),this.lastTimestamp=this.startTime,this.lastRenderTimestamp=this.startTime,this.accumulatedTime=0,this.firstTickDone=!1,this.performanceMonitor.reset(),this.performanceMonitor.startTracking(this.startTime),this.log("Starting main loop"),this.mainLoop(this.lastTimestamp)}async stop(){if(!this.running)return;this.log("Stopping ClientRuntime"),this.running=!1,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=0),this.audioManager&&this.audioManager.stopAll(),this.input&&this.input.stop(),this.mode==="connected"&&this.networkSync&&this.networkSync.disconnect();let e=this.core.getUser(this.userId);e&&this.options.application.destroyUser&&this.options.application.destroyUser(this.core,e,"Runtime stopped"),this.log("ClientRuntime stopped")}getStats(){let e=this.performanceMonitor.getStats();return{mode:this.mode,running:this.running,userCount:this.core.getUsers().length,fps:e.fps,uptime:this.running?performance.now()-this.startTime:0,totalFrames:0,latency:void 0,lastFrameTiming:e.lastFrame,avgFrameTiming:e.avgFrame}}async destroy(){await this.stop(),this.log("Destroying ClientRuntime"),this.visibilityChangeHandler&&(document.removeEventListener("visibilitychange",this.visibilityChangeHandler),this.visibilityChangeHandler=void 0),this.autoplayOverlay&&(this.autoplayOverlay.destroy(),this.autoplayOverlay=null),this.audioManager&&(this.audioManager.destroy(),this.audioManager=null),this.postProcessOverlay&&(this.postProcessOverlay.destroy(),this.postProcessOverlay=null);let e=this.rendererManager.getRenderer();e&&"clearOnResizeCallback"in e&&e.clearOnResizeCallback(),this.options.application.destroy&&this.options.application.destroy(),this.rendererManager.destroy(),this.input&&this.input.destroy(),this.networkSync&&this.networkSync.destroy(),this.log("ClientRuntime destroyed")}async createLocalUser(){let e=this.options;this.log(`Creating local user: ${this.userId}`);let t=this.core.createUser(this.userId,e.username);if(this.audioManager&&t.setAudioProcessor(this.audioManager),this.log("Calling application.initUser()"),this.options.application.initUser(this.core,t,{username:e.username}),t.hasAudioConfigCommands()&&(this.log("Applying audio config commands from initUser()"),t.applyAudioConfigCommands(t.flushAudioConfigCommands())),t.hasPendingMacroOrders()){this.log("Applying macro orders from initUser()");let i=t.flushMacroOrders();t.applyMacroOrders(i)}if(t.hasPostProcessCommands()){this.log("Applying post-process commands from initUser()");let i=t.flushPostProcessCommands(),r=this.postProcessOrderCollector.convertCommands(i);this.applyPostProcessOrders(r)}t.needsSendSounds()&&(await this.loadSoundsFromRegistry(),t.clearSendSounds()),this.log("Performing initial render"),this.core.endTick(),this.render(),this.log("Initial render complete")}async loadSoundsFromRegistry(){if(!this.audioManager){this.log("Cannot load sounds: AudioManager not initialized");return}let e=this.audioManager.getSoundBank();if(!e){this.log("Cannot load sounds: SoundBank not initialized");return}let i=this.core.getSoundRegistry().getAll();if(i.length===0){this.log("No sounds to load from registry");return}this.log(`Loading ${i.length} sounds from Core registry into AudioManager...`);for(let r of i)try{r.loadType==="file"&&r.data?(await e.loadFromData(r.soundId,r.name,r.data),this.log(`\u{1F50A} Loaded sound: ${r.name} (${r.data.length} bytes)`)):r.loadType==="external"&&r.url&&(await e.loadFromUrl(r.soundId,r.name,r.url),this.log(`\u{1F50A} Loaded external sound: ${r.name} from ${r.url}`))}catch(n){console.error(`[ClientRuntime] Failed to load sound "${r.name}":`,n)}this.log(`\u2713 ${e.size} sounds loaded into AudioManager`)}mainLoop(e){if(!this.running){this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=0);return}if(this.renderMode==="on-demand"){this.renderRequested&&(this.renderRequested=!1,this.performanceMonitor.updateFPS(e),this.render()),this.rafId=requestAnimationFrame(s=>this.mainLoop(s));return}let t=e-this.lastRenderTimestamp;if(this.lastRenderTimestamp>0&&t<this.FRAME_TIME_MIN-1){this.rafId=requestAnimationFrame(s=>this.mainLoop(s));return}this.lastRenderTimestamp=e;let i=(e-this.lastTimestamp)/1e3,r=Math.min(i,.1);this.lastTimestamp=e,this.performanceMonitor.updateFPS(e);let n=this.core.getUser(this.userId);if(!n){this.rafId=requestAnimationFrame(s=>this.mainLoop(s));return}if(this.mode==="local"){if(this.tickRate===0){let d=performance.now();this.render();let u=performance.now()-d;this.performanceMonitor.recordFrameTiming(0,u),this.rafId=requestAnimationFrame(l=>this.mainLoop(l));return}if(!this.firstTickDone){this.firstTickDone=!0,this.lastTimestamp=e,this.accumulatedTime=0,this.rafId=requestAnimationFrame(d=>this.mainLoop(d));return}this.accumulatedTime+=r;let s=1/this.tickRate;this.accumulatedTime>.5&&(this.accumulatedTime=s);let a=0,c=0;for(;this.accumulatedTime>=s&&a<5;){let d=performance.now();if(this.collectAndApplyInput(n),this.options.application.update(this.core,s),this.options.application.updateUser(this.core,n,s),n.clearTextInputs(),n.hasAudioConfigCommands()&&n.applyAudioConfigCommands(n.flushAudioConfigCommands()),n.hasSoundCommands()&&n.applyAudioCommands(n.flushSoundCommands()),n.hasPostProcessCommands()){let l=n.flushPostProcessCommands(),p=this.postProcessOrderCollector.convertCommands(l);this.applyPostProcessOrders(p)}if(n.hasPendingMacroOrders()){let l=n.flushMacroOrders();n.applyMacroOrders(l)}let u=n.updateMacros();if(n.processMacroEvents(u),n.hasBridgeMessages()){let l=n.getBridgeMessages();this.dispatchLocalBridgeMessages(l)}this.core.endTickSplit(),c+=performance.now()-d,this.accumulatedTime-=s,a++}if(a>0){let d=performance.now();this.render();let u=performance.now()-d;this.performanceMonitor.recordFrameTiming(c,u)}}else{let s=n.updateMacros();n.processMacroEvents(s),this.collectAndSendInput()}this.rafId=requestAnimationFrame(s=>this.mainLoop(s))}collectAndApplyInput(e){if(!this.input)return;let t=this.rendererManager.getCanvas();if(t){let a=e.getDisplays(),c=a.length>0?a[0].size.x:this.options.width,d=a.length>0?a[0].size.y:this.options.height,l=this.rendererManager.getRenderer()?.getOffsets?.(),p={offsetX:l?.offsetX??0,offsetY:l?.offsetY??0},y=T.collectMousePosition(this.input,t,c,d,p);e.setMousePosition(y.x,y.y,y.over),e.updateMacroMouse(y.x,y.y,y.isLeftDown);let g=T.collectTouchPositions(this.input,t,c,d,10,p);this.options.debug&&g.length>0&&console.warn("\u{1F4F1} Collected touches:",g),g.forEach(h=>{e.setTouchPosition(h.id,h.x,h.y,h.over)})}let i=T.collectTextInputs(this.input);i.length>0&&e.setTextInputs(i);let r=e.getInputBindingRegistry(),n=r.getAllAxes(),s=r.getAllButtons();if(n.length>0||s.length>0){let a=T.collectAxisSources(n,this.input),c=T.collectButtonSourcesWithTransitions(s,this.input);n.forEach(d=>{let u=r.evaluateAxis(d.bindingId,a);e.setAxis(d.name,u)}),s.forEach(d=>{let u=new Map,l=new Map,p=new Map;for(let[C,b]of c)u.set(C,b.pressed),l.set(C,b.justPressed),p.set(C,b.justReleased);let y=r.evaluateButton(d.bindingId,u),g=r.evaluateButton(d.bindingId,l),h=r.evaluateButton(d.bindingId,p);e.setButton(d.name,y),e.setButton(`${d.name}_justPressed`,g),e.setButton(`${d.name}_justReleased`,h)})}this.input.poll?.()}collectAndSendInput(){!this.networkSync||!this.input||this.networkSync.sendInput(this.input)}render(){let e=this.core.getUser(this.userId);if(e){let t=e.getMacroRenderOrders();for(let[i,r]of t){let n=e.getLayerById(i);n&&r.length>0&&n.addTemporaryOrders(r)}}this.rendererManager.render(this.core,this.userId)}onCorePaletteChanged(e){this.log(`Palette changed, updating renderer (${e.size} colors)`);let t=[];for(let r=0;r<256;r++){let n=e.get(r);n?t.push({r:n.r,g:n.g,b:n.b,a:n.a}):t.push({r:0,g:0,b:0,a:0})}let i=this.rendererManager.getRenderer();if(!i){console.warn("[ClientRuntime] Cannot update palette: renderer is null");return}"setPalette"in i&&typeof i.setPalette=="function"?(i.setPalette(t),this.log("\u2713 Renderer palette updated successfully")):console.warn("[ClientRuntime] Renderer does not have setPalette method")}onCoreBitmapFontChanged(e){this.log(`Bitmap font ${e} changed, updating renderer`);let t=this.core.getBitmapFont(e);if(!t){console.warn(`[ClientRuntime] Font ${e} not found in registry`);return}let i=new Map,r=0;for(let s=0;s<256;s++){let a=t.getGlyph(s);a&&(i.set(s,a),r++)}this.log(`Built bitmap font map with ${r} glyphs, dimensions: ${t.getCharWidth()}x${t.getCharHeight()} (cell: ${t.getCellWidth()}x${t.getCellHeight()})`);let n=this.rendererManager.getRenderer();if(!n){console.warn("[ClientRuntime] Cannot update font: renderer is null");return}"setBitmapFont"in n&&typeof n.setBitmapFont=="function"?(n.setBitmapFont(i,t.getCharWidth(),t.getCharHeight(),t.getCellWidth(),t.getCellHeight()),this.log("\u2713 Renderer bitmap font updated successfully"),this.postProcessOverlay&&"syncWithRenderer"in this.postProcessOverlay&&"getCellWidth"in n&&"getCellHeight"in n&&"getCurrentScale"in n&&"getGridSize"in n&&(this.postProcessOverlay.syncWithRenderer(n),this.log("\u2713 PostProcessOverlay synced with renderer dimensions"))):console.warn("[ClientRuntime] Renderer does not have setBitmapFont method")}onCoreImageFontChanged(e){this.log(`Image font ${e} changed, updating renderer`);let t=this.core.getImageFont(e);if(!t){console.warn(`[ClientRuntime] Image font ${e} not found in registry`);return}this.log(`Loading image font with ${t.getAtlasBlocks()} blocks (${t.getAtlasBlocks()*256} chars), glyph: ${t.getGlyphWidth()}x${t.getGlyphHeight()}, cell: ${t.getCellWidth()}x${t.getCellHeight()}`);let i=this.rendererManager.getRenderer();if(!i){console.warn("[ClientRuntime] Cannot update image font: renderer is null");return}"setImageFont"in i&&typeof i.setImageFont=="function"?(i.setImageFont(t.getImageData(),t.getGlyphWidth(),t.getGlyphHeight(),t.getCellWidth(),t.getCellHeight(),t.getAtlasBlocks()),this.log("\u2713 Renderer image font updated successfully"),this.postProcessOverlay&&"syncWithRenderer"in this.postProcessOverlay&&"getCellWidth"in i&&"getCellHeight"in i&&"getCurrentScale"in i&&"getGridSize"in i&&(this.postProcessOverlay.syncWithRenderer(i),this.log("\u2713 PostProcessOverlay synced with renderer dimensions"))):console.warn("[ClientRuntime] Renderer does not have setImageFont method")}getAudioManager(){return this.audioManager}getAudioContext(){return this.audioManager?.getContext()??null}applyAmbientEffectConfig(e){let t=this.rendererManager?.getRenderer();t&&"setAmbientEffect"in t&&(e.enabled?t.setAmbientEffect({blur:e.blur,scale:e.scale}):t.setAmbientEffect(!1),this.log(`Ambient effect ${e.enabled?"enabled":"disabled"}`))}applyPostProcessOrders(e){if(!this.postProcessOverlay){this.log("PostProcessOverlay not initialized, skipping post-process orders");return}for(let t of e)switch(t.type){case I.SetConfig:{let i={};t.scanlines&&(i.scanlines={enabled:t.scanlines.enabled,opacity:t.scanlines.opacity,pattern:this.patternFromType(t.scanlines.pattern),color:{r:t.scanlines.colorR,g:t.scanlines.colorG,b:t.scanlines.colorB}}),t.ambientEffect&&(i.ambientEffect={enabled:t.ambientEffect.enabled,blur:t.ambientEffect.blur,scale:t.ambientEffect.scale}),this.postProcessOverlay.setConfig(Object.keys(i).length>0?i:null),i.ambientEffect&&this.applyAmbientEffectConfig(i.ambientEffect);break}case I.SetScanlines:{this.postProcessOverlay.setScanlines({enabled:t.enabled,opacity:t.opacity,pattern:this.patternFromType(t.pattern),color:{r:t.colorR,g:t.colorG,b:t.colorB}});break}case I.SetAmbientEffect:{this.applyAmbientEffectConfig({enabled:t.enabled,blur:t.blur,scale:t.scale});break}case I.SetScalingMode:{this.applyScalingMode(t.mode);break}case I.SetGrid:{this.applyGridConfig(t);break}}}applyScalingMode(e){let t=this.rendererManager.getRenderer();if(t&&"setScalingMode"in t){let i=$(e);t.setScalingMode(i),this.log(`Scaling mode set to ${i}`)}}applyGridConfig(e){let t=this.rendererManager.getRenderer();if(t&&"setGrid"in t){let i=e.colorA/255;t.setGrid({enabled:e.enabled,color:`rgba(${e.colorR},${e.colorG},${e.colorB},${i})`,lineWidth:e.lineWidth}),this.log(`Grid ${e.enabled?"enabled":"disabled"}`)}}patternFromType(e){switch(e){case 0:return"horizontal";case 1:return"vertical";case 2:return"grid";default:return"horizontal"}}getPostProcessOverlay(){return this.postProcessOverlay}dispatchLocalBridgeMessages(e){for(let t of e){let{channel:i,data:r}=t,n=this.localBridgeHandlers.get(i);if(n)for(let s of n)try{s(r)}catch(a){console.error(`[ClientRuntime] Bridge handler error on '${i}':`,a)}for(let s of this.localBridgeWildcardHandlers)try{s(i,r)}catch(a){console.error("[ClientRuntime] Bridge wildcard handler error:",a)}this.log(`Bridge message dispatched on channel '${i}'`)}}sendBridge(e,t){if(this.mode==="connected"&&this.networkSync)this.networkSync.sendBridge(e,t);else if(this.mode==="local"){let i=this.core.getUser(this.userId);i&&this.options.application.onBridgeMessage&&(this.options.application.onBridgeMessage(this.core,i,e,t),this.log(`Bridge message sent to application on channel '${e}'`))}}onBridge(e,t){this.mode==="connected"&&this.networkSync?this.networkSync.onBridge(e,t):this.mode==="local"&&(e==="*"?this.localBridgeWildcardHandlers.add(t):(this.localBridgeHandlers.has(e)||this.localBridgeHandlers.set(e,new Set),this.localBridgeHandlers.get(e).add(t)),this.log(`Bridge handler registered for channel '${e}'`))}offBridge(e,t){this.mode==="connected"&&this.networkSync?this.networkSync.offBridge(e,t):this.mode==="local"&&(e==="*"?this.localBridgeWildcardHandlers.delete(t):this.localBridgeHandlers.get(e)?.delete(t))}removeAllBridgeHandlers(e){this.mode==="connected"&&this.networkSync?this.networkSync.removeAllBridgeHandlers(e):this.mode==="local"&&(e===void 0?(this.localBridgeHandlers.clear(),this.localBridgeWildcardHandlers.clear()):e==="*"?this.localBridgeWildcardHandlers.clear():this.localBridgeHandlers.delete(e))}log(e){this.options.debug&&console.warn(`[ClientRuntime/${this.mode}] ${e}`)}};f(O,"ClientRuntime");var P=O;import{ScalingMode as Fe}from"@utsp/render";import{AudioManager as ke}from"@utsp/audio";export{ke as AudioManager,P as ClientRuntime,B as RendererType,Fe as ScalingMode};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@utsp/runtime-client",
|
|
3
|
-
"version": "0.9.0
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"description": "UTSP Runtime Client - Local and multi-user client runtime",
|
|
5
5
|
"author": "THP Software",
|
|
6
6
|
"license": "MIT",
|
|
@@ -48,12 +48,12 @@
|
|
|
48
48
|
"access": "public"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@utsp/audio": "0.9.0
|
|
52
|
-
"@utsp/core": "0.9.0
|
|
53
|
-
"@utsp/input": "0.9.0
|
|
54
|
-
"@utsp/network-client": "0.9.0
|
|
55
|
-
"@utsp/render": "0.9.0
|
|
56
|
-
"@utsp/types": "0.9.0
|
|
51
|
+
"@utsp/audio": "0.9.0",
|
|
52
|
+
"@utsp/core": "0.9.0",
|
|
53
|
+
"@utsp/input": "0.9.0",
|
|
54
|
+
"@utsp/network-client": "0.9.0",
|
|
55
|
+
"@utsp/render": "0.9.0",
|
|
56
|
+
"@utsp/types": "0.9.0"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
59
59
|
"typescript": "^5.6.3"
|